repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
weibaohui/korm | src/main/kotlin/com/sdibt/korm/core/callbacks/Callback.kt | 1 | 2176 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sdibt.korm.core.callbacks
class Callback {
var processors: MutableList<CallBackProcessors> = mutableListOf()
var inserts: MutableList<(scope: Scope) -> Scope> = mutableListOf()
var batchInserts: MutableList<(scope: Scope) -> Scope> = mutableListOf()
var updates: MutableList<(scope: Scope) -> Scope> = mutableListOf()
var deletes: MutableList<(scope: Scope) -> Scope> = mutableListOf()
var selects: MutableList<(scope: Scope) -> Scope> = mutableListOf()
var executes: MutableList<(scope: Scope) -> Scope> = mutableListOf()
fun reset() {
processors.clear()
inserts.clear()
batchInserts.clear()
updates.clear()
deletes.clear()
selects.clear()
executes.clear()
}
fun delete(): CallBackProcessors {
return CallBackProcessors("delete", this)
}
fun update(): CallBackProcessors {
return CallBackProcessors("update", this)
}
fun insert(): CallBackProcessors {
return CallBackProcessors("insert", this)
}
fun batchInsert(): CallBackProcessors {
return CallBackProcessors("batchInsert", this)
}
fun select(): CallBackProcessors {
return CallBackProcessors("select", this)
}
fun execute(): CallBackProcessors {
return CallBackProcessors("execute", this)
}
}
| apache-2.0 | 3b99d48826524346a15f30d5b234778b | 31.969697 | 76 | 0.682904 | 4.761488 | false | false | false | false |
http4k/http4k | src/docs/guide/howto/create_a_distributed_tracing_tree/example.kt | 1 | 5532 | package guide.howto.create_a_distributed_tracing_tree
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.http4k.core.HttpHandler
import org.http4k.core.Method
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status
import org.http4k.core.Status.Companion.OK
import org.http4k.core.Uri
import org.http4k.core.then
import org.http4k.events.EventFilters.AddServiceName
import org.http4k.events.EventFilters.AddZipkinTraces
import org.http4k.events.Events
import org.http4k.events.HttpEvent
import org.http4k.events.HttpEvent.Incoming
import org.http4k.events.HttpEvent.Outgoing
import org.http4k.events.MetadataEvent
import org.http4k.events.then
import org.http4k.filter.ClientFilters
import org.http4k.filter.ClientFilters.ResetRequestTracing
import org.http4k.filter.ResponseFilters.ReportHttpTransaction
import org.http4k.filter.ServerFilters.RequestTracing
import org.http4k.filter.ZipkinTraces
import org.http4k.filter.debug
import org.http4k.routing.bind
import org.http4k.routing.reverseProxy
import org.http4k.routing.routes
import org.http4k.testing.RecordingEvents
// standardised events stack which records the service name and adds tracing
fun TraceEvents(actorName: String) = AddZipkinTraces().then(AddServiceName(actorName))
// standardised client filter stack which adds tracing and records traffic events
fun ClientStack(events: Events) = ReportHttpTransaction { events(Outgoing(it)) }
.then(ClientFilters.RequestTracing())
// standardised server filter stack which adds tracing and records traffic events
fun ServerStack(events: Events) = ReportHttpTransaction { events(Incoming(it)) }
.then(RequestTracing())
// Our "User" object who will send a request to our system
class User(rawEvents: Events, rawHttp: HttpHandler) {
private val events = TraceEvents("user").then(rawEvents)
// as the user is the initiator of requests, we need to reset the tracing for each call.
private val http = ResetRequestTracing().then(ClientStack(events)).then(rawHttp)
fun initiateCall() = http(Request(GET, "http://internal1/int1"))
}
// the first internal app
fun Internal1(rawEvents: Events, rawHttp: HttpHandler): HttpHandler {
val events = TraceEvents("internal1").then(rawEvents).then(rawEvents)
val http = ClientStack(events).then(rawHttp)
return ServerStack(events)
.then(
routes("/int1" bind { _: Request ->
http(Request(GET, "http://external1/ext1"))
http(Request(GET, "http://internal2/int2"))
})
)
}
// the second internal app
fun Internal2(rawEvents: Events, rawHttp: HttpHandler): HttpHandler {
val events = TraceEvents("internal2").then(rawEvents).then(rawEvents)
val http = ClientStack(events).then(rawHttp)
return ServerStack(events)
.then(
routes("/int2" bind { _: Request ->
http(Request(GET, "http://external2/ext2"))
})
)
}
// an external fake system
fun FakeExternal1(): HttpHandler = { Response(OK) }
// another external fake system
fun FakeExternal2(): HttpHandler = { Response(OK) }
fun main() {
val events = RecordingEvents()
// compose our application(s) together
val internalApp = Internal1(
events,
reverseProxy(
"external1" to FakeExternal1(),
"internal2" to Internal2(events, FakeExternal2())
)
)
// make a request to the composed stack
User(events, internalApp).initiateCall()
// convert the recorded events into a tree of HTTP calls
val callTree = events.createCallTree()
println(callTree)
// check that we created the correct thing
assertThat(callTree, equalTo(listOf(expectedCallTree)))
}
private fun RecordingEvents.createCallTree(): List<HttpCallTree> {
val outbound = filterIsInstance<MetadataEvent>().filter { it.event is Outgoing }
return outbound
.filter { it.traces().parentSpanId == null }
.map { it.toCallTree(outbound - it) }
}
// recursively create the call tree from the event list
private fun MetadataEvent.toCallTree(calls: List<MetadataEvent>): HttpCallTree {
val httpEvent = event as HttpEvent
return HttpCallTree(
service(),
httpEvent.uri, httpEvent.method, httpEvent.status, calls.filter {
httpEvent.uri.host == it.service() && traces().spanId == it.traces().parentSpanId
}.map { it.toCallTree(calls - it) })
}
private fun MetadataEvent.service() = metadata["service"].toString()
private fun MetadataEvent.traces() = (metadata["traces"] as ZipkinTraces)
data class HttpCallTree(
val origin: String,
val uri: Uri,
val method: Method,
val status: Status,
val children: List<HttpCallTree>
)
val expectedCallTree = HttpCallTree(
"user", Uri.of("http://internal1/int1"), GET, OK,
listOf(
HttpCallTree(
origin = "internal1",
uri = Uri.of("http://external1/ext1"),
method = GET,
status = OK,
children = emptyList()
),
HttpCallTree(
"internal1", Uri.of("http://internal2/int2"), GET, OK, listOf(
HttpCallTree(
origin = "internal2",
uri = Uri.of("http://external2/ext2"),
method = GET,
status = OK,
children = emptyList()
),
)
)
)
)
| apache-2.0 | 6b3198228b34b19ba710549aaf9b3c12 | 33.148148 | 93 | 0.687816 | 4.023273 | false | false | false | false |
tutao/tutanota | app-android/app/src/main/java/de/tutao/tutanota/credentials/AuthenticationPrompt.kt | 1 | 3215 | package de.tutao.tutanota.credentials
import androidx.biometric.BiometricPrompt
import androidx.biometric.BiometricPrompt.PromptInfo
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import de.tutao.tutanota.CredentialAuthenticationException
import java.util.concurrent.Semaphore
/**
* Class to display an authentication prompt using various authentication methods to unlock keystore keys.
*/
class AuthenticationPrompt internal constructor() {
/**
* We use a semaphore to ensure that an authentication prompt can only be displayed once. This prevents multiple
* requests from the web layer trying to open multiple authentication prompts which would lead to a
* [android.security.keystore.UserNotAuthenticatedException].
*/
private val sem: Semaphore = Semaphore(1)
/**
* Displays an authentication prompt. This refreshes ambient system authentication.
* @param activity Activity on which to display the authentication prompt fragment.
* @param promptInfo Configuration object for the authentication prompt to be displayed.
* @throws CredentialAuthenticationException If authentication fails by either cancelling authentication or exceeded limit of failed attempts.
*/
@Throws(CredentialAuthenticationException::class)
fun authenticate(
activity: FragmentActivity,
promptInfo: PromptInfo,
) {
showPrompt(activity, promptInfo, null)
}
/**
* Displays an authentication prompt. This authenticates exactly one operation using {@param cryptoObject}.
* @param activity Activity on which to display the authentication prompt fragment.
* @param promptInfo Configuration object for the authentication prompt to be displayed.
* @param cryptoObject
* @throws CredentialAuthenticationException If authentication fails by either cancelling authentication or exceeded limit of failed attempts.
*/
@Throws(CredentialAuthenticationException::class)
fun authenticateCryptoObject(
activity: FragmentActivity,
promptInfo: PromptInfo,
cryptoObject: BiometricPrompt.CryptoObject?,
) {
showPrompt(activity, promptInfo, cryptoObject)
}
@Throws(CredentialAuthenticationException::class)
private fun showPrompt(
activity: FragmentActivity,
promptInfo: PromptInfo,
cryptoObject: BiometricPrompt.CryptoObject?,
) {
sem.acquireUninterruptibly()
var error: String? = null
activity.runOnUiThread {
val biometricPrompt = BiometricPrompt(
activity,
ContextCompat.getMainExecutor(activity),
object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
error = errString.toString()
sem.release()
}
override fun onAuthenticationSucceeded(
result: BiometricPrompt.AuthenticationResult,
) {
sem.release()
}
override fun onAuthenticationFailed() {}
})
if (cryptoObject != null) {
biometricPrompt.authenticate(promptInfo, cryptoObject)
} else {
biometricPrompt.authenticate(promptInfo)
}
}
try {
sem.acquire()
sem.release()
} catch (ignored: InterruptedException) {
}
error?.let {
throw CredentialAuthenticationException(it)
}
}
} | gpl-3.0 | e3f71ce758b233df270845fff1b13457 | 33.580645 | 143 | 0.766719 | 4.80568 | false | false | false | false |
msebire/intellij-community | java/java-analysis-impl/src/com/intellij/codeInspection/apiUsage/ApiUsageVisitorBase.kt | 1 | 3773 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.apiUsage
import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil
import com.intellij.psi.*
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.infos.MethodCandidateInfo
/**
* Non-recursive PSI visitor that detects usages of APIs and reports them via [ApiUsageDetector] interface.
* This visitor is mainly designed for Java, but may basically work with any language, including Kotlin.
* Inheritors should provide at least implementation of [processReference].
*/
abstract class ApiUsageVisitorBase : PsiElementVisitor(), ApiUsageDetector {
final override fun visitElement(element: PsiElement) {
super.visitElement(element)
if (element is PsiLanguageInjectionHost || element is LeafPsiElement) {
//Better performance.
return
}
when (element) {
is PsiClass -> visitClass(element)
is PsiMethod -> visitMethod(element)
is PsiNewExpression -> visitNewExpression(element)
else -> processReferences(element)
}
}
private fun processReferences(element: PsiElement) {
if (shouldProcessReferences(element)) {
for (reference in element.references) {
processReference(reference)
}
}
}
private fun visitClass(aClass: PsiClass) {
if (aClass is PsiTypeParameter || aClass is PsiAnonymousClass) return
if (aClass.constructors.isEmpty()) {
val superClass = aClass.superClass ?: return
val superConstructors = superClass.constructors
if (superConstructors.isEmpty() || superConstructors.any { it.parameterList.isEmpty }) {
processEmptyConstructorOfSuperClassImplicitInvocationAtSubclassDeclaration(aClass, superClass)
}
}
}
private fun visitMethod(method: PsiMethod) {
if (method.isConstructor) {
checkImplicitCallToSuper(method)
}
else {
checkMethodOverriding(method)
}
}
private fun visitNewExpression(expression: PsiNewExpression) {
var classType = expression.type as? PsiClassType ?: return
val argumentList = expression.argumentList ?: return
val classReference = expression.classOrAnonymousClassReference ?: return
var typeResult = classType.resolveGenerics()
var aClass = typeResult.element ?: return
if (aClass is PsiAnonymousClass) {
classType = aClass.baseClassType
typeResult = classType.resolveGenerics()
aClass = typeResult.element ?: return
}
if (aClass.constructors.isEmpty()) {
processDefaultConstructorInvocation(classReference)
} else {
val results = JavaPsiFacade
.getInstance(expression.project)
.resolveHelper
.multiResolveConstructor(classType, argumentList, argumentList)
val result = results.singleOrNull() as? MethodCandidateInfo ?: return
val constructor = result.element
processConstructorInvocation(classReference, constructor)
}
}
private fun checkImplicitCallToSuper(constructor: PsiMethod) {
val superClass = constructor.containingClass?.superClass ?: return
val statements = constructor.body?.statements ?: return
if (statements.isEmpty() || !JavaHighlightUtil.isSuperOrThisCall(statements.first(), true, true)) {
processEmptyConstructorOfSuperClassImplicitInvocationAtSubclassConstructor(superClass, constructor)
}
}
private fun checkMethodOverriding(method: PsiMethod) {
val superSignatures = method.findSuperMethodSignaturesIncludingStatic(true)
for (superSignature in superSignatures) {
val superMethod = superSignature.method
processMethodOverriding(method, superMethod)
}
}
}
| apache-2.0 | b89f48a746ca70a1f3c9c7217e32ce66 | 36.356436 | 140 | 0.738139 | 5.14734 | false | false | false | false |
kotlin-es/kotlin-JFrame-standalone | 09-start-async-radiobutton-application/src/main/kotlin/components/menuBar/MenuBarImpl.kt | 1 | 2043 | package components.progressBar
import java.awt.event.ActionEvent
import javax.swing.JComponent
import javax.swing.JMenu
import javax.swing.JMenuBar
import javax.swing.JMenuItem
/**
* Created by vicboma on 05/12/16.
*/
class MenuBarImpl internal constructor() : JMenuBar(), MenuBar {
companion object {
fun create() : MenuBar {
return MenuBarImpl()
}
}
init {
}
override fun createMenu(map : Map<String,Map<String, (ActionEvent)-> Unit>>) : JMenu? {
fun createMenu(nameMenu: String, map: Map<String, (ActionEvent) -> Unit>) : JMenu {
val menu = JMenu(nameMenu)
for (entry in map.entries) {
when {
entry.key.subSequence(0, 3) == "---" -> menu.addSeparator()
else -> {
val menuItem = JMenuItem(entry.key)
menuItem.addActionListener(entry.value)
menu.add(menuItem)
}
}
}
return menu
}
var res : JMenu? = null
for(entry in map.entries){
val menuBarMenu = entry.key
val menuBarItems = entry.value
res = createMenu(menuBarMenu, menuBarItems)
}
return res
}
override fun addMenu(name : JComponent?) : MenuBar {
this.add(name)
return this
}
override fun addMenu(list : MutableList<JComponent?>) : MenuBar {
for( it in list)
this.addMenu(it)
return this
}
override fun createSubMenu(parent : JMenu?, child : JComponent?) : MenuBar {
parent?.add(child)
return this
}
override fun createSubMenu(parent : JMenu?, child : MutableList<JComponent?>) : MenuBar {
for( it in child)
parent?.add(it)
return this
}
override fun addSeparator(menu : JMenu?) : MenuBar {
menu?.addSeparator()
return this
}
override fun component(): JMenuBar = this
}
| mit | 4bddd33aceea9e5d949098fa2c14fe95 | 23.035294 | 93 | 0.549682 | 4.632653 | false | false | false | false |
iMeePwni/LCExercise | src/main/kotlin/HammingDistance.kt | 1 | 579 | /**
* Created by guofeng on 2017/6/20.
* https://leetcode.com/problems/hamming-distance/#/description
*/
class HammingDistance {
fun solution(x: Int, y: Int): Int? {
val max = Math.pow(2.0, 31.0).toInt()
if (x !in 0..max - 1 || y !in 0..max - 1) return null
val xi = getIndex(x)
val yi = getIndex(y)
val xyi = (xi + yi) / 2
return Math.pow(2.0, xyi.toDouble()).toInt()
}
fun getIndex(x: Int): Int {
val xb = Integer.toBinaryString(x)
val xi: Int = xb.indexOf("1") + 1
return xi
}
} | apache-2.0 | c9843ba9a5364adc633e7a56800c8dee | 21.307692 | 63 | 0.535406 | 3.163934 | false | false | false | false |
valich/intellij-markdown | src/commonMain/kotlin/org/intellij/markdown/parser/markerblocks/impl/CodeBlockMarkerBlock.kt | 1 | 3549 | package org.intellij.markdown.parser.markerblocks.impl
import org.intellij.markdown.IElementType
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.lexer.Compat.assert
import org.intellij.markdown.parser.LookaheadText
import org.intellij.markdown.parser.ProductionHolder
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.constraints.applyToNextLineAndAddModifiers
import org.intellij.markdown.parser.constraints.getCharsEaten
import org.intellij.markdown.parser.markerblocks.MarkdownParserUtil
import org.intellij.markdown.parser.markerblocks.MarkerBlock
import org.intellij.markdown.parser.markerblocks.MarkerBlockImpl
import org.intellij.markdown.parser.sequentialparsers.SequentialParser
class CodeBlockMarkerBlock(myConstraints: MarkdownConstraints,
private val productionHolder: ProductionHolder,
startPosition: LookaheadText.Position)
: MarkerBlockImpl(myConstraints, productionHolder.mark()) {
init {
productionHolder.addProduction(listOf(SequentialParser.Node(
startPosition.offset..startPosition.nextLineOrEofOffset, MarkdownTokenTypes.CODE_LINE)))
}
override fun allowsSubBlocks(): Boolean = false
override fun isInterestingOffset(pos: LookaheadText.Position): Boolean = true
private var realInterestingOffset = -1
override fun calcNextInterestingOffset(pos: LookaheadText.Position): Int {
return pos.nextLineOrEofOffset
}
override fun getDefaultAction(): MarkerBlock.ClosingAction {
return MarkerBlock.ClosingAction.DONE
}
override fun doProcessToken(pos: LookaheadText.Position, currentConstraints: MarkdownConstraints): MarkerBlock.ProcessingResult {
if (pos.offset < realInterestingOffset) {
return MarkerBlock.ProcessingResult.CANCEL
}
// Eat everything if we're on code line
if (pos.offsetInCurrentLine != -1) {
return MarkerBlock.ProcessingResult.CANCEL
}
assert(pos.offsetInCurrentLine == -1)
val nonemptyPos = MarkdownParserUtil.findNonEmptyLineWithSameConstraints(constraints, pos)
?: return MarkerBlock.ProcessingResult.DEFAULT
val nextConstraints = constraints.applyToNextLineAndAddModifiers(nonemptyPos)
val shifted = nonemptyPos.nextPosition(1 + nextConstraints.getCharsEaten(nonemptyPos.currentLine))
val nonWhitespace = shifted?.nextPosition(shifted.charsToNonWhitespace() ?: 0)
?: return MarkerBlock.ProcessingResult.DEFAULT
if (!MarkdownParserUtil.hasCodeBlockIndent(nonWhitespace, nextConstraints)) {
return MarkerBlock.ProcessingResult.DEFAULT
} else {
// We'll add the current line anyway
val nextLineConstraints = constraints.applyToNextLineAndAddModifiers(pos)
val nodeRange = pos.offset + 1 + nextLineConstraints.getCharsEaten(pos.currentLine)..pos.nextLineOrEofOffset
if (nodeRange.last - nodeRange.first > 0) {
productionHolder.addProduction(listOf(SequentialParser.Node(
nodeRange, MarkdownTokenTypes.CODE_LINE)))
}
realInterestingOffset = pos.nextLineOrEofOffset
return MarkerBlock.ProcessingResult.CANCEL
}
}
override fun getDefaultNodeType(): IElementType {
return MarkdownElementTypes.CODE_BLOCK
}
}
| apache-2.0 | aa87afb3f3cb12648d59df5a4610a48e | 43.3625 | 133 | 0.736546 | 5.633333 | false | false | false | false |
bertilxi/Chilly_Willy_Delivery | mobile/app/src/main/java/dam/isi/frsf/utn/edu/ar/delivery/adapter/SaucesAdapter.kt | 1 | 1748 | package dam.isi.frsf.utn.edu.ar.delivery.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import com.koushikdutta.ion.Ion
import dam.isi.frsf.utn.edu.ar.delivery.R
import dam.isi.frsf.utn.edu.ar.delivery.model.Sauce
class SaucesAdapter(context: Context, sauces: List<Sauce>) : ArrayAdapter<Sauce>(context, R.layout.listview_addins_row, sauces) {
var inflater: LayoutInflater = LayoutInflater.from(context)
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var row = convertView
if (row == null) {
row = inflater.inflate(R.layout.listview_addins_row, parent, false)
}
var holder: SauceHolder? = row!!.tag as SauceHolder?
if (holder == null) {
holder = SauceHolder(row)
row.tag = holder
}
if (this.getItem(position)!!.label !== context.getString(R.string.no_sauce_label)) {
Ion.with(holder.saucePic!!)
.fitCenter()
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.load(this.getItem(position)!!.completeImgURL)
}
holder.textViewName!!.text = this.getItem(position)!!.label
return row
}
internal inner class SauceHolder(row: View) {
var textViewName: TextView? = null
var saucePic: ImageView? = null
init {
textViewName = row.findViewById(R.id.addin_name) as TextView
saucePic = row.findViewById(R.id.imageview_addin) as ImageView
}
}
} | mit | 3688765a95cf9b4bc4477dde3c6095f2 | 34.693878 | 129 | 0.648169 | 3.884444 | false | false | false | false |
wmh-demos/Secret | src/main/java/me/wayne/dp/DynamicProgramming.kt | 1 | 1434 | package me.wayne.dp
import kotlin.math.max
val ARR = arrayListOf(1, 2, 4, 1, 7, 8, 3)
fun main() {
println("recOpt1 = " + recOpt1(ARR, 6))
println("dpOpt1 = " + dpOpt1(ARR, 6))
println("recOpt2 = " + recOpt2(ARR, 6, 19))
}
fun recOpt1(arr: List<Int>, index: Int): Int {
return when (index) {
0 -> {
arr[0]
}
1 -> {
max(arr[0], arr[1])
}
else -> {
val choose = arr[index] + recOpt1(arr, index - 2)
val giveUp = recOpt1(arr, index - 1)
max(choose, giveUp)
}
}
}
fun dpOpt1(arr: List<Int>, index: Int): Int {
val resultArr = mutableListOf<Int>()
resultArr.add(0, arr[0])
resultArr.add(1, max(arr[0], arr[1]))
for (i in 2 until arr.size) {
val choose = arr[i] + resultArr[i - 2]
val giveUp = resultArr[i - 1]
resultArr.add(i, max(choose, giveUp))
}
return resultArr[index]
}
fun recOpt2(arr: List<Int>, index: Int, value: Int): Boolean {
return when {
value == 0 -> {
true
}
index == 0 -> {
arr[index] == value
}
arr[index] > value -> {
return recOpt2(arr, index - 1, value)
}
else -> {
val choose = recOpt2(arr, index - 1, value - arr[index])
val giveUp = recOpt2(arr, index - 1, value)
choose || giveUp
}
}
} | apache-2.0 | 1e7528b61166e32cb04f8ffe6d296b3c | 22.916667 | 68 | 0.486053 | 3.296552 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/ForumActivity.kt | 1 | 4698 | package com.boardgamegeek.ui
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.fragment.app.Fragment
import com.boardgamegeek.R
import com.boardgamegeek.entities.ForumEntity
import com.boardgamegeek.extensions.clearTop
import com.boardgamegeek.extensions.intentFor
import com.boardgamegeek.extensions.linkToBgg
import com.boardgamegeek.provider.BggContract
import com.boardgamegeek.ui.ForumsActivity.Companion.startUp
import com.boardgamegeek.ui.GameActivity.Companion.startUp
import com.boardgamegeek.ui.PersonActivity.Companion.startUpForArtist
import com.boardgamegeek.ui.PersonActivity.Companion.startUpForDesigner
import com.boardgamegeek.ui.PersonActivity.Companion.startUpForPublisher
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.logEvent
class ForumActivity : SimpleSinglePaneActivity() {
private var forumId = BggContract.INVALID_ID
private var forumTitle = ""
private var objectId = BggContract.INVALID_ID
private var objectName = ""
private var objectType = ForumEntity.ForumType.REGION
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (forumTitle.isNotEmpty()) {
if (objectName.isNotEmpty()) {
supportActionBar?.title = objectName
}
supportActionBar?.subtitle = forumTitle
}
if (savedInstanceState == null) {
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM) {
param(FirebaseAnalytics.Param.CONTENT_TYPE, "Forum")
param(FirebaseAnalytics.Param.ITEM_ID, forumId.toString())
param(FirebaseAnalytics.Param.ITEM_NAME, forumTitle)
}
}
}
override fun readIntent(intent: Intent) {
forumId = intent.getIntExtra(KEY_FORUM_ID, BggContract.INVALID_ID)
forumTitle = intent.getStringExtra(KEY_FORUM_TITLE).orEmpty()
objectId = intent.getIntExtra(KEY_OBJECT_ID, BggContract.INVALID_ID)
objectType = intent.getSerializableExtra(KEY_OBJECT_TYPE) as ForumEntity.ForumType
objectName = intent.getStringExtra(KEY_OBJECT_NAME).orEmpty()
}
override fun onCreatePane(intent: Intent): Fragment {
return ForumFragment.newInstance(forumId, forumTitle, objectId, objectName, objectType)
}
override val optionsMenuId = R.menu.view
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
when (objectType) {
ForumEntity.ForumType.REGION -> startUp(this)
ForumEntity.ForumType.GAME -> startUp(this, objectId, objectName)
ForumEntity.ForumType.ARTIST -> startUpForArtist(this, objectId, objectName)
ForumEntity.ForumType.DESIGNER -> startUpForDesigner(this, objectId, objectName)
ForumEntity.ForumType.PUBLISHER -> startUpForPublisher(this, objectId, objectName)
}
finish()
}
R.id.menu_view -> linkToBgg("forum/$forumId")
else -> super.onOptionsItemSelected(item)
}
return true
}
companion object {
private const val KEY_FORUM_ID = "FORUM_ID"
private const val KEY_FORUM_TITLE = "FORUM_TITLE"
private const val KEY_OBJECT_ID = "OBJECT_ID"
private const val KEY_OBJECT_NAME = "OBJECT_NAME"
private const val KEY_OBJECT_TYPE = "OBJECT_TYPE"
fun start(context: Context, forumId: Int, forumTitle: String, objectId: Int, objectName: String, objectType: ForumEntity.ForumType) {
context.startActivity(createIntent(context, forumId, forumTitle, objectId, objectName, objectType))
}
fun startUp(context: Context, forumId: Int, forumTitle: String, objectId: Int, objectName: String, objectType: ForumEntity.ForumType) {
context.startActivity(createIntent(context, forumId, forumTitle, objectId, objectName, objectType).clearTop())
}
private fun createIntent(
context: Context,
forumId: Int,
forumTitle: String,
objectId: Int,
objectName: String,
objectType: ForumEntity.ForumType
): Intent {
return context.intentFor<ForumActivity>(
KEY_FORUM_ID to forumId,
KEY_FORUM_TITLE to forumTitle,
KEY_OBJECT_ID to objectId,
KEY_OBJECT_NAME to objectName,
KEY_OBJECT_TYPE to objectType,
)
}
}
}
| gpl-3.0 | 6dc2716e5e7f867588c542f5b734b851 | 41.709091 | 143 | 0.674117 | 4.950474 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/adapter/BuddyCollectionAdapter.kt | 1 | 2553 | package com.boardgamegeek.ui.adapter
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.boardgamegeek.R
import com.boardgamegeek.databinding.RowCollectionBuddyBinding
import com.boardgamegeek.entities.CollectionItemEntity
import com.boardgamegeek.extensions.firstChar
import com.boardgamegeek.extensions.inflate
import com.boardgamegeek.ui.GameActivity.Companion.start
import com.boardgamegeek.ui.adapter.BuddyCollectionAdapter.BuddyGameViewHolder
import com.boardgamegeek.ui.widget.RecyclerSectionItemDecoration.SectionCallback
import kotlin.properties.Delegates
class BuddyCollectionAdapter : RecyclerView.Adapter<BuddyGameViewHolder>(), AutoUpdatableAdapter, SectionCallback {
var items: List<CollectionItemEntity> by Delegates.observable(emptyList()) { _, oldValue, newValue ->
autoNotify(oldValue, newValue) { old, new ->
old.collectionId == new.collectionId
}
}
override fun getItemCount() = items.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BuddyGameViewHolder {
return BuddyGameViewHolder(parent.inflate(R.layout.row_collection_buddy))
}
override fun onBindViewHolder(holder: BuddyGameViewHolder, position: Int) {
holder.bind(items.getOrNull(position))
}
inner class BuddyGameViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val binding = RowCollectionBuddyBinding.bind(itemView)
fun bind(item: CollectionItemEntity?) {
binding.nameView.text = item?.gameName.orEmpty()
binding.yearView.text = item?.gameId?.toString().orEmpty()
itemView.setOnClickListener {
if (item != null) start(itemView.context, item.gameId, item.gameName)
}
}
}
override fun isSection(position: Int): Boolean {
if (position == RecyclerView.NO_POSITION) return false
if (items.isEmpty()) return false
if (position == 0) return true
val thisLetter = items.getOrNull(position)?.sortName.firstChar()
val lastLetter = items.getOrNull(position - 1)?.sortName.firstChar()
return thisLetter != lastLetter
}
override fun getSectionHeader(position: Int): CharSequence {
return when {
position == RecyclerView.NO_POSITION -> return "-"
items.isEmpty() -> return "-"
position < 0 || position >= items.size -> "-"
else -> items[position].sortName.firstChar()
}
}
}
| gpl-3.0 | 8c1ff5e4c3edcad1cd25040d670c717b | 40.177419 | 115 | 0.710145 | 4.909615 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/api/text/format/TextFormat.kt | 1 | 1841 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
@file:JvmName("TextFormatFactory")
@file:Suppress("UNUSED_PARAMETER", "NOTHING_TO_INLINE", "FunctionName")
package org.lanternpowered.api.text.format
typealias TextColor = net.kyori.adventure.text.format.TextColor
typealias NamedTextColor = net.kyori.adventure.text.format.NamedTextColor
typealias TextDecoration = net.kyori.adventure.text.format.TextDecoration
typealias TextDecorationState = net.kyori.adventure.text.format.TextDecoration.State
typealias TextStyle = net.kyori.adventure.text.format.Style
fun textStyleOf(color: TextColor): TextStyle = TextStyle.style(color as TextColor?)
fun textStyleOf(color: TextColor, vararg decorations: TextDecoration): TextStyle = TextStyle.style(color as TextColor?, *decorations)
fun textStyleOf(vararg decorations: TextDecoration): TextStyle = TextStyle.style(*decorations)
inline operator fun TextStyle.plus(decoration: TextDecoration): TextStyle = decoration(decoration, true)
inline operator fun TextStyle.plus(color: TextColor): TextStyle = color(color)
inline operator fun TextStyle.plus(style: TextStyle): TextStyle = merge(style)
inline operator fun TextStyle.contains(decoration: TextDecoration): Boolean = hasDecoration(decoration)
inline operator fun TextDecoration.plus(decoration: TextDecoration): TextStyle = TextStyle.style(this, decoration)
inline operator fun TextDecoration.plus(color: TextColor): TextStyle = TextStyle.style(this, color)
inline operator fun TextColor.plus(decoration: TextDecoration): TextStyle = TextStyle.style(decoration, this)
| mit | 435e61ee5a0102de1254027445fba093 | 54.787879 | 133 | 0.801195 | 4.383333 | false | false | false | false |
LISTEN-moe/android-app | app/src/main/kotlin/me/echeung/moemoekyun/util/ext/CoroutineExtensions.kt | 1 | 845 | package me.echeung.moemoekyun.util.ext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
private val scope = CoroutineScope(SupervisorJob())
fun launchIO(block: suspend CoroutineScope.() -> Unit): Job =
scope.launch(Dispatchers.IO, CoroutineStart.DEFAULT, block)
fun launchNow(block: suspend CoroutineScope.() -> Unit): Job =
scope.launch(Dispatchers.Main, CoroutineStart.UNDISPATCHED, block)
fun CoroutineScope.launchIO(block: suspend CoroutineScope.() -> Unit): Job =
launch(Dispatchers.IO, block = block)
suspend fun <T> withUIContext(block: suspend CoroutineScope.() -> T) = withContext(Dispatchers.Main, block)
| mit | f925103329028e4383c54f6b5cceb45e | 37.409091 | 107 | 0.79645 | 4.518717 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/action/LatexToggleStarAction.kt | 1 | 3573 | package nl.hannahsten.texifyidea.action
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.source.tree.LeafPsiElement
import nl.hannahsten.texifyidea.TexifyIcons
import nl.hannahsten.texifyidea.lang.magic.magicComment
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.psi.LatexGroup
import nl.hannahsten.texifyidea.psi.LatexTypes
import nl.hannahsten.texifyidea.util.getParentOfType
import nl.hannahsten.texifyidea.util.parentOfType
/**
* @author Hannah Schellekens
*/
class LatexToggleStarAction : EditorAction("Toggle Star", TexifyIcons.TOGGLE_STAR) {
override fun actionPerformed(file: VirtualFile, project: Project, textEditor: TextEditor) {
val element = getElement(file, project, textEditor)
val editor = textEditor.editor
val psiFile = getPsiFile(file, project)
element?.parentOfType(LatexGroup::class)?.let {
println(it.magicComment())
}
val commands = getParentOfType(element, LatexCommands::class.java) ?: return
runWriteAction(project) { toggleStar(editor, psiFile, commands) }
}
/**
* Removes the star from a latex commands or adds it when there was no star in the first place.
*
* @param editor
* The current editor.
* @param psiFile
* The current file.
* @param commands
* The latex command to toggle the star of.
*/
private fun toggleStar(editor: Editor, psiFile: PsiFile?, commands: LatexCommands?) {
if (removeStar(commands!!)) {
return
}
addStar(editor, psiFile, commands)
}
/**
* Removes the star from a LaTeX command.
*
* @param commands
* The command to remove the star from.
* @return `true` when the star was removed, `false` when the star was not removed.
*/
private fun removeStar(commands: LatexCommands): Boolean {
val lastChild = commands.lastChild
var elt: PsiElement? = commands.firstChild
while (elt !== lastChild && elt != null) {
if (elt !is LeafPsiElement) {
elt = elt.nextSibling
continue
}
if (elt.elementType === LatexTypes.STAR) {
elt.delete()
return true
}
elt = elt.nextSibling
}
return false
}
/**
* Adds a star to a latex command.
*
* @param editor
* The current editor.
* @param file
* The current file.
* @param commands
* The latex command to add a star to.
*/
private fun addStar(editor: Editor, file: PsiFile?, commands: LatexCommands) {
val document = editor.document
var position = editor.caretModel.offset
while (position > 0) {
val text = document.getText(TextRange(position, position + 1))
val elt = file!!.findElementAt(position)
val parent = getParentOfType(elt, LatexCommands::class.java)
if (text.equals("\\", ignoreCase = true) && (elt == null || parent === commands)) {
document.insertString(position + commands.commandToken.text.length, "*")
return
}
position--
}
}
} | mit | 3742de173a77cd23a9b24b2357ee23ca | 32.092593 | 99 | 0.629723 | 4.670588 | false | false | false | false |
chandilsachin/DietTracker | app/src/main/java/com/chandilsachin/diettracker/adapters/DietListAdapter.kt | 1 | 2845 | package com.chandilsachin.diettracker.adapters
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Filter
import android.widget.Filterable
import android.widget.TextView
import com.chandilsachin.diettracker.R
import com.chandilsachin.diettracker.database.DietFood
import ru.rambler.libs.swipe_layout.SwipeLayout
/**
* Created by Sachin Chandil on 29/04/2017.
*/
class DietListAdapter(context: android.content.Context, val editable:Boolean = true) : RecyclerView.Adapter<DietListAdapter.ViewHolder>(){
var foodList: List<DietFood> = emptyList()
private val inflater = LayoutInflater.from(context)
var onItemEditClick: (food: DietFood) -> Unit = {}
var onItemDeleteClick: (food: DietFood) -> Unit = {}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): com.chandilsachin.diettracker.adapters.DietListAdapter.ViewHolder {
val holder = ViewHolder(inflater.inflate(R.layout.layout_food_list_item, parent, false))
return holder
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) =
holder.bindView(foodList[position])
override fun getItemCount() = foodList.size
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val textViewFoodName = itemView.findViewById(R.id.textViewFoodName) as TextView
private val textViewFoodDesc = itemView.findViewById(R.id.textViewFoodDesc) as TextView
private val textViewQuantity = itemView.findViewById(R.id.textViewQuantity) as TextView
private val swipeLayoutDietListItem = itemView.findViewById(R.id.swipeLayoutDietListItem) as SwipeLayout
private val textViewDietItemDelete = itemView.findViewById(R.id.textViewDietItemDelete) as TextView
private val textViewDietItemEdit = itemView.findViewById(R.id.textViewDietItemEdit) as TextView
fun bindView(food: DietFood) {
textViewFoodName.text = food.foodName
textViewFoodDesc.text = food.foodDesc
textViewQuantity.text = "x${food.quantity}"
textViewQuantity.visibility = View.VISIBLE
if(editable){
swipeLayoutDietListItem.isRightSwipeEnabled = true
swipeLayoutDietListItem.isLeftSwipeEnabled = true
textViewDietItemEdit.setOnClickListener {
onItemEditClick(food)
swipeLayoutDietListItem.reset()
}
textViewDietItemDelete.setOnClickListener(View.OnClickListener {
onItemDeleteClick(food)
swipeLayoutDietListItem.reset()
})
}
}
}
}
| gpl-3.0 | d68d40ac0ea8fc0017b92bc6a87f456e | 38.070423 | 138 | 0.693146 | 4.991228 | false | false | false | false |
Dimigo-AppClass-Mission/SaveTheEarth | app/src/main/kotlin/me/hyemdooly/sangs/dimigo/app/project/util/DisplayUtils.kt | 1 | 1781 | package me.hyemdooly.sangs.dimigo.app.project.util
import android.content.Context
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.ViewConfiguration
import android.view.View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
import android.app.Activity
import android.os.Build
import android.support.annotation.RequiresApi
import android.view.View
/**
* Created by dsa28s on 8/26/17.
*/
fun getNavigationHeight(context: Context): Int {
val resources = context.getResources()
val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android")
return if(isNavigationBarUsed(context)) {
if (resourceId > 0) {
resources.getDimensionPixelSize(resourceId)
} else 0
} else {
0
}
}
fun isNavigationBarUsed(context: Context): Boolean {
val hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey()
val hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK)
return !hasMenuKey && !hasBackKey
}
@RequiresApi(api = Build.VERSION_CODES.M)
fun setSystemBarTheme(view: View, pIsDark: Boolean) {
if(!pIsDark) {
view.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
} else {
view.systemUiVisibility = 0
}
//val lFlags = pActivity.window.decorView.systemUiVisibility
//pActivity.window.decorView.systemUiVisibility = if (pIsDark) lFlags and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv() else lFlags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
}
fun getStatusBarHeight(context: Context): Int {
var result = 0
val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
if (resourceId > 0) {
result = context.resources.getDimensionPixelSize(resourceId)
}
return result
} | gpl-3.0 | a24919b388a3e4be6e8a180a9dfb4177 | 29.724138 | 172 | 0.729366 | 3.949002 | false | false | false | false |
FHannes/intellij-community | plugins/git4idea/src/git4idea/revert/GitRevertOperation.kt | 2 | 3001 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.revert
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.util.containers.OpenTHashSet
import com.intellij.vcs.log.Hash
import com.intellij.vcs.log.VcsFullCommitDetails
import git4idea.GitApplyChangesProcess
import git4idea.commands.Git
import git4idea.commands.GitCommandResult
import git4idea.commands.GitLineHandlerListener
import git4idea.repo.GitRepository
/**
* Commits should be provided in the "UI" order, i.e. as if `git log --date-order` is called, i.e. in reverse-chronological order.
* They are going to be reverted in the reverse order, but the GitRevertOperation will reverse them on its own.
*/
class GitRevertOperation(private val project: Project,
private val commits: List<VcsFullCommitDetails>,
private val autoCommit: Boolean) {
private val git = Git.getInstance()
fun execute() {
GitApplyChangesProcess(project, commits.reversed(), autoCommit, "revert", "reverted",
command = { repository, hash, autoCommit, listeners ->
doRevert(autoCommit, repository, hash, listeners)
},
emptyCommitDetector = { result -> result.outputAsJoinedString.contains("nothing to commit") },
defaultCommitMessageGenerator = { commit ->
"""
Revert ${commit.subject}
This reverts commit ${commit.id.asString()}""".trimIndent()
},
findLocalChanges = { changesInCommit ->
val allChanges = OpenTHashSet(ChangeListManager.getInstance(project).allChanges)
changesInCommit.mapNotNull { allChanges.get(reverseChange(it)) }
}).execute()
}
private fun doRevert(autoCommit: Boolean,
repository: GitRepository,
hash: Hash,
listeners: List<GitLineHandlerListener>): GitCommandResult {
return git.revert(repository, hash.asString(), autoCommit, *listeners.toTypedArray())
}
private fun reverseChange(change: Change) = Change(change.afterRevision, change.beforeRevision)
} | apache-2.0 | 73becb36b55618642498bf61a06e32df | 45.184615 | 130 | 0.653449 | 4.993344 | false | false | false | false |
thm-projects/arsnova-backend | gateway/src/main/kotlin/de/thm/arsnova/service/httpgateway/service/WsGatewayService.kt | 1 | 2179 | package de.thm.arsnova.service.httpgateway.service
import de.thm.arsnova.service.httpgateway.config.HttpGatewayProperties
import de.thm.arsnova.service.httpgateway.model.WsGatewayStats
import org.slf4j.LoggerFactory
import org.springframework.core.ParameterizedTypeReference
import org.springframework.stereotype.Service
import org.springframework.web.reactive.function.client.WebClient
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import java.util.Optional
@Service
class WsGatewayService(
private val webClient: WebClient,
private val httpGatewayProperties: HttpGatewayProperties
) {
private val logger = LoggerFactory.getLogger(javaClass)
fun getUsercount(roomIds: List<String>): Flux<Optional<Int>> {
val url = "${httpGatewayProperties.httpClient.wsGateway}/roomsubscription/usercount?ids=${roomIds.joinToString(",")}"
val typeRef: ParameterizedTypeReference<List<Int?>> = object : ParameterizedTypeReference<List<Int?>>() {}
return webClient.get()
.uri(url)
.retrieve().bodyToMono(typeRef)
.checkpoint("Request failed in ${this::class.simpleName}::${::getUsercount.name}.")
.flatMapMany { userCounts: List<Int?> ->
Flux.fromIterable(
userCounts.map { entry ->
if (entry != null) {
Optional.of(entry)
} else {
Optional.empty()
}
}
)
}
.onErrorResume { exception ->
logger.debug("Exception on getting room subscription user count from ws gw", exception)
Flux.fromIterable(
roomIds.map {
// using a local var for this is needed because otherwise type can't be interfered
val h: Optional<Int> = Optional.empty()
h
}
)
}
}
fun getGatewayStats(): Mono<WsGatewayStats> {
val url = "${httpGatewayProperties.httpClient.wsGateway}/stats"
logger.trace("Querying ws gateway for stats with url: {}", url)
return webClient.get()
.uri(url)
.retrieve().bodyToMono(WsGatewayStats::class.java)
.checkpoint("Request failed in ${this::class.simpleName}::${::getGatewayStats.name}.")
}
}
| gpl-3.0 | 813ed69d93cb47a12ea7b1c2826dde52 | 36.568966 | 121 | 0.683341 | 4.558577 | false | false | false | false |
cout970/Magneticraft | src/main/kotlin/com/cout970/magneticraft/misc/gui/ValueAverage.kt | 2 | 993 | package com.cout970.magneticraft.misc.gui
import com.cout970.magneticraft.misc.network.FloatSyncVariable
/**
* Created by cout970 on 10/07/2016.
*/
class ValueAverage(val maxCounter: Int = 20) {
private var accumulated: Float = 0f
private var counter: Int = 0
var storage: Float = 0f
var average: Float = 0f
private set
fun tick() {
counter++
if (counter >= maxCounter) {
average = accumulated / counter
accumulated = 0f
counter = 0
}
}
operator fun plusAssign(value: Double) {
accumulated += value.toFloat()
}
operator fun plusAssign(value: Float) {
accumulated += value
}
operator fun plusAssign(value: Int) {
accumulated += value.toFloat()
}
operator fun minusAssign(value: Number) {
accumulated -= value.toFloat()
}
fun toSyncVariable(id: Int) = FloatSyncVariable(id, getter = { average }, setter = { storage = it })
} | gpl-2.0 | fe78c2c9962588b7782a914e5fc14eb6 | 22.666667 | 104 | 0.608258 | 4.280172 | false | false | false | false |
wiltonlazary/kotlin-native | samples/globalState/src/globalStateMain/kotlin/Global.kt | 1 | 2790 | /*
* 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/LICENSE.txt file.
*/
package sample.globalstate
import kotlin.native.concurrent.*
import kotlinx.cinterop.*
import platform.posix.*
inline fun Int.ensureUnixCallResult(op: String, predicate: (Int) -> Boolean = { x -> x == 0} ): Int {
if (!predicate(this)) {
throw Error("$op: ${strerror(posix_errno())!!.toKString()}")
}
return this
}
data class SharedDataMember(val double: Double)
data class SharedData(val string: String, val int: Int, val member: SharedDataMember)
// Here we access the same shared frozen Kotlin object from multiple threads.
val globalObject: SharedData?
get() = sharedData.frozenKotlinObject?.asStableRef<SharedData>()?.get()
fun dumpShared(prefix: String) {
println("""
$prefix: ${pthread_self()} x=${sharedData.x} f=${sharedData.f} s=${sharedData.string!!.toKString()}
""".trimIndent())
}
fun main() {
// Arena owning all native allocs.
val arena = Arena()
// Assign global data.
sharedData.x = 239
sharedData.f = 0.5f
sharedData.string = "Hello Kotlin!".cstr.getPointer(arena)
// Here we create detached mutable object, which could be later reattached by another thread.
sharedData.kotlinObject = DetachedObjectGraph {
SharedData("A string", 42, SharedDataMember(2.39))
}.asCPointer()
// Here we create shared frozen object reference,
val stableRef = StableRef.create(SharedData("Shared", 239, SharedDataMember(2.71)).freeze())
sharedData.frozenKotlinObject = stableRef.asCPointer()
dumpShared("thread1")
println("frozen is $globalObject")
// Start a new thread, that sees the variable.
// memScoped is needed to pass thread's local address to pthread_create().
memScoped {
val thread = alloc<pthread_tVar>()
pthread_create(thread.ptr, null, staticCFunction { argC ->
initRuntimeIfNeeded()
dumpShared("thread2")
val kotlinObject = DetachedObjectGraph<SharedData>(sharedData.kotlinObject).attach()
val arg = DetachedObjectGraph<SharedDataMember>(argC).attach()
println("thread arg is $arg Kotlin object is $kotlinObject frozen is $globalObject")
// Workaround for compiler issue.
null as COpaquePointer?
}, DetachedObjectGraph { SharedDataMember(3.14)}.asCPointer() ).ensureUnixCallResult("pthread_create")
pthread_join(thread.value, null).ensureUnixCallResult("pthread_join")
}
// At this moment we do not need data stored in shared data, so clean up the data
// and free memory.
sharedData.string = null
stableRef.dispose()
arena.clear()
}
| apache-2.0 | 087e4d31184a9b6eee324609f417339e | 36.702703 | 111 | 0.680645 | 4.305556 | false | false | false | false |
equeim/tremotesf-android | torrentfile/src/test/kotlin/org/equeim/tremotesf/torrentfile/NodeTest.kt | 1 | 7909 | package org.equeim.tremotesf.torrentfile
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotSame
import org.junit.Assert.assertSame
import org.junit.Assert.assertThrows
import org.junit.Test
class NodeTest {
@Test
fun `Add file to node without children`() {
val rootNode = TorrentFilesTree.DirectoryNode.createRootNode()
val node = rootNode.addDirectory("0")
val expectedItem = expectedFileItem(99, intArrayOf(0, 0))
node.addFile(expectedItem.fileId, expectedItem.name, expectedItem.size, expectedItem.completedSize, expectedItem.wantedState, expectedItem.priority)
checkLastChild(node, expectedItem)
}
@Test
fun `Add directory to node without children`() {
val rootNode = TorrentFilesTree.DirectoryNode.createRootNode()
val node = rootNode.addDirectory("0")
val expectedItem = expectedDirectoryItem(intArrayOf(0, 0))
node.addDirectory(expectedItem.name)
checkLastChild(node, expectedItem)
}
@Test
fun `Add file to node with children`() {
val rootNode = TorrentFilesTree.DirectoryNode.createRootNode()
val node = rootNode.addDirectory("0")
node.addFile(98, "foo", 1, 0, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Normal)
val expectedItem = expectedFileItem(99, intArrayOf(0, 1))
node.addFile(expectedItem.fileId, expectedItem.name, expectedItem.size, expectedItem.completedSize, expectedItem.wantedState, expectedItem.priority)
checkLastChild(node, expectedItem)
}
@Test
fun `Add file with wrong id`() {
val rootNode = TorrentFilesTree.DirectoryNode.createRootNode()
val node = rootNode.addDirectory("0")
val expectedItem = expectedFileItem(-666, intArrayOf(0, 0))
assertThrows(IllegalArgumentException::class.java) {
node.addFile(expectedItem.fileId, expectedItem.name, expectedItem.size, expectedItem.completedSize, expectedItem.wantedState, expectedItem.priority)
}
}
@Test
fun `Add directory to node with children`() {
val rootNode = TorrentFilesTree.DirectoryNode.createRootNode()
val node = rootNode.addDirectory("0")
node.addFile(98, "foo", 1, 0, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Normal)
val expectedItem = expectedDirectoryItem(intArrayOf(0, 1))
node.addDirectory(expectedItem.name)
checkLastChild(node, expectedItem)
}
private fun checkLastChild(node: TorrentFilesTree.DirectoryNode, expectedItem: TorrentFilesTree.Item) {
val lastChild = node.children.last()
assertEquals(lastChild, node.getChildByItemNameOrNull(expectedItem.name))
assertEquals(expectedItem, lastChild.item)
assertArrayEquals(expectedItem.nodePath, lastChild.path)
}
@Test
fun `Recalculating from children`() {
val rootNode = TorrentFilesTree.DirectoryNode.createRootNode()
val directory = rootNode.addDirectory("0").apply {
addFile(98, "foo", 1, 42, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Normal)
addFile(99, "bar", 1, 42, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Low)
addDirectory("1")
.addFile(100, "foo", 1, 42, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Low)
}
var item = directory.item
assertEquals(0, item.size)
assertEquals(0, item.completedSize)
assertEquals(TorrentFilesTree.Item.WantedState.Wanted, item.wantedState)
assertEquals(TorrentFilesTree.Item.Priority.Normal, item.priority)
directory.recalculateFromChildren()
assertNotSame(item, directory.item)
item = directory.item
assertEquals(2, item.size)
assertEquals(84, item.completedSize)
assertEquals(TorrentFilesTree.Item.WantedState.Wanted, item.wantedState)
assertEquals(TorrentFilesTree.Item.Priority.Mixed, item.priority)
}
@Test
fun `Initially calculate from children recursively`() {
val (directory, nestedDirectory) = createDirectoryWithSubdirectory()
val directoryItem = directory.item
val nestedDirectoryItem = nestedDirectory.item
for (item in listOf(directoryItem, nestedDirectoryItem)) {
assertEquals(0, item.size)
assertEquals(0, item.completedSize)
assertEquals(TorrentFilesTree.Item.WantedState.Wanted, item.wantedState)
assertEquals(TorrentFilesTree.Item.Priority.Normal, item.priority)
}
directory.initiallyCalculateFromChildrenRecursively()
assertSame(nestedDirectoryItem, nestedDirectory.item)
assertEquals(2, nestedDirectoryItem.size)
assertEquals(708, nestedDirectoryItem.completedSize)
assertEquals(TorrentFilesTree.Item.WantedState.Mixed, nestedDirectoryItem.wantedState)
assertEquals(TorrentFilesTree.Item.Priority.Low, nestedDirectoryItem.priority)
assertSame(directoryItem, directory.item)
assertEquals(4, directoryItem.size)
assertEquals(792, directoryItem.completedSize)
assertEquals(TorrentFilesTree.Item.WantedState.Mixed, directoryItem.wantedState)
assertEquals(TorrentFilesTree.Item.Priority.Mixed, directoryItem.priority)
}
@Test
fun `Set wanted state recursively`() {
checkSetWantedStateOrPriority(
operation = { setItemWantedRecursively(false, it) },
itemAssert = { assertEquals(TorrentFilesTree.Item.WantedState.Unwanted, wantedState) }
)
}
@Test
fun `Set priority recursively`() {
checkSetWantedStateOrPriority(
operation = { setItemPriorityRecursively(TorrentFilesTree.Item.Priority.High, it) },
itemAssert = { assertEquals(TorrentFilesTree.Item.Priority.High, priority) }
)
}
private fun checkSetWantedStateOrPriority(operation: TorrentFilesTree.Node.(MutableList<Int>) -> Unit, itemAssert: TorrentFilesTree.Item.() -> Unit) {
val (directory, _) = createDirectoryWithSubdirectory()
directory.initiallyCalculateFromChildrenRecursively()
fun getItems(node: TorrentFilesTree.Node, items: MutableList<TorrentFilesTree.Item>) {
items.add(node.item)
(node as? TorrentFilesTree.DirectoryNode)?.children?.forEach { getItems(it, items) }
}
val oldItems = mutableListOf<TorrentFilesTree.Item>()
getItems(directory, oldItems)
val ids = mutableListOf<Int>()
directory.operation(ids)
val newItems = mutableListOf<TorrentFilesTree.Item>()
getItems(directory, newItems)
oldItems.asSequence().zip(newItems.asSequence()).forEach { (oldItem, newItem) ->
assertNotSame(oldItem, newItem)
newItem.itemAssert()
}
assertEquals(setOf(98, 99, 100, 101), ids.toSet())
}
private fun createDirectoryWithSubdirectory(): Pair<TorrentFilesTree.DirectoryNode, TorrentFilesTree.DirectoryNode> {
val rootNode = TorrentFilesTree.DirectoryNode.createRootNode()
val directory = rootNode.addDirectory("0").apply {
addFile(98, "foo", 1, 42, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Normal)
addFile(99, "bar", 1, 42, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Low)
}
val nestedDirectory = directory.addDirectory("1").apply {
addFile(100, "foo", 1, 42, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Low)
addFile(101, "bar", 1, 666, TorrentFilesTree.Item.WantedState.Unwanted, TorrentFilesTree.Item.Priority.Low)
}
return directory to nestedDirectory
}
}
| gpl-3.0 | 3521afe7e7fa7beec2aaf7b8289e8114 | 42.696133 | 160 | 0.704135 | 5.034373 | false | true | false | false |
bozaro/git-as-svn | src/main/kotlin/svnserver/ext/gitlfs/server/LfsContentManager.kt | 1 | 6127 | /*
* 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.ext.gitlfs.server
import jakarta.servlet.http.HttpServletRequest
import org.apache.commons.io.IOUtils
import org.tmatesoft.svn.core.SVNException
import ru.bozaro.gitlfs.common.Constants
import ru.bozaro.gitlfs.common.data.Meta
import ru.bozaro.gitlfs.server.ContentManager
import ru.bozaro.gitlfs.server.ContentManager.Downloader
import ru.bozaro.gitlfs.server.ContentManager.Uploader
import ru.bozaro.gitlfs.server.ForbiddenError
import ru.bozaro.gitlfs.server.UnauthorizedError
import svnserver.auth.User
import svnserver.context.LocalContext
import svnserver.ext.gitlfs.LfsAuthHelper
import svnserver.ext.gitlfs.storage.LfsStorage
import svnserver.ext.web.server.WebServer
import svnserver.repository.VcsAccess
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream
import java.util.*
/**
* ContentManager wrapper for shared LFS server implementation.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class LfsContentManager internal constructor(private val context: LocalContext, val storage: LfsStorage, private val tokenExpireSec: Long, private val tokenEnsureTime: Float) : ContentManager {
@Throws(IOException::class, ForbiddenError::class, UnauthorizedError::class)
override fun checkDownloadAccess(request: HttpServletRequest): Downloader {
val user = checkDownload(request)
val header: Map<String, String> = createHeader(request, user)
return object : Downloader {
@Throws(IOException::class)
override fun openObject(hash: String): InputStream {
val reader = storage.getReader(LfsStorage.OID_PREFIX + hash, -1) ?: throw FileNotFoundException(hash)
return reader.openStream()
}
@Throws(IOException::class)
override fun openObjectGzipped(hash: String): InputStream? {
val reader = storage.getReader(LfsStorage.OID_PREFIX + hash, -1) ?: throw FileNotFoundException(hash)
return reader.openGzipStream()
}
override fun createHeader(defaultHeader: Map<String, String>): Map<String, String> {
return header
}
}
}
@Throws(IOException::class, UnauthorizedError::class, ForbiddenError::class)
fun checkDownload(request: HttpServletRequest): User {
val access = context.sure(VcsAccess::class.java)
return checkAccess(request) { user: User, branch: String, path: String -> access.checkRead(user, branch, path) }
}
private fun createHeader(request: HttpServletRequest, user: User): Map<String, String> {
val auth = request.getHeader(Constants.HEADER_AUTHORIZATION) ?: return emptyMap()
return if (auth.startsWith(WebServer.AUTH_TOKEN)) {
mapOf(Constants.HEADER_AUTHORIZATION to auth)
} else {
LfsAuthHelper.createTokenHeader(context.shared, user, LfsAuthHelper.getExpire(tokenExpireSec))
}
}
@Throws(IOException::class, UnauthorizedError::class, ForbiddenError::class)
private fun checkAccess(request: HttpServletRequest, checker: Checker): User {
val user = getAuthInfo(request)
try {
// This is a *bit* of a hack.
// If user accesses LFS, it means she is using git. If she uses git, she has whole repository contents.
// If she has full repository contents, it doesn't make sense to apply path-based authorization.
// Setups where where user has Git access but is not allowed to write via path-based authorization are declared bogus.
checker.check(user, org.eclipse.jgit.lib.Constants.MASTER, "/")
} catch (ignored: SVNException) {
if (user.isAnonymous) {
throw UnauthorizedError("Basic realm=\"" + context.shared.realm + "\"")
} else {
throw ForbiddenError()
}
}
return user
}
private fun getAuthInfo(request: HttpServletRequest): User {
val server = context.shared.sure(WebServer::class.java)
val user = server.getAuthInfo(request.getHeader(Constants.HEADER_AUTHORIZATION), Math.round(tokenExpireSec * tokenEnsureTime))
return user ?: User.anonymous
}
@Throws(IOException::class, ForbiddenError::class, UnauthorizedError::class)
override fun checkUploadAccess(request: HttpServletRequest): Uploader {
val user = checkUpload(request)
val header = createHeader(request, user)
return object : Uploader {
@Throws(IOException::class)
override fun saveObject(meta: Meta, content: InputStream) {
storage.getWriter(Objects.requireNonNull(user)).use { writer ->
IOUtils.copy(content, writer)
writer.finish(LfsStorage.OID_PREFIX + meta.oid)
}
}
override fun createHeader(defaultHeader: Map<String, String>): Map<String, String> {
return header
}
}
}
@Throws(IOException::class, UnauthorizedError::class, ForbiddenError::class)
fun checkUpload(request: HttpServletRequest): User {
val access = context.sure(VcsAccess::class.java)
return checkAccess(request) { user: User, branch: String, path: String -> access.checkWrite(user, branch, path) }
}
@Throws(IOException::class)
override fun getMetadata(hash: String): Meta? {
val reader = storage.getReader(LfsStorage.OID_PREFIX + hash, -1) ?: return null
return Meta(reader.getOid(true), reader.size)
}
fun interface Checker {
@Throws(SVNException::class, IOException::class)
fun check(user: User, branch: String, path: String)
}
}
| gpl-2.0 | 7b28243b743efb9f765ec7f84e3b05c4 | 44.385185 | 193 | 0.684185 | 4.552006 | false | false | false | false |
karollewandowski/aem-intellij-plugin | src/main/kotlin/co/nums/intellij/aem/htl/file/HtlFileViewProvider.kt | 1 | 3513 | package co.nums.intellij.aem.htl.file
import co.nums.intellij.aem.htl.HtlLanguage
import co.nums.intellij.aem.htl.psi.*
import com.intellij.lang.*
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.impl.source.PsiFileImpl
import com.intellij.psi.templateLanguages.*
import com.intellij.util.containers.ContainerUtil
class HtlFileViewProvider @JvmOverloads constructor(private val psiManager: PsiManager,
file: VirtualFile,
physical: Boolean,
private val baseLanguage: Language,
private val templateDataLanguage: Language = getTemplateDataLanguage(psiManager, file))
: MultiplePsiFilesPerDocumentFileViewProvider(psiManager, file, physical), ConfigurableTemplateLanguageFileViewProvider {
companion object {
private val HTL_FRAGMENT = HtlElementType("HTL_FRAGMENT")
private val TEMPLATE_DATA_TO_LANG = ContainerUtil.newConcurrentMap<String, TemplateDataElementType>()
}
override fun getBaseLanguage() = baseLanguage
override fun getTemplateDataLanguage() = templateDataLanguage
override fun getLanguages(): Set<Language> = setOf(baseLanguage, templateDataLanguage)
override fun supportsIncrementalReparse(rootLanguage: Language) = false
override fun cloneInner(virtualFile: VirtualFile) =
HtlFileViewProvider(psiManager, virtualFile, false, baseLanguage, templateDataLanguage)
override fun createFile(language: Language): PsiFile? {
val parserDefinition = getParserDefinition(language)
return when {
language === templateDataLanguage -> {
val file = parserDefinition.createFile(this) as PsiFileImpl
file.contentElementType = getTemplateDataElementType(baseLanguage)
file
}
language.isKindOf(baseLanguage) -> parserDefinition.createFile(this)
else -> null
}
}
private fun getParserDefinition(language: Language): ParserDefinition {
val parserLanguage = when {
language === baseLanguage -> language
language.isKindOf(baseLanguage) -> baseLanguage
else -> language
}
return LanguageParserDefinitions.INSTANCE.forLanguage(parserLanguage)
}
private fun getTemplateDataElementType(language: Language): TemplateDataElementType {
val result = TEMPLATE_DATA_TO_LANG[language.id]
if (result != null) {
return result
}
val created = TemplateDataElementType("HTL_TEMPLATE_DATA", language, HtlTypes.OUTER_TEXT, HTL_FRAGMENT)
val prevValue = TEMPLATE_DATA_TO_LANG.putIfAbsent(language.id, created)
return prevValue ?: created
}
}
private fun getTemplateDataLanguage(psiManager: PsiManager, file: VirtualFile): Language {
var dataLanguage = TemplateDataLanguageMappings.getInstance(psiManager.project)?.getMapping(file)
?: HtlLanguage.getTemplateLanguageFileType().language
val substituteLanguage = LanguageSubstitutors.INSTANCE.substituteLanguage(dataLanguage, file, psiManager.project)
// only use a substituted language if it's templateable
if (TemplateDataLanguageMappings.getTemplateableLanguages().contains(substituteLanguage)) {
dataLanguage = substituteLanguage
}
return dataLanguage
}
| gpl-3.0 | cea11f1257b24f7966ae3e3eaeebde7d | 42.37037 | 139 | 0.690009 | 5.611821 | false | false | false | false |
mctoyama/PixelClient | src/main/kotlin/org/pixelndice/table/pixelclient/fx/DistanceRuler.kt | 1 | 2568 | package org.pixelndice.table.pixelclient.fx
import javafx.scene.canvas.GraphicsContext
import javafx.scene.paint.Color
import javafx.scene.text.Font
import org.pixelndice.table.pixelclient.currentBoard
import org.pixelndice.table.pixelclient.currentCampaign
import org.pixelndice.table.pixelclient.currentCanvas
import org.pixelndice.table.pixelclient.misc.Point
import kotlin.math.pow
/**
* @author Marcelo costa Toyama
* Distance Ruler class for measuring distances in PixelCanvas
*/
class DistanceRuler(val origin: Point, val destination: Point){
/**
* Draws arrow and shows distance in board units (default: feet)
*/
fun draw(gc: GraphicsContext){
val dx = destination.x - origin.x
val dy = destination.y - origin.y
val end1 = Point()
end1.x = destination.x - (dx*cos + dy * -sin)
end1.y = destination.y - (dx *sin + dy * cos)
val end2 = Point()
end2.x = destination.x - (dx * cos + dy * sin)
end2.y = destination.y - (dx * -sin + dy * cos)
val mag1 = Math.sqrt((end1.x-destination.x).pow(2) + (end1.y-destination.y).pow(2))
end1.x = destination.x + ((end1.x-destination.x)/mag1) * PixelCanvas.GRID_WIDTH
end1.y = destination.y + ((end1.y-destination.y)/mag1) * PixelCanvas.GRID_HEIGHT
val mag2 = Math.sqrt((end2.x-destination.x).pow(2) + (end2.y-destination.y).pow(2))
end2.x = destination.x + ((end2.x-destination.x)/mag2) * PixelCanvas.GRID_WIDTH
end2.y = destination.y + ((end2.y-destination.y)/mag2) * PixelCanvas.GRID_HEIGHT
gc.save()
gc.lineWidth = 5.0
gc.strokeLine(origin.x, origin.y, destination.x, destination.y)
gc.strokeLine(destination.x, destination.y, end1.x, end1.y)
gc.strokeLine(destination.x, destination.y, end2.x, end2.y)
gc.restore()
val distance = currentCanvas?.distanceCanvasToBoard(origin,destination) ?: Point()
distance.x = distance.x * ((currentBoard?.distance ?: 0.0) / PixelCanvas.GRID_WIDTH)
distance.y = distance.y * ((currentBoard?.distance ?: 0.0) / PixelCanvas.GRID_HEIGHT)
val hypotenuse = Math.sqrt(distance.x.pow(2)+distance.y.pow(2))
gc.save()
gc.fill = Color.BLACK
gc.font = Font(18.0)
gc.fillText("%.2f ${currentBoard?.distanceUnit}".format(hypotenuse),destination.x+PixelCanvas.GRID_WIDTH, destination.y+PixelCanvas.GRID_HEIGHT)
gc.restore()
}
companion object {
private const val cos = 0.866
private const val sin = 0.500
}
} | bsd-2-clause | 0c0d2d6dc1a6f93d6247d0128c40da93 | 37.924242 | 152 | 0.65771 | 3.410359 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/descriptions/DescriptionEditLicenseView.kt | 1 | 3395 | package org.wikipedia.descriptions
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.net.toUri
import androidx.core.view.isVisible
import androidx.core.widget.TextViewCompat
import org.wikipedia.R
import org.wikipedia.auth.AccountUtil
import org.wikipedia.databinding.ViewDescriptionEditLicenseBinding
import org.wikipedia.page.LinkMovementMethodExt
import org.wikipedia.richtext.RichTextUtil
import org.wikipedia.util.StringUtil
import org.wikipedia.util.UriUtil
class DescriptionEditLicenseView constructor(context: Context, attrs: AttributeSet? = null) : LinearLayout(context, attrs) {
fun interface Callback {
fun onLoginClick()
}
var callback: Callback? = null
private val binding = ViewDescriptionEditLicenseBinding.inflate(LayoutInflater.from(context), this)
private val movementMethod = LinkMovementMethodExt { url: String ->
if (url == "https://#login") {
callback?.onLoginClick()
} else {
UriUtil.handleExternalLink(context, url.toUri())
}
}
init {
orientation = VERTICAL
binding.licenseText.movementMethod = movementMethod
binding.anonWarningText.movementMethod = movementMethod
buildLicenseNotice(ARG_NOTICE_DEFAULT)
}
fun buildLicenseNotice(arg: String, lang: String? = null) {
if ((arg == ARG_NOTICE_ARTICLE_DESCRIPTION || arg == ARG_NOTICE_DEFAULT) &&
DescriptionEditFragment.wikiUsesLocalDescriptions(lang.orEmpty())) {
binding.licenseText.text = StringUtil.fromHtml(context.getString(R.string.edit_save_action_license_logged_in,
context.getString(R.string.terms_of_use_url),
context.getString(R.string.cc_by_sa_3_url)))
} else {
binding.licenseText.text = StringUtil.fromHtml(context.getString(when (arg) {
ARG_NOTICE_ARTICLE_DESCRIPTION -> R.string.suggested_edits_license_notice
ARG_NOTICE_IMAGE_CAPTION -> R.string.suggested_edits_image_caption_license_notice
else -> R.string.description_edit_license_notice
}, context.getString(R.string.terms_of_use_url), context.getString(R.string.cc_0_url)))
}
binding.anonWarningText.text = StringUtil.fromHtml(context.getString(R.string.edit_anon_warning))
binding.anonWarningText.isVisible = !AccountUtil.isLoggedIn
RichTextUtil.removeUnderlinesFromLinks(binding.licenseText)
RichTextUtil.removeUnderlinesFromLinks(binding.anonWarningText)
}
fun darkLicenseView() {
val white70 = AppCompatResources.getColorStateList(context, R.color.white70)
setBackgroundResource(android.R.color.black)
binding.licenseText.setTextColor(white70)
binding.licenseText.setLinkTextColor(white70)
TextViewCompat.setCompoundDrawableTintList(binding.licenseText, white70)
binding.anonWarningText.setTextColor(white70)
binding.anonWarningText.setLinkTextColor(white70)
}
companion object {
const val ARG_NOTICE_DEFAULT = "defaultNotice"
const val ARG_NOTICE_IMAGE_CAPTION = "imageCaptionNotice"
const val ARG_NOTICE_ARTICLE_DESCRIPTION = "articleDescriptionNotice"
}
}
| apache-2.0 | a83724ddfa8d054e642f5c008ec7c783 | 44.266667 | 124 | 0.722828 | 4.606513 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/shortcut/ShortcutCreator.kt | 1 | 9064 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util.shortcut
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.os.Build
import android.support.v4.content.pm.ShortcutInfoCompat
import android.support.v4.content.pm.ShortcutManagerCompat
import android.support.v4.graphics.drawable.IconCompat
import com.bumptech.glide.Glide
import nl.komponents.kovenant.Promise
import nl.komponents.kovenant.combine.and
import nl.komponents.kovenant.then
import nl.komponents.kovenant.ui.alwaysUi
import nl.komponents.kovenant.ui.successUi
import org.mariotaku.kpreferences.get
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.annotation.ImageShapeStyle
import de.vanita5.twittnuker.constant.iWantMyStarsBackKey
import de.vanita5.twittnuker.constant.nameFirstKey
import de.vanita5.twittnuker.constant.profileImageStyleKey
import de.vanita5.twittnuker.extension.dismissProgressDialog
import de.vanita5.twittnuker.extension.loadProfileImage
import de.vanita5.twittnuker.extension.showProgressDialog
import de.vanita5.twittnuker.fragment.BaseFragment
import de.vanita5.twittnuker.model.ParcelableUser
import de.vanita5.twittnuker.model.ParcelableUserList
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.util.IntentUtils
import de.vanita5.twittnuker.util.dagger.DependencyHolder
import de.vanita5.twittnuker.util.glide.DeferredTarget
import java.lang.ref.WeakReference
object ShortcutCreator {
private val useAdaptiveIcon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
private const val adaptiveIconSizeDp = 108
private const val adaptiveIconOuterSidesDp = 18
fun user(context: Context, accountKey: UserKey?, user: ParcelableUser): Promise<ShortcutInfoCompat, Exception> {
val holder = DependencyHolder.get(context)
val preferences = holder.preferences
val userColorNameManager = holder.userColorNameManager
val profileImageStyle = if (useAdaptiveIcon) ImageShapeStyle.SHAPE_RECTANGLE else preferences[profileImageStyleKey]
val profileImageCornerRadiusRatio = if (useAdaptiveIcon) 0f else 0.1f
val deferred = Glide.with(context).loadProfileImage(context, user,
shapeStyle = profileImageStyle, cornerRadiusRatio = profileImageCornerRadiusRatio,
size = context.getString(R.string.profile_image_size)).into(DeferredTarget())
val weakContext = WeakReference(context)
return deferred.promise.then { drawable ->
val ctx = weakContext.get() ?: throw InterruptedException()
val builder = ShortcutInfoCompat.Builder(ctx, "$accountKey:user:${user.key}")
builder.setIcon(drawable.toProfileImageIcon(ctx))
builder.setShortLabel(userColorNameManager.getDisplayName(user, preferences[nameFirstKey]))
val launchIntent = IntentUtils.userProfile(accountKey, user.key,
user.screen_name, profileUrl = user.extras?.statusnet_profile_url)
builder.setIntent(launchIntent)
return@then builder.build()
}
}
fun userFavorites(context: Context, accountKey: UserKey?, user: ParcelableUser): Promise<ShortcutInfoCompat, Exception> {
val holder = DependencyHolder.get(context)
val preferences = holder.preferences
val userColorNameManager = holder.userColorNameManager
val launchIntent = IntentUtils.userFavorites(accountKey, user.key,
user.screen_name, profileUrl = user.extras?.statusnet_profile_url)
val builder = ShortcutInfoCompat.Builder(context, "$accountKey:user-favorites:${user.key}")
builder.setIntent(launchIntent)
builder.setShortLabel(userColorNameManager.getDisplayName(user, preferences[nameFirstKey]))
if (preferences[iWantMyStarsBackKey]) {
builder.setIcon(IconCompat.createWithResource(context, R.mipmap.ic_shortcut_favorite))
} else {
builder.setIcon(IconCompat.createWithResource(context, R.mipmap.ic_shortcut_like))
}
return Promise.of(builder.build())
}
fun userTimeline(context: Context, accountKey: UserKey?, user: ParcelableUser): Promise<ShortcutInfoCompat, Exception> {
val holder = DependencyHolder.get(context)
val preferences = holder.preferences
val userColorNameManager = holder.userColorNameManager
val launchIntent = IntentUtils.userTimeline(accountKey, user.key,
user.screen_name, profileUrl = user.extras?.statusnet_profile_url)
val builder = ShortcutInfoCompat.Builder(context, "$accountKey:user-timeline:${user.key}")
builder.setIntent(launchIntent)
builder.setShortLabel(userColorNameManager.getDisplayName(user, preferences[nameFirstKey]))
builder.setIcon(IconCompat.createWithResource(context, R.mipmap.ic_shortcut_quote))
return Promise.of(builder.build())
}
fun userMediaTimeline(context: Context, accountKey: UserKey?, user: ParcelableUser): Promise<ShortcutInfoCompat, Exception> {
val holder = DependencyHolder.get(context)
val preferences = holder.preferences
val userColorNameManager = holder.userColorNameManager
val launchIntent = IntentUtils.userMediaTimeline(accountKey, user.key,
user.screen_name, profileUrl = user.extras?.statusnet_profile_url)
val builder = ShortcutInfoCompat.Builder(context, "$accountKey:user-media-timeline:${user.key}")
builder.setIntent(launchIntent)
builder.setShortLabel(userColorNameManager.getDisplayName(user, preferences[nameFirstKey]))
builder.setIcon(IconCompat.createWithResource(context, R.mipmap.ic_shortcut_gallery))
return Promise.of(builder.build())
}
fun userListTimeline(context: Context, accountKey: UserKey?, list: ParcelableUserList): Promise<ShortcutInfoCompat, Exception> {
val launchIntent = IntentUtils.userListTimeline(accountKey, list.id,
list.user_key, list.user_screen_name, list.name)
val builder = ShortcutInfoCompat.Builder(context, "$accountKey:user-list-timeline:${list.id}")
builder.setIntent(launchIntent)
builder.setShortLabel(list.name)
builder.setIcon(IconCompat.createWithResource(context, R.mipmap.ic_shortcut_list))
return Promise.of(builder.build())
}
inline fun performCreation(fragment: BaseFragment, createPromise: () -> Promise<ShortcutInfoCompat, Exception>) {
if (!ShortcutManagerCompat.isRequestPinShortcutSupported(fragment.context)) return
val promise = fragment.showProgressDialog("create_shortcut")
.and(createPromise())
val weakThis = WeakReference(fragment)
promise.successUi { (_, shortcut) ->
val f = weakThis.get() ?: return@successUi
ShortcutManagerCompat.requestPinShortcut(f.context, shortcut, null)
}.alwaysUi {
val f = weakThis.get() ?: return@alwaysUi
f.dismissProgressDialog("create_shortcut")
}
}
private fun Drawable.toProfileImageIcon(context: Context): IconCompat {
if (useAdaptiveIcon) {
val density = context.resources.displayMetrics.density
val adaptiveIconSize = Math.round(adaptiveIconSizeDp * density)
val adaptiveIconOuterSides = Math.round(adaptiveIconOuterSidesDp * density)
val bitmap = Bitmap.createBitmap(adaptiveIconSize, adaptiveIconSize,
Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
setBounds(adaptiveIconOuterSides, adaptiveIconOuterSides,
adaptiveIconSize - adaptiveIconOuterSides,
adaptiveIconSize - adaptiveIconOuterSides)
draw(canvas)
return IconCompat.createWithAdaptiveBitmap(bitmap)
} else {
val bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
setBounds(0, 0, bitmap.width, bitmap.height)
draw(canvas)
return IconCompat.createWithBitmap(bitmap)
}
}
} | gpl-3.0 | cbd3618f1d6d84eee9bb4570a1c1f63d | 48.266304 | 132 | 0.729369 | 4.867884 | false | false | false | false |
numa08/Gochisou | app/src/main/java/net/numa08/gochisou/data/model/NavigationIdentifier.kt | 1 | 2375 | package net.numa08.gochisou.data.model
import org.parceler.Parcel
import org.parceler.ParcelConstructor
import org.parceler.ParcelProperty
sealed class NavigationIdentifier(val name: String, val avatar: String, val loginProfile: LoginProfile) {
@Parcel(Parcel.Serialization.BEAN)
class PostNavigationIdentifier @ParcelConstructor constructor(
@ParcelProperty("name") name: String,
@ParcelProperty("avatar") avatar: String,
@ParcelProperty("loginProfile") loginProfile: LoginProfile
) : NavigationIdentifier(name, avatar, loginProfile)
@Parcel(Parcel.Serialization.BEAN)
class PostDetailNavigationIdentifier @ParcelConstructor constructor(
@ParcelProperty("name") name: String,
@ParcelProperty("avatar") avatar: String,
@ParcelProperty("loginProfile") loginProfile: LoginProfile,
@ParcelProperty("fullName") val fullName: String
) : NavigationIdentifier(name, avatar, loginProfile) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
if (!super.equals(other)) return false
other as PostDetailNavigationIdentifier
if (fullName != other.fullName) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result += 31 * result + fullName.hashCode()
return result
}
override fun toString(): String{
return "PostDetailNavigationIdentifier(fullName='$fullName')"
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as NavigationIdentifier
if (name != other.name) return false
if (avatar != other.avatar) return false
if (loginProfile != other.loginProfile) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result += 31 * result + avatar.hashCode()
result += 31 * result + loginProfile.hashCode()
return result
}
override fun toString(): String{
return "NavigationIdentifier(name='$name', avatar='$avatar', loginProfile=$loginProfile)"
}
}
| mit | 8c0c663ba36329f8b919ce3836476776 | 31.986111 | 105 | 0.642526 | 5.325112 | false | false | false | false |
stripe/stripe-android | example/src/main/java/com/stripe/example/activity/GooglePayLauncherComposeActivity.kt | 1 | 6076 | package com.stripe.example.activity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.material.LinearProgressIndicator
import androidx.compose.material.Scaffold
import androidx.compose.material.ScaffoldState
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.stripe.android.googlepaylauncher.GooglePayEnvironment
import com.stripe.android.googlepaylauncher.GooglePayLauncher
import kotlinx.coroutines.launch
class GooglePayLauncherComposeActivity : StripeIntentActivity() {
private val googlePayConfig = GooglePayLauncher.Config(
environment = GooglePayEnvironment.Test,
merchantCountryCode = COUNTRY_CODE,
merchantName = "Widget Store",
billingAddressConfig = GooglePayLauncher.BillingAddressConfig(
isRequired = true,
format = GooglePayLauncher.BillingAddressConfig.Format.Full,
isPhoneNumberRequired = false
),
existingPaymentMethodRequired = false
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
GooglePayLauncherScreen()
}
}
@Composable
private fun GooglePayLauncherScreen() {
val scaffoldState = rememberScaffoldState()
val scope = rememberCoroutineScope()
var clientSecret by rememberSaveable { mutableStateOf("") }
var googlePayReady by rememberSaveable { mutableStateOf<Boolean?>(null) }
var completed by rememberSaveable { mutableStateOf(false) }
LaunchedEffect(Unit) {
if (clientSecret.isBlank()) {
viewModel.createPaymentIntent(COUNTRY_CODE).observe(
this@GooglePayLauncherComposeActivity
) { result ->
result.fold(
onSuccess = { json ->
clientSecret = json.getString("secret")
},
onFailure = { error ->
scope.launch {
scaffoldState.snackbarHostState.showSnackbar(
"Could not create PaymentIntent. ${error.message}"
)
}
completed = true
}
)
}
}
}
val googlePayLauncher = GooglePayLauncher.rememberLauncher(
config = googlePayConfig,
readyCallback = { ready ->
if (googlePayReady == null) {
googlePayReady = ready
if (!ready) {
completed = true
}
scope.launch {
scaffoldState.snackbarHostState.showSnackbar("Google Pay ready? $ready")
}
}
},
resultCallback = { result ->
when (result) {
GooglePayLauncher.Result.Completed -> {
"Successfully collected payment."
}
GooglePayLauncher.Result.Canceled -> {
"Customer cancelled Google Pay."
}
is GooglePayLauncher.Result.Failed -> {
"Google Pay failed. ${result.error.message}"
}
}.let {
scope.launch {
scaffoldState.snackbarHostState.showSnackbar(it)
completed = true
}
}
}
)
GooglePayLauncherScreen(
scaffoldState = scaffoldState,
clientSecret = clientSecret,
googlePayReady = googlePayReady,
completed = completed,
onLaunchGooglePay = { googlePayLauncher.presentForPaymentIntent(it) }
)
}
@Composable
private fun GooglePayLauncherScreen(
scaffoldState: ScaffoldState,
clientSecret: String,
googlePayReady: Boolean?,
completed: Boolean,
onLaunchGooglePay: (String) -> Unit
) {
Scaffold(scaffoldState = scaffoldState) {
Column(Modifier.fillMaxWidth()) {
if (googlePayReady == null || clientSecret.isBlank()) {
LinearProgressIndicator(Modifier.fillMaxWidth())
}
Spacer(
Modifier
.height(8.dp)
.fillMaxWidth()
)
AndroidView(
factory = { context ->
GooglePayButton(context)
},
modifier = Modifier
.wrapContentWidth()
.clickable(
enabled = googlePayReady == true &&
clientSecret.isNotBlank() && !completed,
onClick = {
onLaunchGooglePay(clientSecret)
}
)
)
}
}
}
private companion object {
private const val COUNTRY_CODE = "US"
}
}
| mit | bda8e91039b33b4dcf96dc84c93d243c | 35.60241 | 96 | 0.556122 | 6.618736 | false | false | false | false |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/view/PaymentAuthWebViewClient.kt | 1 | 7386 | package com.stripe.android.view
import android.content.Intent
import android.net.Uri
import android.webkit.URLUtil
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.MutableLiveData
import com.stripe.android.core.Logger
import com.stripe.android.payments.DefaultReturnUrl
internal class PaymentAuthWebViewClient(
private val logger: Logger,
private val isPageLoaded: MutableLiveData<Boolean>,
private val clientSecret: String,
returnUrl: String?,
private val activityStarter: (Intent) -> Unit,
private val activityFinisher: (Throwable?) -> Unit
) : WebViewClient() {
// user-specified return URL
private val userReturnUri: Uri? = returnUrl?.let { Uri.parse(it) }
var completionUrlParam: String? = null
private set
internal var hasLoadedBlank: Boolean = false
override fun onPageFinished(view: WebView, url: String?) {
logger.debug("PaymentAuthWebViewClient#onPageFinished() - $url")
super.onPageFinished(view, url)
if (!hasLoadedBlank) {
// hide the progress bar here because doing it in `onPageCommitVisible()`
// potentially causes a crash
hideProgressBar()
}
if (url != null && isCompletionUrl(url)) {
logger.debug("$url is a completion URL")
onAuthCompleted()
}
}
private fun hideProgressBar() {
logger.debug("PaymentAuthWebViewClient#hideProgressBar()")
isPageLoaded.value = true
}
override fun shouldOverrideUrlLoading(
view: WebView,
request: WebResourceRequest
): Boolean {
val url = request.url
logger.debug("PaymentAuthWebViewClient#shouldOverrideUrlLoading(): $url")
updateCompletionUrl(url)
return if (isReturnUrl(url)) {
logger.debug("PaymentAuthWebViewClient#shouldOverrideUrlLoading() - handle return URL")
onAuthCompleted()
true
} else if ("intent".equals(url.scheme, ignoreCase = true)) {
openIntentScheme(url)
true
} else if (!URLUtil.isNetworkUrl(url.toString())) {
// Non-network URLs are likely deep-links into banking apps. If the deep-link can be
// opened via an Intent, start it. Otherwise, stop the authentication attempt.
openIntent(
Intent(Intent.ACTION_VIEW, url)
)
true
} else {
super.shouldOverrideUrlLoading(view, request)
}
}
private fun openIntentScheme(uri: Uri) {
logger.debug("PaymentAuthWebViewClient#openIntentScheme()")
runCatching {
openIntent(
Intent.parseUri(uri.toString(), Intent.URI_INTENT_SCHEME)
)
}.onFailure { error ->
logger.error("Failed to start Intent.", error)
onAuthCompleted(error)
}
}
/**
* See https://developer.android.com/training/basics/intents/package-visibility-use-cases
* for more details on app-to-app interaction.
*/
private fun openIntent(
intent: Intent
) {
logger.debug("PaymentAuthWebViewClient#openIntent()")
runCatching {
activityStarter(intent)
}.onFailure { error ->
logger.error("Failed to start Intent.", error)
if (intent.scheme != "alipays") {
// complete auth if the deep-link can't be opened unless it is Alipay.
// The Alipay web view tries to open the Alipay app as soon as it is opened
// irrespective of whether or not the app is installed.
// If this intent fails to resolve, we should still let the user
// continue on the mobile site.
onAuthCompleted(error)
}
}
}
private fun updateCompletionUrl(uri: Uri) {
logger.debug("PaymentAuthWebViewClient#updateCompletionUrl()")
val returnUrlParam = if (isAuthenticateUrl(uri.toString())) {
uri.getQueryParameter(PARAM_RETURN_URL)
} else {
null
}
if (!returnUrlParam.isNullOrBlank()) {
completionUrlParam = returnUrlParam
}
}
private fun isReturnUrl(uri: Uri): Boolean {
logger.debug("PaymentAuthWebViewClient#isReturnUrl()")
when {
isPredefinedReturnUrl(uri) -> return true
// If the `userReturnUri` is known, look for URIs that match it.
userReturnUri != null ->
return userReturnUri.scheme != null &&
userReturnUri.scheme == uri.scheme &&
userReturnUri.host != null &&
userReturnUri.host == uri.host
else -> {
// Skip opaque (i.e. non-hierarchical) URIs
if (uri.isOpaque) {
return false
}
// If the `userReturnUri` is unknown, look for URIs that contain a
// `payment_intent_client_secret` or `setup_intent_client_secret`
// query parameter, and check if its values matches the given `clientSecret`
// as a query parameter.
val paramNames = uri.queryParameterNames
val clientSecret = when {
paramNames.contains(PARAM_PAYMENT_CLIENT_SECRET) ->
uri.getQueryParameter(PARAM_PAYMENT_CLIENT_SECRET)
paramNames.contains(PARAM_SETUP_CLIENT_SECRET) ->
uri.getQueryParameter(PARAM_SETUP_CLIENT_SECRET)
else -> null
}
return this.clientSecret == clientSecret
}
}
}
// pre-defined return URLs
private fun isPredefinedReturnUrl(uri: Uri): Boolean {
return "stripejs://use_stripe_sdk/return_url" == uri.toString() ||
uri.toString().startsWith(DefaultReturnUrl.PREFIX)
}
/**
* Invoked when authentication flow has completed, whether succeeded or failed.
*/
private fun onAuthCompleted(
error: Throwable? = null
) {
logger.debug("PaymentAuthWebViewClient#onAuthCompleted()")
activityFinisher(error)
}
internal companion object {
internal const val PARAM_PAYMENT_CLIENT_SECRET = "payment_intent_client_secret"
internal const val PARAM_SETUP_CLIENT_SECRET = "setup_intent_client_secret"
private val AUTHENTICATE_URLS = setOf(
"https://hooks.stripe.com/three_d_secure/authenticate"
)
private val COMPLETION_URLS = setOf(
"https://hooks.stripe.com/redirect/complete/",
"https://hooks.stripe.com/3d_secure/complete/",
"https://hooks.stripe.com/3d_secure_2/hosted/complete"
)
private const val PARAM_RETURN_URL = "return_url"
internal const val BLANK_PAGE = "about:blank"
@VisibleForTesting
internal fun isCompletionUrl(
url: String
): Boolean {
return COMPLETION_URLS.any(url::startsWith)
}
private fun isAuthenticateUrl(
url: String
): Boolean {
return AUTHENTICATE_URLS.any(url::startsWith)
}
}
}
| mit | 7d3c2987135c22226922289b10754935 | 34.171429 | 99 | 0.603033 | 5.04853 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/concurrency/TaskRunner.kt | 1 | 2926 | package au.com.codeka.warworlds.client.concurrency
import au.com.codeka.warworlds.client.concurrency.RunnableTask.*
import java.util.*
import java.util.concurrent.ThreadPoolExecutor
/**
* This is a class for running tasks on various threads. You can run a task on any thread defined
* in [Threads].
*/
class TaskRunner {
val backgroundExecutor: ThreadPoolExecutor
private val timer: Timer
/**
* Run the given [Runnable] on the given [Threads].
*
* @return A [Task] that you can use to chain further tasks after this one has finished.
*/
fun runTask(runnable: Runnable?, thread: Threads): Task<*, *> {
return runTask(RunnableTask<Void?, Void>(this, runnable, thread), null)
}
/**
* Run the given [RunnableTask.RunnableP] on the given [Threads].
*
* @return A [Task] that you can use to chain further tasks after this one has finished.
*/
fun <P> runTask(runnable: RunnableP<P>?, thread: Threads): Task<*, *> {
return runTask(RunnableTask<P, Void>(this, runnable, thread), null)
}
/**
* Run the given [RunnableTask.RunnableR] on the given [Threads].
*
* @return A [Task] that you can use to chain further tasks after this one has finished.
*/
fun <R> runTask(runnable: RunnableR<R>?, thread: Threads): Task<*, *> {
return runTask(RunnableTask<Void?, R>(this, runnable, thread), null)
}
/**
* Run the given [RunnableTask.RunnablePR] on the given [Threads].
*
* @return A [Task] that you can use to chain further tasks after this one has finished.
*/
fun <P, R> runTask(runnable: RunnablePR<P, R>?, thread: Threads): Task<*, *> {
return runTask(RunnableTask(this, runnable, thread), null)
}
fun <P> runTask(task: Task<P, *>, param: P?): Task<*, *> {
task.run(param)
return task
}
/**
* Runs the given GmsCore [com.google.android.gms.tasks.Task], and returns a [Task]
* that you can then use to chain other tasks, etc.
*
* @param gmsTask The GmsCore task to run.
* @param <R> The type of result to expect from the GmsCore task.
* @return A [Task] that you can use to chain callbacks.
</R> */
fun <R> runTask(gmsTask: com.google.android.gms.tasks.Task<R>): Task<Void, R> {
return GmsTask(this, gmsTask)
}
/** Run a task after the given delay. */
fun runTask(runnable: Runnable?, thread: Threads, delayMs: Long) {
if (delayMs == 0L) {
runTask(runnable, thread)
} else {
timer.schedule(object : TimerTask() {
override fun run() {
runTask(runnable, thread)
}
}, delayMs)
}
}
init {
val backgroundThreadPool = ThreadPool(
Threads.BACKGROUND,
750 /* maxQueuedItems */,
5 /* minThreads */,
20 /* maxThreads */,
1000 /* keepAliveMs */)
backgroundExecutor = backgroundThreadPool.executor
Threads.BACKGROUND.setThreadPool(backgroundThreadPool)
timer = Timer("Timer")
}
} | mit | 40be2f670e8a055836708a4cc67016cb | 30.473118 | 97 | 0.650376 | 3.87037 | false | false | false | false |
AndroidX/androidx | camera/integration-tests/extensionstestapp/src/androidTest/java/androidx/camera/integration/extensions/AdvancedExtenderValidation.kt | 3 | 17551 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.integration.extensions
import android.content.Context
import android.graphics.ImageFormat
import android.graphics.SurfaceTexture
import android.hardware.camera2.CameraCaptureSession
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraDevice
import android.hardware.camera2.CameraManager
import android.hardware.camera2.CaptureRequest
import android.hardware.camera2.params.OutputConfiguration
import android.hardware.camera2.params.SessionConfiguration
import android.media.ImageReader
import android.util.Size
import android.view.Surface
import androidx.annotation.RequiresApi
import androidx.camera.camera2.internal.compat.params.SessionConfigurationCompat
import androidx.camera.camera2.interop.Camera2CameraInfo
import androidx.camera.core.impl.utils.executor.CameraXExecutors
import androidx.camera.extensions.ExtensionsManager
import androidx.camera.extensions.impl.advanced.AdvancedExtenderImpl
import androidx.camera.extensions.impl.advanced.Camera2OutputConfigImpl
import androidx.camera.extensions.impl.advanced.Camera2SessionConfigImpl
import androidx.camera.extensions.impl.advanced.ImageReaderOutputConfigImpl
import androidx.camera.extensions.impl.advanced.MultiResolutionImageReaderOutputConfigImpl
import androidx.camera.extensions.impl.advanced.OutputSurfaceImpl
import androidx.camera.extensions.impl.advanced.SurfaceOutputConfigImpl
import androidx.camera.extensions.internal.ExtensionVersion
import androidx.camera.extensions.internal.Version
import androidx.camera.integration.extensions.util.CameraXExtensionsTestUtil
import androidx.camera.integration.extensions.utils.CameraSelectorUtil
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.testing.fakes.FakeLifecycleOwner
import androidx.test.core.app.ApplicationProvider
import com.google.common.truth.Truth.assertThat
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.junit.Assume
import org.junit.Assume.assumeTrue
@RequiresApi(28)
class AdvancedExtenderValidation(
private val cameraId: String,
private val extensionMode: Int
) {
private val context = ApplicationProvider.getApplicationContext<Context>()
private lateinit var cameraProvider: ProcessCameraProvider
private lateinit var extensionsManager: ExtensionsManager
private lateinit var cameraCharacteristicsMap: Map<String, CameraCharacteristics>
private lateinit var advancedImpl: AdvancedExtenderImpl
fun setUp(): Unit = runBlocking {
cameraProvider =
ProcessCameraProvider.getInstance(context)[10000, TimeUnit.MILLISECONDS]
extensionsManager = ExtensionsManager.getInstanceAsync(
context,
cameraProvider
)[10000, TimeUnit.MILLISECONDS]
assumeTrue(CameraXExtensionsTestUtil.isAdvancedExtenderImplemented())
val baseCameraSelector = CameraSelectorUtil.createCameraSelectorById(cameraId)
assumeTrue(extensionsManager.isExtensionAvailable(baseCameraSelector, extensionMode))
val extensionCameraSelector = extensionsManager.getExtensionEnabledCameraSelector(
baseCameraSelector,
extensionMode
)
val cameraInfo = withContext(Dispatchers.Main) {
cameraProvider.bindToLifecycle(FakeLifecycleOwner(), extensionCameraSelector).cameraInfo
}
cameraCharacteristicsMap = Camera2CameraInfo.from(cameraInfo).cameraCharacteristicsMap
advancedImpl = CameraXExtensionsTestUtil
.createAdvancedExtenderImpl(extensionMode, cameraId, cameraInfo)
}
private val teardownFunctions = mutableListOf<() -> Unit>()
// Adding block to be invoked when tearing down. The last added will be invoked the first.
private fun addTearDown(teardown: () -> Unit) {
synchronized(teardownFunctions) {
teardownFunctions.add(0, teardown) // added to the head
}
}
fun tearDown(): Unit = runBlocking {
synchronized(teardownFunctions) {
for (teardownFunction in teardownFunctions) {
teardownFunction()
}
teardownFunctions.clear()
}
withContext(Dispatchers.Main) {
extensionsManager.shutdown()[10000, TimeUnit.MILLISECONDS]
cameraProvider.shutdown()[10000, TimeUnit.MILLISECONDS]
}
}
// Test
fun getSupportedPreviewOutputResolutions_returnValidData() {
val map = advancedImpl.getSupportedPreviewOutputResolutions(cameraId)
assertThat(map[ImageFormat.PRIVATE]).isNotEmpty()
}
// Test
fun getSupportedCaptureOutputResolutions_returnValidData() {
val map = advancedImpl.getSupportedCaptureOutputResolutions(cameraId)
assertThat(map[ImageFormat.JPEG]).isNotEmpty()
assertThat(map[ImageFormat.YUV_420_888]).isNotEmpty()
}
// Test
fun getAvailableCaptureRequestKeys_existAfter1_3() {
assumeTrue(ExtensionVersion.getRuntimeVersion()!! >= Version.VERSION_1_3)
advancedImpl.getAvailableCaptureRequestKeys()
}
// Test
fun getAvailableCaptureResultKeys_existAfter1_3() {
assumeTrue(ExtensionVersion.getRuntimeVersion()!! >= Version.VERSION_1_3)
advancedImpl.getAvailableCaptureResultKeys()
}
enum class SizeCategory {
MAXIMUM,
MEDIAN,
MINIMUM
}
private fun createPreviewOutput(
impl: AdvancedExtenderImpl,
sizeCategory: SizeCategory
): OutputSurfaceImpl {
val previewSizeMap = impl.getSupportedPreviewOutputResolutions(cameraId)
assertThat(previewSizeMap[ImageFormat.PRIVATE]).isNotEmpty()
val previewSizes = previewSizeMap[ImageFormat.PRIVATE]!!
val previewSize = getSizeByClass(previewSizes, sizeCategory)
val surfaceTexture = SurfaceTexture(0)
surfaceTexture.setDefaultBufferSize(previewSize.width, previewSize.height)
val previewSurface = Surface(surfaceTexture)
addTearDown {
surfaceTexture.release()
}
return OutputSurface(previewSurface, previewSize, ImageFormat.PRIVATE)
}
private fun createCaptureOutput(
impl: AdvancedExtenderImpl,
sizeCategory: SizeCategory
): OutputSurfaceImpl {
val captureSizeMap = impl.getSupportedCaptureOutputResolutions(cameraId)
assertThat(captureSizeMap[ImageFormat.JPEG]).isNotEmpty()
val captureSizes = captureSizeMap[ImageFormat.JPEG]!!
var captureSize = getSizeByClass(captureSizes, sizeCategory)
val imageReader = ImageReader.newInstance(
captureSize.width, captureSize.height, ImageFormat.JPEG, 1
)
addTearDown {
imageReader.close()
}
return OutputSurface(imageReader.surface, captureSize, ImageFormat.JPEG)
}
private fun getSizeByClass(
sizes: List<Size>,
sizeCategory: SizeCategory
): Size {
val sortedList = sizes.sortedByDescending { it.width * it.height }
var size =
when (sizeCategory) {
SizeCategory.MAXIMUM -> {
sortedList[0]
}
SizeCategory.MEDIAN -> {
sortedList[sortedList.size / 2]
}
SizeCategory.MINIMUM -> {
sortedList[sortedList.size - 1]
}
}
return size
}
private fun createAnalysisOutput(
impl: AdvancedExtenderImpl,
sizeCategory: SizeCategory
): OutputSurfaceImpl {
val analysisSizes = impl.getSupportedYuvAnalysisResolutions(cameraId)
assertThat(analysisSizes).isNotEmpty()
var analysisSize = getSizeByClass(analysisSizes, sizeCategory)
val imageReader = ImageReader.newInstance(
analysisSize.width, analysisSize.height, ImageFormat.YUV_420_888, 1
)
addTearDown {
imageReader.close()
}
return OutputSurface(imageReader.surface, analysisSize, ImageFormat.YUV_420_888)
}
// Test
fun initSession_maxSize_canConfigureSession() = initSessionTest(
previewOutputSizeCategory = SizeCategory.MAXIMUM,
captureOutputSizeCategory = SizeCategory.MAXIMUM
)
// Test
fun initSession_minSize_canConfigureSession() = initSessionTest(
previewOutputSizeCategory = SizeCategory.MINIMUM,
captureOutputSizeCategory = SizeCategory.MINIMUM
)
// Test
fun initSession_medianSize_canConfigureSession() = initSessionTest(
previewOutputSizeCategory = SizeCategory.MEDIAN,
captureOutputSizeCategory = SizeCategory.MEDIAN
)
// Test
fun initSessionWithAnalysis_maxSize_canConfigureSession() = initSessionTest(
previewOutputSizeCategory = SizeCategory.MAXIMUM,
captureOutputSizeCategory = SizeCategory.MAXIMUM,
analysisOutputSizeCategory = SizeCategory.MAXIMUM
)
// Test
fun initSessionWithAnalysis_minSize_canConfigureSession() = initSessionTest(
previewOutputSizeCategory = SizeCategory.MINIMUM,
captureOutputSizeCategory = SizeCategory.MINIMUM,
analysisOutputSizeCategory = SizeCategory.MINIMUM
)
// Test
fun initSessionWithAnalysis_medianSize_canConfigureSession() = initSessionTest(
previewOutputSizeCategory = SizeCategory.MEDIAN,
captureOutputSizeCategory = SizeCategory.MEDIAN,
analysisOutputSizeCategory = SizeCategory.MEDIAN
)
fun initSessionTest(
previewOutputSizeCategory: SizeCategory,
captureOutputSizeCategory: SizeCategory,
analysisOutputSizeCategory: SizeCategory? = null
): Unit = runBlocking {
if (analysisOutputSizeCategory != null) {
Assume.assumeFalse(
advancedImpl.getSupportedYuvAnalysisResolutions(cameraId).isNullOrEmpty()
)
}
val sessionProcessor = advancedImpl.createSessionProcessor()
val previewOutput = createPreviewOutput(advancedImpl, previewOutputSizeCategory)
val captureOutput = createCaptureOutput(advancedImpl, captureOutputSizeCategory)
val analysisOutput = analysisOutputSizeCategory?.let {
createAnalysisOutput(advancedImpl, analysisOutputSizeCategory)
}
addTearDown {
sessionProcessor.deInitSession()
}
var camera2SessionConfigImpl =
sessionProcessor.initSession(
cameraId,
cameraCharacteristicsMap,
context,
previewOutput,
captureOutput,
analysisOutput
)
verifyCamera2SessionConfig(camera2SessionConfigImpl)
}
private class OutputSurface(
private val surface: Surface,
private val size: Size,
private val imageFormat: Int
) : OutputSurfaceImpl {
override fun getSurface() = surface
override fun getSize() = size
override fun getImageFormat() = imageFormat
}
private fun getOutputConfiguration(
outputConfigImpl: Camera2OutputConfigImpl
): OutputConfiguration {
var outputConfiguration: OutputConfiguration
when (outputConfigImpl) {
is SurfaceOutputConfigImpl -> {
val surface = outputConfigImpl.surface
outputConfiguration = OutputConfiguration(outputConfigImpl.surfaceGroupId, surface)
}
is ImageReaderOutputConfigImpl -> {
val imageReader = ImageReader.newInstance(
outputConfigImpl.size.width,
outputConfigImpl.size.height,
outputConfigImpl.imageFormat,
outputConfigImpl.maxImages
)
val surface = imageReader.surface
addTearDown { imageReader.close() }
outputConfiguration = OutputConfiguration(outputConfigImpl.surfaceGroupId, surface)
}
is MultiResolutionImageReaderOutputConfigImpl ->
throw java.lang.UnsupportedOperationException(
"MultiResolutionImageReaderOutputConfigImpl not supported"
)
else -> throw java.lang.UnsupportedOperationException(
"Output configuration type not supported"
)
}
if (outputConfigImpl.physicalCameraId != null) {
outputConfiguration.setPhysicalCameraId(outputConfigImpl.physicalCameraId)
}
if (outputConfigImpl.surfaceSharingOutputConfigs != null) {
for (surfaceSharingOutputConfig in outputConfigImpl.surfaceSharingOutputConfigs) {
val sharingOutputConfiguration = getOutputConfiguration(surfaceSharingOutputConfig)
outputConfiguration.addSurface(sharingOutputConfiguration.surface!!)
outputConfiguration.enableSurfaceSharing()
}
}
return outputConfiguration
}
private suspend fun openCameraDevice(cameraId: String): CameraDevice {
val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
val deferred = CompletableDeferred<CameraDevice>()
cameraManager.openCamera(
cameraId,
CameraXExecutors.ioExecutor(),
object : CameraDevice.StateCallback() {
override fun onOpened(cameraDevice: CameraDevice) {
deferred.complete(cameraDevice)
}
override fun onClosed(camera: CameraDevice) {
super.onClosed(camera)
}
override fun onDisconnected(cameraDevice: CameraDevice) {
deferred.completeExceptionally(RuntimeException("Camera Disconnected"))
}
override fun onError(cameraDevice: CameraDevice, error: Int) {
deferred.completeExceptionally(
RuntimeException("Camera onError(error=$cameraDevice)")
)
}
})
return deferred.await()
}
private suspend fun openCaptureSession(
cameraDevice: CameraDevice,
camera2SessionConfig: Camera2SessionConfigImpl
): CameraCaptureSession {
val outputConfigurationList = mutableListOf<OutputConfiguration>()
for (outputConfig in camera2SessionConfig.outputConfigs) {
val outputConfiguration = getOutputConfiguration(outputConfig)
outputConfigurationList.add(outputConfiguration)
}
val sessionDeferred = CompletableDeferred<CameraCaptureSession>()
val sessionConfiguration = SessionConfiguration(
SessionConfigurationCompat.SESSION_REGULAR,
outputConfigurationList,
CameraXExecutors.ioExecutor(),
object : CameraCaptureSession.StateCallback() {
override fun onConfigured(session: CameraCaptureSession) {
sessionDeferred.complete(session)
}
override fun onConfigureFailed(session: CameraCaptureSession) {
sessionDeferred.completeExceptionally(RuntimeException("onConfigureFailed"))
}
override fun onReady(session: CameraCaptureSession) {
}
override fun onActive(session: CameraCaptureSession) {
}
override fun onCaptureQueueEmpty(session: CameraCaptureSession) {
}
override fun onClosed(session: CameraCaptureSession) {
super.onClosed(session)
}
override fun onSurfacePrepared(session: CameraCaptureSession, surface: Surface) {
super.onSurfacePrepared(session, surface)
}
}
)
val requestBuilder = cameraDevice.createCaptureRequest(
camera2SessionConfig.sessionTemplateId
)
camera2SessionConfig.sessionParameters.forEach { (key, value) ->
@Suppress("UNCHECKED_CAST")
requestBuilder.set(key as CaptureRequest.Key<Any>, value)
}
sessionConfiguration.sessionParameters = requestBuilder.build()
cameraDevice.createCaptureSession(sessionConfiguration)
return sessionDeferred.await()
}
private suspend fun verifyCamera2SessionConfig(camera2SessionConfig: Camera2SessionConfigImpl) {
val cameraDevice = openCameraDevice(cameraId)
assertThat(cameraDevice).isNotNull()
addTearDown { cameraDevice.close() }
val captureSession = openCaptureSession(cameraDevice, camera2SessionConfig)
assertThat(captureSession).isNotNull()
addTearDown { captureSession.close() }
}
} | apache-2.0 | 0442a98f2334bee7e14a1852059efe94 | 38.266219 | 100 | 0.690217 | 6.089868 | false | true | false | false |
AndroidX/androidx | work/work-runtime/src/main/java/androidx/work/impl/constraints/trackers/NetworkStateTracker.kt | 3 | 7462 | /*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.work.impl.constraints.trackers
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.ConnectivityManager.NetworkCallback
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.annotation.RestrictTo
import androidx.core.net.ConnectivityManagerCompat
import androidx.work.Logger
import androidx.work.impl.constraints.NetworkState
import androidx.work.impl.utils.getActiveNetworkCompat
import androidx.work.impl.utils.getNetworkCapabilitiesCompat
import androidx.work.impl.utils.hasCapabilityCompat
import androidx.work.impl.utils.registerDefaultNetworkCallbackCompat
import androidx.work.impl.utils.taskexecutor.TaskExecutor
import androidx.work.impl.utils.unregisterNetworkCallbackCompat
/**
* A [ConstraintTracker] for monitoring network state.
*
*
* For API 24 and up: Network state is tracked using a registered [NetworkCallback] with
* [ConnectivityManager.registerDefaultNetworkCallback], added in API 24.
*
*
* For API 23 and below: Network state is tracked using a [android.content.BroadcastReceiver].
* Much less efficient than tracking with [NetworkCallback]s and [ConnectivityManager].
*
*
* Based on [android.app.job.JobScheduler]'s ConnectivityController on API 26.
* {@see https://android.googlesource.com/platform/frameworks/base/+/oreo-release/services/core/java/com/android/server/job/controllers/ConnectivityController.java}
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun NetworkStateTracker(
context: Context,
taskExecutor: TaskExecutor
): ConstraintTracker<NetworkState> {
// Based on requiring ConnectivityManager#registerDefaultNetworkCallback - added in API 24.
return if (Build.VERSION.SDK_INT >= 24) {
NetworkStateTracker24(context, taskExecutor)
} else {
NetworkStateTrackerPre24(context, taskExecutor)
}
}
private val TAG = Logger.tagWithPrefix("NetworkStateTracker")
internal val ConnectivityManager.isActiveNetworkValidated: Boolean
get() = if (Build.VERSION.SDK_INT < 23) {
false // NET_CAPABILITY_VALIDATED not available until API 23. Used on API 26+.
} else try {
val network = getActiveNetworkCompat()
val capabilities = getNetworkCapabilitiesCompat(network)
(capabilities?.hasCapabilityCompat(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) ?: false
} catch (exception: SecurityException) {
// b/163342798
Logger.get().error(TAG, "Unable to validate active network", exception)
false
}
@Suppress("DEPRECATION")
internal val ConnectivityManager.activeNetworkState: NetworkState
get() {
// Use getActiveNetworkInfo() instead of getNetworkInfo(network) because it can detect VPNs.
val info = activeNetworkInfo
val isConnected = info != null && info.isConnected
val isValidated = isActiveNetworkValidated
val isMetered = ConnectivityManagerCompat.isActiveNetworkMetered(this)
val isNotRoaming = info != null && !info.isRoaming
return NetworkState(isConnected, isValidated, isMetered, isNotRoaming)
} // b/163342798
internal class NetworkStateTrackerPre24(context: Context, taskExecutor: TaskExecutor) :
BroadcastReceiverConstraintTracker<NetworkState>(context, taskExecutor) {
private val connectivityManager: ConnectivityManager =
appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
override fun onBroadcastReceive(intent: Intent) {
@Suppress("DEPRECATION")
if (intent.action == ConnectivityManager.CONNECTIVITY_ACTION) {
Logger.get().debug(TAG, "Network broadcast received")
state = connectivityManager.activeNetworkState
}
}
@Suppress("DEPRECATION")
override val intentFilter: IntentFilter
get() = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
override val initialState: NetworkState
get() = connectivityManager.activeNetworkState
}
@RequiresApi(24)
internal class NetworkStateTracker24(context: Context, taskExecutor: TaskExecutor) :
ConstraintTracker<NetworkState>(context, taskExecutor) {
private val connectivityManager: ConnectivityManager =
appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
override val initialState: NetworkState
get() = connectivityManager.activeNetworkState
private val networkCallback = object : NetworkCallback() {
override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) {
// The Network parameter is unreliable when a VPN app is running - use active network.
Logger.get().debug(TAG, "Network capabilities changed: $capabilities")
state = connectivityManager.activeNetworkState
}
override fun onLost(network: Network) {
Logger.get().debug(TAG, "Network connection lost")
state = connectivityManager.activeNetworkState
}
}
override fun startTracking() {
try {
Logger.get().debug(TAG, "Registering network callback")
connectivityManager.registerDefaultNetworkCallbackCompat(networkCallback)
} catch (e: IllegalArgumentException) {
// Catching the exceptions since and moving on - this tracker is only used for
// GreedyScheduler and there is nothing to be done about device-specific bugs.
// IllegalStateException: Happening on NVIDIA Shield K1 Tablets. See b/136569342.
// SecurityException: Happening on Solone W1450. See b/153246136.
Logger.get().error(TAG, "Received exception while registering network callback", e)
} catch (e: SecurityException) {
Logger.get().error(TAG, "Received exception while registering network callback", e)
}
}
override fun stopTracking() {
try {
Logger.get().debug(TAG, "Unregistering network callback")
connectivityManager.unregisterNetworkCallbackCompat(networkCallback)
} catch (e: IllegalArgumentException) {
// Catching the exceptions since and moving on - this tracker is only used for
// GreedyScheduler and there is nothing to be done about device-specific bugs.
// IllegalStateException: Happening on NVIDIA Shield K1 Tablets. See b/136569342.
// SecurityException: Happening on Solone W1450. See b/153246136.
Logger.get().error(TAG, "Received exception while unregistering network callback", e)
} catch (e: SecurityException) {
Logger.get().error(TAG, "Received exception while unregistering network callback", e)
}
}
} | apache-2.0 | 579605195c7babaa32fda4c11e9d6997 | 44.230303 | 164 | 0.733852 | 5.014785 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/macros/MappedText.kt | 1 | 1436 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.macros
import com.intellij.util.SmartList
data class MappedText(val text: String, val ranges: RangeMap) {
companion object {
val EMPTY: MappedText = MappedText("", RangeMap.EMPTY)
fun single(text: String, srcOffset: Int): MappedText {
return if (text.isNotEmpty()) {
MappedText(
text,
RangeMap.from(SmartList(MappedTextRange(srcOffset, 0, text.length)))
)
} else {
EMPTY
}
}
}
}
class MutableMappedText private constructor(
private val sb: StringBuilder,
private val ranges: MutableList<MappedTextRange> = mutableListOf()
) {
constructor(capacity: Int) : this(StringBuilder(capacity))
val length: Int get() = sb.length
val text: CharSequence get() = sb
fun appendUnmapped(text: CharSequence) {
sb.append(text)
}
fun appendMapped(text: CharSequence, srcOffset: Int) {
if (text.isNotEmpty()) {
ranges.mergeAdd(MappedTextRange(srcOffset, sb.length, text.length))
sb.append(text)
}
}
fun toMappedText(): MappedText = MappedText(sb.toString(), RangeMap.from(SmartList(ranges)))
override fun toString(): String {
return sb.toString()
}
}
| mit | b3e9e43e9ffdcc9107a03278f1e1a77c | 26.615385 | 96 | 0.611421 | 4.378049 | false | false | false | false |
yzbzz/beautifullife | app/src/main/java/com/ddu/ui/activity/phrase/TwoSeparatorActivity.kt | 2 | 2168 | package com.ddu.ui.activity.phrase
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.text.style.StrikethroughSpan
import android.text.style.StyleSpan
import android.text.style.UnderlineSpan
import androidx.appcompat.app.AppCompatActivity
import com.ddu.R
import com.ddu.icore.util.StylePhrase
import kotlinx.android.synthetic.main.activity_one_separator.*
class TwoSeparatorActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_one_separator)
val twoSeparatorString = getString(R.string.text_phrase_two)
tv_description.text = "二种分割符"
tv_original.text = twoSeparatorString
// 设置字体和颜色
val colorAndSize = StylePhrase(twoSeparatorString)
.setInnerFirstColor(Color.BLUE)
.setInnerFirstSize(20)
.setInnerSecondColor(Color.RED)
.setInnerSecondSize(25)
tv_content.text = colorAndSize.format()
// 设置粗斜体
val boldPhrase = StylePhrase(twoSeparatorString)
boldPhrase.setInnerFirstColor(Color.RED)
boldPhrase.setInnerSecondColor(Color.BLUE)
boldPhrase.setInnerSecondSize(13)
boldPhrase.secondBuilder.addParcelableSpan(StyleSpan(Typeface.BOLD_ITALIC))
tv_content_bold_italic.text = boldPhrase.format()
// 设置删除线
val strikeThroughPhrase = StylePhrase(twoSeparatorString)
strikeThroughPhrase.firstBuilder.setColor(Color.BLUE)
strikeThroughPhrase.firstBuilder.addParcelableSpan(StrikethroughSpan())
strikeThroughPhrase.setInnerSecondSize(25)
tv_content_strike_through.text = strikeThroughPhrase.format()
// 设置下划线
val underlinePhrase = StylePhrase(twoSeparatorString)
underlinePhrase.secondBuilder.addParcelableSpan(UnderlineSpan())
tv_content_underline.text = underlinePhrase.format()
tv_separator.text = "${colorAndSize.firstBuilder.separator} ${colorAndSize.secondBuilder.separator}"
}
}
| apache-2.0 | fa256646ca4ddcf5fa95e86df47052a2 | 37.436364 | 108 | 0.727531 | 4.635965 | false | false | false | false |
GoSkyer/blog-service | src/main/kotlin/org/goskyer/service/impl/UserSerImpl.kt | 1 | 2792 | package org.goskyer.service.impl
import org.goskyer.domain.User
import org.goskyer.mapping.UserMapper
import org.goskyer.security.JwtTokenUtils
import org.goskyer.service.UserSer
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.stereotype.Service
/**
* Created by zohar on 2017/3/31.
* desc:
*/
@Service
public class UserSerImpl : UserSer {
private lateinit var userMapper: UserMapper;
private lateinit var jwtTokenUtil: JwtTokenUtils
private lateinit var authenticationManager: AuthenticationManager
private lateinit var userDetailsService: UserDetailsService
@Autowired
constructor(userMapper: UserMapper, jwtTokenUtil: JwtTokenUtils, authenticationManager: AuthenticationManager, userDetailsService: UserDetailsService) {
this.userMapper = userMapper
this.jwtTokenUtil = jwtTokenUtil
this.authenticationManager = authenticationManager
this.userDetailsService = userDetailsService
}
override fun register(user: User): Int? {
var userEmail = user.userEmail
if (userMapper.selectByEmail(userEmail!!) !== null) {
throw RuntimeException("该邮箱已被注册")
}
val bCryptPasswordEncoder = BCryptPasswordEncoder()
user.password = bCryptPasswordEncoder.encode(user.password)
user.role = "ROLE_USER"
return userMapper.insert(user)
}
override fun getUsers(): List<User> {
var a: List<String>
return userMapper.selectAll();
}
override fun selectByEmail(email: String): User? {
return userMapper.selectByEmail(email)
}
override fun login(email: String, password: String): String {
var authenticationToken = UsernamePasswordAuthenticationToken(email, password)//根据用户名密码获取authenticationToken
//根据authenticationToken获取authenticate 这个里面存储每个用户对应的信息,用户名密码不对获取不到会抛出异常
var authenticate = authenticationManager.authenticate(authenticationToken)
SecurityContextHolder.getContext().authentication = authenticate// 保存到SecurityContextHolder里
// 生成登陆用的token
val userDetail = userDetailsService.loadUserByUsername(email)
val token = jwtTokenUtil.generateToken(userDetailsService.loadUserByUsername(email))
return token
}
} | mit | 53823ed717865706885493bd6b5b9451 | 35.589041 | 156 | 0.76367 | 5.16441 | false | false | false | false |
androidx/androidx | resourceinspection/resourceinspection-processor/src/main/kotlin/androidx/resourceinspection/processor/Models.kt | 3 | 2903 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.resourceinspection.processor
import com.squareup.javapoet.ClassName
import javax.lang.model.element.AnnotationMirror
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.TypeElement
/** Represents a view with annotated attributes, mostly a convenience class. */
internal data class View(
val type: TypeElement,
val attributes: List<Attribute>
) {
val className: ClassName = ClassName.get(type)
}
@JvmDefaultWithCompatibility
internal interface Attribute {
val name: String
val namespace: String
val type: AttributeType
val intMapping: List<IntMap>
val invocation: String
val qualifiedName: String
get() = "$namespace:$name"
}
/** Represents an `Attribute` with its getter. */
internal data class GetterAttribute(
val getter: ExecutableElement,
val annotation: AnnotationMirror,
override val namespace: String,
override val name: String,
override val type: AttributeType,
override val intMapping: List<IntMap> = emptyList()
) : Attribute {
override val invocation: String
get() = "${getter.simpleName}()"
}
/**
* Represents a shadowed platform attribute in a different namespace, mainly for AppCompat.
*
* The constructor has some reasonable defaults to make defining these as constants less toilsome.
*/
internal data class ShadowedAttribute(
override val name: String,
override val invocation: String,
override val type: AttributeType = AttributeType.OBJECT,
override val intMapping: List<IntMap> = emptyList(),
override val namespace: String = "androidx.appcompat"
) : Attribute
/** Represents an `Attribute.IntMap` entry. */
internal data class IntMap(
val name: String,
val value: Int,
val mask: Int = 0,
val annotation: AnnotationMirror? = null
)
/** Represents the type of the attribute, determined from context and the annotation itself. */
internal enum class AttributeType(val apiSuffix: String) {
BOOLEAN("Boolean"),
BYTE("Byte"),
CHAR("Char"),
DOUBLE("Double"),
FLOAT("Float"),
INT("Int"),
LONG("Long"),
SHORT("Short"),
OBJECT("Object"),
COLOR("Color"),
GRAVITY("Gravity"),
RESOURCE_ID("ResourceId"),
INT_FLAG("IntFlag"),
INT_ENUM("IntEnum")
}
| apache-2.0 | af05ad02ca3d1a6244dda47fe054807b | 29.557895 | 98 | 0.715467 | 4.425305 | false | false | false | false |
52inc/android-52Kit | library-arch/src/main/java/com/ftinc/kit/arch/presentation/delegates/StatefulActivityDelegate.kt | 1 | 2096 | /*
* Copyright (c) 2019 52inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ftinc.kit.arch.presentation.delegates
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.OnLifecycleEvent
import android.os.Bundle
import com.ftinc.kit.arch.presentation.Stateful
import com.ftinc.kit.arch.presentation.renderers.DisposableStateRenderer
class StatefulActivityDelegate(
private val state: Stateful,
private val lifecycle: Lifecycle.Event = Lifecycle.Event.ON_CREATE
) : ActivityDelegate {
override fun onCreate(savedInstanceState: Bundle?) {
tryStart(Lifecycle.Event.ON_CREATE)
}
override fun onSaveInstanceState(outState: Bundle) {
}
override fun onResume() {
tryStart(Lifecycle.Event.ON_RESUME)
}
override fun onStart() {
tryStart(Lifecycle.Event.ON_START)
}
override fun onStop() {
tryStop(Lifecycle.Event.ON_STOP)
}
override fun onPause() {
tryStop(Lifecycle.Event.ON_PAUSE)
}
override fun onDestroy() {
tryStop(Lifecycle.Event.ON_DESTROY)
}
private fun tryStart(event: Lifecycle.Event) {
if (event == lifecycle) {
state.start()
}
}
private fun tryStop(event: Lifecycle.Event) {
val opposite = when(lifecycle) {
Lifecycle.Event.ON_CREATE -> Lifecycle.Event.ON_DESTROY
Lifecycle.Event.ON_START -> Lifecycle.Event.ON_STOP
else -> Lifecycle.Event.ON_PAUSE
}
if (opposite == event) {
state.stop()
}
}
} | apache-2.0 | 57e5ba08eb38887a36d81c54b3d8873b | 25.884615 | 75 | 0.67271 | 4.208835 | false | false | false | false |
TUWien/DocScan | app/src/main/java/at/ac/tuwien/caa/docscan/ui/docviewer/DocumentViewerViewModel.kt | 1 | 9295 | package at.ac.tuwien.caa.docscan.ui.docviewer
import android.net.Uri
import android.os.Bundle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import at.ac.tuwien.caa.docscan.db.model.DocumentWithPages
import at.ac.tuwien.caa.docscan.db.model.error.DBErrorCode
import at.ac.tuwien.caa.docscan.db.model.isUploaded
import at.ac.tuwien.caa.docscan.logic.*
import at.ac.tuwien.caa.docscan.repository.DocumentRepository
import at.ac.tuwien.caa.docscan.repository.ExportFileRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import java.util.*
class DocumentViewerViewModel(
private val repository: DocumentRepository,
private val exportFileRepository: ExportFileRepository
) : ViewModel() {
val selectedScreen = MutableLiveData(DocumentViewerScreen.DOCUMENTS)
val observableInitDocumentOptions = MutableLiveData<Event<DocumentWithPages>>()
val observableInitCamera = MutableLiveData<Event<Unit>>()
val observableNumOfSelectedElements = MutableLiveData<Int>()
private val observableDocumentAtImages = MutableLiveData<DocumentWithPages?>()
val observableResourceAction = MutableLiveData<Event<DocumentViewerModel>>()
val observableResourceConfirmation =
MutableLiveData<Event<DocumentConfirmationModel>>()
val observableNewExportCount = MutableLiveData<Int>()
init {
viewModelScope.launch(Dispatchers.IO) {
exportFileRepository.getExportFileCount().collectLatest {
observableNewExportCount.postValue(it.toInt())
}
}
}
/**
* This function needs to be called every time the selected fragment in the bottom nav changes.
*/
fun changeScreen(screen: DocumentViewerScreen) {
// every time the screen is changed, the selected elements will get deleted.
observableNumOfSelectedElements.postValue(0)
selectedScreen.postValue(screen)
}
fun informAboutImageViewer(documentWithPages: DocumentWithPages?) {
observableDocumentAtImages.postValue(documentWithPages)
}
fun initDocumentOptions(documentWithPages: DocumentWithPages) {
observableInitDocumentOptions.postValue(Event(documentWithPages))
}
fun setSelectedElements(selectedElements: Int) {
observableNumOfSelectedElements.postValue(selectedElements)
}
fun addNewImages(uris: List<Uri>) {
viewModelScope.launch(Dispatchers.IO) {
val doc = run {
if (selectedScreen.value == DocumentViewerScreen.IMAGES) {
observableDocumentAtImages.value?.document
} else {
null
}
} ?: return@launch
repository.saveNewImportedImageForDocument(doc, uris)
}
}
/**
* Starts imaging with a document, there are several scenarios.
* - If [docId] is available, then this will be the next active document.
* - If [docId] is null but [selectedScreen] is [DocumentViewerScreen.IMAGES], then
* the currently selected document will become active.
* - If none of the previous cases occur, imaging will be continued with the active document.
*/
fun startImagingWith(docId: UUID? = null) {
viewModelScope.launch(Dispatchers.IO) {
val docIdToBecomeActive = docId ?: run {
if (selectedScreen.value == DocumentViewerScreen.IMAGES) {
observableDocumentAtImages.value?.document?.id
} else {
null
}
}
docIdToBecomeActive?.let {
repository.setDocumentAsActive(it)
}
observableInitCamera.postValue(Event(Unit))
}
}
fun uploadSelectedDocument() {
val docWithPages =
if (selectedScreen.value == DocumentViewerScreen.IMAGES) {
observableDocumentAtImages.value ?: kotlin.run {
null
}
} else {
null
}
docWithPages ?: kotlin.run {
observableResourceAction.postValue(
Event(
DocumentViewerModel(
DocumentAction.UPLOAD,
DBErrorCode.ENTRY_NOT_AVAILABLE.asFailure<Unit>(),
Bundle()
)
)
)
return
}
applyActionFor(
action = DocumentAction.UPLOAD,
documentActionArguments = Bundle().appendDocWithPages(docWithPages),
documentWithPages = docWithPages
)
}
fun applyActionFor(
action: DocumentAction,
documentActionArguments: Bundle
) {
val documentWithPages = documentActionArguments.extractDocWithPages() ?: kotlin.run {
observableResourceAction.postValue(
Event(
DocumentViewerModel(
action,
DBErrorCode.ENTRY_NOT_AVAILABLE.asFailure<Unit>(),
documentActionArguments
)
)
)
return
}
applyActionFor(action, documentActionArguments, documentWithPages)
}
private fun applyActionFor(
action: DocumentAction,
documentActionArguments: Bundle,
documentWithPages: DocumentWithPages
) {
viewModelScope.launch(Dispatchers.IO) {
if (!skipConfirmation(action, documentWithPages)) {
// ask for confirmation first, if forceAction, then confirmation is not necessary anymore.
if (action.needsConfirmation && !documentActionArguments.extractIsConfirmed()) {
observableResourceConfirmation.postValue(
Event(
DocumentConfirmationModel(
action,
documentWithPages,
documentActionArguments.appendDocWithPages(documentWithPages)
)
)
)
return@launch
}
}
val resource = when (action) {
DocumentAction.SHARE -> {
repository.shareDocument(documentWithPages.document.id)
}
DocumentAction.DELETE -> {
repository.removeDocument(documentWithPages)
}
DocumentAction.EXPORT_ZIP -> {
repository.exportDocument(
documentWithPages,
skipCropRestriction = true,
ExportFormat.ZIP
)
}
DocumentAction.EXPORT -> {
repository.exportDocument(
documentWithPages,
skipCropRestriction = documentActionArguments.extractSkipCropRestriction(),
if(documentActionArguments.extractUseOCR()) ExportFormat.PDF_WITH_OCR else ExportFormat.PDF
)
}
DocumentAction.CROP -> {
repository.cropDocument(documentWithPages)
}
DocumentAction.UPLOAD -> {
repository.uploadDocument(
documentWithPages,
skipCropRestriction = documentActionArguments.extractSkipCropRestriction(),
skipAlreadyUploadedRestriction = documentActionArguments.extractSkipAlreadyUploadedRestriction()
)
}
DocumentAction.CANCEL_UPLOAD -> {
repository.cancelDocumentUpload(documentWithPages.document.id)
}
}
observableResourceAction.postValue(
Event(
DocumentViewerModel(
action,
resource,
documentActionArguments
)
)
)
}
}
}
/**
* Evaluates if the confirmation can be skipped.
*/
private fun skipConfirmation(
action: DocumentAction,
documentWithPages: DocumentWithPages,
): Boolean {
return when (action) {
DocumentAction.UPLOAD -> {
// if the doc is already uploaded, we do not need to ask for further confirmation
documentWithPages.isUploaded()
}
else -> false
}
}
data class DocumentViewerModel(
val action: DocumentAction,
val resource: Resource<*>,
val arguments: Bundle
)
data class DocumentConfirmationModel(
val action: DocumentAction,
val documentWithPages: DocumentWithPages,
val arguments: Bundle
)
enum class DocumentAction(val needsConfirmation: Boolean, val showSuccessMessage: Boolean) {
DELETE(true, false),
EXPORT_ZIP(false, true),
EXPORT(true, true),
CROP(true, false),
UPLOAD(true, true),
CANCEL_UPLOAD(true, false),
SHARE(false, false)
}
enum class DocumentViewerScreen {
DOCUMENTS,
IMAGES,
PDFS
}
| lgpl-3.0 | fd2e47004c34eecdd087a041bceb6a25 | 34.477099 | 120 | 0.593868 | 5.946897 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/hierarchy/call/LuaHierarchyNodeDescriptor.kt | 2 | 3081 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.hierarchy.call
import com.intellij.icons.AllIcons
import com.intellij.ide.IdeBundle
import com.intellij.ide.hierarchy.HierarchyNodeDescriptor
import com.intellij.openapi.roots.ui.util.CompositeAppearance
import com.intellij.openapi.util.Comparing
import com.intellij.pom.Navigatable
import com.intellij.psi.NavigatablePsiElement
import com.intellij.psi.PsiElement
import com.tang.intellij.lua.psi.LuaLocalFuncDef
class LuaHierarchyNodeDescriptor(parentDescriptor: HierarchyNodeDescriptor?, element: PsiElement, isBase: Boolean)
: HierarchyNodeDescriptor(element.project, parentDescriptor, element, isBase), Navigatable {
override fun navigate(requestFocus: Boolean) {
val element = psiElement
if (element is Navigatable && element.canNavigate()) {
element.navigate(requestFocus)
}
}
override fun canNavigate(): Boolean {
return psiElement is Navigatable
}
override fun canNavigateToSource(): Boolean {
return psiElement is Navigatable
}
override fun update(): Boolean {
var changes = super.update()
val oldText = myHighlightedText
myHighlightedText = CompositeAppearance()
val element = psiElement as NavigatablePsiElement?
if (element == null) {
val invalidPrefix = IdeBundle.message("node.hierarchy.invalid")
if (!myHighlightedText.text.startsWith(invalidPrefix)) {
myHighlightedText.beginning.addText(invalidPrefix, HierarchyNodeDescriptor.getInvalidPrefixAttributes())
}
return true
}
val presentation = element.presentation
if (presentation != null) {
myHighlightedText.ending.addText(presentation.presentableText)
myHighlightedText.ending.addText(" " + presentation.locationString, HierarchyNodeDescriptor.getPackageNameAttributes())
icon = presentation.getIcon(false)
} else {
if (element is LuaLocalFuncDef) {
myHighlightedText.ending.addText(element.name ?: "")
myHighlightedText.ending.addText(" " + element.containingFile.name, HierarchyNodeDescriptor.getPackageNameAttributes())
icon = AllIcons.Nodes.Function
}
}
myName = myHighlightedText.text
if (!Comparing.equal(myHighlightedText, oldText)) {
changes = true
}
return changes
}
} | apache-2.0 | 329103db1ebf08ac8e5108093369a7d9 | 37.049383 | 135 | 0.700097 | 5.143573 | false | false | false | false |
inorichi/tachiyomi-extensions | src/es/lectormanga/src/eu/kanade/tachiyomi/extension/es/lectormanga/LectorMangaUrlActivity.kt | 1 | 1262 | package eu.kanade.tachiyomi.extension.es.lectormanga
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.util.Log
import kotlin.system.exitProcess
/**
* Springboard that accepts https://lectormanga.com/gotobook/:id intents and redirects them to
* the main Tachiyomi process.
*/
class LectorMangaUrlActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val pathSegments = intent?.data?.pathSegments
if (pathSegments != null && pathSegments.size > 1) {
val id = pathSegments[1]
val mainIntent = Intent().apply {
action = "eu.kanade.tachiyomi.SEARCH"
putExtra("query", "${LectorManga.PREFIX_ID_SEARCH}$id")
putExtra("filter", packageName)
}
try {
startActivity(mainIntent)
} catch (e: ActivityNotFoundException) {
Log.e("LectorMangaUrlActivity", e.toString())
}
} else {
Log.e("LectorMangaUrlActivity", "could not parse uri from intent $intent")
}
finish()
exitProcess(0)
}
}
| apache-2.0 | b349db2011eede74d53c83715063d2b1 | 31.358974 | 94 | 0.633122 | 4.674074 | false | false | false | false |
hastebrot/protokola | src/main/kotlin/protokola/transport/dolphinChannel.kt | 1 | 4596 | package protokola.transport
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okio.Buffer
import protokola.Message
import protokola.MessageBus
import protokola.of
import protokola.transport.Transport.ClientRequest
import protokola.transport.Transport.DolphinClientId
import protokola.transport.Transport.SessionCookie
import protokola.transport.Transport.ServerResponse
import java.util.concurrent.ConcurrentHashMap
fun main(args: Array<String>) {
val bus = MessageBus()
bus.subscribe { println(it.payload) }
val channel = DolphinChannel()
channel.dispatchTo(bus)
val dolphinEndpointUrl = "http://localhost:8080/dolphin"
val requestContext = ClientRequest(dolphinEndpointUrl, listOf(
mapOf("id" to "CreateContext")
).toJson())
val requestController = ClientRequest(dolphinEndpointUrl, listOf(
mapOf("id" to "CreateController", "n" to "FooController", "c_id" to null)
).toJson())
val requestLongPoll = ClientRequest(dolphinEndpointUrl, listOf(
mapOf("id" to "StartLongPoll")
).toJson())
bus.dispatch(Message(requestContext))
bus.dispatch(Message(requestController))
bus.dispatch(Message(requestLongPoll))
}
object Transport {
data class ClientRequest(val url: String,
val body: String?)
data class ServerResponse(val status: Int,
val body: String?)
data class DolphinClientId(val value: String)
data class SessionCookie(val value: String)
}
class DolphinChannel {
private val okHttpClient = OkHttpClient.Builder()
// .cookieJar(simpleCookieJar())
.build()
private var dolphinClientId: DolphinClientId? = null
private var sessionCookie: SessionCookie? = null
fun dispatchTo(messageBus: MessageBus) {
messageBus.subscribe { message ->
when (message.payload) {
is ClientRequest -> fetch(messageBus, message.of())
}
}
}
private fun fetch(bus: MessageBus,
clientRequest: Message<ClientRequest>) {
val okHttpRequest = createRequest(
clientRequest.payload,
dolphinClientId,
sessionCookie
)
val okHttpCall = okHttpClient.newCall(okHttpRequest)
okHttpCall.execute().use { okHttpResponse ->
val dolphinClientIdValue = okHttpResponse.header(headerDolphinClientId)
val sessionCookieValue = okHttpResponse.headers(headerSetCookieKey).firstOrNull()
val serverResponse = Message(ServerResponse(
okHttpResponse.code(), okHttpResponse.body()?.string()
))
bus.dispatch(serverResponse)
dolphinClientIdValue?.let {
dolphinClientId = DolphinClientId(it)
bus.dispatch(Message(dolphinClientId))
}
sessionCookieValue?.let {
sessionCookie = SessionCookie(it)
bus.dispatch(Message(sessionCookie))
}
}
}
}
private val headerConnectionKey = "Connection"
private val headerCookieKey = "Cookie"
private val headerSetCookieKey = "Set-Cookie"
private val headerDolphinClientId = "dolphin_platform_intern_dolphinClientId"
private fun createRequest(
clientRequest: ClientRequest,
dolphinClientId: DolphinClientId?,
sessionCookie: SessionCookie?): Request {
val mediaType = MediaType.parse("application/json")
return Request.Builder().apply {
url(clientRequest.url)
post(RequestBody.create(mediaType, clientRequest.body!!))
header(headerConnectionKey, "keep-alive")
if (dolphinClientId != null) {
header(headerDolphinClientId, dolphinClientId.value)
}
if (sessionCookie != null) {
addHeader(headerCookieKey, sessionCookie.value)
}
}.build()
}
private fun List<*>.toJson() = toString()
private fun Map<*, *>.toJson() = toString()
private fun simpleCookieJar() = object : CookieJar {
private val cookieMap = ConcurrentHashMap<String, List<Cookie>>()
override fun saveFromResponse(url: HttpUrl,
unmodifiableCookies: List<Cookie>) {
cookieMap[url.host()] = unmodifiableCookies.toMutableList()
}
override fun loadForRequest(url: HttpUrl) =
cookieMap[url.host()] ?: mutableListOf()
}
private fun RequestBody.string() = Buffer()
.also { writeTo(it) }
.readUtf8()
| apache-2.0 | 2b84ce94861f4f928ac511f0289b0a78 | 30.479452 | 93 | 0.670366 | 4.889362 | false | false | false | false |
kaskasi/VocabularyTrainer | app/src/main/java/de/fluchtwege/vocabulary/questions/QuestionsFragment.kt | 1 | 3438 | package de.fluchtwege.vocabulary.questions
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.view.*
import de.fluchtwege.vocabulary.R
import de.fluchtwege.vocabulary.Vocabulary
import de.fluchtwege.vocabulary.addquestion.AddQuestionActivity
import de.fluchtwege.vocabulary.databinding.FragmentQuestionsBinding
import de.fluchtwege.vocabulary.lessons.LessonsRepository
import de.fluchtwege.vocabulary.quiz.QuizActivity
import io.reactivex.disposables.Disposable
import javax.inject.Inject
class QuestionsFragment : Fragment() {
companion object {
const val KEY_LESSON_NAME = "lesson_name"
const val KEY_QUESTION_POSITION = "question_position"
}
@Inject
lateinit var lessonsRepository: LessonsRepository
lateinit var viewModel: QuestionsViewModel
lateinit var questionsAdapter: QuestionsAdaper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
Vocabulary.appComponent.inject(this)
val lessonName = activity.intent.getStringExtra(KEY_LESSON_NAME)
viewModel = QuestionsViewModel(lessonName, lessonsRepository)
questionsAdapter = QuestionsAdaper(viewModel, this::editQuestion, this::deleteQuestion )
}
private var disposable: Disposable? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val binding = FragmentQuestionsBinding.inflate(inflater!!)
val layoutManager = LinearLayoutManager(context)
binding.questions.adapter = questionsAdapter
binding.questions.layoutManager = layoutManager
binding.questions.addItemDecoration(DividerItemDecoration(context, layoutManager.orientation))
binding.viewModel = viewModel
disposable = viewModel.loadQuestions(questionsAdapter::notifyDataSetChanged)
return binding.root
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.menu_questions, menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when(item?.itemId) {
R.id.add_question -> addQuestion()
R.id.quiz_questions -> startQuiz()
}
return true
}
private fun editQuestion(position: Int) {
val openAddQuestion = Intent(context, AddQuestionActivity::class.java)
openAddQuestion.putExtra(KEY_LESSON_NAME, viewModel.lessonName)
openAddQuestion.putExtra(KEY_QUESTION_POSITION, position)
startActivity(openAddQuestion)
}
private fun deleteQuestion(position: Int) {
disposable = viewModel.deleteQuestion(position, questionsAdapter::notifyDataSetChanged)
}
private fun addQuestion() {
val openAddQuestion = Intent(context, AddQuestionActivity::class.java)
openAddQuestion.putExtra(KEY_LESSON_NAME, viewModel.lessonName)
startActivity(openAddQuestion)
}
private fun startQuiz() {
val openQuiz = Intent(context, QuizActivity::class.java)
openQuiz.putExtra(KEY_LESSON_NAME, viewModel.lessonName)
startActivity(openQuiz)
}
override fun onDestroy() {
super.onDestroy()
disposable?.dispose()
}
} | mit | 65f874531e5c0dc319d0cb1f2128b7c9 | 35.978495 | 117 | 0.736184 | 4.939655 | false | false | false | false |
HabitRPG/habitica-android | wearos/src/main/java/com/habitrpg/wearos/habitica/models/tasks/BulkTaskScoringData.kt | 1 | 821 | package com.habitrpg.wearos.habitica.models.tasks
import com.habitrpg.shared.habitica.models.responses.TaskDirectionData
import com.habitrpg.wearos.habitica.models.user.Buffs
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
class BulkTaskScoringData {
@Json(name="con")
var constitution: Int? = null
@Json(name="str")
var strength: Int? = null
@Json(name="per")
var per: Int? = null
@Json(name="int")
var intelligence: Int? = null
var buffs: Buffs? = null
var points: Int? = null
var lvl: Int? = null
@Json(name="class")
var habitClass: String? = null
var gp: Double? = null
var exp: Double? = null
var mp: Double? = null
var hp: Double? = null
var tasks: List<TaskDirectionData> = listOf()
}
| gpl-3.0 | 701fc990daad23d35c45ad077496be34 | 27.310345 | 70 | 0.679659 | 3.523605 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/opening_hours/model/TimeRange.kt | 1 | 1811 | package de.westnordost.streetcomplete.quests.opening_hours.model
import java.text.DateFormat
import java.util.*
/** A time range from [start,end). */
class TimeRange(minutesStart: Int, minutesEnd: Int, val isOpenEnded: Boolean = false)
: CircularSection(minutesStart, minutesEnd) {
override fun intersects(other: CircularSection): Boolean {
if (other !is TimeRange) return false
if (isOpenEnded && other.start >= start) return true
if (other.isOpenEnded && start >= other.start) return true
return loops && other.loops ||
if (loops || other.loops) other.end > start || other.start < end
else other.end > start && other.start < end
}
fun toStringUsing(locale: Locale, range: String): String {
val sb = StringBuilder()
sb.append(timeOfDayToString(locale, start))
val displayEnd = if(end != 0) end else 60 * 24
if (start != end || !isOpenEnded) {
sb.append(range)
sb.append(timeOfDayToString(locale, displayEnd))
}
if (isOpenEnded) sb.append("+")
return sb.toString()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is TimeRange) return false
return other.isOpenEnded == isOpenEnded && super.equals(other)
}
override fun hashCode() = super.hashCode() * 2 + if (isOpenEnded) 1 else 0
override fun toString() = toStringUsing(Locale.GERMANY, "-")
private fun timeOfDayToString(locale: Locale, minutes: Int): String {
val cal = GregorianCalendar()
cal.set(Calendar.HOUR_OF_DAY, minutes / 60)
cal.set(Calendar.MINUTE, minutes % 60)
return DateFormat.getTimeInstance(DateFormat.SHORT, locale).format(cal.time)
}
}
| gpl-3.0 | cdc0a057c4ff30e1bcd2c842325a6fcb | 37.531915 | 85 | 0.633352 | 4.291469 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osm/osmquest/OsmQuestDao.kt | 1 | 8836 | package de.westnordost.streetcomplete.data.osm.osmquest
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase.CONFLICT_IGNORE
import android.database.sqlite.SQLiteOpenHelper
import androidx.core.content.contentValuesOf
import java.util.Date
import javax.inject.Inject
import de.westnordost.osmapi.map.data.BoundingBox
import de.westnordost.osmapi.map.data.Element
import de.westnordost.streetcomplete.data.*
import de.westnordost.streetcomplete.data.osm.changes.StringMapChanges
import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.Columns.CHANGES_SOURCE
import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.Columns.ELEMENT_ID
import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.Columns.ELEMENT_TYPE
import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.Columns.LAST_UPDATE
import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.Columns.QUEST_ID
import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.Columns.QUEST_STATUS
import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.Columns.QUEST_TYPE
import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.Columns.TAG_CHANGES
import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.NAME
import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuestTable.NAME_MERGED_VIEW
import de.westnordost.streetcomplete.data.quest.QuestStatus.*
import de.westnordost.streetcomplete.data.osm.mapdata.ElementKey
import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementGeometryMapping
import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementGeometryTable
import de.westnordost.streetcomplete.data.quest.QuestStatus
import de.westnordost.streetcomplete.data.quest.QuestTypeRegistry
import de.westnordost.streetcomplete.ktx.*
import de.westnordost.streetcomplete.util.Serializer
/** Stores OsmQuest objects - quests and answers to these for adding data to OSM.
*
* This is just a simple CRUD-like DAO, use OsmQuestController to access the data from the
* application logic.
* */
internal class OsmQuestDao @Inject constructor(
private val dbHelper: SQLiteOpenHelper,
private val mapping: OsmQuestMapping
) {
private val db get() = dbHelper.writableDatabase
fun add(quest: OsmQuest): Boolean {
return addAll(listOf(quest)) == 1
}
fun get(id: Long): OsmQuest? {
return db.queryOne(NAME_MERGED_VIEW, null, "$QUEST_ID = $id") { mapping.toObject(it) }
}
fun update(quest: OsmQuest): Boolean {
quest.lastUpdate = Date()
return db.update(NAME, mapping.toUpdatableContentValues(quest), "$QUEST_ID = ${quest.id}", null) == 1
}
fun updateAll(quests: List<OsmQuest>): Int {
var rows = 0
db.transaction {
quests.forEach {
if (update(it)) rows++
}
}
return rows
}
fun delete(id: Long): Boolean {
return db.delete(NAME, "$QUEST_ID = $id", null) == 1
}
fun addAll(quests: Collection<OsmQuest>): Int {
var addedRows = 0
db.transaction {
for (quest in quests) {
quest.lastUpdate = Date()
val rowId = db.insertWithOnConflict(NAME, null, mapping.toContentValues(quest), CONFLICT_IGNORE)
if (rowId != -1L) {
quest.id = rowId
addedRows++
}
}
}
return addedRows
}
fun deleteAllIds(ids: Collection<Long>): Int {
return db.delete(NAME, "$QUEST_ID IN (${ids.joinToString(",")})", null)
}
fun getLastSolved(): OsmQuest? {
val qb = createQuery(statusIn = listOf(HIDDEN, ANSWERED, CLOSED))
return db.queryOne(NAME_MERGED_VIEW, null, qb, "$LAST_UPDATE DESC") { mapping.toObject(it) }
}
fun getAll(
statusIn: Collection<QuestStatus>? = null,
bounds: BoundingBox? = null,
element: ElementKey? = null,
questTypes: Collection<String>? = null,
changedBefore: Long? = null
): List<OsmQuest> {
val qb = createQuery(statusIn, bounds, element, questTypes, changedBefore)
return db.query(NAME_MERGED_VIEW, null, qb) { mapping.toObject(it) }.filterNotNull()
}
fun getAllIds(
statusIn: Collection<QuestStatus>? = null,
bounds: BoundingBox? = null,
element: ElementKey? = null,
questTypes: Collection<String>? = null,
changedBefore: Long? = null
): List<Long> {
val qb = createQuery(statusIn, bounds, element, questTypes, changedBefore)
return db.query(NAME_MERGED_VIEW, arrayOf(QUEST_ID), qb) { it.getLong(0) }
}
fun getCount(
statusIn: Collection<QuestStatus>? = null,
bounds: BoundingBox? = null,
element: ElementKey? = null,
questTypes: Collection<String>? = null,
changedBefore: Long? = null
): Int {
val qb = createQuery(statusIn, bounds, element, questTypes, changedBefore)
return db.queryOne(NAME_MERGED_VIEW, arrayOf("COUNT(*)"), qb) { it.getInt(0) } ?: 0
}
fun deleteAll(
statusIn: Collection<QuestStatus>? = null,
bounds: BoundingBox? = null,
element: ElementKey? = null,
questTypes: Collection<String>? = null,
changedBefore: Long? = null
): Int {
val qb = createQuery(statusIn, bounds, element, questTypes, changedBefore)
return db.delete(NAME, qb.where, qb.args)
}
}
private fun createQuery(
statusIn: Collection<QuestStatus>? = null,
bounds: BoundingBox? = null,
element: ElementKey? = null,
questTypes: Collection<String>? = null,
changedBefore: Long? = null
) = WhereSelectionBuilder().apply {
if (element != null) {
add("$ELEMENT_TYPE = ?", element.elementType.name)
add("$ELEMENT_ID = ?", element.elementId.toString())
}
if (statusIn != null) {
require(statusIn.isNotEmpty()) { "statusIn must not be empty if not null" }
if (statusIn.size == 1) {
add("$QUEST_STATUS = ?", statusIn.single().name)
} else {
val names = statusIn.joinToString(",") { "\"$it\"" }
add("$QUEST_STATUS IN ($names)")
}
}
if (questTypes != null) {
require(questTypes.isNotEmpty()) { "questTypes must not be empty if not null" }
if (questTypes.size == 1) {
add("$QUEST_TYPE = ?", questTypes.single())
} else {
val names = questTypes.joinToString(",") { "\"$it\"" }
add("$QUEST_TYPE IN ($names)")
}
}
if (bounds != null) {
add(
"(${ElementGeometryTable.Columns.LATITUDE} BETWEEN ? AND ?)",
bounds.minLatitude.toString(),
bounds.maxLatitude.toString()
)
add(
"(${ElementGeometryTable.Columns.LONGITUDE} BETWEEN ? AND ?)",
bounds.minLongitude.toString(),
bounds.maxLongitude.toString()
)
}
if (changedBefore != null) {
add("$LAST_UPDATE < ?", changedBefore.toString())
}
}
class OsmQuestMapping @Inject constructor(
private val serializer: Serializer,
private val questTypeRegistry: QuestTypeRegistry,
private val elementGeometryMapping: ElementGeometryMapping
) : ObjectRelationalMapping<OsmQuest?> {
override fun toContentValues(obj: OsmQuest?) =
obj?.let { toConstantContentValues(it) + toUpdatableContentValues(it) } ?: contentValuesOf()
override fun toObject(cursor: Cursor): OsmQuest? {
val questType = questTypeRegistry.getByName(cursor.getString(QUEST_TYPE)) ?: return null
return OsmQuest(
cursor.getLong(QUEST_ID),
questType as OsmElementQuestType<*>,
Element.Type.valueOf(cursor.getString(ELEMENT_TYPE)),
cursor.getLong(ELEMENT_ID),
valueOf(cursor.getString(QUEST_STATUS)),
cursor.getBlobOrNull(TAG_CHANGES)?.let { serializer.toObject<StringMapChanges>(it) },
cursor.getStringOrNull(CHANGES_SOURCE),
Date(cursor.getLong(LAST_UPDATE)),
elementGeometryMapping.toObject(cursor)
)
}
fun toUpdatableContentValues(obj: OsmQuest) = contentValuesOf(
QUEST_STATUS to obj.status.name,
TAG_CHANGES to obj.changes?.let { serializer.toBytes(it) },
CHANGES_SOURCE to obj.changesSource,
LAST_UPDATE to obj.lastUpdate.time
)
private fun toConstantContentValues(obj: OsmQuest) = contentValuesOf(
QUEST_ID to obj.id,
QUEST_TYPE to obj.type.javaClass.simpleName,
ELEMENT_TYPE to obj.elementType.name,
ELEMENT_ID to obj.elementId
)
}
| gpl-3.0 | f3deea132e4f6c18417a71354b8f0eea | 38.446429 | 112 | 0.652784 | 4.444668 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/secondaryConstructors/basicNoPrimaryOneSink.kt | 5 | 990 | internal var sideEffects: String = ""
internal class A {
var prop: String = ""
init {
sideEffects += prop + "first"
}
constructor() {}
constructor(x: String): this() {
prop = x
sideEffects += "#third"
}
init {
sideEffects += prop + "#second"
}
constructor(x: Int): this(x.toString()) {
prop += "#int"
sideEffects += "#fourth"
}
}
fun box(): String {
val a1 = A("abc")
if (a1.prop != "abc") return "fail1: ${a1.prop}"
if (sideEffects != "first#second#third") return "fail1-sideEffects: ${sideEffects}"
sideEffects = ""
val a2 = A(123)
if (a2.prop != "123#int") return "fail2: ${a2.prop}"
if (sideEffects != "first#second#third#fourth") return "fail2-sideEffects: ${sideEffects}"
sideEffects = ""
val a3 = A()
if (a3.prop != "") return "fail2: ${a3.prop}"
if (sideEffects != "first#second") return "fail3-sideEffects: ${sideEffects}"
return "OK"
}
| apache-2.0 | 1aad023be190be2f9a4f499972c050ce | 23.146341 | 94 | 0.552525 | 3.510638 | false | false | false | false |
da1z/intellij-community | platform/projectModel-impl/src/com/intellij/configurationStore/SchemeManagerIprProvider.kt | 1 | 2948 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.*
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.text.UniqueNameGenerator
import org.jdom.Element
import java.io.InputStream
import java.util.*
class SchemeManagerIprProvider(private val subStateTagName: String) : StreamProvider {
private val nameToData = ContainerUtil.newConcurrentMap<String, ByteArray>()
override fun read(fileSpec: String, roamingType: RoamingType, consumer: (InputStream?) -> Unit): Boolean {
nameToData.get(PathUtilRt.getFileName(fileSpec))?.let(ByteArray::inputStream).let { consumer(it) }
return true
}
override fun delete(fileSpec: String, roamingType: RoamingType): Boolean {
nameToData.remove(PathUtilRt.getFileName(fileSpec))
return true
}
override fun processChildren(path: String,
roamingType: RoamingType,
filter: (String) -> Boolean,
processor: (String, InputStream, Boolean) -> Boolean): Boolean {
for ((name, data) in nameToData) {
if (filter(name) && !data.inputStream().use { processor(name, it, false) }) {
break
}
}
return true
}
override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) {
LOG.assertTrue(content.isNotEmpty())
nameToData.put(PathUtilRt.getFileName(fileSpec), ArrayUtil.realloc(content, size))
}
fun load(state: Element?, nameGetter: ((Element) -> String)? = null) {
nameToData.clear()
if (state == null) {
return
}
val nameGenerator = UniqueNameGenerator()
for (child in state.getChildren(subStateTagName)) {
// https://youtrack.jetbrains.com/issue/RIDER-10052
// ignore empty elements
if (child.isEmpty()) {
continue
}
var name = nameGetter?.invoke(child) ?: child.getAttributeValue("name")
if (name == null) {
for (optionElement in child.getChildren("option")) {
if (optionElement.getAttributeValue("name") == "myName") {
name = optionElement.getAttributeValue("value")
}
}
}
if (name.isNullOrEmpty()) {
continue
}
nameToData.put(nameGenerator.generateUniqueName("${FileUtil.sanitizeFileName(name, false)}.xml"), child.toByteArray())
}
}
fun writeState(state: Element, comparator: Comparator<String>? = null) {
val names = nameToData.keys.toTypedArray()
if (comparator == null) {
names.sort()
}
else {
names.sortWith(comparator)
}
for (name in names) {
nameToData.get(name)?.let { state.addContent(loadElement(it.inputStream())) }
}
}
} | apache-2.0 | 214866a064f6d75e6521fd1160cbfe03 | 32.896552 | 140 | 0.664179 | 4.487062 | false | false | false | false |
y20k/trackbook | app/src/main/java/org/y20k/trackbook/dialogs/RenameTrackDialog.kt | 1 | 2594 | /*
* RenameTrackDialog.kt
* Implements the RenameTrackDialog class
* A RenameTrackDialog offers user to change name of track
*
* This file is part of
* TRACKBOOK - Movement Recorder for Android
*
* Copyright (c) 2016-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*
* Trackbook uses osmdroid - OpenStreetMap-Tools for Android
* https://github.com/osmdroid/osmdroid
*/
package org.y20k.trackbook.dialogs
import android.content.Context
import android.text.InputType
import android.view.LayoutInflater
import android.widget.EditText
import android.widget.TextView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.y20k.trackbook.R
import org.y20k.trackbook.helpers.LogHelper
/*
* RenameTrackDialog class
*/
class RenameTrackDialog (private var renameTrackListener: RenameTrackListener) {
/* Interface used to communicate back to activity */
interface RenameTrackListener {
fun onRenameTrackDialog(textInput: String) {
}
}
/* Define log tag */
private val TAG = LogHelper.makeLogTag(RenameTrackDialog::class.java.simpleName)
/* Construct and show dialog */
fun show(context: Context, trackName: String) {
// prepare dialog builder
val builder: MaterialAlertDialogBuilder = MaterialAlertDialogBuilder(context, R.style.AlertDialogTheme)
// get input field
val inflater = LayoutInflater.from(context)
val view = inflater.inflate(R.layout.dialog_rename_track, null)
val inputField = view.findViewById<EditText>(R.id.dialog_rename_track_input_edit_text)
// pre-fill with current track name
inputField.setText(trackName, TextView.BufferType.EDITABLE)
inputField.setSelection(trackName.length)
inputField.inputType = InputType.TYPE_CLASS_TEXT
// set dialog view
builder.setView(view)
// add "add" button
builder.setPositiveButton(R.string.dialog_rename_track_button) { _, _ ->
// hand text over to initiating activity
inputField.text?.let {
var newStationName: String = it.toString()
if (newStationName.isEmpty()) newStationName = trackName
renameTrackListener.onRenameTrackDialog(newStationName)
}
}
// add cancel button
builder.setNegativeButton(R.string.dialog_generic_button_cancel) { _, _ ->
// listen for click on cancel button
// do nothing
}
// display add dialog
builder.show()
}
} | mit | e1d1d09e8c40f350cf79d15304c14a33 | 30.26506 | 111 | 0.687355 | 4.623886 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/notifications/service/delegates/ExpoSchedulingDelegate.kt | 2 | 4377 | package abi42_0_0.expo.modules.notifications.service.delegates
import android.app.AlarmManager
import android.content.Context
import android.util.Log
import androidx.core.app.AlarmManagerCompat
import expo.modules.notifications.notifications.interfaces.SchedulableNotificationTrigger
import expo.modules.notifications.notifications.model.Notification
import expo.modules.notifications.notifications.model.NotificationRequest
import abi42_0_0.expo.modules.notifications.service.NotificationsService
import abi42_0_0.expo.modules.notifications.service.interfaces.SchedulingDelegate
import java.io.IOException
import java.io.InvalidClassException
class ExpoSchedulingDelegate(protected val context: Context) : SchedulingDelegate {
protected val store = SharedPreferencesNotificationsStore(context)
protected val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
override fun setupScheduledNotifications() {
store.allNotificationRequests.forEach {
try {
scheduleNotification(it)
} catch (e: Exception) {
Log.w("expo-notifications", "Notification ${it.identifier} could not have been scheduled: ${e.message}")
e.printStackTrace()
}
}
}
override fun getAllScheduledNotifications(): Collection<NotificationRequest> =
store.allNotificationRequests
override fun getScheduledNotification(identifier: String): NotificationRequest? = try {
store.getNotificationRequest(identifier)
} catch (e: IOException) {
null
} catch (e: ClassNotFoundException) {
null
} catch (e: NullPointerException) {
null
}
override fun scheduleNotification(request: NotificationRequest) {
// If the trigger is empty, handle receive immediately and return.
if (request.trigger == null) {
NotificationsService.receive(context, Notification(request))
return
}
if (request.trigger !is SchedulableNotificationTrigger) {
throw IllegalArgumentException("Notification request \"${request.identifier}\" does not have a schedulable trigger (it's ${request.trigger}). Refusing to schedule.")
}
(request.trigger as SchedulableNotificationTrigger).nextTriggerDate().let { nextTriggerDate ->
if (nextTriggerDate == null) {
Log.d("expo-notifications", "Notification request \"${request.identifier}\" will not trigger in the future, removing.")
NotificationsService.removeScheduledNotification(context, request.identifier)
} else {
store.saveNotificationRequest(request)
AlarmManagerCompat.setExactAndAllowWhileIdle(
alarmManager,
AlarmManager.RTC_WAKEUP,
nextTriggerDate.time,
NotificationsService.createNotificationTrigger(context, request.identifier)
)
}
}
}
override fun triggerNotification(identifier: String) {
try {
val notificationRequest: NotificationRequest = store.getNotificationRequest(identifier)!!
NotificationsService.receive(context, Notification(notificationRequest))
NotificationsService.schedule(context, notificationRequest)
} catch (e: ClassNotFoundException) {
Log.e("expo-notifications", "An exception occurred while triggering notification " + identifier + ", removing. " + e.message)
e.printStackTrace()
NotificationsService.removeScheduledNotification(context, identifier)
} catch (e: InvalidClassException) {
Log.e("expo-notifications", "An exception occurred while triggering notification " + identifier + ", removing. " + e.message)
e.printStackTrace()
NotificationsService.removeScheduledNotification(context, identifier)
} catch (e: NullPointerException) {
Log.e("expo-notifications", "An exception occurred while triggering notification " + identifier + ", removing. " + e.message)
e.printStackTrace()
NotificationsService.removeScheduledNotification(context, identifier)
}
}
override fun removeScheduledNotifications(identifiers: Collection<String>) {
identifiers.forEach {
alarmManager.cancel(NotificationsService.createNotificationTrigger(context, it))
store.removeNotificationRequest(it)
}
}
override fun removeAllScheduledNotifications() {
store.removeAllNotificationRequests().forEach {
alarmManager.cancel(NotificationsService.createNotificationTrigger(context, it))
}
}
}
| bsd-3-clause | 60bbcee3e441bf7f9e8539fc1bac5643 | 41.911765 | 171 | 0.752799 | 5.363971 | false | false | false | false |
jainsahab/AndroidSnooper | Snooper/src/main/java/com/prateekj/snooper/networksnooper/database/SnooperRepo.kt | 1 | 8980 | package com.prateekj.snooper.networksnooper.database
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import com.prateekj.snooper.database.SnooperDbHelper
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_DATE
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_ERROR
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_HEADER_ID
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_HEADER_NAME
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_HEADER_TYPE
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_HEADER_VALUE
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_HTTP_CALL_RECORD_ID
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_METHOD
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_PAYLOAD
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_RESPONSE_BODY
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_STATUSCODE
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_STATUSTEXT
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.COLUMN_URL
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HEADER_TABLE_NAME
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HEADER_VALUE_TABLE_NAME
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_CALL_RECORD_GET_BY_ID
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_CALL_RECORD_GET_NEXT_SORT_BY_DATE_WITH_SIZE
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_CALL_RECORD_GET_SORT_BY_DATE
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_CALL_RECORD_GET_SORT_BY_DATE_WITH_SIZE
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_CALL_RECORD_SEARCH
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_CALL_RECORD_TABLE_NAME
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_HEADER_GET_BY_CALL_ID
import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_HEADER_VALUE_GET_BY_HEADER_ID
import com.prateekj.snooper.networksnooper.model.HttpCallRecord
import com.prateekj.snooper.networksnooper.model.HttpHeader
import com.prateekj.snooper.networksnooper.model.HttpHeaderValue
import java.util.ArrayList
class SnooperRepo(context: Context) {
private val dbWriteHelper: SnooperDbHelper = SnooperDbHelper.create(context)
private val dbReadHelper: SnooperDbHelper = SnooperDbHelper.create(context)
fun save(httpCallRecord: HttpCallRecord): Long {
val database = dbWriteHelper.writableDatabase
val values = ContentValues()
values.put(COLUMN_URL, httpCallRecord.url)
values.put(COLUMN_PAYLOAD, httpCallRecord.payload)
values.put(COLUMN_RESPONSE_BODY, httpCallRecord.responseBody)
values.put(COLUMN_METHOD, httpCallRecord.method)
values.put(COLUMN_STATUSCODE, httpCallRecord.statusCode)
values.put(COLUMN_STATUSTEXT, httpCallRecord.statusText)
values.put(COLUMN_DATE, httpCallRecord.date!!.time)
values.put(COLUMN_ERROR, httpCallRecord.error)
val httpCallRecordId = database.insert(HTTP_CALL_RECORD_TABLE_NAME, null, values)
try {
database.beginTransaction()
saveHeaders(database, httpCallRecordId, httpCallRecord.requestHeaders!!, "req")
saveHeaders(database, httpCallRecordId, httpCallRecord.responseHeaders!!, "res")
database.setTransactionSuccessful()
} finally {
database.endTransaction()
database.close()
}
return httpCallRecordId
}
fun findAllSortByDate(): List<HttpCallRecord> {
val httpCallRecords = ArrayList<HttpCallRecord>()
val cursorParser = HttpCallRecordCursorParser()
val database = dbReadHelper.readableDatabase
val cursor = database.rawQuery(HTTP_CALL_RECORD_GET_SORT_BY_DATE, null)
while (cursor.moveToNext()) {
httpCallRecords.add(cursorParser.parse(cursor))
}
cursor.close()
database.close()
return httpCallRecords
}
fun searchHttpRecord(text: String): List<HttpCallRecord> {
val httpCallRecords = ArrayList<HttpCallRecord>()
val cursorParser = HttpCallRecordCursorParser()
val database = dbReadHelper.readableDatabase
val cursor = database.rawQuery(
HTTP_CALL_RECORD_SEARCH,
arrayOf(likeParam(text), likeParam(text), likeParam(text), likeParam(text))
)
while (cursor.moveToNext()) {
httpCallRecords.add(cursorParser.parse(cursor))
}
cursor.close()
database.close()
return httpCallRecords
}
private fun likeParam(text: String): String {
return "%$text%"
}
fun findAllSortByDateAfter(id: Long, pageSize: Int): MutableList<HttpCallRecord> {
val httpCallRecords = ArrayList<HttpCallRecord>()
val cursorParser = HttpCallRecordCursorParser()
val database = dbReadHelper.readableDatabase
val cursor: Cursor
cursor = if (id == -1L) {
database.rawQuery(
HTTP_CALL_RECORD_GET_SORT_BY_DATE_WITH_SIZE,
arrayOf(pageSize.toString())
)
} else {
database.rawQuery(
HTTP_CALL_RECORD_GET_NEXT_SORT_BY_DATE_WITH_SIZE,
arrayOf(id.toString(), pageSize.toString())
)
}
while (cursor.moveToNext()) {
httpCallRecords.add(cursorParser.parse(cursor))
}
cursor.close()
database.close()
return httpCallRecords
}
fun findById(id: Long): HttpCallRecord {
val database = dbReadHelper.readableDatabase
val cursorParser = HttpCallRecordCursorParser()
val cursor =
database.rawQuery(HTTP_CALL_RECORD_GET_BY_ID, arrayOf(java.lang.Long.toString(id)))
cursor.moveToNext()
val httpCallRecord = cursorParser.parse(cursor)
httpCallRecord.requestHeaders = findHeader(database, httpCallRecord.id, "req")
httpCallRecord.responseHeaders = findHeader(database, httpCallRecord.id, "res")
database.close()
return httpCallRecord
}
fun deleteAll() {
val database = dbWriteHelper.writableDatabase
try {
database.beginTransaction()
database.delete(HTTP_CALL_RECORD_TABLE_NAME, null, null)
database.setTransactionSuccessful()
} finally {
database.endTransaction()
database.close()
}
}
private fun findHeader(
database: SQLiteDatabase,
callId: Long,
headerType: String
): List<HttpHeader> {
val httpHeaders = ArrayList<HttpHeader>()
val cursorParser = HttpHeaderCursorParser()
val cursor = database.rawQuery(
HTTP_HEADER_GET_BY_CALL_ID,
arrayOf(callId.toString(), headerType)
)
while (cursor.moveToNext()) {
val httpHeader = cursorParser.parse(cursor)
httpHeader.values = findHeaderValue(database, httpHeader.id)
httpHeaders.add(httpHeader)
}
cursor.close()
return httpHeaders
}
private fun findHeaderValue(database: SQLiteDatabase, headerId: Int): List<HttpHeaderValue> {
val httpHeaderValues = ArrayList<HttpHeaderValue>()
val cursorParser = HttpHeaderValueCursorParser()
val cursor = database.rawQuery(
HTTP_HEADER_VALUE_GET_BY_HEADER_ID,
arrayOf(Integer.toString(headerId))
)
while (cursor.moveToNext()) {
httpHeaderValues.add(cursorParser.parse(cursor))
}
cursor.close()
return httpHeaderValues
}
private fun saveHeaders(
database: SQLiteDatabase,
httpCallRecordId: Long,
requestHeaders: List<HttpHeader>,
headerType: String
) {
for (httpHeader in requestHeaders) {
saveHeader(database, httpHeader, httpCallRecordId, headerType)
}
}
private fun saveHeader(
database: SQLiteDatabase,
httpHeader: HttpHeader,
httpCallRecordId: Long,
headerType: String
) {
val values = ContentValues()
values.put(COLUMN_HEADER_NAME, httpHeader.name)
values.put(COLUMN_HEADER_TYPE, headerType)
values.put(COLUMN_HTTP_CALL_RECORD_ID, httpCallRecordId)
val headerId = database.insert(HEADER_TABLE_NAME, null, values)
for (httpHeaderValue in httpHeader.values) {
saveHeaderValue(database, httpHeaderValue, headerId)
}
}
private fun saveHeaderValue(database: SQLiteDatabase, value: HttpHeaderValue, headerId: Long) {
val values = ContentValues()
values.put(COLUMN_HEADER_VALUE, value.value)
values.put(COLUMN_HEADER_ID, headerId)
database.insert(HEADER_VALUE_TABLE_NAME, null, values)
}
}
| apache-2.0 | 4c502fd3389741556785483da76270c7 | 40.382488 | 133 | 0.768374 | 4.544534 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/blockingCallsDetection/CoroutineNonBlockingContextChecker.kt | 3 | 11060 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.blockingCallsDetection
import com.intellij.codeInspection.blockingCallsDetection.ContextType
import com.intellij.codeInspection.blockingCallsDetection.ContextType.*
import com.intellij.codeInspection.blockingCallsDetection.ElementContext
import com.intellij.codeInspection.blockingCallsDetection.NonBlockingContextChecker
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiRecursiveElementVisitor
import com.intellij.psi.util.parentsOfType
import com.intellij.util.castSafelyTo
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.builtins.getReceiverTypeFromFunctionType
import org.jetbrains.kotlin.builtins.isBuiltinFunctionalType
import org.jetbrains.kotlin.builtins.isSuspendFunctionType
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.core.receiverValue
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.BLOCKING_EXECUTOR_ANNOTATION
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.COROUTINE_CONTEXT
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.COROUTINE_SCOPE
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.DEFAULT_DISPATCHER_FQN
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.FLOW_PACKAGE_FQN
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.IO_DISPATCHER_FQN
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.MAIN_DISPATCHER_FQN
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.NONBLOCKING_EXECUTOR_ANNOTATION
import org.jetbrains.kotlin.idea.inspections.blockingCallsDetection.CoroutineBlockingCallInspectionUtils.findFlowOnCall
import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypes
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.checkers.isRestrictsSuspensionReceiver
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
import org.jetbrains.kotlin.types.KotlinType
class CoroutineNonBlockingContextChecker : NonBlockingContextChecker {
override fun isApplicable(file: PsiFile): Boolean {
if (file !is KtFile) return false
val languageVersionSettings = getLanguageVersionSettings(file)
return languageVersionSettings.supportsFeature(LanguageFeature.ReleaseCoroutines)
}
override fun computeContextType(elementContext: ElementContext): ContextType {
val element = elementContext.element
if (element !is KtCallExpression) return Unsure
val containingLambda = element.parents
.filterIsInstance<KtLambdaExpression>()
.firstOrNull()
val containingArgument = containingLambda?.getParentOfType<KtValueArgument>(true, KtCallableDeclaration::class.java)
if (containingArgument != null) {
val callExpression = containingArgument.getStrictParentOfType<KtCallExpression>() ?: return Blocking
val call = callExpression.resolveToCall(BodyResolveMode.PARTIAL) ?: return Blocking
val blockingFriendlyDispatcherUsed = checkBlockingFriendlyDispatcherUsed(call, callExpression)
if (blockingFriendlyDispatcherUsed.isDefinitelyKnown) return blockingFriendlyDispatcherUsed
val parameterForArgument = call.getParameterForArgument(containingArgument) ?: return Blocking
val type = parameterForArgument.returnType ?: return Blocking
if (type.isBuiltinFunctionalType) {
val hasRestrictSuspensionAnnotation = type.getReceiverTypeFromFunctionType()?.isRestrictsSuspensionReceiver() ?: false
return if (!hasRestrictSuspensionAnnotation && type.isSuspendFunctionType) NonBlocking.INSTANCE else Blocking
}
}
if (containingLambda == null) {
val isInSuspendFunctionBody = element.parentsOfType<KtNamedFunction>()
.take(2)
.firstOrNull { function -> function.nameIdentifier != null }
?.hasModifier(KtTokens.SUSPEND_KEYWORD) ?: false
return if (isInSuspendFunctionBody) NonBlocking.INSTANCE else Blocking
}
val containingPropertyOrFunction: KtCallableDeclaration? =
containingLambda.getParentOfTypes(true, KtProperty::class.java, KtNamedFunction::class.java)
if (containingPropertyOrFunction?.typeReference?.hasModifier(KtTokens.SUSPEND_KEYWORD) == true) return NonBlocking.INSTANCE
return if (containingPropertyOrFunction?.hasModifier(KtTokens.SUSPEND_KEYWORD) == true) NonBlocking.INSTANCE else Blocking
}
private fun checkBlockingFriendlyDispatcherUsed(
call: ResolvedCall<out CallableDescriptor>,
callExpression: KtCallExpression
): ContextType {
return union(
{ checkBlockFriendlyDispatcherParameter(call) },
{ checkFunctionWithDefaultDispatcher(callExpression) },
{ checkFlowChainElementWithIODispatcher(call, callExpression) }
)
}
private fun getLanguageVersionSettings(psiElement: PsiElement): LanguageVersionSettings =
psiElement.module?.languageVersionSettings ?: psiElement.project.languageVersionSettings
private fun ResolvedCall<*>.getFirstArgument(): KtExpression? =
valueArgumentsByIndex?.firstOrNull()?.arguments?.firstOrNull()?.getArgumentExpression()
private fun KotlinType.isCoroutineContext(): Boolean =
(this.constructor.supertypes + this).any { it.fqName?.asString() == COROUTINE_CONTEXT }
private fun checkBlockFriendlyDispatcherParameter(call: ResolvedCall<*>): ContextType {
val argumentDescriptor = call.getFirstArgument()?.resolveToCall()?.resultingDescriptor ?: return Unsure
return argumentDescriptor.isBlockFriendlyDispatcher()
}
private fun checkFunctionWithDefaultDispatcher(callExpression: KtCallExpression): ContextType {
val classDescriptor =
callExpression.receiverValue().castSafelyTo<ImplicitClassReceiver>()?.classDescriptor ?: return Unsure
if (classDescriptor.typeConstructor.supertypes.none { it.fqName?.asString() == COROUTINE_SCOPE }) return Unsure
val propertyDescriptor = classDescriptor
.unsubstitutedMemberScope
.getContributedDescriptors(DescriptorKindFilter.VARIABLES)
.filterIsInstance<PropertyDescriptor>()
.singleOrNull { it.isOverridableOrOverrides && it.type.isCoroutineContext() }
?: return Unsure
val initializer = propertyDescriptor.findPsi().castSafelyTo<KtProperty>()?.initializer ?: return Unsure
return initializer.hasBlockFriendlyDispatcher()
}
private fun checkFlowChainElementWithIODispatcher(
call: ResolvedCall<out CallableDescriptor>,
callExpression: KtCallExpression
): ContextType {
val isInsideFlow = call.resultingDescriptor.fqNameSafe.asString().startsWith(FLOW_PACKAGE_FQN)
if (!isInsideFlow) return Unsure
val flowOnCall = callExpression.findFlowOnCall() ?: return NonBlocking.INSTANCE
return checkBlockFriendlyDispatcherParameter(flowOnCall)
}
private fun KtExpression.hasBlockFriendlyDispatcher(): ContextType {
class RecursiveExpressionVisitor : PsiRecursiveElementVisitor() {
var allowsBlocking: ContextType = Unsure
override fun visitElement(element: PsiElement) {
if (element is KtExpression) {
val callableDescriptor = element.getCallableDescriptor()
val allowsBlocking = callableDescriptor.castSafelyTo<DeclarationDescriptor>()
?.isBlockFriendlyDispatcher()
if (allowsBlocking != null && allowsBlocking != Unsure) {
this.allowsBlocking = allowsBlocking
return
}
}
super.visitElement(element)
}
}
return RecursiveExpressionVisitor().also(this::accept).allowsBlocking
}
private fun DeclarationDescriptor?.isBlockFriendlyDispatcher(): ContextType {
if (this == null) return Unsure
val returnTypeDescriptor = this.castSafelyTo<CallableDescriptor>()?.returnType
val typeConstructor = returnTypeDescriptor?.constructor?.declarationDescriptor
if (isTypeOrUsageAnnotatedWith(returnTypeDescriptor, typeConstructor, BLOCKING_EXECUTOR_ANNOTATION)) return Blocking
if (isTypeOrUsageAnnotatedWith(returnTypeDescriptor, typeConstructor, NONBLOCKING_EXECUTOR_ANNOTATION)) return NonBlocking.INSTANCE
val fqnOrNull = fqNameOrNull()?.asString() ?: return NonBlocking.INSTANCE
return when(fqnOrNull) {
IO_DISPATCHER_FQN -> Blocking
MAIN_DISPATCHER_FQN, DEFAULT_DISPATCHER_FQN -> NonBlocking.INSTANCE
else -> Unsure
}
}
private fun isTypeOrUsageAnnotatedWith(type: KotlinType?, typeConstructor: ClassifierDescriptor?, annotationFqn: String): Boolean {
val fqName = FqName(annotationFqn)
return when {
type?.annotations?.hasAnnotation(fqName) == true -> true
typeConstructor?.annotations?.hasAnnotation(fqName) == true -> true
else -> false
}
}
private fun union(vararg checks: () -> ContextType): ContextType {
for (check in checks) {
val iterationResult = check()
if (iterationResult != Unsure) return iterationResult
}
return Unsure
}
} | apache-2.0 | f01ea99b77558148bbce810585195deb | 53.487685 | 158 | 0.758951 | 5.870488 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/interpret/module/ModuleLisp.kt | 1 | 925 | package com.bajdcc.LALR1.interpret.module
import com.bajdcc.LALR1.grammar.Grammar
import com.bajdcc.LALR1.grammar.runtime.RuntimeCodePage
import com.bajdcc.util.ResourceLoader
/**
* 【模块】LISP
*
* @author bajdcc
*/
class ModuleLisp : IInterpreterModule {
private var runtimeCodePage: RuntimeCodePage? = null
override val moduleName: String
get() = "module.lisp"
override val moduleCode: String
get() = ResourceLoader.load(javaClass)
override val codePage: RuntimeCodePage
@Throws(Exception::class)
get() {
if (runtimeCodePage != null)
return runtimeCodePage!!
val base = ResourceLoader.load(javaClass)
val grammar = Grammar(base)
val page = grammar.codePage
runtimeCodePage = page
return page
}
companion object {
val instance = ModuleLisp()
}
} | mit | b5b8331d9d351c43bbeea85b1e555d17 | 21.95 | 56 | 0.63795 | 4.585 | false | false | false | false |
Maccimo/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/ide/impl/IdeDocumentationTargetProviderImpl.kt | 3 | 2234 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.lang.documentation.ide.impl
import com.intellij.codeInsight.documentation.DocumentationManager
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.lang.documentation.DocumentationTarget
import com.intellij.lang.documentation.ide.IdeDocumentationTargetProvider
import com.intellij.lang.documentation.psi.psiDocumentationTarget
import com.intellij.lang.documentation.symbol.impl.symbolDocumentationTargets
import com.intellij.model.Pointer
import com.intellij.model.Symbol
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.component1
import com.intellij.openapi.util.component2
import com.intellij.psi.PsiFile
import com.intellij.util.castSafelyTo
open class IdeDocumentationTargetProviderImpl(private val project: Project) : IdeDocumentationTargetProvider {
override fun documentationTarget(editor: Editor, file: PsiFile, lookupElement: LookupElement): DocumentationTarget? {
val symbolTargets = (lookupElement.`object` as? Pointer<*>)
?.dereference()
?.castSafelyTo<Symbol>()
?.let { symbolDocumentationTargets(file.project, listOf(it)) }
if (!symbolTargets.isNullOrEmpty()) {
return symbolTargets.first()
}
val sourceElement = file.findElementAt(editor.caretModel.offset)
val targetElement = DocumentationManager.getElementFromLookup(project, editor, file, lookupElement)
?: return null
return psiDocumentationTarget(targetElement, sourceElement)
}
override fun documentationTargets(editor: Editor, file: PsiFile, offset: Int): List<DocumentationTarget> {
val symbolTargets = symbolDocumentationTargets(file, offset)
if (symbolTargets.isNotEmpty()) {
return symbolTargets
}
val documentationManager = DocumentationManager.getInstance(project)
val (targetElement, sourceElement) = documentationManager.findTargetElementAndContext(editor, offset, file)
?: return emptyList()
return listOf(psiDocumentationTarget(targetElement, sourceElement))
}
}
| apache-2.0 | 451d99552fe24e5e312c97ce7c9db3f5 | 47.565217 | 120 | 0.779767 | 4.975501 | false | false | false | false |
xiaofei-dev/NineGrid | app/src/main/java/com/github/xiaofei_dev/ninegrid/extensions/util.kt | 1 | 2998 | package com.github.xiaofei_dev.ninegrid.extensions
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.widget.Toast
/**
* Created by xiaofei on 2017/7/19.
*/
object ToastUtil {
private var toast: Toast? = null
fun showToast(context: Context, content: String) {
if (toast == null) {
toast = Toast.makeText(context,
content,
Toast.LENGTH_LONG)
} else {
toast!!.setText(content)
}
toast!!.show()
}
fun showToast(context: Context, content: Int) {
if (toast == null) {
toast = Toast.makeText(context,
content,
Toast.LENGTH_LONG)
} else {
toast!!.setText(content)
}
toast!!.show()
}
}
object OpenUtil {
fun openApplicationMarket(appPackageName: String, marketPackageName: String?,
context: Context) {
try {
val url = "market://details?id=" + appPackageName
val localIntent = Intent(Intent.ACTION_VIEW)
if (marketPackageName != null) {
localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
localIntent.`package` = marketPackageName
}
openLink(context, localIntent, url, true)
} catch (e: Exception) {
e.printStackTrace()
openApplicationMarketForLinkBySystem(appPackageName, context)
}
}
fun openApplicationMarketForLinkBySystem(packageName: String, context: Context) {
val url = "http://www.coolapk.com/apk/" + packageName
val intent = Intent(Intent.ACTION_VIEW)
openLink(context, intent, url, false)
}
fun openLink(context: Context, intent: Intent?, link: String, isThrowException: Boolean) {
var intent = intent
if (intent == null) {
intent = Intent(Intent.ACTION_VIEW)
}
try {
intent.data = Uri.parse(link)
context.startActivity(intent)
} catch (e: Exception) {
if (isThrowException) {
throw e
} else {
e.printStackTrace()
Toast.makeText(context, "打开失败", Toast.LENGTH_SHORT).show()
}
}
}
//打开自己的支付宝付款链接
fun alipayDonate(context: Context) {
val intent = Intent()
intent.action = "android.intent.action.VIEW"
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
val payUrl = "https://qr.alipay.com/FKX06496G2PCRYR0LXR7BC"
intent.data = Uri.parse("alipayqr://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=" + payUrl)
if (intent.resolveActivity(context.packageManager) != null) {
context.startActivity(intent)
} else {
intent.data = Uri.parse(payUrl)
context.startActivity(intent)
}
}
} | apache-2.0 | 4732f1b78ff8677f6756b34166c2062b | 29.587629 | 122 | 0.570128 | 4.273775 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/StatsListItemDecoration.kt | 1 | 1070 | package org.wordpress.android.ui.stats.refresh.lists
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
data class StatsListItemDecoration(
val horizontalSpacing: Int,
val topSpacing: Int,
val bottomSpacing: Int,
val firstSpacing: Int,
val lastSpacing: Int,
val columnCount: Int
) :
RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
val isFirst = parent.getChildAdapterPosition(view) == 0
val isLast = parent.adapter?.let { parent.getChildAdapterPosition(view) == it.itemCount - 1 } ?: false
outRect.set(
if (columnCount == 1) 2 * horizontalSpacing else horizontalSpacing,
if (isFirst) firstSpacing else topSpacing,
if (columnCount == 1) 2 * horizontalSpacing else horizontalSpacing,
if (isLast) lastSpacing else bottomSpacing
)
}
}
| gpl-2.0 | 0ed4da172f5a68fe7719f842da9e0b3d | 38.62963 | 110 | 0.685981 | 4.734513 | false | false | false | false |
wordpress-mobile/WordPress-Android | libs/image-editor/src/main/kotlin/org/wordpress/android/imageeditor/preview/PreviewImageViewModel.kt | 1 | 16208 | package org.wordpress.android.imageeditor.preview
import android.text.TextUtils
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import org.wordpress.android.imageeditor.ImageEditor
import org.wordpress.android.imageeditor.ImageEditor.EditorAction.EditorFinishedEditing
import org.wordpress.android.imageeditor.ImageEditor.EditorAction.EditorShown
import org.wordpress.android.imageeditor.ImageEditor.EditorAction.PreviewCropMenuClicked
import org.wordpress.android.imageeditor.ImageEditor.EditorAction.PreviewImageSelected
import org.wordpress.android.imageeditor.ImageEditor.EditorAction.PreviewInsertImagesClicked
import org.wordpress.android.imageeditor.R
import org.wordpress.android.imageeditor.preview.PreviewImageFragment.Companion.EditImageData.InputData
import org.wordpress.android.imageeditor.preview.PreviewImageFragment.Companion.EditImageData.OutputData
import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageLoadToFileState.ImageLoadToFileFailedState
import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageLoadToFileState.ImageLoadToFileIdleState
import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageLoadToFileState.ImageLoadToFileSuccessState
import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageLoadToFileState.ImageStartLoadingToFileState
import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageUiState.ImageDataStartLoadingUiState
import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageUiState.ImageInHighResLoadFailedUiState
import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageUiState.ImageInHighResLoadSuccessUiState
import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageUiState.ImageInLowResLoadFailedUiState
import org.wordpress.android.imageeditor.preview.PreviewImageViewModel.ImageUiState.ImageInLowResLoadSuccessUiState
import org.wordpress.android.imageeditor.viewmodel.Event
import java.net.URI
import java.util.Locale
import java.util.UUID
class PreviewImageViewModel : ViewModel() {
private val _uiState: MutableLiveData<UiState> = MutableLiveData()
val uiState: LiveData<UiState> = _uiState
private val _loadIntoFile = MutableLiveData<Event<ImageLoadToFileState>>(Event(ImageLoadToFileIdleState))
val loadIntoFile: LiveData<Event<ImageLoadToFileState>> = _loadIntoFile
private val _navigateToCropScreenWithFileInfo = MutableLiveData<Event<Triple<String, String?, Boolean>>>()
val navigateToCropScreenWithFileInfo: LiveData<Event<Triple<String, String?, Boolean>>> =
_navigateToCropScreenWithFileInfo
private val _finishAction = MutableLiveData<Event<List<OutputData>>>()
val finishAction: LiveData<Event<List<OutputData>>> = _finishAction
private lateinit var imageEditor: ImageEditor
var selectedPosition: Int = 0
private set
var numberOfImages = 0
private set
fun onCreateView(imageDataList: List<InputData>, imageEditor: ImageEditor) {
this.imageEditor = imageEditor
this.numberOfImages = imageDataList.size
if (uiState.value == null) {
imageEditor.onEditorAction(EditorShown(numberOfImages))
val newImageUiStates = createViewPagerItemsInitialUiStates(
convertInputDataToImageData(imageDataList)
)
val currentUiState = UiState(
newImageUiStates,
thumbnailsTabLayoutVisible = !newImageUiStates.hasSingleElement()
)
updateUiState(currentUiState)
}
}
private fun convertInputDataToImageData(imageDataList: List<InputData>): List<ImageData> {
return imageDataList
.map { (highRes, lowRes, extension) ->
ImageData(
highResImageUrl = highRes,
lowResImageUrl = lowRes,
outputFileExtension = extension
)
}
}
fun onLoadIntoImageViewSuccess(imageUrlAtPosition: String, position: Int) {
val newImageUiState = createNewImageUiState(imageUrlAtPosition, position, loadSuccess = true)
val newImageUiStates = updateViewPagerItemsUiStates(newImageUiState, position)
val currentUiState = uiState.value as UiState
val imageStateAtPosition = currentUiState.viewPagerItemsStates[position]
if (currentUiState.viewPagerItemsStates.hasSingleElement() && canLoadToFile(newImageUiState)) {
updateLoadIntoFileState(
ImageStartLoadingToFileState(
imageUrlAtPosition = imageStateAtPosition.data.highResImageUrl,
position = position
)
)
}
val enableEditActions = if (position == selectedPosition) {
shouldEnableEditActionsForImageState(newImageUiState)
} else {
currentUiState.editActionsEnabled
}
updateUiState(
currentUiState.copy(
viewPagerItemsStates = newImageUiStates,
editActionsEnabled = enableEditActions
)
)
}
fun onLoadIntoImageViewFailed(imageUrlAtPosition: String, position: Int) {
val newImageUiState = createNewImageUiState(imageUrlAtPosition, position, loadSuccess = false)
val newImageUiStates = updateViewPagerItemsUiStates(newImageUiState, position)
val currentUiState = uiState.value as UiState
updateUiState(currentUiState.copy(viewPagerItemsStates = newImageUiStates))
}
fun onLoadIntoFileSuccess(inputFilePathAtPosition: String, position: Int) {
val imageStateAtPosition = (uiState.value as UiState).viewPagerItemsStates[position]
val outputFileExtension = imageStateAtPosition.data.outputFileExtension
updateLoadIntoFileState(ImageLoadToFileSuccessState(inputFilePathAtPosition, position))
val currentUiState = uiState.value as UiState
_navigateToCropScreenWithFileInfo.value = Event(
Triple(
inputFilePathAtPosition,
outputFileExtension,
!currentUiState.viewPagerItemsStates.hasSingleElement()
)
)
}
fun onLoadIntoFileFailed(exception: Exception?) {
updateLoadIntoFileState(
ImageLoadToFileFailedState(
exception?.message,
R.string.error_failed_to_load_into_file
)
)
}
fun onCropMenuClicked() {
imageEditor.onEditorAction(PreviewCropMenuClicked)
val highResImageUrl = getHighResImageUrl(selectedPosition)
if (isFileUrl(highResImageUrl)) {
onLoadIntoFileSuccess(
inputFilePathAtPosition = URI(highResImageUrl).path as String,
position = selectedPosition
)
} else {
updateLoadIntoFileState(
ImageStartLoadingToFileState(
imageUrlAtPosition = highResImageUrl,
position = selectedPosition
)
)
}
}
fun onPageSelected(selectedPosition: Int) {
this.selectedPosition = selectedPosition
imageEditor.onEditorAction(PreviewImageSelected(getHighResImageUrl(selectedPosition), selectedPosition))
val currentUiState = uiState.value as UiState
val imageStateAtPosition = currentUiState.viewPagerItemsStates[selectedPosition]
updateUiState(
currentUiState.copy(
editActionsEnabled = shouldEnableEditActionsForImageState(imageStateAtPosition)
)
)
}
private fun onLoadIntoImageViewRetry(selectedImageUrl: String, selectedPosition: Int) {
val newImageUiState = createNewImageUiState(
imageUrlAtPosition = selectedImageUrl,
position = selectedPosition,
loadSuccess = false,
retry = true
)
val newImageUiStates = updateViewPagerItemsUiStates(newImageUiState, selectedPosition)
val currentUiState = uiState.value as UiState
updateUiState(currentUiState.copy(viewPagerItemsStates = newImageUiStates))
}
fun onCropResult(outputFilePath: String) {
val imageStateAtPosition = (uiState.value as UiState).viewPagerItemsStates[selectedPosition]
// Update urls with cache file path
val newImageData = imageStateAtPosition.data.copy(
lowResImageUrl = outputFilePath,
highResImageUrl = outputFilePath
)
val newImageUiState = ImageDataStartLoadingUiState(newImageData)
val newImageUiStates = updateViewPagerItemsUiStates(newImageUiState, selectedPosition)
val currentUiState = uiState.value as UiState
updateUiState(currentUiState.copy(viewPagerItemsStates = newImageUiStates))
}
private fun createViewPagerItemsInitialUiStates(
data: List<ImageData>
): List<ImageUiState> = data.map { createImageLoadStartUiState(it) }
private fun updateViewPagerItemsUiStates(
newImageUiState: ImageUiState,
position: Int
): List<ImageUiState> {
val currentUiState = uiState.value as UiState
val items = currentUiState.viewPagerItemsStates.toMutableList()
items[position] = newImageUiState
return items
}
private fun createNewImageUiState(
imageUrlAtPosition: String,
position: Int,
loadSuccess: Boolean,
retry: Boolean = false
): ImageUiState {
val currentUiState = uiState.value as UiState
val imageStateAtPosition = currentUiState.viewPagerItemsStates[position]
val imageDataAtPosition = imageStateAtPosition.data
return when {
loadSuccess -> createImageLoadSuccessUiState(imageUrlAtPosition, imageStateAtPosition)
retry -> createImageLoadStartUiState(imageDataAtPosition)
else -> createImageLoadFailedUiState(imageUrlAtPosition, imageStateAtPosition, position)
}
}
private fun createImageLoadStartUiState(
imageData: ImageData
): ImageUiState {
return ImageDataStartLoadingUiState(imageData)
}
private fun createImageLoadSuccessUiState(
imageUrl: String,
imageState: ImageUiState
): ImageUiState {
val imageData = imageState.data
return if (imageData.hasValidLowResImageUrlEqualTo(imageUrl)) {
val isHighResImageAlreadyLoaded = imageState is ImageInHighResLoadSuccessUiState
if (!isHighResImageAlreadyLoaded) {
val isRetryShown = imageState is ImageInHighResLoadFailedUiState
ImageInLowResLoadSuccessUiState(imageData, isRetryShown)
} else {
imageState
}
} else {
ImageInHighResLoadSuccessUiState(imageData)
}
}
private fun createImageLoadFailedUiState(
imageUrlAtPosition: String,
imageStateAtPosition: ImageUiState,
position: Int
): ImageUiState {
val imageDataAtPosition = imageStateAtPosition.data
val imageUiState = if (imageDataAtPosition.hasValidLowResImageUrlEqualTo(imageUrlAtPosition)) {
val isRetryShown = imageStateAtPosition is ImageInHighResLoadFailedUiState
ImageInLowResLoadFailedUiState(imageDataAtPosition, isRetryShown)
} else {
ImageInHighResLoadFailedUiState(imageDataAtPosition)
}
imageUiState.onItemTapped = {
onLoadIntoImageViewRetry(imageUrlAtPosition, position)
}
return imageUiState
}
private fun updateUiState(state: UiState) {
_uiState.value = state
}
private fun updateLoadIntoFileState(fileState: ImageLoadToFileState) {
_loadIntoFile.value = Event(fileState)
}
private fun shouldEnableEditActionsForImageState(imageState: ImageUiState) =
imageState is ImageInHighResLoadSuccessUiState
// TODO: revisit
@Suppress("ForbiddenComment")
private fun canLoadToFile(imageState: ImageUiState) = imageState is ImageInHighResLoadSuccessUiState
private fun List<ImageUiState>.hasSingleElement() = this.size == 1
fun onInsertClicked() {
with(imageEditor) {
onEditorAction(PreviewInsertImagesClicked(getOutputData()))
onEditorAction(EditorFinishedEditing(getOutputData()))
}
_finishAction.value = Event(getOutputData())
}
fun getThumbnailImageUrl(position: Int): String {
return uiState.value?.viewPagerItemsStates?.get(position)?.data?.let { imageData ->
return if (TextUtils.isEmpty(imageData.lowResImageUrl)) {
imageData.highResImageUrl
} else {
imageData.lowResImageUrl as String
}
} ?: ""
}
fun getHighResImageUrl(position: Int): String =
uiState.value?.viewPagerItemsStates?.get(position)?.data?.highResImageUrl ?: ""
private fun getOutputData() = (uiState.value?.viewPagerItemsStates?.map { OutputData(it.data.highResImageUrl) }
?: emptyList())
private fun isFileUrl(url: String): Boolean = url.lowercase(Locale.ROOT).startsWith(FILE_BASE)
data class ImageData(
val id: Long = UUID.randomUUID().hashCode().toLong(),
val lowResImageUrl: String?,
val highResImageUrl: String,
val outputFileExtension: String?
) {
fun hasValidLowResImageUrlEqualTo(imageUrl: String): Boolean {
val hasValidLowResImageUrl = this.lowResImageUrl?.isNotEmpty() == true &&
this.lowResImageUrl != this.highResImageUrl
val isGivenUrlEqualToLowResImageUrl = imageUrl == this.lowResImageUrl
return hasValidLowResImageUrl && isGivenUrlEqualToLowResImageUrl
}
}
data class UiState(
val viewPagerItemsStates: List<ImageUiState>,
val editActionsEnabled: Boolean = false,
val thumbnailsTabLayoutVisible: Boolean = true
)
sealed class ImageUiState(
val data: ImageData,
val progressBarVisible: Boolean = false,
val retryLayoutVisible: Boolean
) {
var onItemTapped: (() -> Unit)? = null
data class ImageDataStartLoadingUiState(val imageData: ImageData) : ImageUiState(
data = imageData,
progressBarVisible = true,
retryLayoutVisible = false
)
// Continue displaying progress bar on low res image load success
data class ImageInLowResLoadSuccessUiState(val imageData: ImageData, val isRetryShown: Boolean = false) :
ImageUiState(
data = imageData,
progressBarVisible = !isRetryShown,
retryLayoutVisible = isRetryShown
)
data class ImageInLowResLoadFailedUiState(val imageData: ImageData, val isRetryShown: Boolean = false) :
ImageUiState(
data = imageData,
progressBarVisible = true,
retryLayoutVisible = false
)
data class ImageInHighResLoadSuccessUiState(val imageData: ImageData) : ImageUiState(
data = imageData,
progressBarVisible = false,
retryLayoutVisible = false
)
// Display retry only when high res image load failed
data class ImageInHighResLoadFailedUiState(val imageData: ImageData) : ImageUiState(
data = imageData,
progressBarVisible = false,
retryLayoutVisible = true
)
}
sealed class ImageLoadToFileState {
object ImageLoadToFileIdleState : ImageLoadToFileState()
data class ImageStartLoadingToFileState(val imageUrlAtPosition: String, val position: Int) :
ImageLoadToFileState()
data class ImageLoadToFileSuccessState(val filePathAtPosition: String, val position: Int) :
ImageLoadToFileState()
data class ImageLoadToFileFailedState(val errorMsg: String?, val errorResId: Int) :
ImageLoadToFileState()
}
companion object {
private const val FILE_BASE = "file:"
}
}
| gpl-2.0 | 7d2318b97036cb11a859ab6d57339bd0 | 39.621554 | 120 | 0.698235 | 6.144049 | false | false | false | false |
google/identity-credential | appholder/src/main/java/com/android/mdl/app/adapter/ColorAdapter.kt | 1 | 1329 | package com.android.mdl.app.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import androidx.annotation.DrawableRes
import com.android.mdl.app.R
class ColorAdapter(
context: Context,
) : BaseAdapter() {
private val inflater = LayoutInflater.from(context)
private val labels = context.resources.getStringArray(R.array.document_color)
override fun getCount(): Int = labels.size
override fun getItem(position: Int): String = labels[position]
override fun getItemId(position: Int): Long = labels[position].hashCode().toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val view = convertView ?: inflater.inflate(R.layout.color_dropdown_item, null, true)
view.findViewById<TextView>(R.id.label).text = getItem(position)
view.findViewById<View>(R.id.color_preview).setBackgroundResource(backgroundFor(position))
return view
}
@DrawableRes
private fun backgroundFor(position: Int): Int {
return when (position) {
1 -> R.drawable.yellow_gradient
2 -> R.drawable.blue_gradient
else -> R.drawable.green_gradient
}
}
} | apache-2.0 | ff95ef424fe8de9cc84a8ebfefdd073b | 32.25 | 98 | 0.713318 | 4.300971 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertReceiverToParameterIntention.kt | 3 | 5619 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.codeInsight.template.Template
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.codeInsight.template.TemplateEditingAdapter
import com.intellij.codeInsight.template.TemplateManager
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.codeinsight.utils.ChooseStringExpression
import org.jetbrains.kotlin.idea.core.getOrCreateValueParameterList
import org.jetbrains.kotlin.idea.refactoring.changeSignature.*
import org.jetbrains.kotlin.idea.refactoring.resolveToExpectedDescriptorIfPossible
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference
class ConvertReceiverToParameterIntention : SelfTargetingOffsetIndependentIntention<KtTypeReference>(
KtTypeReference::class.java,
KotlinBundle.lazyMessage("convert.receiver.to.parameter")
), LowPriorityAction {
override fun isApplicableTo(element: KtTypeReference): Boolean = (element.parent as? KtNamedFunction)?.receiverTypeReference == element
private fun configureChangeSignature(newName: String? = null): KotlinChangeSignatureConfiguration =
object : KotlinChangeSignatureConfiguration {
override fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor = originalDescriptor.modify {
it.receiver = null
if (newName != null) {
it.parameters.first().name = newName
}
}
override fun performSilently(affectedFunctions: Collection<PsiElement>) = true
}
override fun startInWriteAction() = false
override fun applyTo(element: KtTypeReference, editor: Editor?) {
val function = element.parent as? KtNamedFunction ?: return
val descriptor = function.resolveToExpectedDescriptorIfPossible() as FunctionDescriptor
val project = function.project
if (editor != null && !isUnitTestMode()) {
val receiverNames = suggestReceiverNames(project, descriptor)
val defaultReceiverName = receiverNames.first()
val receiverTypeRef = function.receiverTypeReference!!
val psiFactory = KtPsiFactory(element)
val newParameter = psiFactory.createParameter("$defaultReceiverName: Dummy").apply { typeReference!!.replace(receiverTypeRef) }
project.executeWriteCommand(text) {
function.setReceiverTypeReference(null)
val addedParameter = function.getOrCreateValueParameterList().addParameterAfter(newParameter, null)
with(PsiDocumentManager.getInstance(project)) {
commitDocument(editor.document)
doPostponedOperationsAndUnblockDocument(editor.document)
}
editor.caretModel.moveToOffset(function.startOffset)
val templateBuilder = TemplateBuilderImpl(function)
templateBuilder.replaceElement(addedParameter.nameIdentifier!!, ChooseStringExpression(receiverNames))
TemplateManager.getInstance(project).startTemplate(
editor,
templateBuilder.buildInlineTemplate(),
object : TemplateEditingAdapter() {
private fun revertChanges() {
runWriteAction {
function.setReceiverTypeReference(addedParameter.typeReference)
function.valueParameterList!!.removeParameter(addedParameter)
}
}
override fun templateFinished(template: Template, brokenOff: Boolean) {
val newName = addedParameter.name
revertChanges()
if (!brokenOff) {
runChangeSignature(
element.project,
editor,
function.resolveToExpectedDescriptorIfPossible() as FunctionDescriptor,
configureChangeSignature(newName),
function.receiverTypeReference!!,
text
)
}
}
override fun templateCancelled(template: Template?) {
revertChanges()
}
}
)
}
} else {
runChangeSignature(element.project, editor, descriptor, configureChangeSignature(), element, text)
}
}
}
| apache-2.0 | 5f8793e8acc12a2846f1ec2ac9181ee8 | 49.621622 | 139 | 0.65848 | 6.587339 | false | true | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SoftLinkReferencedChildImpl.kt | 1 | 8860 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
import org.jetbrains.deft.annotations.Open
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SoftLinkReferencedChildImpl : SoftLinkReferencedChild, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(EntityWithSoftLinks::class.java,
SoftLinkReferencedChild::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val parentEntity: EntityWithSoftLinks
get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: SoftLinkReferencedChildData?) : ModifiableWorkspaceEntityBase<SoftLinkReferencedChild>(), SoftLinkReferencedChild.Builder {
constructor() : this(SoftLinkReferencedChildData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SoftLinkReferencedChild is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field SoftLinkReferencedChild#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field SoftLinkReferencedChild#parentEntity should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as SoftLinkReferencedChild
this.entitySource = dataSource.entitySource
if (parents != null) {
this.parentEntity = parents.filterIsInstance<EntityWithSoftLinks>().single()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var parentEntity: EntityWithSoftLinks
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)]!! as EntityWithSoftLinks
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as EntityWithSoftLinks
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityData(): SoftLinkReferencedChildData = result ?: super.getEntityData() as SoftLinkReferencedChildData
override fun getEntityClass(): Class<SoftLinkReferencedChild> = SoftLinkReferencedChild::class.java
}
}
class SoftLinkReferencedChildData : WorkspaceEntityData<SoftLinkReferencedChild>() {
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<SoftLinkReferencedChild> {
val modifiable = SoftLinkReferencedChildImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SoftLinkReferencedChild {
val entity = SoftLinkReferencedChildImpl()
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SoftLinkReferencedChild::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SoftLinkReferencedChild(entitySource) {
this.parentEntity = parents.filterIsInstance<EntityWithSoftLinks>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(EntityWithSoftLinks::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SoftLinkReferencedChildData
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SoftLinkReferencedChildData
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | d07052c2053e501b175dee745482f516 | 37.025751 | 157 | 0.704515 | 5.625397 | false | false | false | false |
sudesh333/unplug | src/co/uproot/unplug/common.kt | 1 | 8261 | package co.uproot.unplug
import javafx.beans.property.SimpleStringProperty
import javafx.beans.property.SimpleListProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.collections.ObservableList
import org.fxmisc.easybind.EasyBind
import java.util.HashMap
import javafx.collections.FXCollections
import javafx.beans.property.SimpleBooleanProperty
import java.util.LinkedList
import com.eclipsesource.json.JsonObject
import javafx.scene.image.Image
import javafx.beans.property.SimpleLongProperty
data class UserState(val id: String) {
val typing = SimpleBooleanProperty(false)
val present = SimpleBooleanProperty(false)
val displayName = SimpleStringProperty("");
val avatarURL = SimpleStringProperty("");
val lastActiveAgo = SimpleLongProperty(java.lang.Long.MAX_VALUE)
private val SECONDS_PER_YEAR = (60L*60L*24L*365L)
private val SECONDS_PER_DECADE = (10L * SECONDS_PER_YEAR)
val weight = EasyBind.combine(typing, present, lastActiveAgo, { t, p, la ->
val laSec = Math.min(la.toLong() / 1000, SECONDS_PER_DECADE)
var result = (1 + (SECONDS_PER_DECADE - laSec )).toInt()
if (t) {
result *= 2
}
if (p) {
result *= 2
}
result
})
override fun toString() = "$id ${typing.get()} ${present.get()} ${weight.get()}"
}
class RoomState(val id:String, val aliases: MutableList<String>)
// TODO: Avoid storing entire user state for every room. Instead have a common store and a lookup table
class AppState() {
val currRoomId = SimpleStringProperty("")
val currChatMessageList = SimpleObjectProperty<ObservableList<Message>>()
val currUserList = SimpleObjectProperty<ObservableList<UserState>>()
val roomStateList = SimpleListProperty<RoomState>(FXCollections.observableArrayList())
val roomNameList = EasyBind.map(roomStateList, { room: RoomState -> room.aliases.firstOrNull() ?: room.id })
private final val roomChatMessageStore = HashMap<String, ObservableList<Message>>()
private final val roomUserStore = HashMap<String, ObservableList<UserState>>()
synchronized fun processSyncResult(result: SyncResult, api:API) {
result.rooms.stream().forEach { room ->
val existingRoomState = roomStateList.firstOrNull { it.id == room.id }
if (existingRoomState == null) {
roomStateList.add(RoomState(room.id, LinkedList(room.aliases)))
} else {
existingRoomState.aliases.addAll(room.aliases)
}
getRoomChatMessages(room.id).setAll(room.chatMessages())
val users = getRoomUsers(room.id)
room.states.forEach { state: State ->
when (state.type) {
"m.room.member" -> {
if (state.content.getString("membership", "") == "join") {
val us = UserState(state.userId)
val displayName = state.content.getStringOrElse("displayname", state.userId)
us.displayName.setValue(displayName)
us.avatarURL.setValue(api.getAvatarThumbnailURL(state.content.getStringOrElse("avatar_url","")))
users.add(us)
} else {
users.removeFirstMatching { it.id == state.userId }
}
}
"m.room.aliases" -> {
// TODO
}
"m.room.power_levels" -> {
// TODO
}
"m.room.join_rules" -> {
// TODO
}
"m.room.create" -> {
// TODO
}
"m.room.topic" -> {
// TODO
}
"m.room.name" -> {
// TODO
}
"m.room.config" -> {
// TODO
}
else -> {
System.err.println("Unhandled state type: " + state.type)
System.err.println(Thread.currentThread().getStackTrace().take(2).joinToString("\n"))
System.err.println()
}
}
}
}
result.presence.forEach { p ->
if (p.type == "m.presence") {
roomUserStore.values().forEach { users ->
val userId = p.content.getString("user_id", null)
users.firstOrNull { it.id == userId }?.let {
it.present.set(p.content.getString("presence", "") == "online")
it.lastActiveAgo.set(p.content.getLong("last_active_ago", java.lang.Long.MAX_VALUE))
}
}
}
}
roomUserStore.values().forEach { users ->
FXCollections.sort(users, { a, b -> b.weight.get() - a.weight.get()})
}
}
fun processEventsResult(eventResult: EventResult, api:API) {
eventResult.messages.forEach { message ->
when (message.type) {
"m.typing" -> {
val usersTyping = message.content.getArray("user_ids").map { it.asString() }
roomUserStore.values().forEach { users ->
users.forEach { it.typing.set(usersTyping.contains(it.id)) }
}
}
"m.presence" -> {
roomUserStore.values().forEach { users ->
val userId = message.content.getString("user_id", null)
users.firstOrNull { it.id == userId }?.let {
it.present.set(message.content.getString("presence", "") == "online")
it.lastActiveAgo.set(message.content.getLong("last_active_ago", java.lang.Long.MAX_VALUE))
}
}
}
"m.room.message" -> {
if (message.roomId != null) {
getRoomChatMessages(message.roomId).add(message)
}
}
"m.room.member" -> {
if (message.roomId != null) {
val users = getRoomUsers(message.roomId)
getRoomChatMessages(message.roomId).add(message)
if (message.content.getString("membership", "") == "join") {
val existingUser = users.firstOrNull { it.id == message.userId }
val displayName = message.content.get("displayname")?.let { if (it.isString()) it.asString() else null } ?: message.userId
val avatarURL = api.getAvatarThumbnailURL(message.content.getStringOrElse("avatar_url", ""))
val user = if (existingUser == null) {
val us = UserState(message.userId)
users.add(us)
us
} else {
existingUser
}
user.displayName.set(displayName)
user.avatarURL.set(avatarURL)
} else {
users.removeFirstMatching { it.id == message.userId }
}
}
}
else -> {
println("Unhandled message: " + message)
}
}
}
roomUserStore.values().forEach { users ->
FXCollections.sort(users, { a, b -> b.weight.get() - a.weight.get()})
}
}
synchronized private fun getRoomChatMessages(roomId: String): ObservableList<Message> {
return getOrCreate(roomChatMessageStore, roomId, { FXCollections.observableArrayList<Message>() })
}
synchronized private fun getRoomUsers(roomId: String): ObservableList<UserState> {
return getOrCreate(roomUserStore, roomId, {
FXCollections.observableArrayList<UserState>({ userState -> array(userState.present, userState.displayName, userState.avatarURL, userState.typing, userState.weight) })
})
}
init {
EasyBind.subscribe(currRoomId, { id: String? ->
if (id != null && !id.isEmpty()) {
currChatMessageList.set(getRoomChatMessages(id))
currUserList.set(getRoomUsers(id))
} else {
currChatMessageList.set(SimpleListProperty<Message>())
currUserList.set(SimpleListProperty<UserState>())
}
})
}
synchronized private fun getOrCreate<T>(store: HashMap<String, ObservableList<T>>, roomId: String, creator: () -> ObservableList<T>): ObservableList<T> {
val messages = store.get(roomId)
if (messages == null) {
val newList = SimpleListProperty(creator())
store.put(roomId, newList)
return newList
} else {
return messages
}
}
}
fun <T> ObservableList<T>.removeFirstMatching(predicate: (T) -> Boolean) {
for ((index,value) in this.withIndex()) {
if (predicate(value)) {
this.remove(index)
break;
}
}
}
fun JsonObject.getStringOrElse(name:String, elseValue:String):String {
return get(name)?.let { if (it.isString()) it.asString() else null } ?: elseValue
}
| gpl-3.0 | c2a46ddd8a5e224a59de6c28a7362dbd | 34.004237 | 173 | 0.612396 | 4.256054 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/checker/infos/SmartCastsWithSafeAccess.kt | 8 | 737 | // FIR_IDENTICAL
interface A {
fun foo()
}
interface B : A {
fun bar()
}
interface C
interface D : A
fun test(a: A?) {
if (a != null && a is B?) {
<info descr="Smart cast to B" tooltip="Smart cast to B">a</info>.bar()
}
if (a is B && a is C) {
<info descr="Smart cast to B" tooltip="Smart cast to B">a</info>.foo()
}
if (a is B? && a is C?) {
<info descr="Smart cast to B?" tooltip="Smart cast to B?">a</info><info>?.</info>bar()
}
a<info>?.</info>foo()
if (a is B? && a is C?) {
a<info>?.</info>foo()
}
if (a is B && a is D) {
//when it's resolved, the message should be 'Smart cast to A'
<info>a</info>.<error>foo</error>
}
}
| apache-2.0 | b1ab608d9df85a2c68b938478c8d6d72 | 18.918919 | 94 | 0.500678 | 2.959839 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database/src/main/kotlin/com/onyx/interactors/query/impl/collectors/FlatFunctionSelectionQueryCollector.kt | 1 | 2232 | package com.onyx.interactors.query.impl.collectors
import com.onyx.descriptor.EntityDescriptor
import com.onyx.interactors.record.data.Reference
import com.onyx.lang.map.OptimisticLockingMap
import com.onyx.persistence.IManagedEntity
import com.onyx.persistence.context.SchemaContext
import com.onyx.persistence.query.Query
import kotlin.collections.HashMap
/**
* Get a single result when executing selection functions that require aggregation without grouping
*/
class FlatFunctionSelectionQueryCollector(
query: Query,
context: SchemaContext,
descriptor: EntityDescriptor
) : BaseQueryCollector<Any?>(query, context, descriptor) {
private var result = OptimisticLockingMap(HashMap<String, Any?>())
private val otherSelections = selections.filter { it.function?.type?.isGroupFunction != true }
private val selectionFunctions = selections.filter { it.function?.type?.isGroupFunction == true }
override fun collect(reference: Reference, entity: IManagedEntity?) {
super.collect(reference, entity)
if(entity == null)
return
selectionFunctions.forEach {
val selectionValue = comparator.getAttribute(it, entity, context)
if(it.function?.preProcess(query, selectionValue) == true) {
otherSelections.forEach { selection ->
val resultAttribute = if (selection.function == null)
comparator.getAttribute(selection, entity, context)
else
selection.function.execute(comparator.getAttribute(selection, entity, context))
resultLock.perform {
result[selection.selection] = resultAttribute
}
}
}
}
}
override fun finalizeResults() {
if(!isFinalized) {
repeat(selections.size) {
selectionFunctions.forEach {
it.function?.postProcess(query)
result[it.selection] = it.function?.getFunctionValue()
}
}
results = arrayListOf(HashMap(result))
numberOfResults.set(1)
isFinalized = true
}
}
} | agpl-3.0 | c6c57e730078919b78b2090ce1a96329 | 35.606557 | 103 | 0.638441 | 5.107551 | false | false | false | false |
kondroid00/SampleProject_Android | app/src/main/java/com/kondroid/sampleproject/viewmodel/AddRoomViewModel.kt | 1 | 3042 | package com.kondroid.sampleproject.viewmodel
import android.content.Context
import android.databinding.ObservableField
import com.kondroid.sampleproject.helper.RxUtils
import com.kondroid.sampleproject.helper.makeWeak
import com.kondroid.sampleproject.helper.validation.Validation
import com.kondroid.sampleproject.model.RoomsModel
import com.kondroid.sampleproject.request.RoomRequest
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.rxkotlin.Observables
import io.reactivex.rxkotlin.combineLatest
import io.reactivex.schedulers.Schedulers
import java.lang.ref.WeakReference
/**
* Created by kondo on 2017/10/05.
*/
class AddRoomViewModel(context: Context) : BaseViewModel(context) {
var nameText: ObservableField<String> = ObservableField("")
var themeText: ObservableField<String> = ObservableField("")
var nameValidationText: ObservableField<String> = ObservableField("")
var themeValidationText: ObservableField<String> = ObservableField("")
var createButtonEnabled: ObservableField<Boolean> = ObservableField(false)
val roomModel = RoomsModel()
lateinit var onTapCreate: () -> Unit
override fun initVM() {
super.initVM()
//Validation
val weakSelf = makeWeak(this)
val nameValid = RxUtils.toObservable(nameText)
.map { return@map Validation.textLength(context.get(), it, 1, 20) }
.share()
val d1 = nameValid.subscribe { weakSelf.get()?.nameValidationText?.set(it) }
val themeValid = RxUtils.toObservable(themeText)
.map { return@map Validation.textLength(context.get(), it, 1, 20) }
.share()
val d2 = themeValid.subscribe { weakSelf.get()?.themeValidationText?.set(it) }
val createButtonValid = Observables.combineLatest(nameValid, themeValid, {name, theme ->
return@combineLatest name == "" && theme == ""
}).share()
val d3 = createButtonValid.subscribe { weakSelf.get()?.createButtonEnabled?.set(it) }
compositeDisposable.addAll(d1, d2, d3)
}
fun createRoom(onSuccess: () -> Unit, onFailed: (e: Throwable) -> Unit) {
if (requesting) return
requesting = true
val weakSelf = makeWeak(this)
val params = RoomRequest.CreateParams(nameText.get(), themeText.get())
val observable = roomModel.createRoom(params)
val d = observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({t ->
weakSelf.get()?.requesting = false
onSuccess()
},{e ->
weakSelf.get()?.requesting = false
onFailed(e)
},{
weakSelf.get()?.requesting = false
})
compositeDisposable.add(d)
}
fun tapCreate() {
if (requesting) return
onTapCreate()
}
} | mit | d9ae69c1e0343a454117112c5cac88b7 | 36.567901 | 96 | 0.660421 | 4.730949 | false | false | false | false |
jk1/intellij-community | python/src/com/jetbrains/python/sdk/PySdkListCellRenderer.kt | 3 | 4482 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.sdk
import com.intellij.icons.AllIcons
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkModificator
import com.intellij.openapi.projectRoots.SdkType
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.LayeredIcon
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.TitledSeparator
import com.intellij.util.ui.JBUI
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor
import com.jetbrains.python.sdk.pipenv.PIPENV_ICON
import com.jetbrains.python.sdk.pipenv.isPipEnv
import java.awt.Component
import javax.swing.Icon
import javax.swing.JList
/**
* @author vlan
*/
open class PySdkListCellRenderer(private val sdkModifiers: Map<Sdk, SdkModificator>?) : ColoredListCellRenderer<Any>() {
override fun getListCellRendererComponent(list: JList<out Any>?, value: Any?, index: Int, selected: Boolean,
hasFocus: Boolean): Component =
when (value) {
SEPARATOR -> TitledSeparator(null).apply {
border = JBUI.Borders.empty()
}
else -> super.getListCellRendererComponent(list, value, index, selected, hasFocus)
}
override fun customizeCellRenderer(list: JList<out Any>, value: Any?, index: Int, selected: Boolean, hasFocus: Boolean) {
when (value) {
is Sdk -> {
appendName(value)
icon = customizeIcon(value)
}
is String -> append(value)
null -> append("<No interpreter>")
}
}
private fun appendName(sdk: Sdk) {
val name = sdkModifiers?.get(sdk)?.name ?: sdk.name
when {
PythonSdkType.isInvalid(sdk) || PythonSdkType.hasInvalidRemoteCredentials(sdk) ->
append("[invalid] $name", SimpleTextAttributes.ERROR_ATTRIBUTES)
PythonSdkType.isIncompleteRemote(sdk) ->
append("[incomplete] $name", SimpleTextAttributes.ERROR_ATTRIBUTES)
!LanguageLevel.SUPPORTED_LEVELS.contains(PythonSdkType.getLanguageLevelForSdk(sdk)) ->
append("[unsupported] $name", SimpleTextAttributes.ERROR_ATTRIBUTES)
else ->
append(name)
}
if (sdk.isPipEnv) {
sdk.versionString?.let {
append(" $it", SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES)
}
}
val homePath = sdk.homePath
val relHomePath = homePath?.let { FileUtil.getLocationRelativeToUserHome(it) }
if (relHomePath != null && homePath !in name && relHomePath !in name) {
append(" $relHomePath", SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES)
}
}
companion object {
const val SEPARATOR: String = "separator"
private fun customizeIcon(sdk: Sdk): Icon? {
val flavor = PythonSdkFlavor.getPlatformIndependentFlavor(sdk.homePath)
val icon = if (flavor != null) flavor.icon else (sdk.sdkType as? SdkType)?.icon ?: return null
return when {
PythonSdkType.isInvalid(sdk) ||
PythonSdkType.isIncompleteRemote(sdk) ||
PythonSdkType.hasInvalidRemoteCredentials(sdk) ||
!LanguageLevel.SUPPORTED_LEVELS.contains(PythonSdkType.getLanguageLevelForSdk(sdk)) ->
wrapIconWithWarningDecorator(icon)
sdk is PyDetectedSdk ->
IconLoader.getTransparentIcon(icon)
// XXX: We cannot provide pipenv SDK flavor by path since it's just a regular virtualenv. Consider
// adding the SDK flavor based on the `Sdk` object itself
// TODO: Refactor SDK flavors so they can actually provide icons for SDKs in all cases
sdk.isPipEnv ->
PIPENV_ICON
else ->
icon
}
}
private fun wrapIconWithWarningDecorator(icon: Icon): LayeredIcon =
LayeredIcon(2).apply {
setIcon(icon, 0)
setIcon(AllIcons.Actions.Cancel, 1)
}
}
}
| apache-2.0 | c148e63f5b8655edb2fe01169d32a26d | 37.973913 | 123 | 0.703704 | 4.473054 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-host-common/jvm/test/io/ktor/tests/hosts/ApplicationEngineEnvironmentReloadingTests.kt | 1 | 18686 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("unused", "UNUSED_PARAMETER")
package io.ktor.tests.hosts
import com.typesafe.config.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.config.*
import io.ktor.server.engine.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import io.ktor.util.*
import kotlinx.coroutines.*
import org.slf4j.helpers.*
import kotlin.reflect.*
import kotlin.reflect.jvm.*
import kotlin.test.*
class ApplicationEngineEnvironmentReloadingTests {
@Test
fun `top level extension function as module function`() {
val environment = applicationEngineEnvironment {
developmentMode = false
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.application.modules" to listOf(Application::topLevelExtensionFunction.fqName)
)
)
)
}
environment.start()
val application = environment.application
assertNotNull(application)
assertEquals("topLevelExtensionFunction", application.attributes[TestKey])
environment.stop()
}
@Test
fun `top level extension function as module function reloading stress`() {
val environment = applicationEngineEnvironment {
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.deployment.watch" to listOf("ktor-server-host-common"),
"ktor.application.modules" to listOf(Application::topLevelExtensionFunction.fqName)
)
)
)
}
environment.start()
repeat(100) {
(environment as ApplicationEngineEnvironmentReloading).reload()
}
environment.stop()
}
@Test
fun `top level non-extension function as module function`() {
val environment = applicationEngineEnvironment {
developmentMode = false
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.application.modules" to listOf<KFunction0<Unit>>(::topLevelFunction).map { it.fqName }
)
)
)
}
environment.start()
val application = environment.application
assertNotNull(application)
assertEquals("topLevelFunction", application.attributes[TestKey])
environment.stop()
}
@Test
fun `companion object extension function as module function`() {
val environment = applicationEngineEnvironment {
developmentMode = false
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.application.modules" to listOf(
Companion::class.jvmName + "." + "companionObjectExtensionFunction"
)
)
)
)
}
environment.start()
val application = environment.application
assertNotNull(application)
assertEquals("companionObjectExtensionFunction", application.attributes[TestKey])
environment.stop()
}
@Test
fun `companion object non-extension function as module function`() {
val environment = applicationEngineEnvironment {
developmentMode = false
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.application.modules" to listOf(
Companion::class.functionFqName("companionObjectFunction")
)
)
)
)
}
environment.start()
val application = environment.application
assertNotNull(application)
assertEquals("companionObjectFunction", application.attributes[TestKey])
environment.stop()
}
@Test
fun `companion object jvmstatic extension function as module function`() {
val environment = applicationEngineEnvironment {
developmentMode = false
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.application.modules" to listOf(
Companion::class.jvmName + "." + "companionObjectJvmStaticExtensionFunction"
)
)
)
)
}
environment.start()
val application = environment.application
assertNotNull(application)
assertEquals("companionObjectJvmStaticExtensionFunction", application.attributes[TestKey])
environment.stop()
}
@Test
fun `companion object jvmstatic non-extension function as module function`() {
val environment = applicationEngineEnvironment {
developmentMode = false
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.application.modules" to listOf(
Companion::class.functionFqName("companionObjectJvmStaticFunction")
)
)
)
)
}
environment.start()
val application = environment.application
assertNotNull(application)
assertEquals("companionObjectJvmStaticFunction", application.attributes[TestKey])
environment.stop()
}
@Test
fun `object holder extension function as module function`() {
val environment = applicationEngineEnvironment {
developmentMode = false
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.application.modules" to listOf(
ObjectModuleFunctionHolder::class.jvmName + "." + "objectExtensionFunction"
)
)
)
)
}
environment.start()
val application = environment.application
assertNotNull(application)
assertEquals("objectExtensionFunction", application.attributes[TestKey])
environment.stop()
}
@Test
fun `object holder non-extension function as module function`() {
val environment = applicationEngineEnvironment {
developmentMode = false
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.application.modules" to listOf(
ObjectModuleFunctionHolder::class.functionFqName("objectFunction")
)
)
)
)
}
environment.start()
val application = environment.application
assertNotNull(application)
assertEquals("objectFunction", application.attributes[TestKey])
environment.stop()
}
@Test
fun `class holder extension function as module function`() {
val environment = applicationEngineEnvironment {
developmentMode = false
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.application.modules" to listOf(
ClassModuleFunctionHolder::class.jvmName + "." + "classExtensionFunction"
)
)
)
)
}
environment.start()
val application = environment.application
assertNotNull(application)
assertEquals("classExtensionFunction", application.attributes[TestKey])
environment.stop()
}
@Test
fun `class holder non-extension function as module function`() {
val environment = applicationEngineEnvironment {
developmentMode = false
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.application.modules" to listOf(ClassModuleFunctionHolder::classFunction.fqName)
)
)
)
}
environment.start()
val application = environment.application
assertNotNull(application)
assertEquals("classFunction", application.attributes[TestKey])
environment.stop()
}
@Test
fun `no-arg module function`() {
val environment = applicationEngineEnvironment {
developmentMode = false
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.application.modules" to listOf(NoArgModuleFunction::class.functionFqName("main"))
)
)
)
}
environment.start()
val application = environment.application
assertNotNull(application)
assertEquals(1, NoArgModuleFunction.result)
environment.stop()
}
@Test
fun `multiple module functions`() {
val environment = applicationEngineEnvironment {
developmentMode = false
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.application.modules" to listOf(MultipleModuleFunctions::class.jvmName + ".main")
)
)
)
}
environment.start()
val application = environment.application
assertNotNull(application)
assertEquals("best function called", application.attributes[TestKey])
environment.stop()
}
@Test
fun `multiple static module functions`() {
val environment = applicationEngineEnvironment {
developmentMode = false
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.application.modules" to listOf(MultipleStaticModuleFunctions::class.jvmName + ".main")
)
)
)
}
environment.start()
val application = environment.application
assertNotNull(application)
assertEquals("best function called", application.attributes[TestKey])
environment.stop()
}
@Test
fun `top level module function with default arg`() {
val environment = applicationEngineEnvironment {
developmentMode = false
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.application.modules" to listOf(
ApplicationEngineEnvironmentReloadingTests::class.jvmName + "Kt.topLevelWithDefaultArg"
)
)
)
)
}
environment.start()
val application = environment.application
assertNotNull(application)
assertEquals("topLevelWithDefaultArg", application.attributes[TestKey])
environment.stop()
}
@Test
fun `static module function with default arg`() {
val environment = applicationEngineEnvironment {
developmentMode = false
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.application.modules" to listOf(Companion::class.jvmName + ".functionWithDefaultArg")
)
)
)
}
environment.start()
val application = environment.application
assertNotNull(application)
assertEquals("functionWithDefaultArg", application.attributes[TestKey])
environment.stop()
}
@Test
fun `top level module function with jvm overloads`() {
val environment = applicationEngineEnvironment {
developmentMode = false
config = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"ktor.deployment.environment" to "test",
"ktor.application.modules" to listOf(
ApplicationEngineEnvironmentReloadingTests::class.jvmName + "Kt.topLevelWithJvmOverloads"
)
)
)
)
}
environment.start()
val application = environment.application
assertNotNull(application)
assertEquals("topLevelWithJvmOverloads", application.attributes[TestKey])
environment.stop()
}
object NoArgModuleFunction {
var result = 0
fun main() {
result++
}
}
object MultipleModuleFunctions {
fun main() {
}
fun main(app: Application) {
app.attributes.put(TestKey, "best function called")
}
}
object MultipleStaticModuleFunctions {
@JvmStatic
fun main() {
}
@JvmStatic
fun main(app: Application) {
app.attributes.put(TestKey, "best function called")
}
}
class ClassModuleFunctionHolder {
@Suppress("UNUSED")
fun Application.classExtensionFunction() {
attributes.put(TestKey, "classExtensionFunction")
}
fun classFunction(app: Application) {
app.attributes.put(TestKey, "classFunction")
}
}
object ObjectModuleFunctionHolder {
@Suppress("UNUSED")
fun Application.objectExtensionFunction() {
attributes.put(TestKey, "objectExtensionFunction")
}
fun objectFunction(app: Application) {
app.attributes.put(TestKey, "objectFunction")
}
}
companion object {
val TestKey = AttributeKey<String>("test-key")
private val KFunction<*>.fqName: String
get() = javaMethod!!.declaringClass.name + "." + name
private fun KClass<*>.functionFqName(name: String) = "$jvmName.$name"
@Suppress("UNUSED")
fun Application.companionObjectExtensionFunction() {
attributes.put(TestKey, "companionObjectExtensionFunction")
}
fun companionObjectFunction(app: Application) {
app.attributes.put(TestKey, "companionObjectFunction")
}
@Suppress("UNUSED")
@JvmStatic
fun Application.companionObjectJvmStaticExtensionFunction() {
attributes.put(TestKey, "companionObjectJvmStaticExtensionFunction")
}
@JvmStatic
fun companionObjectJvmStaticFunction(app: Application) {
app.attributes.put(TestKey, "companionObjectJvmStaticFunction")
}
@JvmStatic
fun Application.functionWithDefaultArg(test: Boolean = false) {
attributes.put(TestKey, "functionWithDefaultArg")
}
}
@Test
fun `application is available before environment start`() {
val env = dummyEnv()
val app = env.application
env.start()
assertEquals(app, env.application)
}
@Test
fun `completion handler is invoked when attached before environment start`() {
val env = dummyEnv()
var invoked = false
env.application.coroutineContext[Job]?.invokeOnCompletion {
invoked = true
}
env.start()
env.stop()
assertTrue(invoked, "On completion handler wasn't invoked")
}
@Test
fun `interceptor is invoked when added before environment start`() {
val engine = TestApplicationEngine(createTestEnvironment())
engine.application.intercept(ApplicationCallPipeline.Plugins) {
call.response.header("Custom", "Value")
}
engine.start()
try {
engine.apply {
application.routing {
get("/") {
call.respondText { "Hello" }
}
}
assertEquals("Value", handleRequest(HttpMethod.Get, "/").response.headers["Custom"])
}
} catch (cause: Throwable) {
fail("Failed with an exception: ${cause.message}")
} finally {
engine.stop(0L, 0L)
}
}
private fun dummyEnv() = ApplicationEngineEnvironmentReloading(
classLoader = this::class.java.classLoader,
log = NOPLogger.NOP_LOGGER,
config = MapApplicationConfig(),
connectors = emptyList(),
modules = emptyList()
)
}
fun Application.topLevelExtensionFunction() {
attributes.put(ApplicationEngineEnvironmentReloadingTests.TestKey, "topLevelExtensionFunction")
}
fun topLevelFunction(app: Application) {
app.attributes.put(ApplicationEngineEnvironmentReloadingTests.TestKey, "topLevelFunction")
}
@Suppress("unused")
fun topLevelFunction() {
error("Shouldn't be invoked")
}
fun Application.topLevelWithDefaultArg(testing: Boolean = false) {
attributes.put(ApplicationEngineEnvironmentReloadingTests.TestKey, "topLevelWithDefaultArg")
}
@JvmOverloads
fun Application.topLevelWithJvmOverloads(testing: Boolean = false) {
attributes.put(ApplicationEngineEnvironmentReloadingTests.TestKey, "topLevelWithJvmOverloads")
}
| apache-2.0 | 393b450598020d1cb75dc746910ce0b2 | 33.09854 | 119 | 0.57214 | 6.084663 | false | true | false | false |
ktorio/ktor | ktor-client/ktor-client-core/js/src/io/ktor/client/engine/js/JsClientEngine.kt | 1 | 4788 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine.js
import io.ktor.client.engine.*
import io.ktor.client.engine.js.compatibility.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.websocket.*
import io.ktor.client.request.*
import io.ktor.client.utils.*
import io.ktor.http.*
import io.ktor.util.*
import io.ktor.util.date.*
import kotlinx.coroutines.*
import org.w3c.dom.*
import org.w3c.dom.events.*
import kotlin.coroutines.*
internal class JsClientEngine(
override val config: HttpClientEngineConfig
) : HttpClientEngineBase("ktor-js") {
override val dispatcher = Dispatchers.Default
override val supportedCapabilities = setOf(HttpTimeout, WebSocketCapability)
init {
check(config.proxy == null) { "Proxy unsupported in Js engine." }
}
@OptIn(InternalAPI::class)
override suspend fun execute(data: HttpRequestData): HttpResponseData {
val callContext = callContext()
val clientConfig = data.attributes[CLIENT_CONFIG]
if (data.isUpgradeRequest()) {
return executeWebSocketRequest(data, callContext)
}
val requestTime = GMTDate()
val rawRequest = data.toRaw(clientConfig, callContext)
val rawResponse = commonFetch(data.url.toString(), rawRequest)
val status = HttpStatusCode(rawResponse.status.toInt(), rawResponse.statusText)
val headers = rawResponse.headers.mapToKtor()
val version = HttpProtocolVersion.HTTP_1_1
val body = CoroutineScope(callContext).readBody(rawResponse)
return HttpResponseData(
status,
requestTime,
headers,
version,
body,
callContext
)
}
// Adding "_capturingHack" to reduce chances of JS IR backend to rename variable,
// so it can be accessed inside js("") function
@Suppress("UNUSED_PARAMETER", "UnsafeCastFromDynamic", "UNUSED_VARIABLE", "LocalVariableName")
private fun createWebSocket(
urlString_capturingHack: String,
headers: Headers
): WebSocket = if (PlatformUtils.IS_NODE) {
val ws_capturingHack = js("eval('require')('ws')")
val headers_capturingHack: dynamic = object {}
headers.forEach { name, values ->
headers_capturingHack[name] = values.joinToString(",")
}
js("new ws_capturingHack(urlString_capturingHack, { headers: headers_capturingHack })")
} else {
js("new WebSocket(urlString_capturingHack)")
}
private suspend fun executeWebSocketRequest(
request: HttpRequestData,
callContext: CoroutineContext
): HttpResponseData {
val requestTime = GMTDate()
val urlString = request.url.toString()
val socket: WebSocket = createWebSocket(urlString, request.headers)
try {
socket.awaitConnection()
} catch (cause: Throwable) {
callContext.cancel(CancellationException("Failed to connect to $urlString", cause))
throw cause
}
val session = JsWebSocketSession(callContext, socket)
return HttpResponseData(
HttpStatusCode.OK,
requestTime,
Headers.Empty,
HttpProtocolVersion.HTTP_1_1,
session,
callContext
)
}
}
private suspend fun WebSocket.awaitConnection(): WebSocket = suspendCancellableCoroutine { continuation ->
if (continuation.isCancelled) return@suspendCancellableCoroutine
val eventListener = { event: Event ->
when (event.type) {
"open" -> continuation.resume(this)
"error" -> {
continuation.resumeWithException(WebSocketException(event.asString()))
}
}
}
addEventListener("open", callback = eventListener)
addEventListener("error", callback = eventListener)
continuation.invokeOnCancellation {
removeEventListener("open", callback = eventListener)
removeEventListener("error", callback = eventListener)
if (it != null) {
[email protected]()
}
}
}
private fun Event.asString(): String = buildString {
append(JSON.stringify(this@asString, arrayOf("message", "target", "type", "isTrusted")))
}
private fun org.w3c.fetch.Headers.mapToKtor(): Headers = buildHeaders {
[email protected]().forEach { value: String, key: String ->
append(key, value)
}
Unit
}
/**
* Wrapper for javascript `error` objects.
* @property origin: fail reason
*/
@Suppress("MemberVisibilityCanBePrivate")
public class JsError(public val origin: dynamic) : Throwable("Error from javascript[$origin].")
| apache-2.0 | 1c55cf7c31340bdc0feb00b9f373d1e1 | 30.92 | 119 | 0.659983 | 4.783217 | false | false | false | false |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/ui/base/AsyncLoader.kt | 1 | 2748 | /*
* Copyright © 2013 dvbviewer-controller Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.dvbviewer.controller.ui.base
import android.content.Context
import androidx.loader.content.AsyncTaskLoader
import java.io.Closeable
/**
* Loader which extends AsyncTaskLoaders and handles caveats
* as pointed out in http://code.google.com/p/android/issues/detail?id=14944.
*
* Based on CursorLoader.java in the Fragment compatibility package
*
* @param <D> mData type
* @author RayBa
* @date 07.04.2013
</D> */
abstract class AsyncLoader<D>
/**
* Instantiates a new async loader.
*
* @param context the context
* @author RayBa
* @date 07.04.2013
*/
(context: Context) : AsyncTaskLoader<D>(context) {
private var mData: D? = null
/* (non-Javadoc)
* @see android.support.v4.content.Loader#deliverResult(java.lang.Object)
*/
override fun deliverResult(data: D?) {
if (isReset) {
// An async query came in while the loader is stopped
closeData(data)
return
}
if (isStarted) {
super.deliverResult(data)
}
val oldData = mData
mData = data
if (oldData !== mData) {
closeData(oldData)
}
}
override fun onCanceled(data: D?) {
super.onCanceled(data)
closeData(data)
}
/* (non-Javadoc)
* @see android.support.v4.content.Loader#onStartLoading()
*/
override fun onStartLoading() {
if (mData != null) {
deliverResult(mData)
}
if (takeContentChanged() || mData == null) {
forceLoad()
}
}
/* (non-Javadoc)
* @see android.support.v4.content.Loader#onStopLoading()
*/
override fun onStopLoading() {
cancelLoad()
}
/* (non-Javadoc)
* @see android.support.v4.content.Loader#onReset()
*/
override fun onReset() {
super.onReset()
// Ensure the loader is stopped
onStopLoading()
closeData(mData)
mData = null
}
private fun closeData(data: D?) {
if (data != null && data is Closeable) {
val c = data as Closeable?
c?.close()
}
}
}
| apache-2.0 | c8282d93317f2bd50ac12f7d2b0f4a8c | 23.096491 | 80 | 0.618857 | 4.051622 | false | false | false | false |
neva-dev/javarel-framework | storage/database/src/main/kotlin/com/neva/javarel/storage/database/impl/MultiDatabaseAdmin.kt | 1 | 5972 | package com.neva.javarel.storage.database.impl
import com.neva.javarel.foundation.api.JavarelConstants
import com.neva.javarel.foundation.api.scanning.BundleScanner
import com.neva.javarel.foundation.api.scanning.BundleWatcher
import com.neva.javarel.foundation.api.scanning.ComponentScanBundleFilter
import com.neva.javarel.storage.database.api.Database
import com.neva.javarel.storage.database.api.DatabaseAdmin
import com.neva.javarel.storage.database.api.DatabaseConnection
import com.neva.javarel.storage.database.api.DatabaseException
import com.neva.javarel.storage.database.impl.connection.DerbyEmbeddedDatabaseConnection
import org.apache.felix.scr.annotations.*
import org.apache.openjpa.persistence.PersistenceProviderImpl
import org.osgi.framework.BundleContext
import org.osgi.framework.BundleEvent
import org.slf4j.LoggerFactory
import java.util.Properties
import javax.persistence.Entity
import javax.persistence.EntityManager
import javax.persistence.spi.PersistenceProvider
import javax.persistence.spi.PersistenceUnitTransactionType
@Component(immediate = true, metatype = true, label = "${JavarelConstants.SERVICE_PREFIX} Storage - Database Admin")
@Service(DatabaseAdmin::class, BundleWatcher::class)
class MultiDatabaseAdmin : DatabaseAdmin, BundleWatcher {
companion object {
val LOG = LoggerFactory.getLogger(MultiDatabaseAdmin::class.java)
@Property(name = NAME_DEFAULT_PROP, value = DerbyEmbeddedDatabaseConnection.NAME_DEFAULT, label = "Default connection name")
const val NAME_DEFAULT_PROP = "nameDefault"
val ENTITY_FILTER = ComponentScanBundleFilter(setOf(Entity::class.java))
val ENTITY_MANAGER_CONFIG = mapOf<String, Any>(
"openjpa.DynamicEnhancementAgent" to "true",
"openjpa.RuntimeUnenhancedClasses" to "supported",
"openjpa.jdbc.SynchronizeMappings" to "buildSchema(foreignKeys=true')",
"openjpa.jdbc.MappingDefaults" to "ForeignKeyDeleteAction=restrict, JoinForeignKeyDeleteAction=restrict"
)
}
@Reference
private lateinit var provider: PersistenceProvider
@Reference
private lateinit var bundleScanner: BundleScanner
@Reference(referenceInterface = DatabaseConnection::class,
cardinality = ReferenceCardinality.MANDATORY_MULTIPLE,
policy = ReferencePolicy.DYNAMIC
)
private var allConnections: MutableMap<String, DatabaseConnection> = mutableMapOf()
private var allConnectedDatabases: MutableMap<String, Database> = mutableMapOf()
private lateinit var context: BundleContext
private lateinit var props: Map<String, Any>
@Activate
protected fun start(context: BundleContext, props: Map<String, Any>) {
this.context = context
this.props = props
}
override val connectionDefault: String
get() = props[NAME_DEFAULT_PROP] as String
override fun database(): Database {
return database(connectionDefault)
}
@Synchronized
override fun database(connectionName: String): Database {
var database = allConnectedDatabases[connectionName]
if (database == null || !database.connected) {
database = connect(connectionByName(connectionName))
allConnectedDatabases.put(connectionName, database)
}
return database
}
override val connections: Set<DatabaseConnection>
get() = allConnections.values.toSet()
override val connectedDatabases: Set<Database>
get() = allConnectedDatabases.values.toSet()
private fun connectionByName(name: String): DatabaseConnection {
return allConnections[name] ?: throw DatabaseException("Database connection named '$name' is not defined.")
}
private fun connect(connection: DatabaseConnection): Database {
val props = Properties()
props.put("openjpa.ConnectionFactory", connection.source)
props.putAll(ENTITY_MANAGER_CONFIG)
val info = BundlePersistenceInfo(context)
info.persistenceProviderClassName = PersistenceProviderImpl::class.java.canonicalName
info.persistenceUnitName = connection.name
info.transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL
info.setExcludeUnlistedClasses(false)
val classes = bundleScanner.scan(ENTITY_FILTER)
for (clazz in classes) {
info.addManagedClassName(clazz.canonicalName)
}
connection.configure(info, props)
val emf = provider.createContainerEntityManagerFactory(info, props)
return ConnectedDatabase(connection, emf)
}
private fun check(connection: DatabaseConnection) {
if (allConnections.contains(connection.name)) {
LOG.warn("Database connection named '${connection.name}' of type '${connection.javaClass.canonicalName}' overrides '${allConnections[connection.name]!!.javaClass}'.")
}
}
private fun disconnect(connection: DatabaseConnection) {
if (allConnectedDatabases.contains(connection.name)) {
LOG.info("Database connection named '${connection.name}' is being disconnected.")
allConnectedDatabases.remove(connection.name)
}
}
private fun bindAllConnections(connection: DatabaseConnection) {
check(connection)
allConnections.put(connection.name, connection)
}
private fun unbindAllConnections(connection: DatabaseConnection) {
disconnect(connection)
allConnections.remove(connection.name)
}
override fun <R> session(connectionName: String, callback: (EntityManager) -> R): R {
return database(connectionName).session(callback)
}
override fun <R> session(callback: (EntityManager) -> R): R {
return database().session(callback)
}
override fun watch(event: BundleEvent) {
if (ENTITY_FILTER.filterBundle(event.bundle)) {
allConnectedDatabases.clear()
}
}
} | apache-2.0 | 6de103028d482b6efd92fa206f2e2ad9 | 37.535484 | 178 | 0.72505 | 4.867156 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/mcp/at/AtFile.kt | 1 | 1186 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.at
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.mcp.McpModuleType
import com.intellij.extapi.psi.PsiFileBase
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.psi.FileViewProvider
class AtFile(viewProvider: FileViewProvider) : PsiFileBase(viewProvider, AtLanguage) {
init {
setup()
}
private fun setup() {
if (ApplicationManager.getApplication().isUnitTestMode) {
return
}
val vFile = viewProvider.virtualFile
val module = ModuleUtilCore.findModuleForFile(vFile, project) ?: return
val mcpModule = MinecraftFacet.getInstance(module, McpModuleType) ?: return
mcpModule.addAccessTransformerFile(vFile)
}
override fun getFileType() = AtFileType
override fun toString() = "Access Transformer File"
override fun getIcon(flags: Int) = PlatformAssets.MCP_ICON
}
| mit | ae421423fcc761bf2c690d021358c8d3 | 27.238095 | 86 | 0.734401 | 4.544061 | false | false | false | false |
mdanielwork/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/statistics/MavenSettingsCollector.kt | 1 | 3432 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.statistics
import com.intellij.internal.statistic.beans.UsageDescriptor
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.internal.statistic.utils.getBooleanUsage
import com.intellij.internal.statistic.utils.getEnumUsage
import com.intellij.openapi.project.Project
import org.jetbrains.idea.maven.execution.MavenRunner
import org.jetbrains.idea.maven.project.MavenProjectsManager
class MavenSettingsCollector : ProjectUsagesCollector() {
override fun getGroupId() = "statistics.build.maven.state"
override fun getUsages(project: Project): Set<UsageDescriptor> {
val manager = MavenProjectsManager.getInstance(project)
if (!manager.isMavenizedProject) return emptySet()
val usages = mutableSetOf<UsageDescriptor>()
val generalSettings = manager.generalSettings
usages.add(getEnumUsage("checksumPolicy", generalSettings.checksumPolicy))
usages.add(getEnumUsage("failureBehavior", generalSettings.failureBehavior))
usages.add(getBooleanUsage("alwaysUpdateSnapshots", generalSettings.isAlwaysUpdateSnapshots))
usages.add(getBooleanUsage("nonRecursive", generalSettings.isNonRecursive))
usages.add(getBooleanUsage("printErrorStackTraces", generalSettings.isPrintErrorStackTraces))
usages.add(getBooleanUsage("usePluginRegistry", generalSettings.isUsePluginRegistry))
usages.add(getBooleanUsage("workOffline", generalSettings.isWorkOffline))
usages.add(getEnumUsage("outputLevel", generalSettings.outputLevel))
usages.add(getEnumUsage("pluginUpdatePolicy", generalSettings.pluginUpdatePolicy))
usages.add(getEnumUsage("loggingLevel", generalSettings.loggingLevel))
val importingSettings = manager.importingSettings
usages.add(getEnumUsage("generatedSourcesFolder", importingSettings.generatedSourcesFolder))
usages.add(getBooleanUsage("createModuleGroups", importingSettings.isCreateModuleGroups))
usages.add(getBooleanUsage("createModulesForAggregators", importingSettings.isCreateModulesForAggregators))
usages.add(getBooleanUsage("downloadDocsAutomatically", importingSettings.isDownloadDocsAutomatically))
usages.add(getBooleanUsage("downloadSourcesAutomatically", importingSettings.isDownloadSourcesAutomatically))
usages.add(getBooleanUsage("excludeTargetFolder", importingSettings.isExcludeTargetFolder))
usages.add(getBooleanUsage("importAutomatically", importingSettings.isImportAutomatically))
usages.add(getBooleanUsage("keepSourceFolders", importingSettings.isKeepSourceFolders))
usages.add(getBooleanUsage("lookForNested", importingSettings.isLookForNested))
usages.add(getBooleanUsage("useMavenOutput", importingSettings.isUseMavenOutput))
usages.add(UsageDescriptor("updateFoldersOnImportPhase." + importingSettings.updateFoldersOnImportPhase))
val runnerSettings = MavenRunner.getInstance(project).settings
usages.add(getBooleanUsage("delegateBuildRun", runnerSettings.isDelegateBuildToMaven));
usages.add(getBooleanUsage("passParentEnv", runnerSettings.isPassParentEnv));
usages.add(getBooleanUsage("runMavenInBackground", runnerSettings.isRunMavenInBackground));
usages.add(getBooleanUsage("skipTests", runnerSettings.isSkipTests));
return usages
}
}
| apache-2.0 | 467988f665f21fe67ac03b6f8ca79775 | 65 | 140 | 0.825466 | 5.215805 | false | false | false | false |
aerisweather/AerisAndroidSDK | Kotlin/AerisSdkDemo/app/src/main/java/com/example/demoaerisproject/service/AerisNotification.kt | 1 | 11898 | package com.example.demoaerisproject.service
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.widget.RemoteViews
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import com.aerisweather.aeris.logging.Logger
import com.aerisweather.aeris.response.ForecastsResponse
import com.aerisweather.aeris.response.ObservationResponse
import com.aerisweather.aeris.util.FileUtil
import com.example.demoaerisproject.BaseApplication
import com.example.demoaerisproject.R
import com.example.demoaerisproject.util.FormatUtil
import com.example.demoaerisproject.view.weather.MainActivity
class AerisNotification {
private var builder: NotificationCompat.Builder? = null
private var remoteViews: RemoteViews? = null
var map = HashMap<String, Int>()
get() {
field["am_pcloudyr"] = R.drawable.mcloudyr
field["am_showers"] = R.drawable.showers
field["am_snowshowers"] = R.drawable.showers
field["am_tstorm"] = R.drawable.tstorms
field["blizzard"] = R.drawable.blizzard
field["blizzardn"] = R.drawable.blizzard
field["blowingsnow"] = R.drawable.snoww
field["blowingsnown"] = R.drawable.snoww
field["chancestorm"] = R.drawable.tstorms
field["chancestormn"] = R.drawable.tstorms
field["clear"] = R.drawable.sunny
field["clearn"] = R.drawable.clearn
field["clearw"] = R.drawable.wind
field["clearwn"] = R.drawable.wind
field["cloudy"] = R.drawable.cloudy
field["cloudyn"] = R.drawable.cloudy
field["cloudyw"] = R.drawable.wind
field["cloudywn"] = R.drawable.wind
field["drizzle"] = R.drawable.drizzle
field["drizzlef"] = R.drawable.drizzle
field["drizzlefn"] = R.drawable.drizzle
field["drizzlen"] = R.drawable.drizzle
field["dust"] = R.drawable.hazy
field["dustn"] = R.drawable.hazyn
field["fair"] = R.drawable.sunny
field["fairn"] = R.drawable.clearn
field["fairnw"] = R.drawable.wind
field["fairnwn"] = R.drawable.wind
field["fdrizzle"] = R.drawable.drizzle
field["fdrizzlen"] = R.drawable.drizzle
field["flurries"] = R.drawable.flurries
field["flurriesn"] = R.drawable.flurries
field["flurriesw"] = R.drawable.flurries
field["flurrieswn"] = R.drawable.flurries
field["fog"] = R.drawable.fog
field["fogn"] = R.drawable.fog
field["freezingrain"] = R.drawable.rain
field["freezingrainn"] = R.drawable.rain
field["hazy"] = R.drawable.hazy
field["hazyn"] = R.drawable.hazyn
field["mcloudy"] = R.drawable.mcloudy
field["mcloudyn"] = R.drawable.mcloudyn
field["mcloudyr"] = R.drawable.mcloudyr
field["mcloudyrn"] = R.drawable.mcloudyrn
field["mcloudyrw"] = R.drawable.mcloudyrw
field["mcloudyrwn"] = R.drawable.mcloudyrwn
field["mcloudys"] = R.drawable.mcloudys
field["mcloudysfn"] = R.drawable.mcloudysn
field["mcloudysfw"] = R.drawable.mcloudysw
field["mcloudysfwn"] = R.drawable.mcloudyswn
field["mcloudysn"] = R.drawable.mcloudysn
field["mcloudysw"] = R.drawable.mcloudysw
field["mcloudyswn"] = R.drawable.mcloudyswn
field["mcloudyt"] = R.drawable.mcloudyt
field["mcloudytn"] = R.drawable.mcloudytn
field["mcloudytw"] = R.drawable.mcloudytw
field["mcloudytwn"] = R.drawable.mcloudytwn
field["mcloudyw"] = R.drawable.wind
field["mcloudywn"] = R.drawable.wind
field["pcloudy"] = R.drawable.pcloudy
field["pcloudyn"] = R.drawable.pcloudyn
field["pcloudyr"] = R.drawable.mcloudyr
field["pcloudyrn"] = R.drawable.mcloudyrn
field["pcloudyrw"] = R.drawable.mcloudyrw
field["pcloudyrwn"] = R.drawable.mcloudyrwn
field["pcloudys"] = R.drawable.mcloudys
field["pcloudysf"] = R.drawable.mcloudys
field["pcloudysfn"] = R.drawable.mcloudysn
field["pcloudysfw"] = R.drawable.snoww
field["pcloudysfwn"] = R.drawable.snoww
field["pcloudysn"] = R.drawable.mcloudysn
field["pcloudysw"] = R.drawable.mcloudysw
field["pcloudyswn"] = R.drawable.mcloudyswn
field["pcloudyt"] = R.drawable.mcloudyt
field["pcloudytn"] = R.drawable.mcloudytn
field["pcloudytw"] = R.drawable.mcloudytw
field["pcloudytwn"] = R.drawable.mcloudytwn
field["pcloudyw"] = R.drawable.wind
field["pcloudywn"] = R.drawable.wind
field["pm_pcloudy"] = R.drawable.pcloudy
field["pm_pcloudyr"] = R.drawable.mcloudyr
field["pm_showers"] = R.drawable.showers
field["pm_snowshowers"] = R.drawable.snowshowers
field["pm_tstorm"] = R.drawable.tstorms
field["rain"] = R.drawable.rain
field["rainn"] = R.drawable.rain
field["rainandsnow"] = R.drawable.rainandsnow
field["rainandsnown"] = R.drawable.rainandsnow
field["raintosnow"] = R.drawable.rainandsnow
field["raintosnown"] = R.drawable.rainandsnow
field["rainw"] = R.drawable.rainw
field["showers"] = R.drawable.showers
field["showersn"] = R.drawable.showers
field["showersw"] = R.drawable.showersw
field["showerswn"] = R.drawable.showersw
field["sleet"] = R.drawable.sleet
field["sleetn"] = R.drawable.sleet
field["sleetsnow"] = R.drawable.sleetsnow
field["sleetsnown"] = R.drawable.sleetsnow
field["smoke"] = R.drawable.hazy
field["smoken"] = R.drawable.hazyn
field["snow"] = R.drawable.snow
field["snown"] = R.drawable.snow
field["snowflurries"] = R.drawable.flurries
field["snowflurriesn"] = R.drawable.flurries
field["snowshowers"] = R.drawable.snowshowers
field["snowshowersn"] = R.drawable.snowshowers
field["snowshowersw"] = R.drawable.snowshowers
field["snowshowerswn"] = R.drawable.snowshowersn
field["snowtorain"] = R.drawable.rainandsnow
field["snowtorainn"] = R.drawable.rainandsnown
field["snoww"] = R.drawable.snoww
field["snowwn"] = R.drawable.snoww
field["sunny"] = R.drawable.sunny
field["sunnyn"] = R.drawable.clearn
field["sunnyw"] = R.drawable.wind
field["sunnywn"] = R.drawable.wind
field["tstorm"] = R.drawable.tstorms
field["tstormn"] = R.drawable.tstorms
field["tstormw"] = R.drawable.tstormsw
field["tstormwn"] = R.drawable.tstormsw
field["tstorms"] = R.drawable.tstorms
field["tstormsn"] = R.drawable.tstorms
field["tstormsw"] = R.drawable.tstormsw
field["tstormswn"] = R.drawable.tstormsw
field["wind"] = R.drawable.wind
field["wintrymix"] = R.drawable.wintrymix
field["wintrymixn"] = R.drawable.wintrymix
return field
}
private set
private val TAG = AerisNotification::class.java.simpleName
/**
* Sets the notification for the observation
*/
private val CHANNEL_ID = "channelID"
private val CHANNEL_NAME = "channelName"
fun setCustom(
context: Context,
isMetrics: Boolean,
obResponse: ObservationResponse,
fResponse: ForecastsResponse
) {
createNotifChannel(context)
Logger.d(TAG, "setCustomNotification()")
val intent = Intent(context, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
val ob = obResponse.observation
var printTemp = ""
if (builder == null) {
builder = NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(context.resources.getString(R.string.app_name))
.setSmallIcon(getDrawableByName(obResponse.observation.icon))
.setOngoing(true)
}
if (remoteViews == null) {
remoteViews = RemoteViews(context.packageName, R.layout.ntf_observation)
builder?.setContent(remoteViews)
}
remoteViews?.apply {
setImageViewResource(
R.id.ivNtfIcon,
FileUtil.getDrawableByName(ob.icon, context)
)
setTextViewText(R.id.tvNtfDesc, ob.weather)
printTemp = FormatUtil.printDegree(context, isMetrics, Pair(ob.tempC, ob.tempF))
builder?.setContentText(ob.weather.toString() + " " + printTemp)
setTextViewText(R.id.tvNtfTemp, printTemp)
val period = fResponse.getPeriod(0)
// reverses order if isday is not true.
val indexes = if (period.isDay) {
listOf(0, 1)
} else {
listOf(1, 0)
}
fResponse.getPeriod(indexes[0]).let {
setTextViewText(
R.id.tvNtfHigh,
FormatUtil.printDegree(context, isMetrics, Pair(it.maxTempC, it.maxTempF))
)
}
fResponse.getPeriod(indexes[1]).let {
setTextViewText(
R.id.tvNtfLow,
FormatUtil.printDegree(context, isMetrics, Pair(it.minTempC, it.minTempF))
)
}
}
// Create Notification Manager
val notificationmanager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationmanager.notify(
BaseApplication.PRIMARY_FOREGROUND_NOTIF_SERVICE_ID,
builder?.build()
)
}
private fun createNotifChannel(context: Context) {
val channel = NotificationChannel(
CHANNEL_ID,
CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT
).apply {
lightColor = Color.BLUE
enableLights(true)
}
val manager =
context.getSystemService(AppCompatActivity.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(channel)
}
fun cancel(context: Context) {
// Create Notification Manager
val notificationmanager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Build Notification with Notification Manager
//notificationmanager.cancel(WEATHER_NTF);
notificationmanager.cancel(BaseApplication.PRIMARY_FOREGROUND_NOTIF_SERVICE_ID)
remoteViews = null
builder = null
}
/**
* Gets the drawable by the string name. This is used in conjunction with
* the icon field in many of the forecast, observation. Accesses the name
* from the drawable folder.
*
* @param name name of the drawable
* @return the int key of the drawable.
*/
private fun getDrawableByName(name: String?): Int {
if (name == null) {
return 0
}
val iconName = name.substring(0, name.indexOf("."))
Logger.d(
TAG,
"getDrawableByName() - ObIcon: $iconName"
)
return map[iconName] ?: if (iconName[iconName.length - 1] == 'n') {
map[iconName.substring(0, iconName.length - 1)] ?: 0
} else 0
}
} | mit | 706ec9fc2ac62d3737c8c39e01c6ce2f | 40.897887 | 99 | 0.598252 | 4.395272 | false | false | false | false |
cdietze/klay | tripleklay/src/test/kotlin/tripleklay/ui/ElementTest.kt | 1 | 5142 | package tripleklay.ui
import klay.core.PaintClock
import klay.core.Platform
import klay.core.StubPlatform
import org.junit.Test
import react.Signal
import tripleklay.ui.layout.AxisLayout
import kotlin.test.assertTrue
// import klay.java.JavaPlatform;
class ElementTest {
val frame = Signal<PaintClock>()
internal open class TestGroup : Group(AxisLayout.vertical()) {
var added: Int = 0
var removed: Int = 0
fun assertAdded(count: Int) {
assertTrue(added == count && removed == count - 1)
}
fun assertRemoved(count: Int) {
assertTrue(removed == count && added == count)
}
override fun wasAdded() {
super.wasAdded()
added++
}
override fun wasRemoved() {
super.wasRemoved()
removed++
}
}
internal var iface = Interface(stub, frame)
internal fun newRoot(): Root {
return iface.createRoot(AxisLayout.vertical(), Stylesheet.builder().create())
}
/** Tests the basic functionality of adding and removing elements and that the wasAdded
* and wasRemoved members are called as expected. */
@Test
fun testAddRemove() {
val root = newRoot()
val g1 = TestGroup()
val g2 = TestGroup()
g1.assertRemoved(0)
root.add(g1)
g1.assertAdded(1)
g1.add(g2)
g1.assertAdded(1)
g2.assertAdded(1)
g1.remove(g2)
g1.assertAdded(1)
g2.assertRemoved(1)
root.remove(g1)
g1.assertRemoved(1)
g2.assertRemoved(1)
g1.add(g2)
g1.assertRemoved(1)
g2.assertRemoved(1)
root.add(g1)
g1.assertAdded(2)
g2.assertAdded(2)
}
/** Tests that a group may add a child into another group whilst being removed and that the
* child receives the appropriate calls to wasAdded and wasRemoved. Similarly tests for
* adding the child during its own add. */
@Test
fun testChildTransfer() {
class Pa : TestGroup() {
var child1 = TestGroup()
var child2 = TestGroup()
var brother = TestGroup()
override fun wasRemoved() {
// hand off the children to brother
brother.add(child1)
super.wasRemoved()
brother.add(child2)
}
override fun wasAdded() {
// steal the children back from brother
add(child1)
super.wasAdded()
add(child2)
}
}
val root = newRoot()
val pa = Pa()
pa.assertRemoved(0)
root.add(pa)
pa.assertAdded(1)
pa.child1.assertAdded(1)
pa.child2.assertAdded(1)
root.remove(pa)
pa.assertRemoved(1)
pa.child1.assertRemoved(1)
pa.child2.assertRemoved(1)
root.add(pa.brother)
pa.child1.assertAdded(2)
pa.child2.assertAdded(2)
root.add(pa)
pa.assertAdded(2)
pa.child1.assertAdded(3)
pa.child2.assertAdded(3)
root.remove(pa)
pa.assertRemoved(2)
pa.child1.assertAdded(4)
pa.child2.assertAdded(4)
}
/** Tests that a group may add a grandchild into another group whilst being removed and that
* the grandchild receives the appropriate calls to wasAdded and wasRemoved. Similarly tests
* for adding the grandchild during its own add. */
@Test
fun testGrandchildTransfer() {
class GrandPa : TestGroup() {
var child = TestGroup()
var grandchild1 = TestGroup()
var grandchild2 = TestGroup()
var brother = TestGroup()
init {
add(child)
}
override fun wasRemoved() {
brother.add(grandchild1)
super.wasRemoved()
brother.add(grandchild2)
}
override fun wasAdded() {
child.add(grandchild1)
super.wasAdded()
child.add(grandchild2)
}
}
val root = newRoot()
val pa = GrandPa()
pa.assertRemoved(0)
root.add(pa)
pa.assertAdded(1)
pa.grandchild1.assertAdded(1)
pa.grandchild2.assertAdded(1)
root.remove(pa)
pa.assertRemoved(1)
pa.grandchild1.assertRemoved(1)
pa.grandchild2.assertRemoved(1)
root.add(pa.brother)
pa.grandchild1.assertAdded(2)
pa.grandchild2.assertAdded(2)
root.add(pa)
pa.assertAdded(2)
pa.grandchild1.assertAdded(3)
pa.grandchild2.assertAdded(3)
root.remove(pa)
pa.assertRemoved(2)
pa.grandchild1.assertAdded(4)
pa.grandchild2.assertAdded(4)
}
companion object {
// static {
// JavaPlatform.Config config = new JavaPlatform.Config();
// config.headless = true;
// JavaPlatform.register(config);
// }
var stub: Platform = StubPlatform()
}
}
| apache-2.0 | 495bb2fb7984c3d1ef5d77593afb48e2 | 24.58209 | 96 | 0.558926 | 4.361323 | false | true | false | false |
mikepenz/FastAdapter | app/src/main/java/com/mikepenz/fastadapter/app/items/SectionHeaderItem.kt | 1 | 1030 | package com.mikepenz.fastadapter.app.items
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.mikepenz.fastadapter.app.R
import com.mikepenz.fastadapter.items.AbstractItem
import com.mikepenz.fastadapter.ui.utils.StringHolder
class SectionHeaderItem(text: String) : AbstractItem<SectionHeaderItem.ViewHolder>() {
val text: StringHolder = StringHolder(text)
override val type: Int
get() = R.id.fastadapter_section_header_item
override val layoutRes: Int
get() = R.layout.section_header_item
override fun bindView(holder: ViewHolder, payloads: List<Any>) {
super.bindView(holder, payloads)
text.applyTo(holder.text)
}
override fun unbindView(holder: ViewHolder) {
holder.text.text = null
}
override fun getViewHolder(v: View): ViewHolder = ViewHolder(v)
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var text: TextView = view.findViewById(R.id.text)
}
}
| apache-2.0 | 0d9dcfb76d0cb2b0b8f3d54312e4abcd | 30.212121 | 86 | 0.729126 | 4.153226 | false | false | false | false |
dahlstrom-g/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/snapshot/CompositeHashIdEnumerator.kt | 11 | 2463 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.indexing.snapshot
import com.intellij.openapi.Forceable
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.Comparing
import com.intellij.util.indexing.ID
import com.intellij.util.indexing.IndexInfrastructure
import com.intellij.util.io.DataInputOutputUtil
import com.intellij.util.io.IOUtil
import com.intellij.util.io.KeyDescriptor
import com.intellij.util.io.PersistentEnumerator
import java.io.Closeable
import java.io.DataInput
import java.io.DataOutput
import java.io.IOException
private val LOG = logger<CompositeHashIdEnumerator>()
internal class CompositeHashIdEnumerator(private val indexId: ID<*, *>): Closeable, Forceable {
@Volatile
private var enumerator = init()
@Throws(IOException::class)
override fun close() = enumerator.close()
override fun isDirty(): Boolean = enumerator.isDirty
override fun force() = enumerator.force()
@Throws(IOException::class)
fun clear() {
try {
close()
}
catch (e: IOException) {
LOG.error(e)
}
finally {
IOUtil.deleteAllFilesStartingWith(getBasePath())
init()
}
}
fun enumerate(hashId: Int, subIndexerTypeId: Int) = enumerator.enumerate(CompositeHashId(hashId, subIndexerTypeId))
private fun getBasePath() = IndexInfrastructure.getIndexRootDir(indexId).resolve("compositeHashId")
private fun init(): PersistentEnumerator<CompositeHashId> {
enumerator = PersistentEnumerator(getBasePath(), CompositeHashIdDescriptor(), 64 * 1024)
return enumerator
}
}
private data class CompositeHashId(val baseHashId: Int, val subIndexerTypeId: Int)
private class CompositeHashIdDescriptor : KeyDescriptor<CompositeHashId> {
override fun getHashCode(value: CompositeHashId): Int {
return value.hashCode()
}
override fun isEqual(val1: CompositeHashId, val2: CompositeHashId): Boolean {
return Comparing.equal(val1, val2)
}
@Throws(IOException::class)
override fun save(out: DataOutput, value: CompositeHashId) {
DataInputOutputUtil.writeINT(out, value.baseHashId)
DataInputOutputUtil.writeINT(out, value.subIndexerTypeId)
}
@Throws(IOException::class)
override fun read(`in`: DataInput): CompositeHashId {
return CompositeHashId(DataInputOutputUtil.readINT(`in`), DataInputOutputUtil.readINT(`in`))
}
} | apache-2.0 | 91d87d9091b6c33fd748edf072f1c943 | 31.421053 | 140 | 0.762891 | 4.359292 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/mcp/version/McpVersion.kt | 1 | 3151 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.version
import com.demonwav.mcdev.platform.mcp.McpVersionPair
import com.demonwav.mcdev.util.fromJson
import com.demonwav.mcdev.util.getMajorVersion
import com.demonwav.mcdev.util.sortVersions
import com.google.gson.Gson
import java.io.IOException
import java.net.URL
import java.util.ArrayList
import kotlin.Int
class McpVersion private constructor(private val map: Map<String, Map<String, List<Int>>>) {
val versions: List<String> by lazy {
sortVersions(map.keys)
}
data class McpVersionSet(val goodVersions: List<McpVersionPair>, val badVersions: List<McpVersionPair>)
private fun getSnapshot(version: String): McpVersionSet {
return get(version, "snapshot")
}
private fun getStable(version: String): McpVersionSet {
return get(version, "stable")
}
private operator fun get(version: String, type: String): McpVersionSet {
val good = ArrayList<McpVersionPair>()
val bad = ArrayList<McpVersionPair>()
val keySet = map.keys
for (mcVersion in keySet) {
val versions = map[mcVersion]
if (versions != null) {
versions[type]?.let { vers ->
val pairs = vers.map { McpVersionPair("${type}_$it", mcVersion) }
if (mcVersion.startsWith(version)) {
good.addAll(pairs)
} else {
bad.addAll(pairs)
}
}
}
}
return McpVersionSet(good, bad)
}
fun getMcpVersionList(version: String): List<McpVersionEntry> {
val result = mutableListOf<McpVersionEntry>()
val majorVersion = getMajorVersion(version)
val stable = getStable(majorVersion)
stable.goodVersions.asSequence().sortedWith(Comparator.reverseOrder())
.mapTo(result) { s -> McpVersionEntry(s) }
val snapshot = getSnapshot(majorVersion)
snapshot.goodVersions.asSequence().sortedWith(Comparator.reverseOrder())
.mapTo(result) { s -> McpVersionEntry(s) }
// The "seconds" in the pairs are bad, but still available to the user
// We will color them read
stable.badVersions.asSequence().sortedWith(Comparator.reverseOrder())
.mapTo(result) { s -> McpVersionEntry(s, true) }
snapshot.badVersions.asSequence().sortedWith(Comparator.reverseOrder())
.mapTo(result) { s -> McpVersionEntry(s, true) }
return result
}
companion object {
fun downloadData(): McpVersion? {
try {
val text = URL("http://export.mcpbot.bspk.rs/versions.json").readText()
val map = Gson().fromJson<Map<String, Map<String, List<Int>>>>(text)
val mcpVersion = McpVersion(map)
mcpVersion.versions
return mcpVersion
} catch (ignored: IOException) {
}
return null
}
}
}
| mit | aad7ac4eebd372aed9682cbd9e783479 | 30.828283 | 107 | 0.612821 | 4.627019 | false | false | false | false |
georocket/georocket | src/main/kotlin/io/georocket/cli/ImportCommand.kt | 1 | 9575 | package io.georocket.cli
import de.undercouch.underline.InputReader
import de.undercouch.underline.Option.ArgumentType
import de.undercouch.underline.OptionDesc
import de.undercouch.underline.UnknownAttributes
import io.georocket.ImporterVerticle
import io.georocket.constants.AddressConstants
import io.georocket.index.PropertiesParser
import io.georocket.index.TagsParser
import io.georocket.tasks.ImportingTask
import io.georocket.tasks.TaskRegistry
import io.georocket.util.MimeTypeUtils
import io.georocket.util.SizeFormat
import io.georocket.util.formatUntilNow
import io.vertx.core.buffer.Buffer
import io.vertx.core.json.JsonArray
import io.vertx.core.json.JsonObject
import io.vertx.core.streams.WriteStream
import io.vertx.kotlin.core.deploymentOptionsOf
import io.vertx.kotlin.coroutines.await
import kotlinx.coroutines.delay
import org.antlr.v4.runtime.misc.ParseCancellationException
import org.apache.commons.io.FilenameUtils
import org.apache.commons.lang3.SystemUtils
import org.apache.tools.ant.Project
import org.apache.tools.ant.types.FileSet
import org.bson.types.ObjectId
import org.fusesource.jansi.AnsiConsole
import org.slf4j.LoggerFactory
import java.io.File
import java.io.IOException
import java.nio.file.Paths
/**
* Import one or more files into GeoRocket
*/
class ImportCommand : GeoRocketCommand() {
companion object {
private val log = LoggerFactory.getLogger(ImportCommand::class.java)
}
override val usageName = "import"
override val usageDescription = "Import one or more files into GeoRocket"
private data class Metrics(val bytesImported: Long)
/**
* The patterns of the files to import
*/
@set:UnknownAttributes("FILE PATTERN")
var patterns = emptyList<String>()
@set:OptionDesc(longName = "layer", shortName = "l",
description = "absolute path to the destination layer",
argumentName = "PATH", argumentType = ArgumentType.STRING)
var layer: String? = null
@set:OptionDesc(longName = "fallbackCRS", shortName = "c",
description = "the CRS to use for indexing if the file does not specify one",
argumentName = "CRS", argumentType = ArgumentType.STRING)
var fallbackCRS: String? = null
@set:OptionDesc(longName = "tags", shortName = "t",
description = "comma-separated list of tags to attach to the file(s)",
argumentName = "TAGS", argumentType = ArgumentType.STRING)
var tags: String? = null
@set:OptionDesc(longName = "properties", shortName = "props",
description = "comma-separated list of properties (key:value) to attach to the file(s)",
argumentName = "PROPERTIES", argumentType = ArgumentType.STRING)
var properties: String? = null
override fun checkArguments(): Boolean {
if (patterns.isEmpty()) {
error("no file pattern given. provide at least one file to import.")
return false
}
if (tags != null) {
try {
TagsParser.parse(tags)
} catch (e: ParseCancellationException) {
error("Invalid tag syntax: ${e.message}")
return false
}
}
if (properties != null) {
try {
PropertiesParser.parse(properties)
} catch (e: ParseCancellationException) {
error("Invalid property syntax: ${e.message}")
return false
}
}
return super.checkArguments()
}
/**
* Check if the given string contains a glob character ('*', '{', '?', or '[')
* @param s the string
* @return true if the string contains a glob character, false otherwise
*/
private fun hasGlobCharacter(s: String): Boolean {
var i = 0
while (i < s.length) {
val c = s[i]
if (c == '\\') {
++i
} else if (c == '*' || c == '{' || c == '?' || c == '[') {
return true
}
++i
}
return false
}
override suspend fun doRun(remainingArgs: Array<String>, reader: InputReader,
out: WriteStream<Buffer>): Int {
val start = System.currentTimeMillis()
// resolve file patterns
val files = ArrayList<String>()
for (p in patterns) {
// convert Windows backslashes to slashes (necessary for Files.newDirectoryStream())
val pattern = if (SystemUtils.IS_OS_WINDOWS) {
FilenameUtils.separatorsToUnix(p)
} else {
p
}
// collect paths and glob patterns
val roots = ArrayList<String>()
val globs = ArrayList<String>()
val parts = pattern.split("/")
var rootParsed = false
for (part in parts) {
if (!rootParsed) {
if (hasGlobCharacter(part)) {
globs.add(part)
rootParsed = true
} else {
roots.add(part)
}
} else {
globs.add(part)
}
}
if (globs.isEmpty()) {
// string does not contain a glob pattern at all
files.add(pattern)
} else {
// string contains a glob pattern
if (roots.isEmpty()) {
// there are no paths in the string. start from the current
// working directory
roots.add(".")
}
// add all files matching the pattern
val root = roots.joinToString("/")
val glob = globs.joinToString("/")
val project = Project()
val fs = FileSet()
fs.dir = File(root)
fs.setIncludes(glob)
val ds = fs.getDirectoryScanner(project)
ds.includedFiles.mapTo(files) { Paths.get(root, it).toString() }
}
}
if (files.isEmpty()) {
error("given pattern didn't match any files")
return 1
}
return try {
val metrics = doImport(files)
var m = "file"
if (files.size > 1) {
m += "s"
}
println("Successfully imported ${files.size} $m")
println(" Total time: ${start.formatUntilNow()}")
println(" Total data size: ${SizeFormat.format(metrics.bytesImported)}")
0
} catch (t: Throwable) {
error(t.message)
1
}
}
/**
* Determine the sizes of all given files
* @param files the files
* @return a list of pairs containing file names and sizes
*/
private suspend fun getFileSizes(files: List<String>): List<Pair<String, Long>> {
val fs = vertx.fileSystem()
return files.map { path ->
val props = fs.props(path).await()
Pair(path, props.size())
}
}
/**
* Import files using a HTTP client and finally call a handler
* @param files the files to import
* @return an observable that will emit metrics when all files have been imported
*/
private suspend fun doImport(files: List<String>): Metrics {
AnsiConsole.systemInstall()
// launch importer verticle
val importerVerticleId = vertx.deployVerticle(ImporterVerticle(),
deploymentOptionsOf(config = config)).await()
try {
ImportProgressRenderer(vertx).use { progress ->
progress.totalFiles = files.size
val filesWithSizes = getFileSizes(files)
val totalSize = filesWithSizes.sumOf { it.second }
progress.totalSize = totalSize
var bytesImported = 0L
for (file in filesWithSizes.withIndex()) {
val path = file.value.first
val size = file.value.second
val index = file.index
progress.startNewFile(Paths.get(path).fileName.toString())
progress.index = index
progress.size = size
val m = importFile(path, size, progress)
bytesImported += m.bytesImported
}
return Metrics(bytesImported)
}
} finally {
vertx.undeploy(importerVerticleId).await()
AnsiConsole.systemUninstall()
}
}
/**
* Try to detect the content type of a file with the given [filepath].
*/
private suspend fun detectContentType(filepath: String): String {
return vertx.executeBlocking<String> { f ->
try {
var mimeType = MimeTypeUtils.detect(File(filepath))
if (mimeType == null) {
log.warn("Could not detect file type of $filepath. Falling back to " +
"application/octet-stream.")
mimeType = "application/octet-stream"
}
f.complete(mimeType)
} catch (e: IOException) {
f.fail(e)
}
}.await()
}
/**
* Upload a file to GeoRocket
* @param path the path to the file to import
* @param fileSize the size of the file
* @param progress a renderer that display the progress on the terminal
* @return a metrics object
*/
private suspend fun importFile(path: String, fileSize: Long,
progress: ImportProgressRenderer): Metrics {
val detectedContentType = detectContentType(path).also {
log.info("Guessed mime type '$it'.")
}
val correlationId = ObjectId().toString()
val msg = JsonObject()
.put("filepath", path)
.put("layer", layer)
.put("contentType", detectedContentType)
.put("correlationId", correlationId)
if (tags != null) {
msg.put("tags", JsonArray(TagsParser.parse(tags)))
}
if (properties != null) {
msg.put("properties", JsonObject(PropertiesParser.parse(properties)))
}
if (fallbackCRS != null) {
msg.put("fallbackCRSString", fallbackCRS)
}
// run importer
val taskId = vertx.eventBus().request<String>(AddressConstants.IMPORTER_IMPORT, msg).await().body()
while (true) {
val t = (TaskRegistry.getById(taskId) ?: break) as ImportingTask
progress.current = t.bytesProcessed
if (t.endTime != null) {
break
}
delay(100)
}
progress.current = fileSize
return Metrics(fileSize)
}
}
| apache-2.0 | be2cec6527fe15be761729c421a9cc56 | 29.396825 | 103 | 0.641984 | 4.257448 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/simpleapp1_16_0/SO_LIST_ALL_INVOKE.kt | 2 | 5758 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0
import org.apache.causeway.client.kroviz.snapshots.Response
object SO_LIST_ALL_INVOKE : Response() {
override val url = "http://localhost:8080/restful/services/simple.SimpleObjectMenu/actions/listAll/invoke"
override val str = """{
"links": [
{
"rel": "self",
"href": "http://localhost:8080/restful/services/simple.SimpleObjectMenu/actions/listAll/invoke",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/action-result\"",
"args": {}
}
],
"resulttype": "list",
"result": {
"value": [
{
"rel": "urn:org.restfulobjects:rels/element",
"href": "http://localhost:8080/restful/objects/simple.SimpleObject/0",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Object: Foo"
},
{
"rel": "urn:org.restfulobjects:rels/element",
"href": "http://localhost:8080/restful/objects/simple.SimpleObject/1",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Object: Bar"
},
{
"rel": "urn:org.restfulobjects:rels/element",
"href": "http://localhost:8080/restful/objects/simple.SimpleObject/2",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Object: Baz"
},
{
"rel": "urn:org.restfulobjects:rels/element",
"href": "http://localhost:8080/restful/objects/simple.SimpleObject/3",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Object: Frodo"
},
{
"rel": "urn:org.restfulobjects:rels/element",
"href": "http://localhost:8080/restful/objects/simple.SimpleObject/4",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Object: Froyo"
},
{
"rel": "urn:org.restfulobjects:rels/element",
"href": "http://localhost:8080/restful/objects/simple.SimpleObject/5",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Object: Fizz"
},
{
"rel": "urn:org.restfulobjects:rels/element",
"href": "http://localhost:8080/restful/objects/simple.SimpleObject/6",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Object: Bip"
},
{
"rel": "urn:org.restfulobjects:rels/element",
"href": "http://localhost:8080/restful/objects/simple.SimpleObject/7",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Object: Bop"
},
{
"rel": "urn:org.restfulobjects:rels/element",
"href": "http://localhost:8080/restful/objects/simple.SimpleObject/8",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Object: Bang"
},
{
"rel": "urn:org.restfulobjects:rels/element",
"href": "http://localhost:8080/restful/objects/simple.SimpleObject/9",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Object: Boo"
}
],
"links": [
{
"rel": "urn:org.restfulobjects:rels/return-type",
"href": "http://localhost:8080/restful/domain-types/java.util.List",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/domain-type\""
}
],
"extensions": {}
}
}"""
}
| apache-2.0 | c8575bb9f114f6540996e8865c46871f | 46.983333 | 112 | 0.511636 | 4.613782 | false | false | false | false |
google/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/JavaStandardMethodsConversion.kt | 4 | 4407 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.nj2k.conversions
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMethod
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.j2k.ast.Nullability.NotNull
import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext
import org.jetbrains.kotlin.nj2k.psi
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.nj2k.types.JKClassType
import org.jetbrains.kotlin.nj2k.types.JKJavaVoidType
import org.jetbrains.kotlin.nj2k.types.updateNullability
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class JavaStandardMethodsConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element !is JKClass) return recurse(element)
for (declaration in element.classBody.declarations) {
if (declaration !is JKMethodImpl) continue
if (fixToStringMethod(declaration)) continue
if (fixFinalizeMethod(declaration, element)) continue
if (fixCloneMethod(declaration)) {
val cloneableClass = JavaPsiFacade.getInstance(context.project)
.findClass("java.lang.Cloneable", GlobalSearchScope.allScope(context.project)) ?: continue
val directlyImplementsCloneable = element.psi<PsiClass>()?.isInheritor(cloneableClass, false) ?: continue
val hasCloneableInSuperClasses =
declaration.psi<PsiMethod>()
?.findSuperMethods()
?.any { superMethod ->
superMethod.containingClass?.kotlinFqName?.asString() != "java.lang.Object"
} == true
if (directlyImplementsCloneable && hasCloneableInSuperClasses) {
val directCloneableSupertype = element.inheritance.implements.find {
it.type.safeAs<JKClassType>()?.classReference?.fqName == "java.lang.Cloneable"
} ?: continue
element.inheritance.implements -= directCloneableSupertype
} else if (!directlyImplementsCloneable && !hasCloneableInSuperClasses) {
element.inheritance.implements += JKTypeElement(
JKClassType(
context.symbolProvider.provideClassSymbol("kotlin.Cloneable"),
nullability = NotNull
)
)
}
}
}
return recurse(element)
}
private fun fixToStringMethod(method: JKMethodImpl): Boolean {
if (method.name.value != "toString") return false
if (method.parameters.isNotEmpty()) return false
val type = (method.returnType.type as? JKClassType)
?.takeIf { it.classReference.name == "String" }
?.updateNullability(NotNull) ?: return false
method.returnType = JKTypeElement(type, method.returnType::annotationList.detached())
return true
}
private fun fixCloneMethod(method: JKMethodImpl): Boolean {
if (method.name.value != "clone") return false
if (method.parameters.isNotEmpty()) return false
val type = (method.returnType.type as? JKClassType)
?.takeIf { it.classReference.name == "Object" }
?.updateNullability(NotNull) ?: return false
method.returnType = JKTypeElement(type, method.returnType::annotationList.detached())
return true
}
private fun fixFinalizeMethod(method: JKMethodImpl, containingClass: JKClass): Boolean {
if (method.name.value != "finalize") return false
if (method.parameters.isNotEmpty()) return false
if (method.returnType.type != JKJavaVoidType) return false
if (method.hasOtherModifier(OtherModifier.OVERRIDE)) {
method.modality =
if (containingClass.modality == Modality.OPEN) Modality.OPEN
else Modality.FINAL
method.otherModifierElements -= method.otherModifierElements.first { it.otherModifier == OtherModifier.OVERRIDE }
}
return true
}
} | apache-2.0 | 4f4162e04e0fd105bb30c7527765e2c7 | 50.255814 | 125 | 0.657136 | 5.130384 | false | false | false | false |
denzelby/telegram-bot-bumblebee | telegram-bot-bumblebee-core/src/main/kotlin/com/github/bumblebee/command/statistics/entity/Statistic.kt | 2 | 1013 | package com.github.bumblebee.command.statistics.entity
import java.time.LocalDate
import javax.persistence.*
@Entity
@Table(name = "BB_STATISTICS")
class Statistic {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long? = null
var postedDate: LocalDate? = null
var messageCount: Int = 0
var chatId: Long = 0
var authorId: Long = 0
var authorName: String? = null
@Suppress("unused")
constructor()
constructor(postedDate: LocalDate,
messageCount: Int,
chatId: Long,
authorId: Long,
authorName: String?) {
this.postedDate = postedDate
this.messageCount = messageCount
this.chatId = chatId
this.authorId = authorId
this.authorName = authorName
}
override fun toString(): String {
return "Statistic(id=$id, postedDate=$postedDate, messageCount=$messageCount, chatId=$chatId, authorId=$authorId, authorName=$authorName)"
}
} | mit | 11cfabfbc125bea8825ea7ce696edef9 | 23.142857 | 146 | 0.638697 | 4.604545 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ToOrdinaryStringLiteralIntention.kt | 1 | 4357 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.idea.inspections.collections.isCalling
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class ToOrdinaryStringLiteralIntention : SelfTargetingOffsetIndependentIntention<KtStringTemplateExpression>(
KtStringTemplateExpression::class.java,
KotlinBundle.lazyMessage("to.ordinary.string.literal")
), LowPriorityAction {
companion object {
private val TRIM_INDENT_FUNCTIONS = listOf(FqName("kotlin.text.trimIndent"), FqName("kotlin.text.trimMargin"))
}
override fun isApplicableTo(element: KtStringTemplateExpression): Boolean {
return element.text.startsWith("\"\"\"")
}
override fun applyTo(element: KtStringTemplateExpression, editor: Editor?) {
val startOffset = element.startOffset
val endOffset = element.endOffset
val currentOffset = editor?.caretModel?.currentCaret?.offset ?: startOffset
val entries = element.entries
val trimIndentCall = getTrimIndentCall(element, entries)
val text = buildString {
append("\"")
if (trimIndentCall != null) {
append(trimIndentCall.stringTemplateText)
} else {
entries.joinTo(buffer = this, separator = "") {
if (it is KtLiteralStringTemplateEntry) it.text.escape() else it.text
}
}
append("\"")
}
val replaced = (trimIndentCall?.qualifiedExpression ?: element).replaced(KtPsiFactory(element.project).createExpression(text))
val offset = when {
currentOffset - startOffset < 2 -> startOffset
endOffset - currentOffset < 2 -> replaced.endOffset
else -> maxOf(currentOffset - 2, replaced.startOffset)
}
editor?.caretModel?.moveToOffset(offset)
}
private fun String.escape(escapeLineSeparators: Boolean = true): String {
var text = this
text = text.replace("\\", "\\\\")
text = text.replace("\"", "\\\"")
return if (escapeLineSeparators) text.escapeLineSeparators() else text
}
private fun String.escapeLineSeparators(): String {
return StringUtil.convertLineSeparators(this, "\\n")
}
private fun getTrimIndentCall(
element: KtStringTemplateExpression,
entries: Array<KtStringTemplateEntry>
): TrimIndentCall? {
val qualifiedExpression = element.getQualifiedExpressionForReceiver()?.takeIf {
it.callExpression?.isCalling(TRIM_INDENT_FUNCTIONS) == true
} ?: return null
val marginPrefix = if (qualifiedExpression.calleeName == "trimMargin") {
when (val arg = qualifiedExpression.callExpression?.valueArguments?.singleOrNull()?.getArgumentExpression()) {
null -> "|"
is KtStringTemplateExpression -> arg.entries.singleOrNull()?.takeIf { it is KtLiteralStringTemplateEntry }?.text
else -> null
} ?: return null
} else {
null
}
val stringTemplateText = entries
.joinToString(separator = "") {
if (it is KtLiteralStringTemplateEntry) it.text.escape(escapeLineSeparators = false) else it.text
}
.let { if (marginPrefix != null) it.trimMargin(marginPrefix) else it.trimIndent() }
.escapeLineSeparators()
return TrimIndentCall(qualifiedExpression, stringTemplateText)
}
private data class TrimIndentCall(
val qualifiedExpression: KtQualifiedExpression,
val stringTemplateText: String
)
}
| apache-2.0 | 319494a351c8229b14b6b5c51589c1d6 | 41.715686 | 158 | 0.683039 | 5.412422 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/matchAndConvert.kt | 1 | 17488 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions.loopToCallChain
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.Ref
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.cfg.pseudocode.Pseudocode
import org.jetbrains.kotlin.cfg.pseudocode.PseudocodeUtil
import org.jetbrains.kotlin.cfg.containingDeclarationForPseudocode
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.result.*
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence.*
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils.isSubtypeOfClass
import org.jetbrains.kotlin.resolve.calls.smartcasts.ExplicitSmartCasts
import org.jetbrains.kotlin.resolve.calls.smartcasts.ImplicitSmartCasts
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
object MatcherRegistrar {
val matchers: Collection<TransformationMatcher> = listOf(
FindTransformationMatcher,
AddToCollectionTransformation.Matcher,
CountTransformation.Matcher,
SumTransformationBase.Matcher,
MaxOrMinTransformation.Matcher,
IntroduceIndexMatcher,
FilterTransformationBase.Matcher,
MapTransformation.Matcher,
FlatMapTransformation.Matcher,
ForEachTransformation.Matcher
)
}
data class MatchResult(
val sequenceExpression: KtExpression,
val transformationMatch: TransformationMatch.Result,
val initializationStatementsToDelete: Collection<KtExpression>
)
//TODO: loop which is already over Sequence
fun match(loop: KtForExpression, useLazySequence: Boolean, reformat: Boolean): MatchResult? {
val (inputVariable, indexVariable, sequenceExpression) = extractLoopData(loop) ?: return null
var state = createInitialMatchingState(loop, inputVariable, indexVariable, useLazySequence, reformat) ?: return null
// used just as optimization to avoid unnecessary checks
val loopContainsEmbeddedBreakOrContinue = loop.containsEmbeddedBreakOrContinue()
MatchLoop@
while (true) {
state = state.unwrapBlock()
val inputVariableUsed = state.inputVariable.hasUsages(state.statements)
// drop index variable if it's not used anymore
if (state.indexVariable != null && !state.indexVariable!!.hasUsages(state.statements)) {
state = state.copy(indexVariable = null)
}
val restContainsEmbeddedBreakOrContinue =
loopContainsEmbeddedBreakOrContinue && state.statements.any { it.containsEmbeddedBreakOrContinue() }
MatchersLoop@
for (matcher in MatcherRegistrar.matchers) {
if (state.indexVariable != null && !matcher.indexVariableAllowed) continue
if (matcher.shouldUseInputVariables && !inputVariableUsed && state.indexVariable == null) continue
val match = matcher.match(state)
if (match != null) {
when (match) {
is TransformationMatch.Sequence -> {
// check that old input variable is not needed anymore
var newState = match.newState
if (state.inputVariable != newState.inputVariable && state.inputVariable.hasUsages(newState.statements)) return null
if (matcher.shouldUseInputVariables
&& !state.inputVariable.hasDifferentSetsOfUsages(state.statements, newState.statements)
&& state.indexVariable?.hasDifferentSetsOfUsages(state.statements, newState.statements) != true
) {
// matched part of the loop uses neither input variable nor index variable
continue@MatchersLoop
}
if (state.indexVariable != null && match.sequenceTransformations.any { it.affectsIndex }) {
// index variable is still needed but index in the new sequence is different
if (state.indexVariable!!.hasUsages(newState.statements)) return null
newState = newState.copy(indexVariable = null)
}
if (restContainsEmbeddedBreakOrContinue && !matcher.embeddedBreakOrContinuePossible) {
val countBefore = state.statements.sumOf { it.countEmbeddedBreaksAndContinues() }
val countAfter = newState.statements.sumOf { it.countEmbeddedBreaksAndContinues() }
if (countAfter != countBefore) continue@MatchersLoop // some embedded break or continue in the matched part
}
state.previousTransformations += match.sequenceTransformations
state = newState
continue@MatchLoop
}
is TransformationMatch.Result -> {
if (restContainsEmbeddedBreakOrContinue && !matcher.embeddedBreakOrContinuePossible) continue@MatchersLoop
state.previousTransformations += match.sequenceTransformations
var result = TransformationMatch.Result(match.resultTransformation, state.previousTransformations)
result = mergeTransformations(result, reformat)
if (useLazySequence) {
val sequenceTransformations = result.sequenceTransformations
val resultTransformation = result.resultTransformation
if (sequenceTransformations.isEmpty() && !resultTransformation.lazyMakesSense
|| sequenceTransformations.size == 1 && resultTransformation is AssignToListTransformation
) {
return null // it makes no sense to use lazy sequence if no intermediate sequences produced
}
val asSequence = AsSequenceTransformation(loop)
result = TransformationMatch.Result(resultTransformation, listOf(asSequence) + sequenceTransformations)
}
return MatchResult(sequenceExpression, result, state.initializationStatementsToDelete)
.takeIf { checkSmartCastsPreserved(loop, it) }
}
}
}
}
return null
}
}
fun convertLoop(loop: KtForExpression, matchResult: MatchResult): KtExpression {
val resultTransformation = matchResult.transformationMatch.resultTransformation
val commentSavingRange = resultTransformation.commentSavingRange
val commentSaver = CommentSaver(commentSavingRange)
val commentSavingRangeHolder = CommentSavingRangeHolder(commentSavingRange)
matchResult.initializationStatementsToDelete.forEach { commentSavingRangeHolder.add(it) }
val callChain = matchResult.generateCallChain(loop, true)
commentSavingRangeHolder.remove(loop.unwrapIfLabeled()) // loop will be deleted in all cases
val result = resultTransformation.convertLoop(callChain, commentSavingRangeHolder)
commentSavingRangeHolder.add(result)
for (statement in matchResult.initializationStatementsToDelete) {
commentSavingRangeHolder.remove(statement)
statement.delete()
}
// we need to adjust indent of the result because in some cases it's made incorrect when moving statement closer to the loop
commentSaver.restore(commentSavingRangeHolder.range, forceAdjustIndent = true)
return result
}
data class LoopData(
val inputVariable: KtCallableDeclaration,
val indexVariable: KtCallableDeclaration?,
val sequenceExpression: KtExpression
)
private fun extractLoopData(loop: KtForExpression): LoopData? {
val loopRange = loop.loopRange ?: return null
val destructuringParameter = loop.destructuringDeclaration
if (destructuringParameter != null && destructuringParameter.entries.size == 2) {
val qualifiedExpression = loopRange as? KtDotQualifiedExpression
if (qualifiedExpression != null) {
val call = qualifiedExpression.selectorExpression as? KtCallExpression
if (call != null && call.calleeExpression.isSimpleName(Name.identifier("withIndex")) && call.valueArguments.isEmpty()) {
val receiver = qualifiedExpression.receiverExpression
if (!isExpressionTypeSupported(receiver)) return null
return LoopData(destructuringParameter.entries[1], destructuringParameter.entries[0], receiver)
}
}
}
if (!isExpressionTypeSupported(loopRange)) return null
return LoopData(loop.loopParameter ?: return null, null, loopRange)
}
private fun createInitialMatchingState(
loop: KtForExpression,
inputVariable: KtCallableDeclaration,
indexVariable: KtCallableDeclaration?,
useLazySequence: Boolean,
reformat: Boolean
): MatchingState? {
val pseudocodeProvider: () -> Pseudocode = object : () -> Pseudocode {
val pseudocode: Pseudocode by lazy {
val declaration = loop.containingDeclarationForPseudocode!!
val bindingContext = loop.analyze(BodyResolveMode.FULL)
PseudocodeUtil.generatePseudocode(declaration, bindingContext)
}
override fun invoke() = pseudocode
}
return MatchingState(
outerLoop = loop,
innerLoop = loop,
statements = listOf(loop.body ?: return null),
inputVariable = inputVariable,
indexVariable = indexVariable,
lazySequence = useLazySequence,
pseudocodeProvider = pseudocodeProvider,
reformat = reformat
)
}
private fun isExpressionTypeSupported(expression: KtExpression): Boolean {
val type = expression.analyze(BodyResolveMode.PARTIAL).getType(expression) ?: return false
val builtIns = expression.builtIns
return when {
isSubtypeOfClass(type, builtIns.iterable) -> true
isSubtypeOfClass(type, builtIns.array) -> true
KotlinBuiltIns.isPrimitiveArray(type) -> true
// TODO: support Sequence<T>
else -> false
}
}
private fun checkSmartCastsPreserved(loop: KtForExpression, matchResult: MatchResult): Boolean {
val bindingContext = loop.analyze(BodyResolveMode.FULL)
// we declare these keys locally to avoid possible race-condition problems if this code is executed in 2 threads simultaneously
val SMARTCAST_KEY = Key<Ref<ExplicitSmartCasts>>("SMARTCAST_KEY")
val IMPLICIT_RECEIVER_SMARTCAST_KEY = Key<Ref<ImplicitSmartCasts>>("IMPLICIT_RECEIVER_SMARTCAST")
val storedUserData = mutableListOf<Ref<*>>()
var smartCastCount = 0
try {
loop.forEachDescendantOfType<KtExpression> { expression ->
bindingContext[BindingContext.SMARTCAST, expression]?.let { explicitSmartCasts ->
Ref(explicitSmartCasts).apply {
expression.putCopyableUserData(SMARTCAST_KEY, this)
storedUserData += this
}
smartCastCount++
}
bindingContext[BindingContext.IMPLICIT_RECEIVER_SMARTCAST, expression]?.let { implicitSmartCasts ->
Ref(implicitSmartCasts).apply {
expression.putCopyableUserData(IMPLICIT_RECEIVER_SMARTCAST_KEY, this)
storedUserData += this
}
smartCastCount++
}
}
if (smartCastCount == 0) return true // optimization
val callChain = matchResult.generateCallChain(loop, false)
val newBindingContext = callChain.analyzeAsReplacement(loop, bindingContext)
var preservedSmartCastCount = 0
callChain.forEachDescendantOfType<KtExpression> { expression ->
val smartCastType = expression.getCopyableUserData(SMARTCAST_KEY)?.get()
if (smartCastType != null) {
if (newBindingContext[BindingContext.SMARTCAST, expression] == smartCastType || newBindingContext.getType(expression) == smartCastType) {
preservedSmartCastCount++
}
}
val implicitReceiverSmartCastType = expression.getCopyableUserData(IMPLICIT_RECEIVER_SMARTCAST_KEY)?.get()
if (implicitReceiverSmartCastType != null) {
if (newBindingContext[BindingContext.IMPLICIT_RECEIVER_SMARTCAST, expression] == implicitReceiverSmartCastType) {
preservedSmartCastCount++
}
}
}
if (preservedSmartCastCount == smartCastCount) return true
// not all smart cast expressions has been found in the result or have the same type after conversion, perform more expensive check
val expression = matchResult.transformationMatch.resultTransformation.generateExpressionToReplaceLoopAndCheckErrors(callChain)
if (!tryChangeAndCheckErrors(loop) { it.replace(expression) }) return false
return true
} finally {
storedUserData.forEach { it.set(null) }
if (smartCastCount > 0) {
loop.forEachDescendantOfType<KtExpression> {
it.putCopyableUserData(SMARTCAST_KEY, null)
it.putCopyableUserData(IMPLICIT_RECEIVER_SMARTCAST_KEY, null)
}
}
}
}
private fun MatchResult.generateCallChain(loop: KtForExpression, reformat: Boolean): KtExpression {
var sequenceTransformations = transformationMatch.sequenceTransformations
var resultTransformation = transformationMatch.resultTransformation
while (true) {
val last = sequenceTransformations.lastOrNull() ?: break
resultTransformation = resultTransformation.mergeWithPrevious(last, reformat) ?: break
sequenceTransformations = sequenceTransformations.dropLast(1)
}
val chainCallCount = sequenceTransformations.sumOf { it.chainCallCount } + resultTransformation.chainCallCount
val lineBreak = if (chainCallCount > 1) "\n" else ""
var callChain = sequenceExpression
val psiFactory = KtPsiFactory(loop.project)
val chainedCallGenerator = object : ChainedCallGenerator {
override val receiver: KtExpression
get() = callChain
override val reformat: Boolean
get() = reformat
override fun generate(pattern: String, vararg args: Any, receiver: KtExpression, safeCall: Boolean): KtExpression {
val dot = if (safeCall) "?." else "."
val newPattern = "$" + args.size + lineBreak + dot + pattern
return psiFactory.createExpressionByPattern(newPattern, *args, receiver, reformat = reformat)
}
}
for (transformation in sequenceTransformations) {
callChain = transformation.generateCode(chainedCallGenerator)
}
callChain = resultTransformation.generateCode(chainedCallGenerator)
return callChain
}
private fun mergeTransformations(match: TransformationMatch.Result, reformat: Boolean): TransformationMatch.Result {
val transformations = (match.sequenceTransformations + match.resultTransformation).toMutableList()
var anyChange: Boolean
do {
anyChange = false
for (index in 0 until transformations.lastIndex) {
val transformation = transformations[index] as SequenceTransformation
val next = transformations[index + 1]
val merged = next.mergeWithPrevious(transformation, reformat) ?: continue
transformations[index] = merged
transformations.removeAt(index + 1)
anyChange = true
break
}
} while (anyChange)
@Suppress("UNCHECKED_CAST")
return TransformationMatch.Result(
transformations.last() as ResultTransformation,
transformations.dropLast(1) as List<SequenceTransformation>
)
}
data class IntroduceIndexData(
val indexVariable: KtCallableDeclaration,
val initializationStatement: KtExpression,
val incrementExpression: KtUnaryExpression
)
fun matchIndexToIntroduce(loop: KtForExpression, reformat: Boolean): IntroduceIndexData? {
if (loop.destructuringDeclaration != null) return null
val (inputVariable, indexVariable) = extractLoopData(loop) ?: return null
if (indexVariable != null) return null // loop is already with "withIndex"
val state = createInitialMatchingState(loop, inputVariable, indexVariable = null, useLazySequence = false, reformat = reformat)?.unwrapBlock()
?: return null
val match = IntroduceIndexMatcher.match(state) ?: return null
assert(match.sequenceTransformations.isEmpty())
val newState = match.newState
val initializationStatement = newState.initializationStatementsToDelete.single()
val incrementExpression = newState.incrementExpressions.single()
return IntroduceIndexData(newState.indexVariable!!, initializationStatement, incrementExpression)
}
| apache-2.0 | 6c8e2b292d02f062ec94a81ea4a10c05 | 44.072165 | 158 | 0.685213 | 5.796487 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/entity/model/special/TextureEntity.kt | 2 | 2999 | package io.github.chrislo27.rhre3.entity.model.special
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.fasterxml.jackson.databind.node.ObjectNode
import io.github.chrislo27.rhre3.editor.ClickOccupation
import io.github.chrislo27.rhre3.editor.Editor
import io.github.chrislo27.rhre3.entity.model.IStretchable
import io.github.chrislo27.rhre3.entity.model.ModelEntity
import io.github.chrislo27.rhre3.sfxdb.datamodel.impl.special.TextureModel
import io.github.chrislo27.rhre3.theme.Theme
import io.github.chrislo27.rhre3.track.Remix
class TextureEntity(remix: Remix, datamodel: TextureModel)
: ModelEntity<TextureModel>(remix, datamodel), IStretchable {
var textureHash: String? = null
override val isStretchable: Boolean = true
override val renderText: String
get() = if (textureHash != null) datamodel.name else "${datamodel.name}\n<no texture>"
override val glassEffect: Boolean = false
override val renderOnTop: Boolean = true
init {
this.bounds.height = 1f
}
override fun getRenderColor(editor: Editor, theme: Theme): Color {
return theme.entities.cue
}
override fun renderWithGlass(editor: Editor, batch: SpriteBatch, glass: Boolean) {
val textureHash = textureHash
if (textureHash != null) {
val tex = remix.textureCache[textureHash] ?: return super.render(editor, batch)
val renderBacking = this.isSelected || editor.clickOccupation is ClickOccupation.CreatingSelection
if (renderBacking) {
super.renderWithGlass(editor, batch, glass)
}
if (this.isSelected) {
batch.color = editor.theme.entities.selectionTint
}
if (renderBacking) {
batch.color = batch.color.apply { a *= 0.25f }
}
val ratio = tex.height.toFloat() / tex.width
batch.draw(tex, bounds.x + lerpDifference.x, bounds.y + lerpDifference.y, bounds.width + lerpDifference.width, (bounds.width + lerpDifference.height) * ratio / (Editor.ENTITY_HEIGHT / Editor.ENTITY_WIDTH))
batch.setColor(1f, 1f, 1f, 1f)
} else {
super.renderWithGlass(editor, batch, glass)
}
}
override fun onStart() {
}
override fun whilePlaying() {
}
override fun onEnd() {
}
override fun saveData(objectNode: ObjectNode) {
super.saveData(objectNode)
objectNode.put("texHash", textureHash)
}
override fun readData(objectNode: ObjectNode) {
super.readData(objectNode)
textureHash = objectNode["texHash"].asText(null)
}
override fun copy(remix: Remix): TextureEntity {
return TextureEntity(remix, datamodel).also {
it.updateBounds {
it.bounds.set([email protected])
}
// Set image ID
it.textureHash = [email protected]
}
}
} | gpl-3.0 | 429afde3a045b65cb96dde149030dbf4 | 34.714286 | 217 | 0.663555 | 4.17688 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/course_info/ui/adapter/delegates/CourseInfoInstructorsDelegate.kt | 1 | 2334 | package org.stepik.android.view.course_info.ui.adapter.delegates
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import by.kirich1409.viewbindingdelegate.viewBinding
import org.stepic.droid.R
import org.stepic.droid.databinding.ViewCourseInfoInstructorsBlockBinding
import org.stepik.android.model.user.User
import org.stepik.android.view.course_info.model.CourseInfoItem
import org.stepik.android.view.course_info.ui.adapter.delegates.instructors.CourseInfoInstructorDataAdapterDelegate
import org.stepik.android.view.course_info.ui.adapter.delegates.instructors.CourseInfoInstructorPlaceholderAdapterDelegate
import ru.nobird.android.ui.adapterdelegates.AdapterDelegate
import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder
import ru.nobird.android.ui.adapters.DefaultDelegateAdapter
class CourseInfoInstructorsDelegate(
private val onInstructorClicked: (User) -> Unit
) : AdapterDelegate<CourseInfoItem, DelegateViewHolder<CourseInfoItem>>() {
override fun onCreateViewHolder(parent: ViewGroup): ViewHolder =
ViewHolder(createView(parent, R.layout.view_course_info_instructors_block))
override fun isForViewType(position: Int, data: CourseInfoItem): Boolean =
data is CourseInfoItem.WithTitle.InstructorsBlock
inner class ViewHolder(root: View) : DelegateViewHolder<CourseInfoItem>(root) {
private val viewBinding: ViewCourseInfoInstructorsBlockBinding by viewBinding { ViewCourseInfoInstructorsBlockBinding.bind(root) }
private val adapter = DefaultDelegateAdapter<User?>()
init {
adapter += CourseInfoInstructorDataAdapterDelegate(onInstructorClicked)
adapter += CourseInfoInstructorPlaceholderAdapterDelegate()
viewBinding.blockInstructors.let {
it.adapter = adapter
it.layoutManager = LinearLayoutManager(root.context)
it.isNestedScrollingEnabled = false
}
}
override fun onBind(data: CourseInfoItem) {
data as CourseInfoItem.WithTitle.InstructorsBlock
viewBinding.blockHeader.blockIcon.setImageResource(data.type.icon)
viewBinding.blockHeader.blockTitle.setText(data.type.title)
adapter.items = data.instructors
}
}
} | apache-2.0 | 5970e0f70ae6b686e7707dcccc0f7b0b | 46.653061 | 138 | 0.770351 | 5.019355 | false | false | false | false |
silvertern/nox | src/main/kotlin/nox/compilation/ManifestUnpackingAction.kt | 1 | 1914 | /*
* Copyright (c) Oleg Sklyar 2017. License: MIT
*/
package nox.compilation
import nox.manifest.OsgiManifest
import org.gradle.api.Project
import org.gradle.api.internal.project.ProjectInternal
import org.gradle.jvm.tasks.Jar
import java.net.URI
import java.nio.file.*
class ManifestUnpackingAction {
private val manifestFile: Path
constructor(target: Project) {
val project = target as ProjectInternal
this.manifestFile = Paths.get(project.projectDir.absolutePath, "META-INF", "MANIFEST.MF")
val tasks = project.tasks
val ext = project.extensions
val platform = ext.findByType(OSGiExt::class.java)!!
val jarTask = tasks.getByName("jar") as Jar
// extension value has precedency over ext; default=unpack
if ((jarTask.manifest as OsgiManifest).from != null) {
return
} else if (platform.unpackOSGiManifest != null) {
if (!platform.unpackOSGiManifest!!) {
return
}
} else {
val extProps = ext.extraProperties
if (extProps.has(unpackOSGiManifest)) {
if (!java.lang.Boolean.valueOf(extProps.get(unpackOSGiManifest).toString())!!) {
return
}
}
}
val assembleTask = tasks.getByName("assemble")
val cleanTask = tasks.getByName("clean")
assembleTask.doLast { _ -> unpack(jarTask) }
cleanTask.doLast { _ -> clean() }
}
private fun unpack(jarTask: Jar) {
// ignore failure here, will throw below
manifestFile.parent.toFile().mkdirs()
val jarUri = URI.create("jar:" + jarTask.archivePath.toURI())
FileSystems.newFileSystem(jarUri, mapOf<String, Any>()).use { jarfs ->
val source = jarfs.getPath("META-INF", "MANIFEST.MF")
Files.copy(source, manifestFile, StandardCopyOption.REPLACE_EXISTING)
}
}
private fun clean() {
manifestFile.toFile().delete()
}
companion object {
/**
* Add osgiUnpackManifest=false to gradle.properties to prevent copying
*/
private val unpackOSGiManifest = "unpackOSGiManifest"
}
}
| mit | d09a8525bfbeee663a365fbbf14ec633 | 25.583333 | 91 | 0.713166 | 3.537893 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/editor/rendering/PlayalongRendering.kt | 2 | 7235 | package io.github.chrislo27.rhre3.editor.rendering
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.utils.Align
import io.github.chrislo27.rhre3.RHRE3Application
import io.github.chrislo27.rhre3.editor.Editor
import io.github.chrislo27.rhre3.playalong.Playalong
import io.github.chrislo27.rhre3.playalong.PlayalongChars
import io.github.chrislo27.rhre3.theme.Theme
import io.github.chrislo27.rhre3.util.scaleFont
import io.github.chrislo27.rhre3.util.unscaleFont
import io.github.chrislo27.toolboks.registry.AssetRegistry
import io.github.chrislo27.toolboks.util.gdxutils.fillRect
import io.github.chrislo27.toolboks.util.gdxutils.getTextHeight
import io.github.chrislo27.toolboks.util.gdxutils.getTextWidth
import io.github.chrislo27.toolboks.util.gdxutils.scaleMul
import kotlin.math.roundToInt
fun Editor.renderPlayalong(batch: SpriteBatch, beatRange: IntRange, alpha: Float) {
remix.playalong.renderPlayalong(main, camera, theme, batch, beatRange, alpha)
}
fun Playalong.renderPlayalong(main: RHRE3Application, camera: OrthographicCamera, theme: Theme,
batch: SpriteBatch, beatRange: IntRange, alpha: Float) {
if (alpha <= 0f) return
val largeFont = main.defaultBorderedFontLarge
largeFont.scaleFont(camera)
val playalong: Playalong = this
val recommendedHeight = largeFont.getTextHeight(PlayalongChars.FILLED_A)
val recommendedWidth = largeFont.getTextWidth(PlayalongChars.FILLED_A)
val blockHeight = recommendedHeight * 1.5f
val blockWidth = recommendedWidth * 1.1f
val baseY = camera.position.y + 1.5f
val skillStarInputPair = playalong.skillStarInput
val skillStarInput = skillStarInputPair?.first
for ((beatAt, list) in playalong.inputActionsByBeat) {
val listSize = list.size
if (skillStarInput != null && skillStarInput.beat == beatAt) {
val bottomY = baseY + (blockHeight * listSize) / 2 - (-1 + 0.5f) * blockHeight
largeFont.setColor(1f, 1f, 0f, 1f * alpha)
val star = "★"
val width = largeFont.getTextWidth(star)
val height = largeFont.getTextHeight(star)
largeFont.draw(batch, star, skillStarInput.beat + (if (!skillStarInputPair.second) skillStarInput.duration else 0f) + width * 0.02f, bottomY + height / 2, 0f, Align.center, false)
largeFont.setColor(1f, 1f, 1f, 1f)
}
list.forEachIndexed { index, inputAction ->
if (inputAction.beat.roundToInt() > beatRange.last || (inputAction.beat + inputAction.duration).roundToInt() < beatRange.first) return@forEachIndexed
largeFont.setColor(1f, 1f, 1f, 1f * alpha)
val bottomY = baseY + (blockHeight * listSize) / 2 - (index + 0.5f) * blockHeight
// Backing line
if (!inputAction.isInstantaneous) {
batch.setColor(theme.trackLine.r, theme.trackLine.g, theme.trackLine.b, theme.trackLine.a * alpha)
batch.fillRect(inputAction.beat, bottomY - 0.5f, inputAction.duration, 1f)
}
val results = playalong.inputted[inputAction]
val inProgress = playalong.inputsInProgress[inputAction]
if (inProgress != null) largeFont.setColor(0.2f, 0.57f, 1f, 1f * alpha)
if (results != null && results.results.isNotEmpty()) {
if (!results.missed) {
largeFont.setColor(0.2f, 1f, 0.2f, 1f * alpha)
batch.setColor(0.2f, 1f, 0.2f, 1f * alpha)
} else {
largeFont.setColor(1f, 0.15f, 0.15f, 1f * alpha)
batch.setColor(1f, 0.15f, 0.15f, 1f * alpha)
}
} else {
// if (inputAction.method == PlayalongMethod.RELEASE_AND_HOLD) {
// batch.setColor(0.75f, 0.35f, 1f, 1f * alpha)
// largeFont.setColor(0.75f, 0.35f, 1f, 1f * alpha)
// }
}
// For non-instantaneous inputs, draw a long line (progress)
if (!inputAction.isInstantaneous) {
val defWidth = inputAction.duration
val width = if (inProgress != null) {
batch.setColor(0.2f, 0.57f, 1f, 1f * alpha)
largeFont.setColor(0.2f, 0.57f, 1f, 1f * alpha)
remix.tempos.secondsToBeats(remix.tempos.beatsToSeconds((remix.beat - inputAction.beat)) - (if (inputAction.input.isTouchScreen) playalong.calibratedMouseOffset else playalong.calibratedKeyOffset))
} else if (results != null) {
(defWidth + (remix.tempos.secondsToBeats(remix.tempos.beatsToSeconds(inputAction.beat + inputAction.duration) + results.results.last().offset) - (inputAction.beat + inputAction.duration)))
} else 0f
batch.fillRect(inputAction.beat, bottomY - 0.5f, width.coerceAtLeast(0f), 1f)
}
val x = inputAction.beat
val y = bottomY
val boxWidth = blockWidth
val boxHeight = blockHeight
val lastBatchColor = batch.packedColor
// Backing box
batch.setColor(0f, 0f, 0f, 0.4f * alpha)
batch.fillRect(x - boxWidth / 2, y - boxHeight / 2, boxWidth, boxHeight)
batch.setColor(1f, 1f, 1f, 0.75f * alpha)
val thinWidth = boxWidth * 0.05f
batch.fillRect(x - thinWidth / 2, y - boxHeight / 2, thinWidth, boxHeight)
batch.setColor(1f, 1f, 1f, 1f * alpha)
// Render text or texture
val trackDisplayText = if (inputAction.method.isRelease) inputAction.input.releaseTrackDisplayText else inputAction.input.trackDisplayText
val isTexID = if (inputAction.method.isRelease) inputAction.input.releaseTrackDisplayIsTexID else inputAction.input.trackDisplayIsTexID
if (isTexID) {
batch.packedColor = lastBatchColor
batch.draw(AssetRegistry.get<Texture>(trackDisplayText), x - boxWidth / 2, y - boxHeight / 2, boxWidth, boxHeight)
batch.setColor(1f, 1f, 1f, 1f)
} else {
val estHeight = largeFont.getTextHeight(trackDisplayText)
val scaleY = if (estHeight > recommendedHeight) {
recommendedHeight / estHeight
} else 1f
largeFont.scaleMul(scaleY)
val estWidth = largeFont.getTextWidth(trackDisplayText)
val scaleX = if (estWidth > recommendedWidth) {
recommendedWidth / estWidth
} else 1f
largeFont.scaleMul(scaleX)
// val width = largeFont.getTextWidth(trackDisplayText)
val height = largeFont.getTextHeight(trackDisplayText)
largeFont.draw(batch, trackDisplayText, x, y + height / 2, 0f, Align.center, false)
largeFont.setColor(1f, 1f, 1f, 1f)
largeFont.scaleMul(1f / scaleX)
largeFont.scaleMul(1f / scaleY)
}
}
}
batch.setColor(1f, 1f, 1f, 1f)
largeFont.unscaleFont()
}
| gpl-3.0 | 8e41f887136c2843b568427b282f9eb0 | 52.183824 | 217 | 0.634038 | 4.12607 | false | false | false | false |
scenerygraphics/scenery | src/main/kotlin/graphics/scenery/proteins/Rainbow.kt | 1 | 2177 | package graphics.scenery.proteins
import graphics.scenery.Node
import org.joml.Vector3f
/**
* This is the class which stores the calculation for a color vector along a Mesh.
*
* @author Justin Buerger <[email protected]>
*/
//TODO implement iteration depth that the number of children is flexible
class Rainbow {
/*
Palette Rainbow colors palette has 7 HEX, RGB codes colors:
HEX: #ff0000 RGB: (255, 0, 0),
HEX: #ffa500 RGB: (255, 165, 0),
HEX: #ffff00 RGB: (255, 255, 0),
HEX: #008000 RGB: (0, 128, 0),
HEX: #0000ff RGB: (0, 0, 255),
HEX: #4b0082 RGB: (75, 0, 130),
HEX: #ee82ee RGB: (238, 130, 238).*
*see: https://colorswall.com/palette/102/
*/
private val rainbowPaletteNotScaled = listOf(Vector3f(255f, 0f, 0f), Vector3f(255f, 165f, 0f),
Vector3f(255f, 255f, 0f), Vector3f(0f, 128f, 0f), Vector3f(0f, 0f, 255f),
Vector3f(75f, 0f, 135f), Vector3f(238f, 130f, 238f))
private val rainbowPalette = rainbowPaletteNotScaled.map { it.mul(1/255f) }
/**
* Assigns each child its color.
*/
fun colorVector(subProtein: Node) {
var childrenSize = 0
subProtein.children.forEach { ss ->
ss.children.forEach {
childrenSize++
}
}
val childrenCount = childrenSize
val sixth = (childrenCount/6)
val colorList = ArrayList<Vector3f>(childrenCount)
for(j in 1..6) {
val dif = Vector3f()
rainbowPalette[j].sub(rainbowPalette[j-1], dif)
for(i in 0 until sixth) {
val color = Vector3f()
colorList.add(dif.mul(i.toFloat()/sixth.toFloat(), color).add(rainbowPalette[j-1], color))
}
}
for(k in 0 until (childrenCount - colorList.size)) {
colorList.add(rainbowPalette[6])
}
var listIndex = 0
subProtein.children.forEach { ss ->
ss.children.forEach {
it.ifMaterial {
diffuse = colorList[listIndex]
}
listIndex++
}
}
}
}
| lgpl-3.0 | 9163e11dc77a75c6e07756c9d088630b | 32.492308 | 106 | 0.558107 | 3.708688 | false | false | false | false |
allotria/intellij-community | platform/vcs-code-review/src/com/intellij/util/ui/codereview/BaseHtmlEditorPane.kt | 2 | 3272 | // 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.util.ui.codereview
import com.intellij.ide.ui.AntialiasingType
import com.intellij.openapi.util.IconLoader
import com.intellij.ui.BrowserHyperlinkListener
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.JBHtmlEditorKit
import com.intellij.util.ui.JBUI
import org.jetbrains.annotations.Nls
import java.awt.Graphics
import java.awt.Shape
import javax.swing.JEditorPane
import javax.swing.SizeRequirements
import javax.swing.text.DefaultCaret
import javax.swing.text.Element
import javax.swing.text.View
import javax.swing.text.ViewFactory
import javax.swing.text.html.HTML
import javax.swing.text.html.InlineView
import javax.swing.text.html.ParagraphView
import kotlin.math.max
private const val ICON_INLINE_ELEMENT_NAME = "icon-inline" // NON-NLS
open class BaseHtmlEditorPane(iconsClass: Class<*>) : JEditorPane() {
init {
editorKit = object : JBHtmlEditorKit(true) {
override fun getViewFactory() = createViewFactory(iconsClass)
}
isEditable = false
isOpaque = false
addHyperlinkListener(BrowserHyperlinkListener.INSTANCE)
margin = JBUI.emptyInsets()
GraphicsUtil.setAntialiasingType(this, AntialiasingType.getAAHintForSwingComponent())
val caret = caret as DefaultCaret
caret.updatePolicy = DefaultCaret.NEVER_UPDATE
}
fun setBody(@Nls body: String) {
if (body.isEmpty()) {
text = ""
}
else {
text = "<html><body>$body</body></html>"
}
}
protected open fun createViewFactory(iconsClass: Class<*>): ViewFactory = HtmlEditorViewFactory(iconsClass)
protected open class HtmlEditorViewFactory(private val iconsClass: Class<*>) : JBHtmlEditorKit.JBHtmlFactory() {
override fun create(elem: Element): View {
if (ICON_INLINE_ELEMENT_NAME == elem.name) {
val icon = elem.attributes.getAttribute(HTML.Attribute.SRC)
?.let { IconLoader.getIcon(it as String, iconsClass) }
if (icon != null) {
return object : InlineView(elem) {
override fun getPreferredSpan(axis: Int): Float {
when (axis) {
View.X_AXIS -> return icon.iconWidth.toFloat() + super.getPreferredSpan(axis)
else -> return super.getPreferredSpan(axis)
}
}
override fun paint(g: Graphics, allocation: Shape) {
super.paint(g, allocation)
icon.paintIcon(null, g, allocation.bounds.x, allocation.bounds.y)
}
}
}
}
val view = super.create(elem)
if (view is ParagraphView) {
return MyParagraphView(elem)
}
return view
}
}
protected open class MyParagraphView(elem: Element) : ParagraphView(elem) {
override fun calculateMinorAxisRequirements(axis: Int, r: SizeRequirements?): SizeRequirements {
var r = r
if (r == null) {
r = SizeRequirements()
}
r.minimum = layoutPool.getMinimumSpan(axis).toInt()
r.preferred = max(r.minimum, layoutPool.getPreferredSpan(axis).toInt())
r.maximum = Integer.MAX_VALUE
r.alignment = 0.5f
return r
}
}
} | apache-2.0 | 08958ff52754ad5f9fe9cd380662c3f0 | 32.397959 | 140 | 0.686125 | 4.168153 | false | false | false | false |
spring-projects/spring-framework | spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/server/ServerRequestExtensions.kt | 1 | 5813 | /*
* 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 kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.reactor.awaitSingleOrNull
import kotlinx.coroutines.reactive.awaitSingle
import kotlinx.coroutines.reactive.asFlow
import org.springframework.core.ParameterizedTypeReference
import org.springframework.http.MediaType
import org.springframework.http.codec.multipart.Part
import org.springframework.util.CollectionUtils
import org.springframework.util.MultiValueMap
import org.springframework.web.server.WebSession
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import java.net.InetSocketAddress
import java.security.Principal
import kotlin.reflect.KClass
/**
* Extension for [ServerRequest.bodyToMono] providing a `bodyToMono<Foo>()` variant
* leveraging Kotlin reified type parameters. This extension is not subject to type
* erasure and retains actual generic type arguments.
*
* @author Sebastien Deleuze
* @since 5.0
*/
inline fun <reified T : Any> ServerRequest.bodyToMono(): Mono<T> =
bodyToMono(object : ParameterizedTypeReference<T>() {})
/**
* Extension for [ServerRequest.bodyToFlux] providing a `bodyToFlux<Foo>()` variant
* leveraging Kotlin reified type parameters. This extension is not subject to type
* erasure and retains actual generic type arguments.
*
* @author Sebastien Deleuze
* @since 5.0
*/
inline fun <reified T : Any> ServerRequest.bodyToFlux(): Flux<T> =
bodyToFlux(object : ParameterizedTypeReference<T>() {})
/**
* Coroutines [kotlinx.coroutines.flow.Flow] based variant of [ServerRequest.bodyToFlux].
*
* @author Sebastien Deleuze
* @since 5.2
*/
inline fun <reified T : Any> ServerRequest.bodyToFlow(): Flow<T> =
bodyToFlux<T>().asFlow()
/**
* `KClass` coroutines [kotlinx.coroutines.flow.Flow] based variant of [ServerRequest.bodyToFlux].
* Please consider `bodyToFlow<Foo>` variant if possible.
*
* @author Igor Manushin
* @since 5.3
*/
fun <T : Any> ServerRequest.bodyToFlow(clazz: KClass<T>): Flow<T> =
bodyToFlux(clazz.java).asFlow()
/**
* Non-nullable Coroutines variant of [ServerRequest.bodyToMono].
*
* @author Sebastien Deleuze
* @since 5.2
*/
suspend inline fun <reified T : Any> ServerRequest.awaitBody(): T =
bodyToMono<T>().awaitSingle()
/**
* `KClass` non-nullable Coroutines variant of [ServerRequest.bodyToMono].
* Please consider `awaitBody<Foo>` variant if possible.
*
* @author Igor Manushin
* @since 5.3
*/
suspend fun <T : Any> ServerRequest.awaitBody(clazz: KClass<T>): T =
bodyToMono(clazz.java).awaitSingle()
/**
* Nullable Coroutines variant of [ServerRequest.bodyToMono].
*
* @author Sebastien Deleuze
* @since 5.2
*/
@Suppress("DEPRECATION")
suspend inline fun <reified T : Any> ServerRequest.awaitBodyOrNull(): T? =
bodyToMono<T>().awaitSingleOrNull()
/**
* `KClass` nullable Coroutines variant of [ServerRequest.bodyToMono].
* Please consider `awaitBodyOrNull<Foo>` variant if possible.
*
* @author Igor Manushin
* @since 5.3
*/
@Suppress("DEPRECATION")
suspend fun <T : Any> ServerRequest.awaitBodyOrNull(clazz: KClass<T>): T? =
bodyToMono(clazz.java).awaitSingleOrNull()
/**
* Coroutines variant of [ServerRequest.formData].
*
* @author Sebastien Deleuze
* @since 5.2
*/
suspend fun ServerRequest.awaitFormData(): MultiValueMap<String, String> =
formData().awaitSingle()
/**
* Coroutines variant of [ServerRequest.multipartData].
*
* @author Sebastien Deleuze
* @since 5.2
*/
suspend fun ServerRequest.awaitMultipartData(): MultiValueMap<String, Part> =
multipartData().awaitSingle()
/**
* Coroutines variant of [ServerRequest.principal].
*
* @author Sebastien Deleuze
* @since 5.2
*/
@Suppress("DEPRECATION")
suspend fun ServerRequest.awaitPrincipal(): Principal? =
principal().awaitSingleOrNull()
/**
* Coroutines variant of [ServerRequest.session].
*
* @author Sebastien Deleuze
* @since 5.2
*/
suspend fun ServerRequest.awaitSession(): WebSession =
session().awaitSingle()
/**
* Nullable variant of [ServerRequest.remoteAddress]
*
* @author Sebastien Deleuze
* @since 5.2.2
*/
fun ServerRequest.remoteAddressOrNull(): InetSocketAddress? = remoteAddress().orElse(null)
/**
* Nullable variant of [ServerRequest.attribute]
*
* @author Sebastien Deleuze
* @since 5.2.2
*/
fun ServerRequest.attributeOrNull(name: String): Any? = attributes()[name]
/**
* Nullable variant of [ServerRequest.queryParam]
*
* @author Sebastien Deleuze
* @since 5.2.2
*/
fun ServerRequest.queryParamOrNull(name: String): String? {
val queryParamValues = queryParams()[name]
return if (CollectionUtils.isEmpty(queryParamValues)) {
null
} else {
var value: String? = queryParamValues!![0]
if (value == null) {
value = ""
}
value
}
}
/**
* Nullable variant of [ServerRequest.Headers.contentLength]
*
* @author Sebastien Deleuze
* @since 5.2.2
*/
fun ServerRequest.Headers.contentLengthOrNull(): Long? =
contentLength().run { if (isPresent) asLong else null }
/**
* Nullable variant of [ServerRequest.Headers.contentType]
*
* @author Sebastien Deleuze
* @since 5.2.2
*/
fun ServerRequest.Headers.contentTypeOrNull(): MediaType? =
contentType().orElse(null)
| apache-2.0 | b7ec7b8ebcd49baeca67b86ca196cdf0 | 27.495098 | 98 | 0.736797 | 3.962509 | false | false | false | false |
google/oboe | samples/minimaloboe/src/main/java/com/example/minimaloboe/ui/theme/Type.kt | 2 | 612 | package com.example.minimaloboe.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 24.sp
),
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 20.sp
)
)
| apache-2.0 | 02189e913b936ff15aa51ce9f7fe1ed5 | 28.142857 | 50 | 0.720588 | 4.22069 | false | false | false | false |
leafclick/intellij-community | plugins/stats-collector/src/com/intellij/completion/ml/common/CommonLocationFeatures.kt | 1 | 2625 | // 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.completion.ml.common
import com.intellij.codeInsight.completion.ml.CompletionEnvironment
import com.intellij.codeInsight.completion.ml.ContextFeatureProvider
import com.intellij.codeInsight.completion.ml.MLFeatureValue
import com.intellij.completion.ngram.NGram
import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.util.PlatformUtils
class CommonLocationFeatures : ContextFeatureProvider {
override fun getName(): String = "common"
override fun calculateFeatures(environment: CompletionEnvironment): Map<String, MLFeatureValue> {
val lookup = environment.lookup
val editor = lookup.topLevelEditor
val caretOffset = lookup.lookupStart
val logicalPosition = editor.offsetToLogicalPosition(caretOffset)
val lineStartOffset = editor.document.getLineStartOffset(logicalPosition.line)
val linePrefix = editor.document.getText(TextRange(lineStartOffset, caretOffset))
putNGramScorer(environment)
val result = mutableMapOf(
"line_num" to MLFeatureValue.float(logicalPosition.line),
"col_num" to MLFeatureValue.float(logicalPosition.column),
"indent_level" to MLFeatureValue.float(LocationFeaturesUtil.indentLevel(linePrefix, EditorUtil.getTabSize(editor))),
"is_in_line_beginning" to MLFeatureValue.binary(StringUtil.isEmptyOrSpaces(linePrefix))
)
if (DumbService.isDumb(lookup.project)) {
result["dumb_mode"] = MLFeatureValue.binary(true)
}
result.addPsiParents(environment.parameters.position, 10)
return result
}
private fun putNGramScorer(environment: CompletionEnvironment) {
val scoringFunction = NGram.createScoringFunction(environment.parameters, 4)
if(scoringFunction != null) {
environment.putUserData(NGram.NGRAM_SCORER_KEY, scoringFunction)
}
}
private fun MutableMap<String, MLFeatureValue>.addPsiParents(position: PsiElement, numParents: Int) {
// First parent is always referenceExpression
var curParent: PsiElement? = position.parent ?: return
for (i in 1..numParents) {
curParent = curParent?.parent ?: return
val parentName = "parent_$i"
this[parentName] = MLFeatureValue.className(curParent::class.java)
if (curParent is PsiFileSystemItem) return
}
}
} | apache-2.0 | 2aca152d3f8bfd84f53cef0d9efe012b | 42.766667 | 140 | 0.776 | 4.557292 | false | false | false | false |
leafclick/intellij-community | platform/lang-api/src/com/intellij/refactoring/suggested/SuggestedRefactoringExecution.kt | 1 | 4762 | // 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.refactoring.suggested
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.RefactoringFactory
/**
* A service performing actual changes in the code when user executes suggested refactoring.
*/
abstract class SuggestedRefactoringExecution(protected val refactoringSupport: SuggestedRefactoringSupport) {
open fun rename(data: SuggestedRenameData, project: Project, editor: Editor) {
val relativeCaretOffset = editor.caretModel.offset - anchorOffset(data.declaration)
val newName = data.declaration.name!!
runWriteAction {
data.declaration.setName(data.oldName)
}
var refactoring = RefactoringFactory.getInstance(project).createRename(data.declaration, newName, true, true)
refactoring.respectEnabledAutomaticRenames()
val usages = refactoring.findUsages()
if (usages.any { it.isNonCodeUsage } && !ApplicationManager.getApplication().isHeadlessEnvironment) {
val question = RefactoringBundle.message(
"suggested.refactoring.rename.comments.strings.occurrences",
data.oldName,
newName
)
val result = Messages.showOkCancelDialog(
project,
question,
RefactoringBundle.message("suggested.refactoring.rename.comments.strings.occurrences.title"),
RefactoringBundle.message("suggested.refactoring.rename.with.preview.button.text"),
RefactoringBundle.message("suggested.refactoring.ignore.button.text"),
Messages.getQuestionIcon()
)
if (result != Messages.OK) {
refactoring = RefactoringFactory.getInstance(project).createRename(data.declaration, newName, false, false)
refactoring.respectEnabledAutomaticRenames()
}
}
refactoring.run()
if (data.declaration.isValid) {
editor.caretModel.moveToOffset(relativeCaretOffset + anchorOffset(data.declaration))
}
}
open fun changeSignature(
data: SuggestedChangeSignatureData,
newParameterValues: List<NewParameterValue>,
project: Project,
editor: Editor
) {
val preparedData = prepareChangeSignature(data)
val relativeCaretOffset = editor.caretModel.offset - anchorOffset(data.declaration)
val restoreNewSignature = runWriteAction {
data.restoreInitialState(refactoringSupport)
}
performChangeSignature(data, newParameterValues, preparedData)
runWriteAction {
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document)
restoreNewSignature()
editor.caretModel.moveToOffset(relativeCaretOffset + anchorOffset(data.declaration))
}
}
/**
* Prepares data for Change Signature refactoring while the declaration has state with user changes (the new signature).
*/
abstract fun prepareChangeSignature(data: SuggestedChangeSignatureData): Any?
/**
* Performs Change Signature refactoring. This method is invoked with the declaration reverted to its original state
* before user changes (the old signature). The list of imports is also reverted to the original state.
*/
abstract fun performChangeSignature(data: SuggestedChangeSignatureData, newParameterValues: List<NewParameterValue>, preparedData: Any?)
private fun anchorOffset(declaration: PsiElement): Int {
return refactoringSupport.nameRange(declaration)?.startOffset ?: declaration.startOffset
}
/**
* Use this implementation of [SuggestedRefactoringExecution], if only Rename refactoring is supported for the language.
*/
open class RenameOnly(refactoringSupport: SuggestedRefactoringSupport) : SuggestedRefactoringExecution(refactoringSupport) {
override fun performChangeSignature(
data: SuggestedChangeSignatureData,
newParameterValues: List<NewParameterValue>,
preparedData: Any?
) {
throw UnsupportedOperationException()
}
override fun prepareChangeSignature(data: SuggestedChangeSignatureData): Any? {
throw UnsupportedOperationException()
}
}
/**
* Class representing value for a new parameter to be used for updating arguments of calls.
*/
sealed class NewParameterValue {
object None : NewParameterValue()
data class Expression(val expression: PsiElement) : NewParameterValue()
object AnyVariable : NewParameterValue()
}
} | apache-2.0 | 4840a180900e0bbaf52735f651240a51 | 38.691667 | 140 | 0.761445 | 5.41752 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/main/kotlin/com/vrem/util/StringUtils.kt | 1 | 1140 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.util
import java.util.*
val String.Companion.EMPTY: String get() = ""
val String.Companion.SPACE_SEPARATOR: String get() = " "
fun String.specialTrim(): String =
this.trim { it <= ' ' }.replace(" +".toRegex(), String.SPACE_SEPARATOR)
fun String.toCapitalize(locale: Locale): String =
this.replaceFirstChar { word -> word.uppercase(locale) }
| gpl-3.0 | 39cc403c479a99825f9572b47d266579 | 38.310345 | 90 | 0.725439 | 4.071429 | false | false | false | false |
code-helix/slatekit | src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_SmartValues.kt | 1 | 2601 | /**
<slate_header>
author: Kishore Reddy
url: www.github.com/code-helix/slatekit
copyright: 2015 Kishore Reddy
license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md
desc: A tool-kit, utility library and server-backend
usage: Please refer to license on github for more info.
</slate_header>
*/
package slatekit.examples
//<doc:import_required>
import slatekit.common.smartvalues.Email
import slatekit.results.Try
import slatekit.results.Success
//</doc:import_required>
//<doc:import_examples>
import slatekit.results.Outcome
//</doc:import_examples>
class Example_SmartValues : Command("results") {
override fun execute(request: CommandRequest): Try<Any> {
//<doc:examples>
// Smart strings provide a way to store, validate and describe
// a strongly typed/formatted string. This concept is called
// a smart string and is designed to be used specifically at
// application boundaries ( such as API endpoints ).
// There are a few smart strings provided out of the box such as
// 1. Email
// 2. PhoneUS
// 3. SSN
// 4. ZipCode
val email = Email.of("[email protected]")
// Case 1: Get the actual value
println("value: " + email.value)
// Case 2: Check if valid
println("valid?: " + Email.isValid("[email protected]"))
// Case 3: Get the name / type of smart string
println("name: " + email.meta.name)
// Case 4: Description
println("desc: " + email.meta.desc)
// Case 4: Examples of valid string
println("examples: " + email.meta.examples)
// Case 5: Format of the string
println("format(s): " + email.meta.formats)
// Case 6: The regular expression representing string
println("reg ex: " + email.meta.expressions)
// Case 7: Get the first example
println("example: " + email.meta.example)
// Case 9: Using slatekit.result types
// Try<Email> = Result<Email,Exception>
val email2:Try<Email> = Email.attempt("[email protected]")
// Outcome<Email> = Result<Email,Err>
val email3:Outcome<Email> = Email.outcome("[email protected]")
//</doc:examples>
return Success("")
}
/*
//<doc:output>
{{< highlight yaml >}}
value: [email protected]
valid?: true
name: Email
desc: Email Address
examples: [[email protected]]
format(s): [xxxx@xxxxxxx]
reg ex: [([\w\$\.\-_]+)@([\w\.]+)]
example: [email protected]
domain?: gotham.com
dashed?: false
{{< /highlight >}}
//</doc:output>
*/
}
| apache-2.0 | c8630aa9c378c444726bb38755913888 | 26.378947 | 72 | 0.630142 | 3.819383 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-apis/src/main/kotlin/slatekit/apis/Verbs.kt | 1 | 1792 | package slatekit.apis
import slatekit.apis.setup.Parentable
/* ktlint-disable */
object Verbs {
/**
* This allows for automatically determining the verb based on the method name
* e.g.
* 1. getXX = "get"
* 2. createXX = "post"
* 3. updateXX = "put"
* 4. deleteXX = "delete"
* 5. patchXX = "patch"
*/
const val AUTO = "auto"
/**
* Core operations supported
*/
const val GET = "get"
const val CREATE = "create"
const val UPDATE = "update"
const val DELETE = "delete"
/**
* Here for compatibility with HTTP/REST
*/
const val POST = "post"
const val PUT = "put"
const val PATCH = "patch"
const val PARENT = ApiConstants.parent
}
sealed class Verb(override val name: String) : Parentable<Verb> {
object Auto : Verb(Verbs.AUTO)
object Get : Verb(Verbs.GET)
object Create : Verb(Verbs.CREATE)
object Update : Verb(Verbs.UPDATE)
object Put : Verb(Verbs.PUT)
object Post : Verb(Verbs.POST)
object Patch : Verb(Verbs.PATCH)
object Delete : Verb(Verbs.DELETE)
object Parent : Verb(Verbs.PARENT)
fun isMatch(other:String):Boolean = this.name == other
companion object {
fun parse(name:String): Verb {
return when(name) {
Verbs.AUTO -> Verb.Auto
Verbs.GET -> Verb.Get
Verbs.CREATE -> Verb.Create
Verbs.UPDATE -> Verb.Update
Verbs.PUT -> Verb.Put
Verbs.POST -> Verb.Post
Verbs.PATCH -> Verb.Patch
Verbs.DELETE -> Verb.Delete
Verbs.PARENT -> Verb.Parent
else -> Verb.Auto
}
}
}
}
/* ktlint-enable */
| apache-2.0 | 89deac72e2c6a5de795fb45531b3a626 | 24.239437 | 82 | 0.548549 | 3.982222 | false | false | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/daemon/DaemonCodeAnalyzerSettingsImpl.kt | 1 | 2256 | // 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.codeInsight.daemon
import com.intellij.codeInspection.ex.ApplicationInspectionProfileManager
import com.intellij.codeInspection.ex.DEFAULT_PROFILE_NAME
import com.intellij.codeInspection.ex.InspectionProfileImpl
import com.intellij.configurationStore.serializeObjectInto
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.util.JDOMUtil
import com.intellij.util.xmlb.XmlSerializer.deserializeInto
import org.jdom.Element
@State(name = "DaemonCodeAnalyzerSettings", storages = [Storage("editor.xml"), Storage("editor.codeinsight.xml", deprecated = true)])
open class DaemonCodeAnalyzerSettingsImpl : DaemonCodeAnalyzerSettings(), PersistentStateComponent<Element>, Cloneable {
override fun isCodeHighlightingChanged(oldSettings: DaemonCodeAnalyzerSettings): Boolean {
return !JDOMUtil.areElementsEqual((oldSettings as DaemonCodeAnalyzerSettingsImpl).state, state)
}
public override fun clone(): DaemonCodeAnalyzerSettingsImpl {
val settings = DaemonCodeAnalyzerSettingsImpl()
settings.autoReparseDelay = autoReparseDelay
settings.myShowAddImportHints = myShowAddImportHints
settings.SHOW_METHOD_SEPARATORS = SHOW_METHOD_SEPARATORS
settings.NO_AUTO_IMPORT_PATTERN = NO_AUTO_IMPORT_PATTERN
return settings
}
override fun getState(): Element? {
val element = Element("state")
serializeObjectInto(this, element)
val profile = ApplicationInspectionProfileManager.getInstanceImpl().rootProfileName
if (DEFAULT_PROFILE_NAME != profile) {
element.setAttribute("profile", profile)
}
return element
}
override fun loadState(state: Element) {
deserializeInto(this, state)
val profileManager = ApplicationInspectionProfileManager.getInstanceImpl()
profileManager.converter.storeEditorHighlightingProfile(state, InspectionProfileImpl(InspectionProfileConvertor.OLD_HIGHTLIGHTING_SETTINGS_PROFILE))
profileManager.setRootProfile(state.getAttributeValue("profile") ?: "Default")
}
}
| apache-2.0 | 22003f0fa080ca265b4760bd9f04ccde | 48.043478 | 152 | 0.808067 | 4.99115 | false | false | false | false |
blokadaorg/blokada | android5/app/src/main/java/model/AppModel.kt | 1 | 989 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package model
import com.squareup.moshi.JsonClass
typealias AppId = String
class App(
val id: AppId,
val name: String,
val isBypassed: Boolean,
val isSystem: Boolean
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as App
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id.hashCode()
}
}
@JsonClass(generateAdapter = true)
class BypassedAppIds(
val ids: List<AppId>
)
enum class AppState {
Deactivated, Paused, Activated
} | mpl-2.0 | a7a24b5690aae832e0e256b129fb6e3a | 19.604167 | 70 | 0.65081 | 3.770992 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/safeCall/primitiveNotEqSafeCall.kt | 4 | 948 | fun Long.id() = this
fun String.drop2() = if (length >= 2) subSequence(2, length) else null
fun String.anyLength(): Any = length
fun doSimple(s: String?) = 3 != s?.length
fun doLongReceiver(x: Long) = 3L != x?.id()
fun doChain(s: String?) = 1 != s?.drop2()?.length
fun doIf(s: String?) =
if (1 != s?.length) "A" else "B"
fun doCmpWithAny(s: String?) =
3 != s?.anyLength()
fun box(): String = when {
!doSimple(null) -> "failed 1"
!doSimple("1") -> "failed 2"
doSimple("123") -> "failed 3"
!doLongReceiver(2L) -> "failed 4"
doLongReceiver(3L) -> "failed 5"
!doChain(null) -> "failed 6"
!doChain("1") -> "failed 7"
doChain("123") -> "failed 7"
doIf("1") == "A" -> "failed 8"
doIf("123") == "B" -> "failed 9"
doIf(null) == "B" -> "failed 10"
!doCmpWithAny(null) -> "failed 11"
!doCmpWithAny("1") -> "failed 12"
doCmpWithAny("123") -> "failed 13"
else -> "OK"
} | apache-2.0 | 362d28dee33b37d12531936ef6a73c51 | 21.069767 | 70 | 0.547468 | 2.846847 | false | false | false | false |
AndroidX/androidx | compose/ui/ui-test/src/androidAndroidTest/kotlin/androidx/compose/ui/test/FindersTest.kt | 3 | 8879 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.test
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.SemanticsPropertyReceiver
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTag
import androidx.compose.ui.semantics.text
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.text.AnnotatedString
import androidx.test.filters.MediumTest
import androidx.compose.testutils.expectError
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.editableText
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import androidx.test.ext.junit.runners.AndroidJUnit4
@MediumTest
@RunWith(AndroidJUnit4::class)
class FindersTest {
@get:Rule
val rule = createComposeRule()
@Test
fun findAll_zeroOutOfOne_findsNone() {
rule.setContent {
BoundaryNode { testTag = "not_myTestTag" }
}
rule.onAllNodes(hasTestTag("myTestTag")).assertCountEquals(0)
}
@Test
fun findAll_oneOutOfTwo_findsOne() {
rule.setContent {
BoundaryNode { testTag = "myTestTag" }
BoundaryNode { testTag = "myTestTag2" }
}
rule.onAllNodes(hasTestTag("myTestTag"))
.assertCountEquals(1)
.onFirst()
.assert(hasTestTag("myTestTag"))
}
@Test
fun findAll_twoOutOfTwo_findsTwo() {
rule.setContent {
BoundaryNode { testTag = "myTestTag" }
BoundaryNode { testTag = "myTestTag" }
}
rule.onAllNodes(hasTestTag("myTestTag"))
.assertCountEquals(2)
.apply {
get(0).assert(hasTestTag("myTestTag"))
get(1).assert(hasTestTag("myTestTag"))
}
}
@Test
fun findByText_matches() {
rule.setContent {
BoundaryNode { text = AnnotatedString("Hello World") }
}
rule.onNodeWithText("Hello World").assertExists()
}
@Test
fun findByText_withEditableText_matches() {
rule.setContent {
BoundaryNode { editableText = AnnotatedString("Hello World") }
}
rule.onNodeWithText("Hello World").assertExists()
}
@Test
fun findByText_merged_matches() {
rule.setContent {
Box(Modifier.semantics(mergeDescendants = true) { }) {
Text("Hello")
Text("World")
}
}
rule.onNodeWithText("Hello").assertExists()
rule.onNodeWithText("World").assertExists()
rule.onAllNodesWithText("Hello").assertCountEquals(1)
rule.onAllNodesWithText("World").assertCountEquals(1)
}
@Test(expected = AssertionError::class)
fun findByText_fails() {
rule.setContent {
BoundaryNode { text = AnnotatedString("Hello World") }
}
// Need to assert exists or it won't fail
rule.onNodeWithText("World").assertExists()
}
@Test(expected = AssertionError::class)
fun findByText_merged_fails() {
rule.setContent {
Box(Modifier.semantics(mergeDescendants = true) { }) {
Text("Hello")
Text("World")
}
}
rule.onNodeWithText("Hello, World").assertExists()
}
@Test
fun findBySubstring_matches() {
rule.setContent {
BoundaryNode { text = AnnotatedString("Hello World") }
}
rule.onNodeWithText("World", substring = true).assertExists()
}
@Test
fun findBySubstring_merged_matches() {
rule.setContent {
Box(Modifier.semantics(mergeDescendants = true) { }) {
Text("Hello")
Text("World")
}
}
rule.onNodeWithText("Wo", substring = true).assertExists()
rule.onNodeWithText("He", substring = true).assertExists()
}
@Test
fun findBySubstring_ignoreCase_matches() {
rule.setContent {
BoundaryNode { text = AnnotatedString("Hello World") }
}
rule.onNodeWithText("world", substring = true, ignoreCase = true).assertExists()
}
@Test
fun findBySubstring_wrongCase_fails() {
rule.setContent {
BoundaryNode { text = AnnotatedString("Hello World") }
}
expectError<AssertionError> {
// Need to assert exists or it won't fetch nodes
rule.onNodeWithText("world", substring = true).assertExists()
}
}
@Test
fun findAllBySubstring() {
rule.setContent {
BoundaryNode { text = AnnotatedString("Hello World") }
BoundaryNode { text = AnnotatedString("Wello Horld") }
}
rule.onAllNodesWithText("Yellow World", substring = true).assertCountEquals(0)
rule.onAllNodesWithText("Hello", substring = true).assertCountEquals(1)
rule.onAllNodesWithText("Wello", substring = true).assertCountEquals(1)
rule.onAllNodesWithText("ello", substring = true).assertCountEquals(2)
}
@Test
fun findByContentDescription_matches() {
rule.setContent {
BoundaryNode { contentDescription = "Hello World" }
}
rule.onNodeWithContentDescription("Hello World").assertExists()
}
@Test
fun findByContentDescription_merged_matches() {
rule.setContent {
Box(Modifier.semantics(mergeDescendants = true) { }) {
Box(Modifier.semantics { contentDescription = "Hello" })
Box(Modifier.semantics { contentDescription = "World" })
}
}
rule.onNodeWithContentDescription("Hello").assertExists()
rule.onNodeWithContentDescription("World").assertExists()
rule.onAllNodesWithContentDescription("Hello").assertCountEquals(1)
rule.onAllNodesWithContentDescription("World").assertCountEquals(1)
}
@Test(expected = AssertionError::class)
fun findByContentDescription_fails() {
rule.setContent {
BoundaryNode { contentDescription = "Hello World" }
}
rule.onNodeWithContentDescription("Hello").assertExists()
}
@Test(expected = AssertionError::class)
fun findByContentDescription_merged_fails() {
rule.setContent {
Box(Modifier.semantics(mergeDescendants = true) { }) {
Box(Modifier.semantics { contentDescription = "Hello" })
Box(Modifier.semantics { contentDescription = "World" })
}
}
rule.onNodeWithText("Hello, World").assertExists()
}
@Test
fun findByContentDescription_substring_matches() {
rule.setContent {
BoundaryNode { contentDescription = "Hello World" }
}
rule.onNodeWithContentDescription("World", substring = true).assertExists()
}
@Test
fun findByContentDescription_merged_substring_matches() {
rule.setContent {
Box(Modifier.semantics(mergeDescendants = true) { }) {
Box(Modifier.semantics { contentDescription = "Hello" })
Box(Modifier.semantics { contentDescription = "World" })
}
}
rule.onNodeWithContentDescription("Wo", substring = true).assertExists()
rule.onNodeWithContentDescription("He", substring = true).assertExists()
}
fun findByContentDescription_substring_noResult() {
rule.setContent {
BoundaryNode { contentDescription = "Hello World" }
}
rule.onNodeWithContentDescription("world", substring = true)
.assertDoesNotExist()
}
@Test
fun findByContentDescription_substring_ignoreCase_matches() {
rule.setContent {
BoundaryNode { contentDescription = "Hello World" }
}
rule.onNodeWithContentDescription("world", substring = true, ignoreCase = true)
.assertExists()
}
@Composable
fun BoundaryNode(props: (SemanticsPropertyReceiver.() -> Unit)) {
Column(Modifier.semantics(properties = props)) {}
}
} | apache-2.0 | 29710d291ab8885d4ceeef5ed8867e9d | 30.267606 | 88 | 0.632729 | 5.062144 | false | true | false | false |
smmribeiro/intellij-community | build/tasks/test/org/jetbrains/intellij/build/tasks/ReorderJarsTest.kt | 2 | 4676 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("UsePropertyAccessSyntax")
package org.jetbrains.intellij.build.tasks
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.rules.InMemoryFsExtension
import com.intellij.util.io.inputStream
import com.intellij.util.lang.ImmutableZipFile
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.common.Attributes
import io.opentelemetry.api.trace.Span
import org.apache.commons.compress.archivers.zip.ZipFile
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.intellij.build.io.zip
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.ForkJoinTask
import java.util.zip.ZipEntry
import kotlin.random.Random
private val testDataPath: Path
get() = Path.of(PlatformTestUtil.getPlatformTestDataPath(), "plugins/reorderJars")
class ReorderJarsTest {
@RegisterExtension
@JvmField
val fs = InMemoryFsExtension()
@Test
fun `keep all dirs with resources`() {
// check that not only immediate parent of resource file is preserved, but also any dir in a path
val random = Random(42)
val rootDir = fs.root.resolve("dir")
val dir = rootDir.resolve("dir2/dir3")
Files.createDirectories(dir)
Files.write(dir.resolve("resource.txt"), random.nextBytes(random.nextInt(128)))
val dir2 = rootDir.resolve("anotherDir")
Files.createDirectories(dir2)
Files.write(dir2.resolve("resource2.txt"), random.nextBytes(random.nextInt(128)))
val archiveFile = fs.root.resolve("archive.jar")
zip(archiveFile, mapOf(rootDir to ""), compress = false, addDirEntries = true)
doReorderJars(mapOf(archiveFile to emptyList()), archiveFile.parent, archiveFile.parent)
ImmutableZipFile.load(archiveFile).use { zipFile ->
assertThat(zipFile.getResource("anotherDir")).isNotNull()
assertThat(zipFile.getResource("dir2")).isNotNull()
assertThat(zipFile.getResource("dir2/dir3")).isNotNull()
}
ImmutableZipFile.load(archiveFile).use { zipFile ->
assertThat(zipFile.getResource("anotherDir")).isNotNull()
}
}
@Test
fun testReordering(@TempDir tempDir: Path) {
val path = testDataPath
ZipFile("$path/annotations.jar").use { zipFile1 ->
zipFile1.entries.toList()
}
Files.createDirectories(tempDir)
doReorderJars(readClassLoadingLog(path.resolve("order.txt").inputStream(), path, "idea.jar"), path, tempDir)
val files = tempDir.toFile().listFiles()!!
assertThat(files).isNotNull()
assertThat(files).hasSize(1)
val file = files[0].toPath()
assertThat(file.fileName.toString()).isEqualTo("annotations.jar")
var data: ByteArray
ZipFile(Files.newByteChannel(file)).use { zipFile2 ->
val entries = zipFile2.entriesInPhysicalOrder.toList()
val entry = entries[0]
data = zipFile2.getInputStream(entry).readNBytes(entry.size.toInt())
assertThat(data).hasSize(548)
assertThat(entry.name).isEqualTo("org/jetbrains/annotations/Nullable.class")
assertThat(entries[1].name).isEqualTo("org/jetbrains/annotations/NotNull.class")
assertThat(entries[2].name).isEqualTo("META-INF/MANIFEST.MF")
}
}
@Test
fun testPluginXml(@TempDir tempDir: Path) {
Files.createDirectories(tempDir)
val path = testDataPath
doReorderJars(readClassLoadingLog(path.resolve("zkmOrder.txt").inputStream(), path, "idea.jar"), path, tempDir)
val files = tempDir.toFile().listFiles()!!
assertThat(files).isNotNull()
val file = files[0]
assertThat(file.name).isEqualTo("zkm.jar")
ZipFile(file).use { zipFile ->
val entries: List<ZipEntry> = zipFile.entries.toList()
assertThat(entries.first().name).isEqualTo("META-INF/plugin.xml")
}
}
}
private fun doReorderJars(sourceToNames: Map<Path, List<String>>, sourceDir: Path, targetDir: Path) {
ForkJoinTask.invokeAll(sourceToNames.mapNotNull { (jarFile, orderedNames) ->
if (Files.notExists(jarFile)) {
Span.current().addEvent("cannot find jar", Attributes.of(AttributeKey.stringKey("file"), sourceDir.relativize(jarFile).toString()))
return@mapNotNull null
}
task(tracer.spanBuilder("reorder jar")
.setAttribute("file", sourceDir.relativize(jarFile).toString())) {
reorderJar(jarFile, orderedNames, if (targetDir == sourceDir) jarFile else targetDir.resolve(sourceDir.relativize(jarFile)))
}
})
} | apache-2.0 | 43f8c63c586f124cf1a44ba001958cce | 38.974359 | 158 | 0.735885 | 4.163847 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/rename/renameBundle/before/usages.kt | 13 | 286 | import org.jetbrains.annotations.PropertyKey
private val BUNDLE_NAME = "FooBundle"
public fun message(@PropertyKey(resourceBundle = "FooBundle") key: String) = key
public fun message2(@PropertyKey(resourceBundle = BUNDLE_NAME) key: String) = key
fun test() {
message("foo.bar")
} | apache-2.0 | 4d0dbdfa5d02a7e2783b84ebcbe26e5d | 27.7 | 81 | 0.751748 | 3.813333 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.