repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Softmotions/ncms | ncms-engine/ncms-engine-core/src/main/java/com/softmotions/ncms/mtt/http/MttVHostsFilter.kt | 1 | 1464 | package com.softmotions.ncms.mtt.http
import com.google.inject.Singleton
import com.softmotions.commons.re.RegexpHelper
import org.slf4j.LoggerFactory
import javax.annotation.concurrent.ThreadSafe
import javax.servlet.http.HttpServletRequest
@Singleton
@ThreadSafe
open class MttVHostsFilter : MttFilterHandler {
companion object {
val log = LoggerFactory.getLogger(MttVHostsFilter::class.java)
}
override val type: String = "vhosts"
override fun matched(ctx: MttFilterHandlerContext, req: HttpServletRequest): Boolean {
if (!ctx.contains("pattern")) {
synchronized(this) {
if (ctx.contains("pattern")) return@synchronized
val spec = ctx.spec
val mode = spec.path("mode").asText("")
val pattern = spec.path("pattern").asText("")
if (mode == "regexp") {
ctx["pattern"] = Regex(pattern)
} else if (mode == "glob") {
ctx["pattern"] = Regex(RegexpHelper.convertGlobToRegEx(pattern))
} else {
log.error("Invalid filter spec: ${spec}")
return false
}
}
}
val re = (ctx["pattern"] as Regex)
if (log.isDebugEnabled) {
log.debug("regexp='${re}' pattern='${req.serverName}' res=${re.matches(req.serverName)}")
}
return re.matches(req.serverName)
}
} | apache-2.0 | 69016821e89d5c765f1699abcb029599 | 33.880952 | 101 | 0.583333 | 4.532508 | false | false | false | false |
kun368/ACManager | src/main/java/com/zzkun/controller/api/CptApi.kt | 1 | 6905 | package com.zzkun.controller.api
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.github.salomonbrys.kotson.jsonObject
import com.zzkun.dao.CptTreeRepo
import com.zzkun.model.User
import com.zzkun.service.UserService
import com.zzkun.util.cpt.Node
import com.zzkun.util.cpt.NodeAnalyser
import com.zzkun.util.cpt.NodeType
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import java.util.*
import kotlin.collections.set
/**
* Created by Administrator on 2017/2/24 0024.
*/
@RestController
@RequestMapping("/api/cpt")
open class CptApi(
@Autowired private val nodeAnalyser: NodeAnalyser,
@Autowired private val cptTreeRepo: CptTreeRepo,
@Autowired private val userService: UserService) {
companion object {
private val logger: Logger = LoggerFactory.getLogger(CptApi::class.java)
}
/////////// 章节树增删改差
@RequestMapping(value = ["/seeNode/{cptId}/{nodeId}"],
method = [(RequestMethod.GET)],
produces = ["text/html;charset=UTF-8"])
fun seeNode(@PathVariable cptId: Int,
@PathVariable nodeId: Int): String {
val rootNode = nodeAnalyser.getNode(cptId)!!
val curNode = rootNode.findSon(nodeId)!!
val sons = JSONArray()
curNode.son.forEach {
sons.add(mapOf("id" to it.id, "name" to it.name))
}
return JSONObject(mapOf("id" to curNode.id, "name" to curNode.name, "sons" to sons)).toJSONString()
}
@RequestMapping(value = ["/{cptId}/ztreestr"],
method = [(RequestMethod.GET)],
produces = ["text/html;charset=UTF-8"])
fun zTreeStr(@PathVariable cptId: Int):String {
val rootNode = nodeAnalyser.getNode(cptId)
val res = JSONArray()
if (rootNode != null) {
val qu = ArrayDeque<Pair<Node, Int>>()
qu.addLast(Pair(rootNode, 0))
while (qu.isNotEmpty()) {
val cur = qu.pollFirst()!!
val map = HashMap<String, Any>(3)
map["id"] = cur.first.id
map["pId"] = cur.second
map["isParent"] = cur.first.type == NodeType.LIST
map["name"] = cur.first.name
res.add(JSONObject(map))
for (i in cur.first.son)
qu.addLast(Pair(i, cur.first.id))
}
}
return res.toJSONString()
}
@RequestMapping(value = ["/{treeID}/delete/{nodeID}"],
method = [(RequestMethod.POST)],
produces = ["text/html;charset=UTF-8"])
fun deleteSon(@PathVariable treeID: Int,
@PathVariable nodeID: Int,
@SessionAttribute(required = false) user: User?): String {
logger.info("删除节点:${treeID} - ${nodeID}")
if (user == null || !user.isAdmin) {
return jsonObject(
"ok" to "false",
"status" to "没有权限!").toString()
}
if (nodeAnalyser.deleteSon(treeID, nodeID)) {
return JSON.toJSONString(mapOf("ok" to "true", "status" to "操作成功!"))
} else {
return JSON.toJSONString(mapOf("ok" to "false", "status" to "操作有误,情重试!"))
}
}
@RequestMapping(value = ["/{treeID}/rename/{nodeID}/{newName}"],
method = [(RequestMethod.POST)],
produces = ["text/html;charset=UTF-8"])
fun renameNode(@PathVariable treeID: Int,
@PathVariable nodeID: Int,
@PathVariable newName: String,
@SessionAttribute(required = false) user: User?): String {
logger.info("重命名节点:${treeID} - ${nodeID} - ${newName}")
if (user == null || !user.isAdmin) {
return jsonObject(
"ok" to "false",
"status" to "没有权限!").toString()
}
if (nodeAnalyser.renameSon(treeID, nodeID, newName)) {
return JSON.toJSONString(mapOf("ok" to "true", "status" to "操作成功!"))
} else {
return JSON.toJSONString(mapOf("ok" to "false", "status" to "操作有误,情重试!"))
}
}
@RequestMapping(value = ["/{treeID}/addNode"],
method = [(RequestMethod.POST)],
produces = ["text/html;charset=UTF-8"])
fun addNode(@PathVariable treeID: Int,
@RequestParam id: Int,
@RequestParam pId: Int,
@RequestParam isParent: Boolean,
@RequestParam name: String,
@SessionAttribute(required = false) user: User?): String {
logger.info("添加节点:treeID = [$treeID], id = [$id], pId = [$pId], isParent = [$isParent], name = [$name], user = [${user?.username}]")
if (user == null || !user.isAdmin) {
return jsonObject(
"ok" to "false",
"status" to "没有权限!").toString()
}
if (nodeAnalyser.addSon(treeID, pId, id, isParent, name)) {
return JSON.toJSONString(mapOf("ok" to "true", "status" to "操作成功!"))
} else {
return JSON.toJSONString(mapOf("ok" to "false", "status" to "操作有误,情重试!"))
}
}
//////// 统计数据
@RequestMapping(value = ["/statistic/{cptId}/{nodeId}"],
method = [(RequestMethod.GET)],
produces = ["text/html;charset=UTF-8"])
fun statistic(@PathVariable cptId: Int,
@PathVariable nodeId: Int): String {
val rootNode = nodeAnalyser.getNode(cptId)!!
val curNode = rootNode.findSon(nodeId)!!
val list = ArrayList<Node>()
list.add(curNode)
list.addAll(curNode.son)
val users = userService.allNormalNotNullUsers()
val res = ArrayList<HashMap<String, Any>>()
for (user in users) {
val map = LinkedHashMap<String, Any>()
map["userId"] = user.id
map["userName"] = user.username
map["userReal"] = user.realName
map["userMajor"] = user.major
map["userType"] = user.type.toShortStr()
val ac = user.acPbList.map { "${it.ojPbId}@${it.ojName}" }.toHashSet()
for (node in list) {
map["acCount${node.id}"] = node.allPids().intersect(ac).size
map["sumProb${node.id}"] = node.allPids().size
}
res.add(map)
}
return JSON.toJSONString(mapOf("data" to res))
}
} | gpl-3.0 | c0a069ebe32fb5d5f5dc47a502dd3d4c | 38.113095 | 140 | 0.546089 | 4.01969 | false | false | false | false |
sk89q/SquirrelID | buildSrc/src/main/kotlin/ArtifactoryConfig.kt | 1 | 1438 | import org.gradle.api.Project
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.named
import org.jfrog.gradle.plugin.artifactory.dsl.ArtifactoryPluginConvention
import org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask
private const val ARTIFACTORY_CONTEXT_URL = "artifactory_contextUrl"
private const val ARTIFACTORY_USER = "artifactory_user"
private const val ARTIFACTORY_PASSWORD = "artifactory_password"
fun Project.applyArtifactoryConfig() {
if (!project.hasProperty(ARTIFACTORY_CONTEXT_URL)) ext[ARTIFACTORY_CONTEXT_URL] = "http://localhost"
if (!project.hasProperty(ARTIFACTORY_USER)) ext[ARTIFACTORY_USER] = "guest"
if (!project.hasProperty(ARTIFACTORY_PASSWORD)) ext[ARTIFACTORY_PASSWORD] = ""
apply(plugin = "com.jfrog.artifactory")
configure<ArtifactoryPluginConvention> {
setContextUrl("${project.property(ARTIFACTORY_CONTEXT_URL)}")
clientConfig.publisher.run {
repoKey = when {
"${project.version}".contains("SNAPSHOT") -> "libs-snapshot-local"
else -> "libs-release-local"
}
username = "${project.property(ARTIFACTORY_USER)}"
password = "${project.property(ARTIFACTORY_PASSWORD)}"
isMaven = true
isIvy = false
}
}
tasks.named<ArtifactoryTask>("artifactoryPublish") {
publications("maven")
}
}
| lgpl-3.0 | baa6eff7305046fde707817e84de4f43 | 41.294118 | 104 | 0.696106 | 4.050704 | false | true | false | false |
aosp-mirror/platform_frameworks_support | jetifier/jetifier/standalone/src/main/kotlin/com/android/tools/build/jetifier/standalone/Main.kt | 1 | 6251 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.build.jetifier.standalone
import com.android.tools.build.jetifier.core.config.ConfigParser
import com.android.tools.build.jetifier.core.utils.Log
import com.android.tools.build.jetifier.processor.FileMapping
import com.android.tools.build.jetifier.processor.Processor
import org.apache.commons.cli.CommandLine
import org.apache.commons.cli.DefaultParser
import org.apache.commons.cli.HelpFormatter
import org.apache.commons.cli.Option
import org.apache.commons.cli.Options
import org.apache.commons.cli.ParseException
import java.io.File
import java.nio.file.Paths
class Main {
companion object {
const val TAG = "Main"
const val TOOL_NAME = "Jetifier (standalone)"
val OPTIONS = Options()
val OPTION_INPUT = createOption(
argName = "i",
argNameLong = "input",
desc = "Input library path (jar, aar, zip)",
isRequired = true
)
val OPTION_OUTPUT = createOption(
argName = "o",
argNameLong = "output",
desc = "Output file path",
isRequired = true
)
val OPTION_CONFIG = createOption(
argName = "c",
argNameLong = "config",
desc = "Input config path (otherwise default is used)",
isRequired = false
)
val OPTION_LOG_LEVEL = createOption(
argName = "l",
argNameLong = "log",
desc = "Logging level. Values: error, warning (default), info, verbose",
isRequired = false
)
val OPTION_REVERSED = createOption(
argName = "r",
argNameLong = "reversed",
desc = "Run reversed process (de-jetification)",
hasArgs = false,
isRequired = false
)
val OPTION_STRICT = createOption(
argName = "s",
argNameLong = "strict",
desc = "Don't fallback in case rules are missing and throw errors instead",
hasArgs = false,
isRequired = false
)
val OPTION_REBUILD_TOP_OF_TREE = createOption(
argName = "rebuildTopOfTree",
argNameLong = "rebuildTopOfTree",
desc = "Rebuild the zip of maven distribution according to the generated pom file." +
"If set, all libraries being rewritten are assumed to be part of Support " +
"Library. Not needed for jetification.",
hasArgs = false,
isRequired = false
)
val OPTION_VERSIONS = createOption(
argName = "v",
argNameLong = "versions",
desc = "Versions of dependencies to be substituted by Jetifier. In most cases you " +
"want to leave the default which is 'latestReleased'. Check Jetifier's config " +
"file for more types of configurations.",
hasArgs = true,
isRequired = false
)
private fun createOption(
argName: String,
argNameLong: String,
desc: String,
hasArgs: Boolean = true,
isRequired: Boolean = true
): Option {
val op = Option(argName, argNameLong, hasArgs, desc)
op.isRequired = isRequired
OPTIONS.addOption(op)
return op
}
@JvmStatic fun main(args: Array<String>) {
Main().run(args)
}
}
fun run(args: Array<String>) {
val cmd = parseCmdLine(args)
if (cmd == null) {
System.exit(1)
return
}
Log.setLevel(cmd.getOptionValue(OPTION_LOG_LEVEL.opt))
val inputLibrary = File(cmd.getOptionValue(OPTION_INPUT.opt))
val output = cmd.getOptionValue(OPTION_OUTPUT.opt)
val rebuildTopOfTree = cmd.hasOption(OPTION_REBUILD_TOP_OF_TREE.opt)
val fileMappings = mutableSetOf<FileMapping>()
if (rebuildTopOfTree) {
val tempFile = createTempFile(suffix = "zip")
fileMappings.add(FileMapping(inputLibrary, tempFile))
} else {
fileMappings.add(FileMapping(inputLibrary, File(output)))
}
val config = if (cmd.hasOption(OPTION_CONFIG.opt)) {
val configPath = Paths.get(cmd.getOptionValue(OPTION_CONFIG.opt))
ConfigParser.loadFromFile(configPath)
} else {
ConfigParser.loadDefaultConfig()
}
if (config == null) {
Log.e(TAG, "Failed to load the config file")
System.exit(1)
return
}
val versionSetName = cmd.getOptionValue(OPTION_VERSIONS.opt)
val isReversed = cmd.hasOption(OPTION_REVERSED.opt)
val isStrict = cmd.hasOption(OPTION_STRICT.opt)
val processor = Processor.createProcessor(
config = config,
reversedMode = isReversed,
rewritingSupportLib = rebuildTopOfTree,
useFallbackIfTypeIsMissing = !isStrict,
versionSetName = versionSetName)
processor.transform(fileMappings)
if (rebuildTopOfTree) {
val tempFile = fileMappings.first().to
TopOfTreeBuilder().rebuildFrom(inputZip = tempFile, outputZip = File(output))
tempFile.delete()
}
}
private fun parseCmdLine(args: Array<String>): CommandLine? {
try {
return DefaultParser().parse(OPTIONS, args)
} catch (e: ParseException) {
Log.e(TAG, e.message.orEmpty())
HelpFormatter().printHelp(TOOL_NAME, OPTIONS)
}
return null
}
}
| apache-2.0 | 51db454bdc8b47c6220513589b7d8290 | 34.316384 | 97 | 0.600224 | 4.569444 | false | true | false | false |
Yorxxx/played-next-kotlin | app/src/test/java/com/piticlistudio/playednext/data/repository/datasource/room/relation/RoomRelationRepositoryImplTest.kt | 1 | 6408 | package com.piticlistudio.playednext.data.repository.datasource.room.relation
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import com.piticlistudio.playednext.data.entity.mapper.datasources.relation.RoomRelationMapper
import com.piticlistudio.playednext.data.entity.room.RoomGameRelation
import com.piticlistudio.playednext.data.repository.datasource.room.game.RoomGameRepositoryImpl
import com.piticlistudio.playednext.data.repository.datasource.room.platform.RoomGamePlatformRepositoryImpl
import com.piticlistudio.playednext.domain.model.GameRelation
import com.piticlistudio.playednext.test.factory.DataFactory
import com.piticlistudio.playednext.test.factory.GameFactory.Factory.makeGame
import com.piticlistudio.playednext.test.factory.GameRelationFactory.Factory.makeGameRelation
import com.piticlistudio.playednext.test.factory.GameRelationFactory.Factory.makeRoomGameRelationProxy
import com.piticlistudio.playednext.test.factory.PlatformFactory.Factory.makePlatform
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.observers.TestObserver
import io.reactivex.subscribers.TestSubscriber
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.mockito.ArgumentMatchers.anyInt
internal class RoomRelationRepositoryImplTest {
@Nested
@DisplayName("Given a RelationDaoRepositoryImpl instance")
inner class Instance {
private lateinit var repository: RoomRelationRepositoryImpl
val dao: RoomRelationService = mock()
val mapper: RoomRelationMapper = mock()
val gamesRepository: RoomGameRepositoryImpl = mock()
val platformRepositoryImpl: RoomGamePlatformRepositoryImpl = mock()
@BeforeEach
internal fun setUp() {
reset(dao, mapper, gamesRepository, platformRepositoryImpl)
repository = RoomRelationRepositoryImpl(dao, gamesRepository, platformRepositoryImpl, mapper)
}
@Nested
@DisplayName("When we call save")
inner class SaveCalled {
private var observer: TestObserver<Void>? = null
private val source = makeGameRelation()
private val result = makeRoomGameRelationProxy()
@BeforeEach
internal fun setUp() {
whenever(mapper.mapIntoDataLayerModel(source)).thenReturn(result)
whenever(dao.insert(result.relation)).thenReturn(DataFactory.randomLong())
observer = repository.save(source).test()
}
@Test
@DisplayName("Then should request dao service")
fun shouldRequestDao() {
verify(dao).insert(result.relation)
}
@Test
@DisplayName("Then should emit without errors")
fun withoutErrors() {
assertNotNull(observer)
observer?.apply {
assertNoErrors()
assertComplete()
assertNoValues()
}
}
@Nested
@DisplayName("And dao fails to insert")
inner class InsertFailed {
@BeforeEach
internal fun setUp() {
reset(dao)
whenever(dao.insert(result.relation)).thenReturn(-1)
observer = repository.save(source).test()
}
@Test
@DisplayName("Then should emit error")
fun withoutErrors() {
assertNotNull(observer)
observer?.apply {
assertError { it is RelationSaveException }
assertNotComplete()
assertNoValues()
}
}
}
}
@Nested
@DisplayName("When we call loadForGameAndPlatform")
inner class LoadForGameAndPlatformCalled {
private var observer: TestSubscriber<List<GameRelation>>? = null
private val daomodel1 = makeRoomGameRelationProxy()
private val game = makeGame()
private val platform = makePlatform()
private val gameId = 10
private val platformId = 5
@BeforeEach
internal fun setUp() {
val flowable = Flowable.create<List<RoomGameRelation>>({
it.onNext(listOf(daomodel1.relation))
}, BackpressureStrategy.MISSING)
whenever(dao.findForGameAndPlatform(gameId, platformId)).thenReturn(flowable)
whenever(gamesRepository.load(anyInt())).thenReturn(Flowable.just(game))
whenever(platformRepositoryImpl.load(anyInt())).thenReturn(Flowable.just(platform))
observer = repository.loadForGameAndPlatform(gameId, platformId).test()
}
@Test
@DisplayName("Then should request dao service")
fun shouldRequestDao() {
verify(dao).findForGameAndPlatform(gameId, platformId)
}
@Test
@DisplayName("Then should request game")
fun shouldRequestGame() {
verify(gamesRepository).load(gameId)
}
@Test
@DisplayName("Then should request platform")
fun shouldRequestPlatform() {
verify(platformRepositoryImpl).load(platformId)
}
@Test
@DisplayName("Then should emit without errors")
fun withoutErrors() {
assertNotNull(observer)
observer?.apply {
assertNoErrors()
assertNotComplete()
assertValueCount(1)
assertValue { it.size == 1 }
assertValue { it.first().game == game }
assertValue { it.first().platform == platform }
assertValue { it.first().updatedAt == daomodel1.relation.updated_at }
assertValue { it.first().createdAt == daomodel1.relation.created_at }
}
}
}
}
} | mit | 5f472c181031fc1e4164e5a6b6b06f44 | 39.308176 | 107 | 0.622347 | 5.472246 | false | true | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/kpspemu/TouchButtonsScene.kt | 1 | 7805 | package com.soywiz.kpspemu
import com.soywiz.compat.*
import com.soywiz.korev.*
import com.soywiz.korge.component.*
import com.soywiz.korge.input.*
import com.soywiz.korge.scene.*
import com.soywiz.korge.view.*
import com.soywiz.korim.atlas.*
import com.soywiz.korio.async.*
import com.soywiz.korio.file.std.*
import com.soywiz.korma.geom.*
import com.soywiz.kpspemu.ctrl.*
import kotlin.math.*
class TouchButtonsScene(val emulator: Emulator) : Scene() {
val controller get() = emulator.controller
lateinit var atlas: Atlas
override suspend fun Container.sceneInit() {
val sceneView = this
//atlas = rootLocalVfs["buttons.json"].readAtlas2(views)
atlas = resourcesVfs["buttons.json"].readAtlas2()
sceneView.scale = 480.0 / 1280.0
val buttonsPos = Point(1100, 720 / 2)
val dpadPos = Point(170, 300)
val pseparation = 0.15
val bseparation = 0.2
val pscale = 1.1
val bscale = 1.1
addButton("up.png", PspCtrlButtons.up, dpadPos, 0.5, 1.0 + pseparation, pscale)
addButton("left.png", PspCtrlButtons.left, dpadPos, 1.0 + pseparation, 0.5, pscale)
addButton("right.png", PspCtrlButtons.right, dpadPos, -pseparation, 0.5, pscale)
addButton("down.png", PspCtrlButtons.down, dpadPos, 0.5, -pseparation, pscale)
addButton("triangle.png", PspCtrlButtons.triangle, buttonsPos, 0.5, 1.0 + bseparation, bscale)
addButton("square.png", PspCtrlButtons.square, buttonsPos, 1.0 + bseparation, 0.5, bscale)
addButton("circle.png", PspCtrlButtons.circle, buttonsPos, -bseparation, 0.5, bscale)
addButton("cross.png", PspCtrlButtons.cross, buttonsPos, 0.5, -bseparation, bscale)
addButton("trigger_l.png", PspCtrlButtons.leftTrigger, Point(160, 0), 0.5, 0.0)
addButton("trigger_r.png", PspCtrlButtons.rightTrigger, Point(1280 - 160, 0), 0.5, 0.0)
addButton("start.png", PspCtrlButtons.start, Point(1280 - 160, 720), 0.5, 1.0)
addButton("select.png", PspCtrlButtons.select, Point(1280 - 380, 720), 0.5, 1.0)
addButton("home.png", PspCtrlButtons.home, Point(1280 / 2, 0), 1.1, 0.0).apply {
view.onClick {
println("home.onClick")
emulator.onHomePress()
}
}
addButton("load.png", PspCtrlButtons.hold, Point(1280 / 2, 0), -0.1, 0.0).apply {
view.onClick {
println("load.onClick")
emulator.onLoadPress()
}
}
addThumb(Point(172.0, 600.0))
sceneView.addComponent(object : TouchComponent {
override val view: View = sceneView
override fun onTouchEvent(views: Views, e: TouchEvent) {
updateEvent()
}
fun View.testAnyTouch(): Boolean {
for (touch in views.input.activeTouches) {
if (touch.id == thumbTouchId) continue // Ignore the thumb touch
//if (hitTest(touch.current) != null) return true
println("Missing hitTest(touch.current)")
}
return false
}
fun updateEvent() {
//println("views.nativeMouseX=${views.nativeMouseX}, views.nativeMouseY=${views.nativeMouseY}")
for (button in buttons) {
if (button.view.testAnyTouch()) {
button.view.alpha = alphaDown
controller.updateButton(button.button, true)
} else {
button.view.alpha = alphaUp
controller.updateButton(button.button, false)
}
}
}
})
updateTouch()
sceneView.gamepad {
connected { updateTouch() }
disconnected { updateTouch() }
}
sceneView.onStageResized { width, height ->
//println("resized:" + views.input.isTouchDevice)
updateTouch()
}
}
var View.visibleEnabled: Boolean
get() = visible
set(value) {
visible = value
mouseEnabled = value
}
fun updateTouch() {
val touch = views.input.connectedGamepads.isEmpty() && views.input.isTouchDevice
thumbContainer.visibleEnabled = touch
for (button in buttons) {
button.view.visibleEnabled = touch
if (button.button == PspCtrlButtons.home || button.button == PspCtrlButtons.hold) {
button.view.visibleEnabled = true
}
}
}
val alphaUp = 0.2
val alphaDown = 0.5
class Button(val button: PspCtrlButtons, val view: View) {
val onClick = Signal<Unit>()
}
val buttons = arrayListOf<Button>()
fun addButton(
file: String,
pspButton: PspCtrlButtons,
pos: Point,
anchorX: Double,
anchorY: Double,
scale: Double = 1.0
): Button {
//onDown { this.alpha = alphaDown; controller.updateButton(button, true) }
//onDownFromOutside { this.alpha = alphaDown; controller.updateButton(button, true) }
//onUpAnywhere{ this.alpha = alphaUp; controller.updateButton(button, false) }
val button = Button(pspButton, Image(atlas[file]).apply {
this.x = pos.x
this.y = pos.y
this.anchorX = anchorX
this.anchorY = anchorY
this.alpha = alphaUp
this.scale = scale
})
button.view.alpha = alphaUp
button.view.onOver { button.view.alpha = alphaDown }
button.view.onOut { button.view.alpha = alphaUp }
button.view.onClick { button.onClick(Unit) }
buttons += button
sceneView += button.view
return button
}
val thumbTouchIdNone = Int.MIN_VALUE
var thumbTouchId = thumbTouchIdNone
lateinit var thumbContainer: Container
fun addThumb(pos: Point) {
thumbContainer = Container().apply {
sceneView += this
this.x = pos.x
this.y = pos.y
val bg = image(atlas["thumb_bg.png"]).apply {
this.anchorX = 0.5
this.anchorY = 0.5
this.alpha = 0.2
}
val thumb = image(atlas["thumb.png"]).apply {
this.anchorX = 0.5
this.anchorY = 0.5
this.alpha = 0.2
}
bg.apply {
launchImmediately {
onMouseDrag {
if (it.start){
//thumbTouchId = it.id
thumbTouchId = 0
//println("START")
bg.alpha = alphaDown
thumb.alpha = alphaDown
} else if (it.end) {
thumbTouchId = thumbTouchIdNone
//println("END")
thumb.x = 0.0
thumb.y = 0.0
bg.alpha = alphaUp
thumb.alpha = alphaUp
controller.updateAnalog(0f, 0f)
} else {
//println("Moving: $it")
it.dx
val angle = atan2(it.dx, it.dy)
val magnitude = min(32.0, hypot(it.dx, it.dy))
thumb.x = sin(angle) * magnitude
thumb.y = cos(angle) * magnitude
controller.updateAnalog(sin(angle).toFloat(), cos(angle).toFloat())
}
}
}
}
}
}
}
| mit | 506f800d8fc854079d91b74f1dc293c4 | 35.302326 | 111 | 0.527098 | 4.255725 | false | false | false | false |
kaltura/playkit-android | playkit/src/main/java/com/kaltura/playkit/PKPlaybackException.kt | 1 | 6336 | package com.kaltura.playkit
import android.media.MediaCodec.CryptoException
import android.util.Pair
import com.kaltura.android.exoplayer2.ExoPlaybackException
import com.kaltura.android.exoplayer2.ExoTimeoutException
import com.kaltura.android.exoplayer2.PlaybackException
import com.kaltura.android.exoplayer2.mediacodec.MediaCodecRenderer.DecoderInitializationException
import com.kaltura.android.exoplayer2.mediacodec.MediaCodecUtil
import com.kaltura.playkit.player.PKPlayerErrorType
class PKPlaybackException {
companion object {
private val log = PKLog.get("PKPlaybackException")
// Miscellaneous errors (1xxx).
private const val MISC_ERROR_CODE = 1000
// Input/Output errors (2xxx).
private const val IO_ERROR_CODE = 2000
// Content parsing errors (3xxx).
private const val CONTENT_PARSING_ERROR_CODE = 3000
// Decoding errors (4xxx).
private const val DECODING_ERROR_CODE = 4000
// AudioTrack errors (5xxx).
private const val AUDIO_TRACK_ERROR_CODE = 5000
// DRM errors (6xxx).
private const val DRM_ERROR_CODE = 6000
private const val CUSTOM_ERROR_CODE = 1000000
@JvmStatic
fun getPlaybackExceptionType(playbackException: PlaybackException): Pair<PKPlayerErrorType, String> {
var errorStr = playbackException.errorCodeName
val playerErrorType = when (playbackException.errorCode) {
PlaybackException.ERROR_CODE_TIMEOUT -> {
PKPlayerErrorType.TIMEOUT
}
in (MISC_ERROR_CODE + 1) until IO_ERROR_CODE -> {
PKPlayerErrorType.MISCELLANEOUS
}
in (IO_ERROR_CODE + 1) until CONTENT_PARSING_ERROR_CODE -> {
PKPlayerErrorType.IO_ERROR
}
in (CONTENT_PARSING_ERROR_CODE + 1) until DECODING_ERROR_CODE -> {
PKPlayerErrorType.SOURCE_ERROR
}
in (DECODING_ERROR_CODE + 1) until AUDIO_TRACK_ERROR_CODE,
in (AUDIO_TRACK_ERROR_CODE + 1) until DRM_ERROR_CODE -> {
PKPlayerErrorType.RENDERER_ERROR
}
in (DRM_ERROR_CODE + 1) until CUSTOM_ERROR_CODE -> {
PKPlayerErrorType.DRM_ERROR
}
else -> {
PKPlayerErrorType.UNEXPECTED
}
}
getExoPlaybackException(playbackException, playerErrorType)?.let { errorMessage ->
errorStr = "$errorMessage-$errorStr"
}
return Pair(playerErrorType, errorStr)
}
/**
* If Playback exception is ExoPlaybackException then
* fire the error details in the traditional way
*
* @param playbackException Exception on player error
*/
private fun getExoPlaybackException(playbackException: PlaybackException, playerErrorType: PKPlayerErrorType): String? {
if (playbackException is ExoPlaybackException) {
var errorMessage = playbackException.message
when (playbackException.type) {
ExoPlaybackException.TYPE_SOURCE -> {
errorMessage = getSourceErrorMessage(playbackException, errorMessage)
}
ExoPlaybackException.TYPE_RENDERER -> {
errorMessage = getRendererExceptionDetails(playbackException, errorMessage)
}
ExoPlaybackException.TYPE_UNEXPECTED -> {
errorMessage = getUnexpectedErrorMessage(playbackException, errorMessage)
}
}
val errorStr = errorMessage ?: "Player error: " + playerErrorType.name
log.e(errorStr)
return errorStr
}
return null
}
private fun getRendererExceptionDetails(
error: ExoPlaybackException,
errorMessage: String?
): String? {
var message: String? = errorMessage
when (val cause = error.rendererException) {
is DecoderInitializationException -> {
// Special case for decoder initialization failures.
message = if (cause.codecInfo == null) {
when {
cause.cause is MediaCodecUtil.DecoderQueryException -> {
"Unable to query device decoders"
}
cause.secureDecoderRequired -> {
"This device does not provide a secure decoder for " + cause.mimeType
}
else -> {
"This device does not provide a decoder for " + cause.mimeType
}
}
} else {
"Unable to instantiate decoder" + cause.codecInfo?.name
}
}
is CryptoException -> {
message = cause.message ?: "MediaCodec.CryptoException occurred"
message = "DRM_ERROR:$message"
}
is ExoTimeoutException -> {
message = cause.message ?: "Exo timeout exception"
message = "EXO_TIMEOUT_EXCEPTION:$message"
}
}
return message
}
private fun getUnexpectedErrorMessage(
error: ExoPlaybackException,
errorMessage: String?
): String? {
var message: String? = errorMessage
val cause: Exception = error.unexpectedException
cause.cause?.let {
message = it.message
}
return message
}
private fun getSourceErrorMessage(
error: ExoPlaybackException,
errorMessage: String?
): String? {
var message: String? = errorMessage
val cause: Exception = error.sourceException
cause.cause?.let {
message = it.message
}
return message
}
}
}
| agpl-3.0 | a361dea94cb87edea56fca7af0c279bc | 39.101266 | 128 | 0.547191 | 5.682511 | false | false | false | false |
yrsegal/CommandControl | src/main/java/wiresegal/cmdctrl/common/commands/biome/CommandGetBiome.kt | 1 | 3495 | package wiresegal.cmdctrl.common.commands.biome
import net.minecraft.command.CommandBase
import net.minecraft.command.CommandException
import net.minecraft.command.CommandResultStats
import net.minecraft.command.ICommandSender
import net.minecraft.server.MinecraftServer
import net.minecraft.util.math.BlockPos
import net.minecraft.world.biome.Biome
import wiresegal.cmdctrl.common.CommandControl
import wiresegal.cmdctrl.common.core.CTRLException
import wiresegal.cmdctrl.common.core.CTRLUsageException
import wiresegal.cmdctrl.common.core.notifyCTRLListener
/**
* @author WireSegal
* Created at 5:43 PM on 12/3/16.
*/
object CommandGetBiome : CommandBase() {
@Throws(CommandException::class)
override fun execute(server: MinecraftServer, sender: ICommandSender, args: Array<out String>) {
if (args.size > 1) {
val senderPos = sender.position
val x = parseDouble(senderPos.x.toDouble(), args[0], -3000000, 3000000, false)
val z = parseDouble(senderPos.z.toDouble(), args[1], -3000000, 3000000, false)
val pos = BlockPos(x, 0.0, z)
val world = sender.entityWorld
if (world.isBlockLoaded(pos)) {
if (args.size > 2) {
val biome = CommandSetBiome.parseBiome(args[2])
val id = Biome.getIdForBiome(biome).toByte()
val name = Biome.REGISTRY.getNameForObject(biome)
val realBiome = world.getBiome(pos)
if (biome == realBiome) {
notifyCTRLListener(sender, this, "commandcontrol.testforbiome.match", x.toInt(), z.toInt(), id, name)
sender.setCommandStat(CommandResultStats.Type.AFFECTED_BLOCKS, 1)
} else {
val realId = Biome.getIdForBiome(realBiome).toByte()
val realName = Biome.REGISTRY.getNameForObject(realBiome)
throw CTRLException("commandcontrol.testforbiome.nomatch", x.toInt(), z.toInt(), realId, realName, id, name)
}
} else {
val biome = world.getBiome(pos)
val id = Biome.getIdForBiome(biome).toByte()
val name = Biome.REGISTRY.getNameForObject(biome)
notifyCTRLListener(sender, this, "commandcontrol.testforbiome.success", x.toInt(), z.toInt(), id, name)
sender.setCommandStat(CommandResultStats.Type.AFFECTED_BLOCKS, 1)
sender.setCommandStat(CommandResultStats.Type.QUERY_RESULT, Biome.getIdForBiome(biome))
}
} else
throw CTRLException("commandcontrol.testforbiome.range", x.toInt(), z.toInt())
} else
throw CTRLUsageException(getCommandUsage(sender))
}
override fun getTabCompletionOptions(server: MinecraftServer, sender: ICommandSender, args: Array<out String>, pos: BlockPos?): List<String> {
return when (args.size) {
1 -> getTabCompletionCoordinate(args, 0, pos)
2 -> getTabCompletionCoordinate(args, -1, pos)
3 -> getListOfStringsMatchingLastWord(args, CommandSetBiome.biomes)
else -> emptyList()
}
}
override fun getRequiredPermissionLevel() = 2
override fun getCommandName() = "testforbiome"
override fun getCommandUsage(sender: ICommandSender?) = CommandControl.translate("commandcontrol.testforbiome.usage")
}
| mit | 80e93f8bdcdc1fcc4eec210f66d90f77 | 44.986842 | 146 | 0.640629 | 4.36875 | false | true | false | false |
sirlantis/rubocop-for-rubymine | src/io/github/sirlantis/rubymine/rubocop/RubocopAnnotator.kt | 1 | 5616 | package io.github.sirlantis.rubymine.rubocop
import com.intellij.lang.annotation.ExternalAnnotator
import com.intellij.psi.PsiFile
import com.intellij.lang.annotation.Annotation
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.psi.PsiDocumentManager
import com.intellij.openapi.module.Module
import io.github.sirlantis.rubymine.rubocop.model.FileResult
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.codeInsight.daemon.HighlightDisplayKey
import com.intellij.openapi.editor.Document
import io.github.sirlantis.rubymine.rubocop.model.Offense
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.EditorColorsScheme
import com.intellij.openapi.project.Project
import io.github.sirlantis.rubymine.rubocop.utils.NotifyUtil
fun clamp(min: Int, max: Int, value: Int): Int {
return Math.max(Math.min(value, max), min)
}
class RubocopAnnotator : ExternalAnnotator<RubocopAnnotator.Input, RubocopAnnotator.Result>() {
class Input(val module: Module,
val file: PsiFile,
val content: String,
val colorScheme: EditorColorsScheme?)
class Result(val input: Input,
val result: FileResult?,
val warnings: List<String>?)
val inspectionKey: HighlightDisplayKey by lazy {
val id = "Rubocop"
HighlightDisplayKey.find(id) ?: HighlightDisplayKey(id, id)
}
override fun collectInformation(file: PsiFile, editor: Editor, hasErrors: Boolean): Input? {
return collectInformation(file, editor)
}
override fun collectInformation(file: PsiFile): Input? {
return collectInformation(file, null)
}
fun collectInformation(file: PsiFile, editor: Editor?): Input? {
if (file.context != null || !isRubyFile(file)) {
return null
}
val virtualFile = file.virtualFile
if (!virtualFile.isInLocalFileSystem) {
return null
}
val project = file.project
val module = RubocopTask.getModuleForFile(project, virtualFile) ?: return null
val document = PsiDocumentManager.getInstance(project).getDocument(file) ?: return null
return Input(module,
file,
document.text,
editor?.colorsScheme)
}
fun isRubyFile(file: PsiFile): Boolean {
return file.fileType.name == "Ruby"
}
override fun apply(file: PsiFile, annotationResult: Result?, holder: AnnotationHolder) {
if (annotationResult == null) {
return
}
showWarnings(annotationResult)
val result = annotationResult.result ?: return
val document = PsiDocumentManager.getInstance(file.project).getDocument(file) ?: return
result.offenses.forEach { offense ->
val severity = severityForOffense(offense)
createAnnotation(holder, document, offense, "RuboCop: ", severity, false)
// TODO: offer fix option (at least suppress)
}
}
fun showWarnings(result: Result) {
val warnings = result.warnings ?: return
if (warnings.isEmpty()) {
return
}
val message = buildString {
append("Some warnings were found while calling RuboCop:")
append("<ul>")
warnings.forEach { warning ->
append("<li>")
append(warning)
append("</li>")
}
append("</ul>")
}
NotifyUtil.notifyInfo(result.input.module.project, "RuboCop Warning", message)
}
fun severityForOffense(offense: Offense): HighlightSeverity {
when (offense.severity) {
"error" -> return HighlightSeverity.ERROR
"fatal" -> return HighlightSeverity.ERROR
"warning" -> return HighlightSeverity.WARNING
"convention" -> return HighlightSeverity.WEAK_WARNING
"refactor" -> return HighlightSeverity.INFO
else -> return HighlightSeverity.INFO
}
}
fun createAnnotation(holder: AnnotationHolder,
document: Document,
offense: Offense,
prefix: String,
severity: HighlightSeverity,
showErrorOnWholeLine: Boolean): Annotation {
val offenseLine = clamp(0, document.lineCount - 1, offense.location.line - 1)
val lineEndOffset = document.getLineEndOffset(offenseLine)
val lineStartOffset = document.getLineStartOffset(offenseLine)
val range: TextRange
if (showErrorOnWholeLine || offense.location.length <= 0) {
range = TextRange(lineStartOffset, lineEndOffset)
} else {
val length = offense.location.length
val start = lineStartOffset + (offense.location.column - 1)
range = TextRange(start, start + length)
}
val message = prefix + offense.message.trim() + " (" + offense.cop + ")"
return holder.createAnnotation(severity, range, message)
}
override fun doAnnotate(collectedInfo: Input?): Result? {
if (collectedInfo == null) {
return null
}
val task = RubocopTask.forFiles(collectedInfo.module, collectedInfo.file.virtualFile)
task.run()
return Result(collectedInfo, task.result?.fileResults?.firstOrNull(), task.result?.warnings)
}
companion object {
val INSTANCE: RubocopAnnotator = RubocopAnnotator()
}
}
| mit | 0f7df3b0918f84fc169bc710093cdf92 | 33.036364 | 100 | 0.640135 | 4.727273 | false | false | false | false |
googlecodelabs/android-compose-codelabs | AnimationCodelab/start/src/main/java/com/example/android/codelab/animation/ui/Theme.kt | 2 | 1083 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.codelab.animation.ui
import androidx.compose.material.MaterialTheme
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
@Composable
fun AnimationCodelabTheme(content: @Composable () -> Unit) {
val colors = lightColors(
primary = Purple500,
primaryVariant = Purple700,
secondary = Teal200
)
MaterialTheme(
colors = colors,
content = content
)
}
| apache-2.0 | 0c16babc35383c135764a8c8fad85f6f | 30.852941 | 75 | 0.727608 | 4.384615 | false | false | false | false |
wax911/android-emojify | emojify/src/androidTest/java/io/wax911/emojify/EmojiManagerTest.kt | 1 | 6297 | package io.wax911.emojify
import androidx.startup.AppInitializer
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import androidx.test.platform.app.InstrumentationRegistry
import io.wax911.emojify.initializer.EmojiInitializer
import io.wax911.emojify.model.Emoji
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumentation test, which will execute on an Android device.
*
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
@RunWith(AndroidJUnit4ClassRunner::class)
class EmojiManagerTest {
private val context by lazy {
InstrumentationRegistry.getInstrumentation().context
}
private val emojiManager by lazy {
AppInitializer.getInstance(context)
.initializeComponent(EmojiInitializer::class.java)
}
@Before
fun testApplicationContext() {
assertNotNull(context)
}
@Before
fun testEmojiLoading() {
assertNotNull(emojiManager)
assertTrue(emojiManager.emojiList.isNotEmpty())
}
@Test
fun getTrimmedAlias() {
// GIVEN
val alias = ":smile:"
// WHEN
val trimmed = emojiManager.trimAlias(alias)
// THEN
assertEquals("smile", trimmed)
}
@Test
fun getForTag_with_unknown_tag_returns_null() {
// GIVEN
// WHEN
val emojis = emojiManager.getForTag("jkahsgdfjksghfjkshf")
// THEN
assertNull(emojis)
}
@Test
fun getForTag_returns_the_emojis_for_the_tag() {
// GIVEN
// WHEN
val emojis = emojiManager.getForTag("happy")
// THEN
assertEquals(4, emojis!!.size)
assertTrue(containsEmojis(
emojis,
"smile",
"smiley",
"grinning",
"satisfied"
))
}
@Test
fun getForAlias_with_unknown_alias_returns_null() {
// GIVEN
// WHEN
val emoji = emojiManager.getForAlias("jkahsgdfjksghfjkshf")
// THEN
assertNull(emoji)
}
@Test
fun getForAlias_returns_the_emoji_for_the_alias() {
// GIVEN
// WHEN
val emoji = emojiManager.getForAlias("smile")
// THEN
assertEquals(
"smiling face with open mouth and smiling eyes",
emoji!!.description
)
}
@Test
fun getForAlias_with_colons_returns_the_emoji_for_the_alias() {
// GIVEN
// WHEN
val emoji = emojiManager.getForAlias(":smile:")
// THEN
assertEquals(
"smiling face with open mouth and smiling eyes",
emoji!!.description
)
}
@Test
fun isEmoji_for_an_emoji_returns_true() {
// GIVEN
val emoji = "😀"
// WHEN
val isEmoji = emojiManager.isEmoji(emoji)
// THEN
assertTrue(isEmoji)
}
@Test
fun isEmoji_with_fitzpatric_modifier_returns_true() {
// GIVEN
val emoji = "\uD83E\uDD30\uD83C\uDFFB"
// WHEN
val isEmoji = emojiManager.isEmoji(emoji)
// THEN
assertTrue(isEmoji)
}
@Test
fun isEmoji_for_a_non_emoji_returns_false() {
// GIVEN
val str = "test"
// WHEN
val isEmoji = emojiManager.isEmoji(str)
// THEN
assertFalse(isEmoji)
}
@Test
fun isEmoji_for_an_emoji_and_other_chars_returns_false() {
// GIVEN
val str = "😀 test"
// WHEN
val isEmoji = emojiManager.isEmoji(str)
// THEN
assertFalse(isEmoji)
}
@Test
fun isOnlyEmojis_for_an_emoji_returns_true() {
// GIVEN
val str = "😀"
// WHEN
val isEmoji = emojiManager.isOnlyEmojis(str)
// THEN
assertTrue(isEmoji)
}
@Test
fun isOnlyEmojis_for_emojis_returns_true() {
// GIVEN
val str = "😀😀😀"
// WHEN
val isEmoji = emojiManager.isOnlyEmojis(str)
// THEN
assertTrue(isEmoji)
}
@Test
fun isOnlyEmojis_for_random_string_returns_false() {
// GIVEN
val str = "😀a"
// WHEN
val isEmoji = emojiManager.isOnlyEmojis(str)
// THEN
assertFalse(isEmoji)
}
@Test
fun getAllTags_returns_the_tags() {
// GIVEN
// WHEN
val tags = emojiManager.getAllTags()
// THEN
// We know the number of distinct tags int the...!
assertEquals(656, tags.size)
}
@Test
fun getAll_does_not_return_duplicates() {
// GIVEN
// WHEN
val emojis = emojiManager.emojiList
// THEN
val unicodes = HashSet<String>()
for (emoji in emojis) {
assertFalse(
"Duplicate: " + emoji.description!!,
unicodes.contains(emoji.unicode)
)
unicodes.add(emoji.unicode)
}
assertEquals(unicodes.size, emojis.size)
}
@Test
fun no_duplicate_alias() {
// GIVEN
// WHEN
val emojis = emojiManager.emojiList
// THEN
val aliases = HashSet<String>()
val duplicates = HashSet<String>()
for (emoji in emojis) {
for (alias in emoji.aliases!!) {
if (aliases.contains(alias)) {
duplicates.add(alias)
}
aliases.add(alias)
}
}
assertEquals("Duplicates: $duplicates", duplicates.size, 0)
}
companion object {
fun containsEmojis(emojis: Iterable<Emoji>, vararg aliases: String): Boolean {
for (alias in aliases) {
val contains = containsEmoji(emojis, alias)
if (!contains) {
return false
}
}
return true
}
private fun containsEmoji(emojis: Iterable<Emoji>, alias: String): Boolean {
for (emoji in emojis) {
emoji.aliases?.forEach { al ->
if (alias == al)
return true
}
}
return false
}
}
}
| mit | 117c314aa0f3a5272fa140b212f4e5a1 | 21.414286 | 86 | 0.541268 | 4.370474 | false | true | false | false |
thaleslima/GuideApp | app/src/main/java/com/guideapp/utilities/Constants.kt | 1 | 862 | package com.guideapp.utilities
object Constants {
const val ACTION_DATA_UPDATED = "com.guideapp.ACTION_DATA_UPDATED"
const val ACTION_DATA_SYNC_ERROR = "com.guideapp.ACTION_DATA_SYNC_ERROR"
interface City {
companion object {
const val ID = 5659118702428160L
const val LATITUDE = -20.3449802
const val LONGITUDE = -46.8551188
}
}
internal interface Menu {
companion object {
const val ALIMENTATION = 5684666375864320L
const val ATTRACTIVE = 5651124426113024L
const val ACCOMMODATION = 5679413765079040L
}
}
interface Analytics {
companion object {
const val SAVE_FAVORITE = "save_favorite"
const val REMOVE_FAVORITE = "remove_favorite"
const val SCREEN = "screen"
}
}
}
| apache-2.0 | ef346afe6a3bc3cba3f5fab30bfa27fe | 27.733333 | 76 | 0.609049 | 4.046948 | false | false | false | false |
proxer/ProxerAndroid | src/main/kotlin/me/proxer/app/auth/LoginDialog.kt | 1 | 7019 | package me.proxer.app.auth
import android.app.Dialog
import android.os.Bundle
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import com.jakewharton.rxbinding3.widget.editorActionEvents
import com.jakewharton.rxbinding3.widget.textChanges
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial
import com.mikepenz.iconics.utils.colorInt
import com.mikepenz.iconics.utils.sizeDp
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import kotterknife.bindView
import me.proxer.app.R
import me.proxer.app.base.BaseDialog
import me.proxer.app.util.extension.dip
import me.proxer.app.util.extension.linkClicks
import me.proxer.app.util.extension.linkify
import me.proxer.app.util.extension.resolveColor
import me.proxer.app.util.extension.safeText
import me.proxer.app.util.extension.toast
import me.proxer.library.util.ProxerUrls
import org.koin.androidx.viewmodel.ext.android.viewModel
/**
* @author Ruben Gees
*/
class LoginDialog : BaseDialog() {
companion object {
private val websiteRegex = Regex("Proxer \\b(.+?)\\b")
fun show(activity: AppCompatActivity) = LoginDialog().show(activity.supportFragmentManager, "login_dialog")
}
private val viewModel by viewModel<LoginViewModel>()
private val inputContainer: ViewGroup by bindView(R.id.inputContainer)
private val usernameContainer: TextInputLayout by bindView(R.id.usernameContainer)
private val username: TextInputEditText by bindView(R.id.username)
private val passwordContainer: TextInputLayout by bindView(R.id.passwordContainer)
private val password: TextInputEditText by bindView(R.id.password)
private val secretContainer: TextInputLayout by bindView(R.id.secretContainer)
private val secret: TextInputEditText by bindView(R.id.secret)
private val registrationInfo: TextView by bindView(R.id.registrationInfo)
private val progress: ProgressBar by bindView(R.id.progress)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setLikelyUrl(ProxerUrls.registerWeb())
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = MaterialDialog(requireContext())
.noAutoDismiss()
.title(R.string.dialog_login_title)
.positiveButton(R.string.dialog_login_positive) { validateAndLogin() }
.negativeButton(R.string.cancel) { it.dismiss() }
.customView(R.layout.dialog_login, scrollable = true)
override fun onDialogCreated(savedInstanceState: Bundle?) {
super.onDialogCreated(savedInstanceState)
if (savedInstanceState == null) {
username.requestFocus()
dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
}
setupViews()
setupListeners()
setupViewModel()
}
private fun setupViews() {
secret.transformationMethod = null
registrationInfo.compoundDrawablePadding = dip(12)
registrationInfo.text = requireContext().getString(R.string.dialog_login_registration)
.linkify(web = false, mentions = false, custom = arrayOf(websiteRegex))
registrationInfo.setCompoundDrawables(generateInfoDrawable(), null, null, null)
}
private fun setupListeners() {
listOf(password, secret).forEach {
it.editorActionEvents { event -> event.actionId == EditorInfo.IME_ACTION_GO }
.filter { event -> event.actionId == EditorInfo.IME_ACTION_GO }
.autoDisposable(dialogLifecycleOwner.scope())
.subscribe { validateAndLogin() }
}
listOf(username to usernameContainer, password to passwordContainer).forEach { (input, container) ->
input.textChanges()
.skipInitialValue()
.autoDisposable(dialogLifecycleOwner.scope())
.subscribe { setError(container, null) }
}
registrationInfo.linkClicks()
.map { ProxerUrls.registerWeb() }
.autoDisposable(dialogLifecycleOwner.scope())
.subscribe { showPage(it, skipCheck = true) }
}
private fun setupViewModel() {
viewModel.success.observe(
dialogLifecycleOwner,
Observer {
it?.let {
dismiss()
}
}
)
viewModel.error.observe(
dialogLifecycleOwner,
Observer {
it?.let {
viewModel.error.value = null
requireContext().toast(it.message)
}
}
)
viewModel.isLoading.observe(
dialogLifecycleOwner,
Observer {
inputContainer.isGone = it == true
progress.isVisible = it == true
}
)
viewModel.isTwoFactorAuthenticationEnabled.observe(
dialogLifecycleOwner,
Observer {
secretContainer.isVisible = it == true
secret.imeOptions = if (it == true) EditorInfo.IME_ACTION_GO else EditorInfo.IME_ACTION_NEXT
password.imeOptions = if (it == true) EditorInfo.IME_ACTION_NEXT else EditorInfo.IME_ACTION_GO
}
)
}
private fun validateAndLogin() {
val username = username.safeText.trim().toString()
val password = password.safeText.trim().toString()
val secretKey = secret.safeText.trim().toString()
if (validateInput(username, password)) {
viewModel.login(username, password, secretKey)
}
}
private fun validateInput(username: String, password: String) = when {
username.isBlank() -> {
setError(usernameContainer, getString(R.string.dialog_login_error_username))
false
}
password.isBlank() -> {
setError(passwordContainer, getString(R.string.dialog_login_error_password))
false
}
else -> true
}
private fun setError(container: TextInputLayout, errorText: String?) {
container.isErrorEnabled = errorText != null
container.error = errorText
}
private fun generateInfoDrawable() = IconicsDrawable(requireContext()).apply {
icon = CommunityMaterial.Icon2.cmd_information_outline
colorInt = requireContext().resolveColor(R.attr.colorIcon)
sizeDp = 20
}
}
| gpl-3.0 | 3630b68d12092a4f1e65fdc492952494 | 35.557292 | 115 | 0.680581 | 4.8947 | false | false | false | false |
jean79/yested_fw | src/jsMain/kotlin/net/yested/ext/bootstrap3/modal.kt | 1 | 3326 | package net.yested.ext.bootstrap3
import globals.jQuery
import net.yested.core.html.*
import net.yested.core.utils.Div
import net.yested.ext.jquery.modal
import org.w3c.dom.HTMLDivElement
import org.w3c.dom.HTMLHeadingElement
import kotlin.dom.appendText
interface DialogControl {
fun showDialog()
fun hideDialog()
fun destroyDialog()
}
class DialogContext internal constructor(val header: HTMLHeadingElement, val body: HTMLDivElement, val footer: HTMLDivElement) {
var focusElement: org.w3c.dom.HTMLElement? = null
fun header(init:HTMLHeadingElement.()->Unit) {
header.init()
}
fun body(init:HTMLDivElement.()->Unit) {
body.removeClass2("hidden")
body.init()
}
fun footer(init:HTMLDivElement.()->Unit) {
footer.removeClass2("hidden")
footer.init()
}
}
enum class DialogSize(val code: String) {
Small("sm"),
Default("default"),
Large("lg")
}
fun openDialog(size: DialogSize = DialogSize.Default, init:DialogContext.(dialog: DialogControl)->Unit): DialogControl {
val dialog = prepareDialog(size, init)
dialog.showDialog()
return dialog
}
/**
* Prepares a dialog without showing it.
* This is useful as a lazy value so that it can be shown and hidden multiple times without wasting resources.
* Any callbacks should be tied to a button added to the dialog.
* @return DialogControl to enable showing and hiding it.
*/
fun prepareDialog(size: DialogSize = DialogSize.Default, init:DialogContext.(dialog: DialogControl)->Unit): DialogControl {
var header: HTMLHeadingElement? = null
var body: HTMLDivElement? = null
var footer: HTMLDivElement? = null
val dialogElement = Div {
className = "modal fade"
div { className = "modal-dialog modal-${size.code}"
div {
className = "modal-content"
div {
className = "modal-header"
button {
type = "button"; className = "close"; setAttribute("data-dismiss", "modal")
span { appendText(Typography.times.toString()) }
}
h4 {
className = "modal-title"
header = this
}
}
div {
addClass2("modal-body hidden") // DialogContext.body will unhide this
body = this
}
div {
addClass2("modal-footer hidden") // DialogContext.footer will unhide this
footer = this
}
}
}
}
val dialogContext = DialogContext(header = header!!, body = body!!, footer = footer!!)
val dialogControl = object: DialogControl {
override fun showDialog() {
val jQuery = jQuery(dialogElement)
jQuery.modal("show")
jQuery.on("shown.bs.modal") { _, _ ->
dialogContext.focusElement?.focus()
}
}
override fun hideDialog() {
jQuery(dialogElement).modal("hide")
}
override fun destroyDialog() {
jQuery(dialogElement).modal("destroy")
}
}
dialogContext.init(dialogControl)
return dialogControl
}
| mit | 3427dfb4083a7e30f53ba5fb997fabfb | 28.175439 | 128 | 0.58659 | 4.581267 | false | false | false | false |
vanniktech/Emoji | emoji/src/androidMain/kotlin/com/vanniktech/emoji/internal/EmojiPagerAdapter.kt | 1 | 2605 | /*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.vanniktech.emoji.internal
import android.view.View
import android.view.ViewGroup
import androidx.viewpager.widget.PagerAdapter
import com.vanniktech.emoji.EmojiManager
import com.vanniktech.emoji.EmojiTheming
import com.vanniktech.emoji.recent.NoRecentEmoji
import com.vanniktech.emoji.recent.RecentEmoji
import com.vanniktech.emoji.variant.VariantEmoji
internal class EmojiPagerAdapter(
private val delegate: EmojiPagerDelegate,
private val recentEmoji: RecentEmoji,
private val variantManager: VariantEmoji,
private val theming: EmojiTheming,
) : PagerAdapter() {
private var recentEmojiGridView: RecentEmojiGridView? = null
fun hasRecentEmoji() = recentEmoji !is NoRecentEmoji
fun recentAdapterItemCount() = if (hasRecentEmoji()) 1 else 0
override fun getCount() = EmojiManager.categories().size + recentAdapterItemCount()
override fun instantiateItem(pager: ViewGroup, position: Int): Any {
val newView = when {
hasRecentEmoji() && position == RECENT_POSITION -> {
val view = RecentEmojiGridView(pager.context).init(delegate, delegate, theming, recentEmoji)
recentEmojiGridView = view
view
}
else -> {
val category = EmojiManager.categories()[position - recentAdapterItemCount()]
CategoryGridView(pager.context).init(delegate, delegate, theming, category, variantManager)
}
}
pager.addView(newView)
return newView
}
override fun destroyItem(pager: ViewGroup, position: Int, view: Any) {
pager.removeView(view as View)
if (hasRecentEmoji() && position == RECENT_POSITION) {
recentEmojiGridView = null
}
}
override fun isViewFromObject(view: View, `object`: Any) = view === `object`
fun numberOfRecentEmojis() = recentEmoji.getRecentEmojis().size
fun invalidateRecentEmojis() {
recentEmojiGridView?.invalidateEmojis()
}
internal companion object {
private const val RECENT_POSITION = 0
}
}
| apache-2.0 | ed54ad43da7e7fce1d55968d25554a55 | 32.805195 | 100 | 0.738379 | 4.360134 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/hitbtc/HitBTCAuthInterceptor.kt | 1 | 2913 | package com.baulsupp.okurl.services.hitbtc
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.AuthInterceptor
import com.baulsupp.okurl.authenticator.BasicCredentials
import com.baulsupp.okurl.authenticator.ValidatedCredentials
import com.baulsupp.okurl.authenticator.basic.BasicAuthServiceDefinition
import com.baulsupp.okurl.completion.ApiCompleter
import com.baulsupp.okurl.completion.BaseUrlCompleter
import com.baulsupp.okurl.completion.CompletionVariableCache
import com.baulsupp.okurl.completion.UrlList
import com.baulsupp.okurl.credentials.CredentialsStore
import com.baulsupp.okurl.credentials.Token
import com.baulsupp.okurl.credentials.TokenValue
import com.baulsupp.okurl.kotlin.queryList
import com.baulsupp.okurl.secrets.Secrets
import com.baulsupp.okurl.services.hitbtc.model.Currency
import com.baulsupp.okurl.services.hitbtc.model.Symbol
import okhttp3.Credentials
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
class HitBTCAuthInterceptor : AuthInterceptor<BasicCredentials>() {
override val serviceDefinition = BasicAuthServiceDefinition(
"api.hitbtc.com", "HitBTC API", "hitbtc",
"https://api.hitbtc.com/", "https://hitbtc.com/settings/api-keys"
)
override suspend fun intercept(chain: Interceptor.Chain, credentials: BasicCredentials): Response {
var request = chain.request()
request = request.newBuilder()
.addHeader("Authorization", Credentials.basic(credentials.user, credentials.password))
.build()
return chain.proceed(request)
}
override suspend fun authorize(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
authArguments: List<String>
): BasicCredentials {
val user = Secrets.prompt("BitHTC API Key", "bithtc.apiKey", "", false)
val password = Secrets.prompt("BitHTC Secret Key", "bithtc.secretKey", "", true)
return BasicCredentials(user, password)
}
override suspend fun validate(
client: OkHttpClient,
credentials: BasicCredentials
): ValidatedCredentials {
client.queryList<Any>(
"https://api.hitbtc.com/api/2/account/balance",
TokenValue(credentials)
)
return ValidatedCredentials()
}
override suspend fun apiCompleter(
prefix: String,
client: OkHttpClient,
credentialsStore: CredentialsStore,
completionVariableCache: CompletionVariableCache,
tokenSet: Token
): ApiCompleter {
val urlList = UrlList.fromResource(name())
val completer = BaseUrlCompleter(urlList!!, hosts(credentialsStore), completionVariableCache)
completer.withVariable("currency") {
client.queryList<Currency>("https://api.hitbtc.com/api/2/public/currency", tokenSet).map { it.id }
}
completer.withVariable("symbol") {
client.queryList<Symbol>("https://api.hitbtc.com/api/2/public/symbol", tokenSet).map { it.id }
}
return completer
}
}
| apache-2.0 | 870c3ceaf3221b443bb2e29ebd238753 | 34.52439 | 104 | 0.76725 | 4.400302 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/misc/network/IBD.kt | 2 | 5492 | package com.cout970.magneticraft.misc.network
import io.netty.buffer.ByteBuf
@Suppress("unused")
/**
* Created by cout970 on 09/07/2016.
*
* Indexed Binary Data
* Encodes and decodes data from a ByteBuf using an index to identify the data,
* this way more efficient than NBT for network packets because doesn't use Strings for indexing
* See gui.common.core.Constants.kt for ids
*/
class IBD {
private val map = mutableMapOf<Int, Any>()
fun setInteger(id: Int, value: Int): IBD {
map[id] = value
return this
}
fun setLong(id: Int, value: Long): IBD {
map[id] = value
return this
}
fun setFloat(id: Int, value: Float): IBD {
map[id] = value
return this
}
fun setDouble(id: Int, value: Double): IBD {
map[id] = value
return this
}
fun setBoolean(id: Int, value: Boolean): IBD {
map[id] = value
return this
}
fun setString(id: Int, value: String): IBD {
map[id] = value
return this
}
fun setByteArray(id: Int, value: ByteArray): IBD {
map[id] = value
return this
}
fun setIntArray(id: Int, value: IntArray): IBD {
map[id] = value
return this
}
fun getInteger(id: Int) = map[id] as Int
fun getLong(id: Int) = map[id] as Long
fun getFloat(id: Int) = map[id] as Float
fun getDouble(id: Int) = map[id] as Double
fun getBoolean(id: Int) = map[id] as Boolean
fun getString(id: Int) = map[id] as String
fun getByteArray(id: Int) = map[id] as ByteArray
fun getIntArray(id: Int) = map[id] as IntArray
fun getInteger(id: Int, action: (Int) -> Unit) {
if (hasKey(id)) {
val value = map[id]
if (value is Int) {
action.invoke(value)
}
}
}
fun getLong(id: Int, action: (Long) -> Unit) {
if (hasKey(id)) {
val value = map[id]
if (value is Long) {
action.invoke(value)
}
}
}
fun getFloat(id: Int, action: (Float) -> Unit) {
if (hasKey(id)) {
val value = map[id]
if (value is Float) {
action.invoke(value)
}
}
}
fun getDouble(id: Int, action: (Double) -> Unit) {
if (hasKey(id)) {
val value = map[id]
if (value is Double) {
action.invoke(value)
}
}
}
fun getBoolean(id: Int, action: (Boolean) -> Unit) {
if (hasKey(id)) {
val value = map[id]
if (value is Boolean) {
action.invoke(value)
}
}
}
fun getString(id: Int, action: (String) -> Unit) {
if (hasKey(id)) {
val value = map[id]
if (value is String) {
action.invoke(value)
}
}
}
fun getByteArray(id: Int, action: (ByteArray) -> Unit) {
if (hasKey(id)) {
val value = map[id]
if (value is ByteArray) {
action.invoke(value)
}
}
}
fun getIntArray(id: Int, action: (IntArray) -> Unit) {
if (hasKey(id)) {
val value = map[id]
if (value is IntArray) {
action.invoke(value)
}
}
}
fun hasKey(id: Int) = map.containsKey(id)
fun remove(id: Int) {
map.remove(id)
}
fun clear() {
map.clear()
}
fun merge(other: IBD) {
for ((key, value) in other.map) {
map[key] = value
}
}
fun fromBuffer(buf: ByteBuf) {
clear()
val size = buf.readInt()
for (i in 0 until size) {
val type = buf.readByte()
val id = buf.readInt()
when (type.toInt()) {
1 -> setInteger(id, buf.readInt())
2 -> setLong(id, buf.readLong())
3 -> setFloat(id, buf.readFloat())
4 -> setDouble(id, buf.readDouble())
5 -> setBoolean(id, buf.readBoolean())
6 -> setString(id, buf.readString())
7 -> setByteArray(id, buf.readByteArray())
8 -> setIntArray(id, buf.readIntArray())
}
}
}
fun toBuffer(buf: ByteBuf) {
buf.writeInt(map.size)
for ((id, value) in map) {
val type = when (value) {
is Int -> 1
is Long -> 2
is Float -> 3
is Double -> 4
is Boolean -> 5
is String -> 6
is ByteArray -> 7
is IntArray -> 8
else -> throw IllegalStateException("Invalid value type: ${value.javaClass}, value:$value")
}
buf.writeByte(type)
buf.writeInt(id)
when (type) {
1 -> buf.writeInt(value as Int)
2 -> buf.writeLong(value as Long)
3 -> buf.writeFloat(value as Float)
4 -> buf.writeDouble(value as Double)
5 -> buf.writeBoolean(value as Boolean)
6 -> buf.writeString(value as String)
7 -> buf.writeByteArray(value as ByteArray)
8 -> buf.writeIntArray(value as IntArray)
else -> throw IllegalStateException("Invalid value type: ${value.javaClass}, value:$value")
}
}
}
}
| gpl-2.0 | 4dce7b8b4663489f62a087adf9b6ec4a | 24.90566 | 107 | 0.486526 | 4.044183 | false | false | false | false |
mplatvoet/kovenant | projects/disruptor/src/test/kotlin/validate/validate01.kt | 1 | 2113 | /*
* Copyright (c) 2015 Mark Platvoet<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* THE SOFTWARE.
*/
package validate.disruptor
import nl.komponents.kovenant.Kovenant
import nl.komponents.kovenant.all
import nl.komponents.kovenant.disruptor.queue.disruptorWorkQueue
import nl.komponents.kovenant.task
import support.fib
import java.util.Random
import java.util.concurrent.atomic.AtomicInteger
fun main(args: Array<String>) {
Kovenant.context {
callbackContext {
dispatcher {
concurrentTasks = 1
workQueue = disruptorWorkQueue(capacity = 2048)
}
}
}
validate(100000)
}
fun validate(n: Int) {
val errors = AtomicInteger()
val successes = AtomicInteger()
val promises = Array(n) { _ ->
errors.incrementAndGet()
task {
val i = Random().nextInt(10)
Pair(i, fib(i))
} success {
errors.decrementAndGet()
successes.incrementAndGet()
}
}
all(*promises) always {
println("validate with $n attempts, errors: ${errors.get()}, successes: ${successes.get()}")
}
} | mit | 6e79bdaa146deca2972879d9c07e33a6 | 32.555556 | 100 | 0.690961 | 4.429769 | false | false | false | false |
yole/jkid | src/main/kotlin/Util.kt | 2 | 1471 | package ru.yole.jkid
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import kotlin.reflect.KAnnotatedElement
import kotlin.reflect.KClass
inline fun <reified T> KAnnotatedElement.findAnnotation(): T?
= annotations.filterIsInstance<T>().firstOrNull()
internal fun <T : Any> KClass<T>.createInstance(): T {
val noArgConstructor = constructors.find {
it.parameters.isEmpty()
}
noArgConstructor ?: throw IllegalArgumentException(
"Class must have a no-argument constructor")
return noArgConstructor.call()
}
fun Type.asJavaClass(): Class<Any> = when (this) {
is Class<*> -> this as Class<Any>
is ParameterizedType -> rawType as? Class<Any>
?: throw UnsupportedOperationException("Unknown type $this")
else -> throw UnsupportedOperationException("Unknown type $this")
}
fun <T> Iterable<T>.joinToStringBuilder(stringBuilder: StringBuilder, separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", callback: ((T) -> Unit)? = null): StringBuilder {
return joinTo(stringBuilder, separator, prefix, postfix, limit, truncated) {
if (callback == null) return@joinTo it.toString()
callback(it)
""
}
}
fun Type.isPrimitiveOrString(): Boolean {
val cls = this as? Class<Any> ?: return false
return cls.kotlin.javaPrimitiveType != null || cls == String::class.java
} | apache-2.0 | d41e165a748ca8f0be87c02f7e60b5f1 | 36.74359 | 256 | 0.693406 | 4.339233 | false | false | false | false |
google/horologist | media-ui/src/main/java/com/google/android/horologist/media/ui/components/controls/MediaButton.kt | 1 | 5462 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.media.ui.components.controls
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Forward10
import androidx.compose.material.icons.filled.Forward30
import androidx.compose.material.icons.filled.Forward5
import androidx.compose.material.icons.filled.Replay
import androidx.compose.material.icons.filled.Replay10
import androidx.compose.material.icons.filled.Replay30
import androidx.compose.material.icons.filled.Replay5
import androidx.compose.material.icons.materialIcon
import androidx.compose.material.icons.materialPath
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Button
import androidx.wear.compose.material.ButtonColors
import androidx.wear.compose.material.ButtonDefaults
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.MaterialTheme
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
import com.google.android.horologist.media.ui.components.controls.MediaButtonDefaults.mediaButtonDefaultColors
import com.google.android.horologist.media.ui.semantics.CustomSemanticsProperties.iconImageVector
/**
* A base button for media controls.
*/
@ExperimentalHorologistMediaUiApi
@Composable
public fun MediaButton(
onClick: () -> Unit,
icon: ImageVector,
contentDescription: String,
modifier: Modifier = Modifier,
enabled: Boolean = true,
colors: ButtonColors = mediaButtonDefaultColors,
iconSize: Dp = 30.dp,
tapTargetSize: DpSize = DpSize(48.dp, 60.dp),
iconAlign: Alignment.Horizontal = Alignment.CenterHorizontally
) {
Button(
onClick = onClick,
modifier = modifier.size(tapTargetSize),
enabled = enabled,
colors = colors
) {
Icon(
modifier = Modifier
.size(iconSize)
.run {
when (iconAlign) {
Alignment.Start -> {
offset(x = -7.5.dp)
}
Alignment.End -> {
offset(x = 7.5.dp)
}
else -> {
this
}
}
}
.align(Alignment.Center)
.semantics { iconImageVector = icon },
imageVector = icon,
contentDescription = contentDescription
)
}
}
@ExperimentalHorologistMediaUiApi
public object MediaButtonDefaults {
public val mediaButtonDefaultColors: ButtonColors
@Composable
get() = ButtonDefaults.buttonColors(
backgroundColor = Color.Transparent,
contentColor = MaterialTheme.colors.onSurface,
disabledBackgroundColor = Color.Transparent
)
public fun seekBackIcon(seekButtonIncrement: SeekButtonIncrement): ImageVector =
when (seekButtonIncrement) {
SeekButtonIncrement.Five -> Icons.Default.Replay5
SeekButtonIncrement.Ten -> Icons.Default.Replay10
SeekButtonIncrement.Thirty -> Icons.Default.Replay30
else -> Icons.Default.Replay
}
public fun seekForwardIcon(seekButtonIncrement: SeekButtonIncrement): ImageVector =
when (seekButtonIncrement) {
SeekButtonIncrement.Five -> Icons.Default.Forward5
SeekButtonIncrement.Ten -> Icons.Default.Forward10
SeekButtonIncrement.Thirty -> Icons.Default.Forward30
else -> ForwardEmpty
}
// Icons.Default.Forward is not the same group as 5, 10 and 30 variant
private val ForwardEmpty = materialIcon(name = "Filled.ForwardEmpty") {
materialPath {
moveTo(18.0f, 13.0f)
curveToRelative(0.0f, 3.31f, -2.69f, 6.0f, -6.0f, 6.0f)
reflectiveCurveToRelative(-6.0f, -2.69f, -6.0f, -6.0f)
reflectiveCurveToRelative(2.69f, -6.0f, 6.0f, -6.0f)
verticalLineToRelative(4.0f)
lineToRelative(5.0f, -5.0f)
lineToRelative(-5.0f, -5.0f)
verticalLineToRelative(4.0f)
curveToRelative(-4.42f, 0.0f, -8.0f, 3.58f, -8.0f, 8.0f)
curveToRelative(0.0f, 4.42f, 3.58f, 8.0f, 8.0f, 8.0f)
reflectiveCurveToRelative(8.0f, -3.58f, 8.0f, -8.0f)
horizontalLineTo(18.0f)
close()
}
}
}
| apache-2.0 | 0f5deac7c2f47e6495b7ff69f77a646f | 38.294964 | 110 | 0.673014 | 4.277212 | false | false | false | false |
Shashi-Bhushan/General | cp-trials/src/main/kotlin/in/shabhushan/cp_trials/DirectionReduction.kt | 1 | 2650 | package `in`.shabhushan.cp_trials
object DirectionReduction {
/**
* Imperative Solution
*/
fun dirReduc(
arr: Array<String>
): Array<String> {
// iterate over each pair of entries in array
// if pair could be reduced, reduce it and start again
// otherwise, on reaching the end, return the final array
val reduciblePair = mutableMapOf<String, String>()
reduciblePair["NORTH"] = "SOUTH"
reduciblePair["SOUTH"] = "NORTH"
reduciblePair["EAST"] = "WEST"
reduciblePair["WEST"] = "EAST"
// Assume list is changed
var changed = true
var list = arr.toMutableList()
while (changed) {
var changedInThisIteration = false
(0 until list.size - 1).forEach {
// pair of it and it + 1
if (!changedInThisIteration && reduciblePair[list[it]] == list[it + 1]) {
list = list.apply {
// Remove it and it + 1. Note: on removing it first will have negative consequences here.
removeAt(it + 1)
removeAt(it)
}
changedInThisIteration = true
}
}
changed = changedInThisIteration
}
return list.toTypedArray()
}
private const val SEPARATOR = "-"
/**
* Recursive Solution
*/
fun dirReduc2(
arr: Array<String>
): Array<String> = arr.joinToString(SEPARATOR)
.replace(Regex("NORTH${SEPARATOR}SOUTH[${SEPARATOR}]?"), "")
.replace(Regex("SOUTH${SEPARATOR}NORTH[${SEPARATOR}]?"), "")
.replace(Regex("WEST${SEPARATOR}EAST[${SEPARATOR}]?"), "")
.replace(Regex("EAST${SEPARATOR}WEST[${SEPARATOR}]?"), "")
.replace(Regex("[${SEPARATOR}]?$"), "")
.split(SEPARATOR)
.toTypedArray().let {
if (it.size == arr.size)
it
else
dirReduc2(it)
}
private fun getOppositeDirection(direction: String): String = when (direction) {
"NORTH" -> "SOUTH"
"SOUTH" -> "NORTH"
"EAST" -> "WEST"
"WEST" -> "EAST"
else -> ""
}
/**
* Functional Solution, good thing is it's in one pass
*/
fun dirReduc3(
arr: Array<String>
): Array<String> = arr.fold(listOf<String>()) { accumulator, direction ->
if (accumulator.lastOrNull() == getOppositeDirection(direction))
accumulator.take(accumulator.size - 1)
else
accumulator.plus(direction)
}.toTypedArray()
}
| gpl-2.0 | 48f3e8bd2389fcdcea60bf3d1e9ecad9 | 29.113636 | 113 | 0.527925 | 4.461279 | false | false | false | false |
kory33/SignVote | src/main/kotlin/com/github/kory33/signvote/manager/vote/VoteManager.kt | 1 | 8281 | package com.github.kory33.signvote.manager.vote
import com.github.kory33.signvote.exception.VotePointAlreadyVotedException
import com.github.kory33.signvote.exception.VotePointNotVotedException
import com.github.kory33.signvote.session.VoteSession
import com.github.kory33.signvote.utils.FileUtils
import com.github.kory33.signvote.utils.transformValues
import com.github.kory33.signvote.vote.Vote
import com.github.kory33.signvote.vote.VotePoint
import com.github.kory33.signvote.vote.VoteScore
import com.google.gson.JsonObject
import java.io.File
import java.io.IOException
import java.util.*
/**
* A class which handles all the vote data
*/
class VoteManager {
private val cacheFromUUID: UUIDToPlayerVotesCacheMap
private val cacheFromVotePoint: VotePointToVoteSetCacheMap
private val parentSession: VoteSession
/**
* Construct a VoteManager object from data at given file location
* @param voteDataDirectory directory in which vote data is stored player-wise
* *
* @param parentSession session which is responsible for votes that are about to be read
* *
* @throws IllegalArgumentException when null value or a non-directory file is given as a parameter
*/
@Throws(IOException::class)
constructor(voteDataDirectory: File?, parentSession: VoteSession) {
this.parentSession = parentSession
this.cacheFromUUID = UUIDToPlayerVotesCacheMap()
this.cacheFromVotePoint = VotePointToVoteSetCacheMap()
if (voteDataDirectory == null) {
throw IllegalArgumentException("Directory cannot be null!")
}
if (!voteDataDirectory.isDirectory) {
throw IOException("Directory has to be specified for save location!")
}
FileUtils.getFileListStream(voteDataDirectory).forEach { playerVoteDataFile ->
var jsonObject: JsonObject? = null
try {
jsonObject = FileUtils.readJSON(playerVoteDataFile)
} catch (e: IOException) {
e.printStackTrace()
}
val uuid = UUID.fromString(FileUtils.getFileBaseName(playerVoteDataFile))
this.loadPlayerVoteData(uuid, jsonObject!!)
}
}
private fun loadPlayerVoteData(playerUUID: UUID, jsonObject: JsonObject) {
jsonObject.entrySet().forEach { entry ->
val score = VoteScore(Integer.parseInt(entry.key))
entry.value.asJsonArray.forEach votePointLoad@{ elem ->
val votePoint = this.parentSession.getVotePoint(elem.asString) ?: return@votePointLoad
try {
this.addVotePointData(playerUUID, score, votePoint)
} catch (ignored: VotePointAlreadyVotedException) {
}
}
}
}
/**
* Get the players' vote data, as a map of Player to JsonObject
* @return mapping of (player's)UUID -> json object containing votes of the player
*/
val playersVoteData: Map<UUID, JsonObject>
get() = this.cacheFromUUID.toMap().transformValues { it.toJsonObject() }
/**
* Construct an empty VoteManager object.
*/
constructor(parentSession: VoteSession) {
this.cacheFromUUID = UUIDToPlayerVotesCacheMap()
this.cacheFromVotePoint = VotePointToVoteSetCacheMap()
this.parentSession = parentSession
}
/**
* Get the mapping of voted score to a list of voted points
*/
private fun getVotedPointsMap(uuid: UUID): VoteScoreToVotePointCacheMap {
return this.cacheFromUUID[uuid]
}
/**
* Get the mapping of [vote score] to the [number of times the score has been voted by the player]
* @param uuid UUID of the player
* *
* @return A map containing vote scores as keys and vote counts(with the score of corresponding key) as values
*/
fun getVotedPointsCount(uuid: UUID): Map<VoteScore, Int> {
return this.getVotedPointsMap(uuid).toMap().transformValues { it.size }
}
/**
* Add a vote data related to the score and the votepoint to which the player has voted
* @param voterUUID UUID of a player who has voted
* *
* @param voteScore score which the player has voted
* *
* @param votePoint vote point to which the player has voted
* *
* @throws IllegalArgumentException when there is a duplicate in the vote
*/
@Throws(VotePointAlreadyVotedException::class)
fun addVotePointData(voterUUID: UUID, voteScore: VoteScore, votePoint: VotePoint) {
val cacheByScores = this.cacheFromUUID[voterUUID]
if (this.hasVoted(voterUUID, votePoint)) {
throw VotePointAlreadyVotedException(voterUUID, votePoint)
}
cacheByScores[voteScore].add(votePoint)
this.cacheFromVotePoint[votePoint].add(Vote(voteScore, voterUUID))
}
/**
* Remove a vote casted by the given player to the given vote point.
* @param playerUUID UUID of a player who tries to cancel the vote
* *
* @param votePoint vote point whose vote by the player is being cancelled
* *
* @throws VotePointNotVotedException when the player has not voted to the target vote point
*/
@Throws(VotePointNotVotedException::class)
fun removeVote(playerUUID: UUID, votePoint: VotePoint) {
val playerVotes = this.getVotedPointsMap(playerUUID)
val targetVotePointSet = playerVotes.toMap()
.filter { voteScoreSetEntry -> voteScoreSetEntry.value.contains(votePoint) }
.map({ it.value })
.firstOrNull()
val votePointToVoteSetCacheMap = this.cacheFromVotePoint
val targetVoteCache = votePointToVoteSetCacheMap[votePoint]
.filter { vote -> vote.voterUuid == playerUUID }
.firstOrNull()
if (targetVotePointSet == null || targetVoteCache == null) {
throw VotePointNotVotedException(playerUUID, votePoint, this.parentSession)
}
targetVotePointSet.remove(votePoint)
votePointToVoteSetCacheMap[votePoint].remove(targetVoteCache)
}
/**
* Remove all the votes associated with the given votepoint.
* @param votePoint vote point from which votes will be removed
*/
fun removeAllVotes(votePoint: VotePoint) {
val votes = this.cacheFromVotePoint[votePoint]
// purge votepoint names present in cacheFromUUID
votes.forEach { (score, voterUuid) ->
try {
this.cacheFromUUID[voterUuid][score].remove(votePoint)
} catch (exception: NullPointerException) {
// NPE should be thrown If and Only If
// cacheFromUUID and cacheFromVotePoint are not synchronized correctly
exception.printStackTrace()
}
}
// clear cacheFromVotePoint
this.cacheFromVotePoint.remove(votePoint)
}
/**
* Get a set of votes casted to the given vote point.
* @param votePoint target vote point
* *
* @return set containing all the votes casted to the vote point.
*/
fun getVotes(votePoint: VotePoint): Set<Vote> {
return this.cacheFromVotePoint[votePoint]
}
/**
* Get the score a given player has voted to a given name of votepoint.
* The returned optional object contains no value if the player has not voted.
* @param playerUUID UUID of the player
*
* @param votePoint vote point from which score data is fetched
*
* @return an Optional object containing score vote by the player
*/
fun getVotedScore(playerUUID: UUID, votePoint: VotePoint): VoteScore? {
return this.getVotedPointsMap(playerUUID).toMap()
.filter { entry -> entry.value.contains(votePoint) }
.map({ it.key })
.firstOrNull()
}
/**
* Check if the given player has voted to the specified votepoint.
* @param playerUUID UUID of the player
* *
* @param votePoint target vote point
* *
* @return boolean value true iff player has voted to the given vote point.
*/
fun hasVoted(playerUUID: UUID, votePoint: VotePoint): Boolean {
return this.getVotedScore(playerUUID, votePoint) != null
}
}
| gpl-3.0 | 0938434db8eff8358555532f67a8cd90 | 36.986239 | 114 | 0.665741 | 4.454545 | false | false | false | false |
xfournet/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/propertyUtil.kt | 1 | 1098 | // 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.plugins.groovy.lang.psi.util
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiPrimitiveType.getUnboxedType
import com.intellij.psi.PsiType
import org.jetbrains.plugins.groovy.lang.resolve.PropertyKind
import org.jetbrains.plugins.groovy.lang.resolve.PropertyKind.*
/**
* This method doesn't check if method name is an accessor name
*/
internal fun PsiMethod.checkKind(kind: PropertyKind): Boolean {
val expectedParamCount = if (kind === SETTER) 1 else 0
if (parameterList.parametersCount != expectedParamCount) return false
if (kind == GETTER && returnType == PsiType.VOID) return false
if (kind == BOOLEAN_GETTER && !returnType.isBooleanOrBoxed()) return false
return true
}
private fun PsiType?.isBooleanOrBoxed(): Boolean {
return this == PsiType.BOOLEAN || getUnboxedType(this) == PsiType.BOOLEAN
}
internal fun String.isPropertyName(): Boolean {
return GroovyPropertyUtils.isPropertyName(this)
}
| apache-2.0 | e8f17164ba54fb594077e6db24bb8eaf | 36.862069 | 140 | 0.775046 | 4.143396 | false | false | false | false |
jtlalka/fiszki | app/src/main/kotlin/net/tlalka/fiszki/view/adapters/LanguageAdapter.kt | 1 | 931 | package net.tlalka.fiszki.view.adapters
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import net.tlalka.fiszki.R
import net.tlalka.fiszki.model.types.LanguageType
class LanguageAdapter(context: Context, languageTypes: List<LanguageType>)
: AbstractAdapter<LanguageType>(context, languageTypes) {
override fun getView(position: Int, convertView: View?, viewGroup: ViewGroup?): View {
val itemView = super.getItemView(convertView, viewGroup, R.layout.settings_spinner_item)
itemView.tag = itemView.tag ?: ViewHolderPattern(itemView)
val viewHolderPattern = itemView.tag as ViewHolderPattern
viewHolderPattern.item.text = super.getItem(position).name
return itemView
}
private class ViewHolderPattern(view: View) {
val item: TextView = view.findViewById(R.id.settings_spinner_item)
}
}
| mit | 7388b395d831ee3a546d9b17bb290a41 | 36.24 | 96 | 0.750806 | 4.290323 | false | false | false | false |
paronos/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/library/DeleteLibraryMangasDialog.kt | 3 | 1621 | package eu.kanade.tachiyomi.ui.library
import android.app.Dialog
import android.os.Bundle
import com.afollestad.materialdialogs.MaterialDialog
import com.bluelinelabs.conductor.Controller
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.ui.base.controller.DialogController
import eu.kanade.tachiyomi.widget.DialogCheckboxView
class DeleteLibraryMangasDialog<T>(bundle: Bundle? = null) :
DialogController(bundle) where T : Controller, T: DeleteLibraryMangasDialog.Listener {
private var mangas = emptyList<Manga>()
constructor(target: T, mangas: List<Manga>) : this() {
this.mangas = mangas
targetController = target
}
override fun onCreateDialog(savedViewState: Bundle?): Dialog {
val view = DialogCheckboxView(activity!!).apply {
setDescription(R.string.confirm_delete_manga)
setOptionDescription(R.string.also_delete_chapters)
}
return MaterialDialog.Builder(activity!!)
.title(R.string.action_remove)
.customView(view, true)
.positiveText(android.R.string.yes)
.negativeText(android.R.string.no)
.onPositive { _, _ ->
val deleteChapters = view.isChecked()
(targetController as? Listener)?.deleteMangasFromLibrary(mangas, deleteChapters)
}
.build()
}
interface Listener {
fun deleteMangasFromLibrary(mangas: List<Manga>, deleteChapters: Boolean)
}
} | apache-2.0 | 618f002bb0a40f4105a2d3f612927510 | 35.744186 | 100 | 0.653917 | 4.684971 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/test/java/com/ichi2/libanki/template/ParserTest.kt | 1 | 8734 | /*
* Copyright (c) 2020 Arthur Milchior <[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.ichi2.libanki.template
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.ichi2.anki.RobolectricTest
import com.ichi2.libanki.template.TokenizerTest.Companion.new_to_legacy_template
import com.ichi2.testutils.assertThrows
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ParserTest : RobolectricTest() {
private fun testParsing(template: String, node: ParsedNode) {
assertThat(ParsedNode.parse_inner(template), equalTo(node))
val legacyTemplate = new_to_legacy_template(template)
assertThat(ParsedNode.parse_inner(legacyTemplate), equalTo(node))
}
@Test
fun testParsing() {
testParsing("", EmptyNode())
testParsing("Test", Text("Test"))
testParsing("{{Test}}", Replacement("Test"))
testParsing("{{filter:Test}}", Replacement("Test", "filter"))
testParsing("{{filter:}}", Replacement("", "filter"))
testParsing("{{}}", Replacement(""))
testParsing("{{!Test}}", Replacement("!Test"))
testParsing("{{Filter2:Filter1:Test}}", Replacement("Test", "Filter1", "Filter2"))
testParsing(
"Foo{{Test}}",
ParsedNodes(
Text("Foo"),
Replacement("Test")
)
)
testParsing("{{#Foo}}{{Test}}{{/Foo}}", Conditional("Foo", Replacement("Test")))
testParsing("{{^Foo}}{{Test}}{{/Foo}}", NegatedConditional("Foo", Replacement("Test")))
assertThrows<TemplateError.NoClosingBrackets> {
ParsedNode.parse_inner("{{foo")
}
assertThrows<TemplateError.ConditionalNotClosed> {
ParsedNode.parse_inner("{{#foo}}")
}
assertThrows<TemplateError.ConditionalNotOpen> {
ParsedNode.parse_inner("{{/foo}}")
}
assertThrows<TemplateError.WrongConditionalClosed> {
ParsedNode.parse_inner("{{#bar}}{{/foo}}")
}
}
private fun testParsingIsEmpty(template: String, vararg nonempty_fields: String) {
assertThat(
ParsedNode.parse_inner(template).template_is_empty(*nonempty_fields),
equalTo(true)
)
}
private fun testParsingIsNonEmpty(template: String, vararg nonempty_fields: String) {
assertThat(
ParsedNode.parse_inner(template).template_is_empty(*nonempty_fields),
equalTo(false)
)
}
@Test
fun test_emptiness() {
/* In the comment below, I assume Testi is the field FOOi in position i*/
// No field. Req was `("none", [], [])`
testParsingIsEmpty("")
// Single field. Req was `("all", [0])`
testParsingIsEmpty("{{Field0}}")
testParsingIsEmpty("{{!Field0}}")
testParsingIsEmpty("{{Field0}}", "Field1")
testParsingIsNonEmpty("{{Field0}}", "Field0")
testParsingIsEmpty("{{type:Field0}}")
testParsingIsEmpty("{{Filter2:Filter1:Field0}}")
testParsingIsNonEmpty("{{Filter2:Filter1:Field0}}", "Field0")
testParsingIsEmpty("{{Filter2:Filter1:Field0}}", "Field1")
testParsingIsEmpty("Foo{{Field0}}")
testParsingIsNonEmpty("Foo{{Field0}}", "Field0")
testParsingIsEmpty("Foo{{Field0}}", "Field1")
// Two fields. Req was `("any", [0, 1])`
val twoFields = "{{Field0}}{{Field1}}"
testParsingIsEmpty(twoFields)
testParsingIsNonEmpty(twoFields, "Field0")
testParsingIsNonEmpty(twoFields, "Field1")
testParsingIsNonEmpty(twoFields, "Field0", "Field1")
// Two fields required, one shown, req used to be `("all", [0, 1])`
val mandatoryAndField = "{{#Mandatory1}}{{Field0}}{{/Mandatory1}}"
testParsingIsEmpty(mandatoryAndField)
testParsingIsEmpty(mandatoryAndField, "Field0")
testParsingIsEmpty(mandatoryAndField, "Mandatory1")
testParsingIsNonEmpty(mandatoryAndField, "Field0", "Mandatory1")
// Three required fields , req used to be`("all", [0, 1, 2])`
val twoMandatoriesOneField =
"{{#Mandatory2}}{{#Mandatory1}}{{Field0}}{{/Mandatory1}}{{/Mandatory2}}"
testParsingIsEmpty(twoMandatoriesOneField)
testParsingIsEmpty(twoMandatoriesOneField, "Field0")
testParsingIsEmpty(twoMandatoriesOneField, "Mandatory1")
testParsingIsEmpty(twoMandatoriesOneField, "Field0", "Mandatory1")
testParsingIsEmpty(twoMandatoriesOneField, "Mandatory2")
testParsingIsEmpty(twoMandatoriesOneField, "Field0", "Mandatory2")
testParsingIsEmpty(twoMandatoriesOneField, "Mandatory1", "Mandatory2")
testParsingIsNonEmpty(twoMandatoriesOneField, "Field0", "Mandatory1", "Mandatory2")
// A mandatory field and one of two to display , req used to be`("all", [2])`
val mandatoryAndTwoField = "{{#Mandatory2}}{{Field1}}{{Field0}}{{/Mandatory2}}"
testParsingIsEmpty(mandatoryAndTwoField)
testParsingIsEmpty(mandatoryAndTwoField, "Field0")
testParsingIsEmpty(mandatoryAndTwoField, "Field1")
testParsingIsEmpty(mandatoryAndTwoField, "Field0", "Field1")
testParsingIsEmpty(
mandatoryAndTwoField,
"Mandatory2"
) // This one used to be false, because the only mandatory field was filled
testParsingIsNonEmpty(mandatoryAndTwoField, "Field0", "Mandatory2")
testParsingIsNonEmpty(mandatoryAndTwoField, "Field1", "Mandatory2")
testParsingIsNonEmpty(mandatoryAndTwoField, "Field0", "Field1", "Mandatory2")
// either first field, or two next one , req used to be`("any", [0])`
val oneOrTwo = "{{#Condition2}}{{Field1}}{{/Condition2}}{{Field0}}"
testParsingIsEmpty(oneOrTwo)
testParsingIsNonEmpty(oneOrTwo, "Field0")
testParsingIsEmpty(oneOrTwo, "Field1")
testParsingIsNonEmpty(oneOrTwo, "Field0", "Field1")
testParsingIsEmpty(oneOrTwo, "Condition2")
testParsingIsNonEmpty(oneOrTwo, "Field0", "Condition2")
testParsingIsNonEmpty(
oneOrTwo,
"Field1",
"Condition2"
) // This one was broken, because the field Field0 was not filled, and the two other fields are not sufficient for generating alone
testParsingIsNonEmpty(oneOrTwo, "Field0", "Field1", "Condition2")
// One forbidden field. This means no card used to be filled. Requirement used to be `("none", [], [])`
val oneForbidden = "{{^Forbidden1}}{{Field0}}{{/Forbidden1}}"
testParsingIsEmpty(oneForbidden)
testParsingIsEmpty(oneForbidden, "Forbidden1")
testParsingIsNonEmpty(oneForbidden, "Field0")
testParsingIsEmpty(oneForbidden, "Forbidden1", "Field0")
// One field, a useless one. Req used to be `("all", [0])`
// Realistically, that can be used to display differently conditionally on useless1
val oneUselessOneField =
"{{^Useless1}}{{Field0}}{{/Useless1}}{{#Useless1}}{{Field0}}{{/Useless1}}"
testParsingIsEmpty(oneUselessOneField)
testParsingIsEmpty(oneUselessOneField, "Useless1")
testParsingIsNonEmpty(oneUselessOneField, "Field0")
testParsingIsNonEmpty(oneUselessOneField, "Useless1", "Field0")
// Switch from shown field. Req used to be `("all", [2])`
val switchField = "{{^Useless1}}{{Field0}}{{/Useless1}}{{#Useless1}}{{Field2}}{{/Useless1}}"
testParsingIsEmpty(switchField)
testParsingIsEmpty(switchField, "Useless1")
testParsingIsNonEmpty(switchField, "Field0") // < 2.1.28 would return true by error
testParsingIsEmpty(switchField, "Useless1", "Field0")
testParsingIsEmpty(switchField, "Field2") // < 2.1.28 would return false by error
testParsingIsNonEmpty(switchField, "Useless1", "Field2")
testParsingIsNonEmpty(switchField, "Field0", "Field2")
testParsingIsNonEmpty(switchField, "Useless1", "Field0", "Field2")
}
}
| gpl-3.0 | 9d3d38f873aca02a6029eb2faea0c253 | 46.461957 | 139 | 0.656704 | 3.994968 | false | true | false | false |
tipsy/javalin | javalin/src/test/kotlin/io/javalin/examples/HelloWorldSecure.kt | 1 | 1400 | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin.examples
import io.javalin.Javalin
import org.eclipse.jetty.server.Connector
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.server.ServerConnector
import org.eclipse.jetty.util.ssl.SslContextFactory
// This is a very basic example, a better one can be found at:
// https://github.com/eclipse/jetty.project/blob/jetty-9.4.x/examples/embedded/src/main/java/org/eclipse/jetty/embedded/LikeJettyXml.java#L139-L163
fun main() {
val app = Javalin.create {
it.server {
val server = Server()
val sslConnector = ServerConnector(server, sslContextFactory())
sslConnector.port = 443
val connector = ServerConnector(server)
connector.port = 80
server.connectors = arrayOf<Connector>(sslConnector, connector)
server
}
}.start()
app.get("/") { it.result("Hello World") } // valid endpoint for both connectors
}
private fun sslContextFactory(): SslContextFactory {
val sslContextFactory = SslContextFactory()
sslContextFactory.keyStorePath = HelloWorldSecure::class.java.getResource("/keystore.jks").toExternalForm()
sslContextFactory.setKeyStorePassword("password")
return sslContextFactory
}
| apache-2.0 | f1c3b04ee97bdfde0aad87de5b14dc6d | 34.871795 | 147 | 0.712652 | 4.151335 | false | false | false | false |
pdvrieze/ProcessManager | darwin/src/commonMain/kotlin/uk/ac/bournemouth/darwin/sharedhtml/darwinHtmlShared.kt | 1 | 8737 | /*
* Copyright (c) 2017.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package uk.ac.bournemouth.darwin.sharedhtml
import kotlinx.html.*
import kotlinx.html.stream.appendHTML
import org.w3c.dom.events.Event
const val FIELD_USERNAME = "username"
const val FIELD_PASSWORD = "password"
const val FIELD_PUBKEY = "pubkey"
const val FIELD_REDIRECT = "redirect"
const val FIELD_KEYID = "keyid"
const val FIELD_APPNAME = "app"
const val FIELD_RESPONSE = "response"
const val FIELD_RESETTOKEN = "resettoken"
const val FIELD_NEWPASSWORD1 = "newpassword1"
const val FIELD_NEWPASSWORD2 = "newpassword2"
/**
* A class representing the idea of sending sufficient html to replace the content, but not the layout of the page.
*/
class XMLBody(initialAttributes: Map<String, String>, override val consumer: TagConsumer<*>) : HTMLTag("body", consumer, initialAttributes, null, false, false), HtmlBlockTag
open class ContextTagConsumer<out T>(val context:ServiceContext, private val myDelegate: TagConsumer<T>): TagConsumer<T> {
@Suppress("NOTHING_TO_INLINE")
inline operator fun CharSequence.unaryPlus() = onTagContent(this)
override fun finalize() = myDelegate.finalize()
override fun onTagAttributeChange(tag: Tag, attribute: String, value: String?) = myDelegate.onTagAttributeChange(tag, attribute, value)
override fun onTagContent(content: CharSequence) = myDelegate.onTagContent(content)
override fun onTagComment(content: CharSequence) = myDelegate.onTagComment(content)
override fun onTagContentEntity(entity: Entities) = myDelegate.onTagContentEntity(entity)
override fun onTagContentUnsafe(block: Unsafe.() -> Unit) = myDelegate.onTagContentUnsafe(block)
override fun onTagEnd(tag: Tag) = myDelegate.onTagEnd(tag)
override fun onTagEvent(tag: Tag, event: String, value: (Event) -> Unit) = myDelegate.onTagEvent(tag, event, value)
override fun onTagStart(tag: Tag) = myDelegate.onTagStart(tag)
}
open class SharedButton(val label:String, val id:String)
@Suppress("NOTHING_TO_INLINE")
inline fun <T,C:TagConsumer<T>> C.withContext(context:ServiceContext) = ContextTagConsumer(context, this)
@Suppress("NOTHING_TO_INLINE", "UNCHECKED_CAST")
inline fun <T:Tag> T.withContext(context:ServiceContext) = (consumer as TagConsumer<T>).withContext(context)
/** Just inline for now, as this is just a forwarder. */
fun <O : Appendable> O.appendXML(prettyPrint: Boolean = true): TagConsumer<O>
= this.appendHTML(prettyPrint)
class PartialHTML(initialAttributes: Map<String, String>, override val consumer: TagConsumer<*>) : HTMLTag("root", consumer, initialAttributes, null, false, false) {
fun title(block: TITLE.() -> Unit = {}): Unit = TITLE(emptyMap, consumer).visit(block)
fun title(content: String = ""): Unit = TITLE(emptyMap, consumer).visit({ +content })
fun body(block: XMLBody.() -> Unit = {}): Unit = XMLBody(emptyMap, consumer).visit(block)
}
fun <T, C : TagConsumer<T>> C.partialHTML(block: PartialHTML.() -> Unit = {}): T = PartialHTML(emptyMap, this).visitAndFinalize(this, block)
fun <T, C : ContextTagConsumer<T>> C.darwinBaseDialog(title: String, id: String? = null,
bodyContent: ContextTagConsumer<DIV>.() -> Unit = {}):T {
return div(classes = "dialog centerContents") {
if (id != null) {
this.id = id
}
div(classes = "dialogOuter") {
h1(classes = "dlgTitle") { +title }
div(classes = "dialogInner centerContents") {
withContext(context).bodyContent()
}
}
}
}
fun <T, C : ContextTagConsumer<T>> C.darwinDialog(title: String, id: String? = null, positiveButton:SharedButton?=SharedButton("Ok","btn_dlg_ok"), negativeButton:SharedButton?=null, vararg otherButtons:SharedButton, bodyContent: ContextTagConsumer<*>.() -> Unit = {}):T {
return darwinBaseDialog(title, id) {
div(classes = "dlgContent") {
withContext(context).bodyContent()
}
dialogButtons(positiveButton, negativeButton, *otherButtons)
}
}
private fun ContextTagConsumer<DIV>.dialogButtons(positiveButton: SharedButton?,
negativeButton: SharedButton?,
vararg otherButtons: SharedButton) {
div {
div(classes = "dlgButtons") {
style = "margin-top: 1em; float: right;"
if (negativeButton != null && negativeButton.label.isNotEmpty()) {
input(type = InputType.button, classes = "dlgbutton dialogcancel") {
value = negativeButton.label
id = negativeButton.id
}
}
for (otherButton in otherButtons) {
input(type = InputType.button, classes = "dlgbutton dialogother") {
value = otherButton.label
id = otherButton.id
}
}
if (positiveButton != null && positiveButton.label.isNotEmpty()) {
input(type = InputType.submit, classes = "dlgbutton dialogconfirm") {
value = positiveButton.label
id = positiveButton.id
}
}
}
}
}
fun DIV.loginPanelContent(context: ServiceContext, username: String?) {
consumer.loginPanelContent(context, username)
}
fun <T, C: TagConsumer<T>> C.loginPanelContent(context: ServiceContext, username: String?) {
if (username == null) {
a(href = context.accountMgrPath + "login") {
id = "logout"
+"login"
}
} else {
a(href = context.accountMgrPath + "myaccount") { id = "username"; +username }
span("hide")
a(href = context.accountMgrPath + "logout") { id = "logout"; +"logout" }
}
}
interface ServiceContext {
val accountMgrPath:String
val assetPath:String
val cssPath:String
val jsGlobalPath:String
val jsLocalPath:String
fun cssRef(filename: String): String = "$cssPath$filename"
fun jsGlobalRef(filename: String): String = "$jsGlobalPath$filename"
fun jsLocalRef(filename: String): String = "$jsLocalPath$filename"
}
fun <T, C : ContextTagConsumer<T>> C.loginDialog(context: ServiceContext, errorMsg: String? = null, username: String? = null, password: String? = null, redirect: String? = null, cancelEnabled: Boolean = true): T {
return darwinBaseDialog(title="Log in") {
div("errorMsg") {
if (errorMsg==null) style="display:none" else +errorMsg
}
if (errorMsg!=null) {
}
form(action = "${context.accountMgrPath}login", method = FormMethod.post, encType = FormEncType.applicationXWwwFormUrlEncoded) {
acceptCharset="utf8"
if(redirect!=null) {
input(name=FIELD_REDIRECT, type = InputType.hidden) { value = redirect }
}
table {
style = "border:none"
tr {
td {
label { htmlFor = "#$FIELD_USERNAME"
+"User name:"
}
}
td {
input(name=FIELD_USERNAME, type= InputType.text) {
if (username !=null) { value= username }
}
}
}
tr {
td {
label { htmlFor = "#$FIELD_PASSWORD"
+"Password:"
}
}
td {
input(name=FIELD_PASSWORD, type= InputType.password) {
if (password!=null) { value = password }
}
}
}
} // table
dialogButtons(positiveButton = SharedButton("Log in", "btn_login"),
negativeButton = if (cancelEnabled) SharedButton("Cancel","btn_login_cancel") else null)
div { id="forgotpasswd"
a(href="${context.accountMgrPath}resetpasswd") { +"Forgot password" }
}
}
}
}
fun <T, C:ContextTagConsumer<T>> C.setAliasDialog(oldAlias:String?):T =
darwinDialog("Set alias", negativeButton = SharedButton("Cancel", "btn_alias_cancel")) {
form(action="${context.accountMgrPath}setAlias") {
div {
label { htmlFor = "#alias"; +"Alias" }
input(type= InputType.text, name="alias") {
placeholder="Alias"
oldAlias?.let { value=oldAlias }
}
}
}
}
object shared {
fun <T, C:ContextTagConsumer<T>> setAliasDialog(consumer: C, oldAlias:String?):T {
return consumer.setAliasDialog(oldAlias)
}
} | lgpl-3.0 | 35f3567ae206e18fa67b8e69b35d079b | 36.025424 | 271 | 0.659036 | 4.02256 | false | false | false | false |
Team-Antimatter-Mod/AntiMatterMod | src/main/java/antimattermod/core/Fluid/AMMFluidTank.kt | 1 | 1247 | package antimattermod.core.Fluid
import cpw.mods.fml.relauncher.Side
import cpw.mods.fml.relauncher.SideOnly
import net.minecraftforge.fluids.Fluid
import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.fluids.FluidTank
/**
* @author kojin15.
*/
class AMMFluidTank : FluidTank {
constructor(capacity: Int) : super(capacity) {
}
constructor(stack: FluidStack, capacity: Int) : super(stack, capacity) {
}
constructor(fluid: Fluid, amount: Int, capacity: Int) : super(fluid, amount, capacity) {
}
fun getFluidType(): Fluid? {
return if (getFluid() != null) getFluid().getFluid() else null
}
fun getFluidLocalizedName(): String {
return if (this.fluid != null && this.fluid.getFluid() != null) this.fluid.getFluid().getLocalizedName(this.fluid) else "Empty"
}
fun isEmpty(): Boolean {
return (getFluid() == null) || getFluid().getFluid() == null || (getFluid().amount <= 0)
}
fun isFull(): Boolean {
return getFluid() != null && getFluid().amount == getCapacity()
}
@SideOnly(Side.CLIENT)
fun setAmount(amount: Int) {
if (fluid != null && fluid.getFluid() != null) {
fluid.amount = amount
}
}
}
| gpl-3.0 | 0f275e35c592c526629609116f9238f4 | 26.108696 | 135 | 0.639936 | 3.836923 | false | false | false | false |
pokk/mvp-magazine | app/src/main/kotlin/taiwan/no1/app/ui/listeners/YouTubeThumbnailInitListener.kt | 1 | 1679 | package taiwan.no1.app.ui.listeners
import com.google.android.youtube.player.YouTubeInitializationResult
import com.google.android.youtube.player.YouTubeThumbnailLoader
import com.google.android.youtube.player.YouTubeThumbnailView
import com.google.android.youtube.player.YouTubeThumbnailView.OnInitializedListener
/**
*
* @author Jieyi
* @since 2/21/17
*/
open class YouTubeThumbnailInitListener(val youTubeKey: String): OnInitializedListener {
// More like Kotlin style Chain style.
private var successFunction: (YouTubeThumbnailInitListener.(thumbnailView: YouTubeThumbnailView, loader: YouTubeThumbnailLoader) -> Unit)? = null
private var failureFunction: (YouTubeThumbnailInitListener.(thumbnailView: YouTubeThumbnailView, result: YouTubeInitializationResult) -> Unit)? = null
override fun onInitializationSuccess(thumbnailView: YouTubeThumbnailView, loader: YouTubeThumbnailLoader) =
this.successFunction?.let { it(thumbnailView, loader) } ?: Unit
override fun onInitializationFailure(thumbnailView: YouTubeThumbnailView, result: YouTubeInitializationResult) =
this.failureFunction?.let { it(thumbnailView, result) } ?: Unit
fun onSuccess(onSuccessFunction: YouTubeThumbnailInitListener.(thumbnailView: YouTubeThumbnailView, loader: YouTubeThumbnailLoader) -> Unit):
YouTubeThumbnailInitListener = this.also { it.successFunction = onSuccessFunction }
fun onFailure(onFailureFunction: YouTubeThumbnailInitListener.(thumbnailView: YouTubeThumbnailView, result: YouTubeInitializationResult) -> Unit):
YouTubeThumbnailInitListener = this.also { it.failureFunction = onFailureFunction }
} | apache-2.0 | 800123ac57d260e83fd772c0010f6a5f | 55 | 154 | 0.794521 | 4.797143 | false | false | false | false |
debop/debop4k | debop4k-redis/src/test/kotlin/debop4k/redisson/kotlin/examples/GeospatialKotlinTest.kt | 1 | 2081 | /*
* Copyright (c) 2016. Sunghyouk Bae <[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 debop4k.redisson.kotlin.examples
import debop4k.redisson.kotlin.AbstractRedissonKotlinTest
import org.junit.Test
import org.redisson.api.GeoEntry
import org.redisson.api.GeoUnit
class GeospatialKotlinTest : AbstractRedissonKotlinTest() {
@Test fun geoAdd() {
val geo = redisson.getGeo<String>("test")
// 두 지점을 저장
geo.add(GeoEntry(13.361389, 38.115556, "Palermo"), GeoEntry(15.087269, 37.502669, "Catania"))
// 한 지점을 비동기로 저장
geo.addAsync(37.618423, 55.751244, "Moscow")
// 두 지점의 거리를 계산
val distance = geo.dist("Palermo", "Catania", GeoUnit.KILOMETERS)
println("Palermo - Catania distance: $distance")
// 지정한 지점들의 GeoHash 문자열(11자리)을 나타낸다
val map = geo.hashAsync("Palermo", "Catania")
println("geo hash: ${map.get()}")
// 지점들의 위치를 얻습니다
val positions = geo.pos("test2", "Palermo", "test3", "Catania")
println("positions = $positions")
// 원 형태의 영역에 속한 모든 등록 지점들을 조회합니다
val cities = geo.radius(15.0, 37.0, 200.0, GeoUnit.KILOMETERS)
println("cities = $cities")
// 원 형태의 영역에 속한 모든 등록 지점과 지점의 경위도 정보를 가져옵니다.
val cityWithPositions = geo.radiusWithPosition(15.0, 37.0, 200.0, GeoUnit.KILOMETERS)
println("city with positions = $cityWithPositions")
}
} | apache-2.0 | 2d41b7c54a2631d160985fef748c5171 | 33.666667 | 97 | 0.700695 | 3.027508 | false | true | false | false |
jeffgbutler/mybatis-qbe | src/test/kotlin/examples/kotlin/mybatis3/column/comparison/ColumnComparisonDynamicSqlSupport.kt | 1 | 1279 | /*
* Copyright 2016-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples.kotlin.mybatis3.column.comparison
import org.mybatis.dynamic.sql.SqlTable
import org.mybatis.dynamic.sql.util.kotlin.elements.column
import java.sql.JDBCType
object ColumnComparisonDynamicSqlSupport {
val columnComparison = ColumnComparison()
val number1 = columnComparison.number1
val number2 = columnComparison.number2
val columnList = listOf(number1, number2)
class ColumnComparison : SqlTable("ColumnComparison") {
val number1 = column<Int>(name = "number1", jdbcType = JDBCType.INTEGER)
val number2 = column<Int>(name = "number2", jdbcType = JDBCType.INTEGER)
}
}
| apache-2.0 | 12bc379102262f7d8ae40aa7221cb4c5 | 37.757576 | 80 | 0.729476 | 4.099359 | false | false | false | false |
sephiroth74/AndroidUIGestureRecognizer | uigesturerecognizer/src/androidTest/java/it/sephiroth/android/library/uigestures/Interaction.kt | 1 | 16569 | package it.sephiroth.android.library.uigestures
import android.app.UiAutomation
import android.graphics.Point
import android.graphics.PointF
import android.os.SystemClock
import android.util.Log
import android.view.InputDevice
import android.view.InputEvent
import android.view.MotionEvent
import android.view.MotionEvent.ACTION_DOWN
import android.view.MotionEvent.PointerCoords
import android.view.ViewConfiguration
import android.view.accessibility.AccessibilityEvent
import androidx.test.core.view.PointerCoordsBuilder
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import androidx.test.uiautomator.Configurator
import androidx.test.uiautomator.Tracer
import androidx.test.uiautomator.UiObject
import androidx.test.uiautomator.UiObjectNotFoundException
import timber.log.Timber
import java.util.concurrent.TimeoutException
import kotlin.math.min
class Interaction {
private var mDownTime: Long = 0
fun clickNoSync(x: Int, y: Int, tapTimeout: Long = REGULAR_CLICK_LENGTH): Boolean {
Log.d(LOG_TAG, "clickNoSync ($x, $y)")
if (touchDown(x, y)) {
SystemClock.sleep(tapTimeout)
if (touchUp(x, y))
return true
}
return false
}
fun clickAndSync(x: Int, y: Int, timeout: Long): Boolean {
val logString = String.format("clickAndSync(%d, %d)", x, y)
Log.d(LOG_TAG, logString)
return runAndWaitForEvents(clickRunnable(x, y), WaitForAnyEventPredicate(
AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED or AccessibilityEvent.TYPE_VIEW_SELECTED), timeout) != null
}
fun longTapNoSync(x: Int, y: Int, timeout: Long = ViewConfiguration.getLongPressTimeout().toLong()): Boolean {
if (DEBUG) {
Log.d(LOG_TAG, "longTapNoSync ($x, $y)")
}
if (touchDown(x, y)) {
SystemClock.sleep(timeout)
if (touchUp(x, y)) {
return true
}
}
return false
}
fun longTapAndSync(x: Int, y: Int, timeout: Long): Boolean {
val logString = String.format("clickAndSync(%d, %d)", x, y)
Log.d(LOG_TAG, logString)
return runAndWaitForEvents(longTapRunnable(x, y), WaitForAnyEventPredicate(
AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED or AccessibilityEvent.TYPE_VIEW_SELECTED), timeout) != null
}
@Throws(UiObjectNotFoundException::class)
fun swipeLeftMultiTouch(view: UiObject, steps: Int, fingers: Int = 1): Boolean {
if (steps < 2)
throw RuntimeException("at least 2 steps required")
if (fingers < 2)
throw RuntimeException("at least 2 fingers required")
Tracer.trace(steps)
Tracer.trace(fingers)
val rect = view.visibleBounds
rect.inset(SWIPE_MARGIN_LIMIT, SWIPE_MARGIN_LIMIT)
Timber.v("visibleBounds: $rect")
if (rect.width() <= SWIPE_MARGIN_LIMIT * 2) return false
val array = arrayListOf<Array<MotionEvent.PointerCoords>>()
var pointArray = Array(fingers, init = { PointerCoords() })
val height = rect.height() / 2
val stepHeight = height / (fingers - 1)
val top = rect.top + (rect.height() - height) / 2
val width = rect.width()
val startPoint = Point(rect.right, top)
for (i in 0 until fingers) {
pointArray[i] =
PointerCoordsBuilder.newBuilder()
.setCoords(startPoint.x.toFloat(), startPoint.y + (stepHeight * i).toFloat())
.setSize(1f)
.build()
}
array.add(pointArray)
for (step in 1 until steps) {
pointArray = Array(fingers, init = { PointerCoords() })
for (i in 0 until fingers) {
pointArray[i] =
PointerCoordsBuilder.newBuilder()
.setCoords(startPoint.x.toFloat() - (width / steps) * step, startPoint.y + (stepHeight * i).toFloat())
.setSize(1f)
.build()
}
array.add(pointArray)
}
return performMultiPointerGesture(array.toTypedArray())
}
fun swipe(downX: Int, downY: Int, upX: Int, upY: Int, steps: Int, drag: Boolean = false,
timeout: Long = ViewConfiguration.getLongPressTimeout().toLong()): Boolean {
var ret: Boolean
var swipeSteps = steps
var xStep: Double
var yStep: Double
if (swipeSteps == 0) swipeSteps = 1
xStep = (upX - downX).toDouble() / swipeSteps
yStep = (upY - downY).toDouble() / swipeSteps
ret = touchDown(downX, downY)
if (drag) SystemClock.sleep(timeout)
for (i in 1 until swipeSteps) {
ret = ret and touchMove(downX + (xStep * i).toInt(), downY + (yStep * i).toInt())
if (!ret) {
break
}
SystemClock.sleep(MOTION_EVENT_INJECTION_DELAY_MILLIS.toLong())
}
if (drag) SystemClock.sleep(REGULAR_CLICK_LENGTH)
ret = ret and touchUp(upX, upY)
return ret
}
fun touchDown(x: Int, y: Int): Boolean {
if (DEBUG) {
Log.d(LOG_TAG, "touchDown ($x, $y)")
}
mDownTime = SystemClock.uptimeMillis()
val event = getMotionEvent(mDownTime, mDownTime, ACTION_DOWN, x.toFloat(), y.toFloat())
return injectEventSync(event)
}
fun touchUp(x: Int, y: Int): Boolean {
if (DEBUG) {
Log.d(LOG_TAG, "touchUp ($x, $y)")
}
val eventTime = SystemClock.uptimeMillis()
val event = getMotionEvent(mDownTime, eventTime, MotionEvent.ACTION_UP, x.toFloat(), y.toFloat())
mDownTime = 0
return injectEventSync(event)
}
fun touchMove(x: Int, y: Int): Boolean {
if (DEBUG) {
Log.d(LOG_TAG, "touchMove ($x, $y)")
}
val eventTime = SystemClock.uptimeMillis()
val event = getMotionEvent(mDownTime, eventTime, MotionEvent.ACTION_MOVE, x.toFloat(), y.toFloat())
return injectEventSync(event)
}
fun rotate(view: UiObject, deg: Float, steps: Int): Boolean {
val rect = view.visibleBounds
val size = min(rect.height(), rect.width()).toFloat()
val pt1 = PointF(rect.centerX().toFloat(), (rect.centerY() - (size / 4)))
val pt2 = PointF(rect.centerX().toFloat(), (rect.centerY() + (size / 4)))
val pt11 = PointF(pt1.x, pt1.y)
val pt21 = PointF(pt2.x, pt2.y)
val center = PointF(rect.centerX().toFloat(), rect.centerY().toFloat())
val array = arrayListOf<Array<MotionEvent.PointerCoords>>()
array.add(arrayOf(
PointerCoordsBuilder.newBuilder().setCoords(pt1.x, pt1.y).setSize(1f).build(),
PointerCoordsBuilder.newBuilder().setCoords(pt2.x, pt2.y).setSize(1f).build()))
for (i in 1 until steps) {
val p1 = Point2D.rotateAroundBy(pt11, center, (i.toFloat() / (steps - 1)) * deg)
val p2 = Point2D.rotateAroundBy(pt21, center, (i.toFloat() / (steps - 1)) * deg)
array.add(arrayOf(
PointerCoordsBuilder.newBuilder().setCoords(p1.x, p1.y).setSize(1f).build(),
PointerCoordsBuilder.newBuilder().setCoords(p2.x, p2.y).setSize(1f).build()))
}
return performMultiPointerGesture(array.toTypedArray())
}
fun performMultiPointerGesture(touches: Array<Array<PointerCoords>>,
sleepBeforeMove: Long = MOTION_EVENT_INJECTION_DELAY_MILLIS.toLong(),
sleepBeforeUp: Long = MOTION_EVENT_INJECTION_DELAY_MILLIS.toLong()):
Boolean {
Log.i(LOG_TAG, "performMultiPointerGesture, size: ${touches.size}")
var ret = true
// Get the pointer with the max steps to inject.
val maxSteps = touches.size - 1
// ACTION_DOWN
val currentPointer = touches[0][0]
val downTime = SystemClock.uptimeMillis()
Log.i(LOG_TAG, "ACTION_DOWN (${currentPointer.x}, ${currentPointer.y})")
var event: MotionEvent
event =
getMotionEvent(downTime, ACTION_DOWN, currentPointer.x, currentPointer.y, currentPointer.pressure, currentPointer.size)
ret = ret and injectEventSync(event)
SystemClock.sleep(MOTION_EVENT_INJECTION_DELAY_MILLIS.toLong())
// ACTION_POINTER_DOWN
Log.i(LOG_TAG, "ACTION_POINTER_DOWN")
// specify the properties for each pointer as finger touch
var properties = arrayOfNulls<MotionEvent.PointerProperties>(touches[0].size)
var pointerCoords = Array(touches[0].size) { PointerCoords() }
for (x in touches[0].indices) {
val prop = MotionEvent.PointerProperties()
prop.id = x
prop.toolType = Configurator.getInstance().toolType
properties[x] = prop
pointerCoords[x] = touches[0][x]
}
for (x in 1 until touches[0].size) {
event = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(),
getPointerAction(MotionEvent.ACTION_POINTER_DOWN, x), x + 1, properties,
pointerCoords, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
ret = ret and injectEventSync(event)
}
// ACTION_MOVE
if (maxSteps > 1) {
SystemClock.sleep(sleepBeforeMove)
// specify the properties for each pointer as finger touch
for (step in 1..maxSteps) {
Log.i(LOG_TAG, "ACTION_MOVE, steps: $step of $maxSteps")
val currentTouchArray = touches[step]
properties = arrayOfNulls(currentTouchArray.size)
pointerCoords = currentTouchArray
for (touchIndex in currentTouchArray.indices) {
val prop = MotionEvent.PointerProperties()
prop.id = touchIndex
prop.toolType = Configurator.getInstance().toolType
properties[touchIndex] = prop
}
event = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(),
MotionEvent.ACTION_MOVE, currentTouchArray.size, properties, pointerCoords, 0, 0, 1f, 1f,
0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
ret = ret and injectEventSync(event)
SystemClock.sleep(MOTION_EVENT_INJECTION_DELAY_MILLIS.toLong())
}
}
SystemClock.sleep(sleepBeforeUp)
// ACTION_POINTER_UP
Log.i(LOG_TAG, "ACTION_POINTER_UP")
val currentTouchArray = touches[touches.size - 1]
for (x in 1 until currentTouchArray.size) {
event = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(),
getPointerAction(MotionEvent.ACTION_POINTER_UP, x), x + 1, properties,
pointerCoords, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
ret = ret and injectEventSync(event)
}
// first to touch down is last up
Log.i(LOG_TAG, "ACTION_UP")
event = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 1,
properties, pointerCoords, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
ret = ret and injectEventSync(event)
return ret
}
fun clickRunnable(x: Int, y: Int): Runnable {
return Runnable {
if (touchDown(x, y)) {
SystemClock.sleep(REGULAR_CLICK_LENGTH)
touchUp(x, y)
}
}
}
fun longTapRunnable(x: Int, y: Int): Runnable {
return Runnable {
if (touchDown(x, y)) {
SystemClock.sleep(ViewConfiguration.getLongPressTimeout().toLong())
touchUp(x, y)
}
}
}
fun getUiAutomation(): UiAutomation {
return getInstrumentation().uiAutomation
}
private fun runAndWaitForEvents(command: Runnable,
filter: UiAutomation.AccessibilityEventFilter, timeout: Long): AccessibilityEvent? {
return try {
getUiAutomation().executeAndWaitForEvent(command, filter, timeout)
} catch (e: TimeoutException) {
Log.w(LOG_TAG, "runAndwaitForEvents timed out waiting for events")
null
} catch (e: Exception) {
Log.e(LOG_TAG, "exception from executeCommandAndWaitForAccessibilityEvent", e)
null
}
}
fun injectEventSync(event: InputEvent): Boolean {
return getUiAutomation().injectInputEvent(event, true)
}
internal inner class WaitForAnyEventPredicate(private var mMask: Int) : UiAutomation.AccessibilityEventFilter {
override fun accept(t: AccessibilityEvent): Boolean {
return t.eventType and mMask != 0
}
}
companion object {
const val DEBUG: Boolean = true
const val REGULAR_CLICK_LENGTH: Long = 100
const val MOTION_EVENT_INJECTION_DELAY_MILLIS = 5
const val SWIPE_MARGIN_LIMIT = 5
val LOG_TAG: String = Interaction::class.java.name
fun getMotionEvent(downTime: Long, eventTime: Long, action: Int,
x: Float, y: Float, pressure: Float = 1f, size: Float = 1f, pointerCount: Int = 1): MotionEvent {
val properties = MotionEvent.PointerProperties()
properties.id = 0
properties.toolType = Configurator.getInstance().toolType
val coords = MotionEvent.PointerCoords()
coords.pressure = pressure
coords.size = size
coords.x = x
coords.y = y
return MotionEvent.obtain(downTime, eventTime, action, pointerCount,
arrayOf(properties), arrayOf(coords),
0, 0, 1.0f, 1.0f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
}
fun getMotionEvent(downTime: Long, action: Int, x: Float, y: Float, pressure: Float = 1f, size: Float = 1f, pointerCount: Int = 1): MotionEvent {
return getMotionEvent(downTime, SystemClock.uptimeMillis(), action, x, y, pressure, size, pointerCount)
}
fun getPointerAction(motionEnvent: Int, index: Int): Int {
return motionEnvent + (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
}
}
}
object Point2D {
/**
* Rotate a point around a pivot point. The point will be updated in place
*
* @param position - The point to be rotated
* @param center - The center point
* @param angle - The angle, in degrees
*/
fun rotateAroundBy(position: PointF, center: PointF, angle: Float): PointF {
val angleInRadians = angle * (Math.PI / 180)
val cosTheta = Math.cos(angleInRadians)
val sinTheta = Math.sin(angleInRadians)
val x = (cosTheta * (position.x - center.x) - sinTheta * (position.y - center.y) + center.x).toFloat()
val y = (sinTheta * (position.x - center.x) + cosTheta * (position.y - center.y) + center.y).toFloat()
return PointF(x, y)
}
/**
* Rotate a point in place around it's origin
*
* @param point - point to rotate
* @param origin - origin point
* @param deg - angle in degrees
*/
fun rotateAroundOrigin(point: PointF, origin: PointF, deg: Float) {
val rad = radians(deg.toDouble()).toFloat()
val s = Math.sin(rad.toDouble()).toFloat()
val c = Math.cos(rad.toDouble()).toFloat()
point.x -= origin.x
point.y -= origin.y
val xnew = point.x * c - point.y * s
val ynew = point.x * s + point.y * c
point.x = xnew + origin.x
point.y = ynew + origin.y
}
/**
* Get the point between 2 points at the given t distance ( between 0 and 1 )
*
* @param pt1 the first point
* @param pt2 the second point
* @param t the distance to calculate the average point ( 0 >= t <= 1 )
* @param dstPoint the destination point
*/
fun getLerp(pt1: PointF, pt2: PointF, t: Float): PointF {
return PointF(pt1.x + (pt2.x - pt1.x) * t, pt1.y + (pt2.y - pt1.y) * t)
}
/**
* Degrees to radians.
*
* @param degree the degree
* @return the double
*/
fun radians(degree: Double): Double {
return degree * (Math.PI / 180)
}
} | mit | 91f50e34a94e336efc3c3a1486ddd4d2 | 35.822222 | 153 | 0.594423 | 4.176708 | false | false | false | false |
tasks/tasks | app/src/main/java/com/todoroo/andlib/sql/Operator.kt | 1 | 627 | package com.todoroo.andlib.sql
class Operator private constructor(private val operator: String) {
override fun toString() = operator
companion object {
val eq = Operator("=")
val isNull = Operator("IS NULL")
val isNotNull = Operator("IS NOT NULL")
val and = Operator("AND")
val or = Operator("OR")
val not = Operator("NOT")
val like = Operator("LIKE")
val `in` = Operator("IN")
val exists = Operator("EXISTS")
val gt = Operator(">")
val gte = Operator(">=")
val lt = Operator("<")
val lte = Operator("<=")
}
} | gpl-3.0 | b6be0db4e24f8d8c00c9c4b7e64194cd | 28.904762 | 66 | 0.555024 | 4.543478 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-casc/src/main/java/net/nemerosa/ontrack/extension/casc/graphql/CascMutationProvider.kt | 1 | 1166 | package net.nemerosa.ontrack.extension.casc.graphql
import graphql.schema.DataFetchingEnvironment
import graphql.schema.GraphQLFieldDefinition
import graphql.schema.GraphQLInputObjectField
import graphql.schema.GraphQLType
import net.nemerosa.ontrack.extension.casc.CascLoadingService
import net.nemerosa.ontrack.graphql.schema.Mutation
import net.nemerosa.ontrack.graphql.schema.MutationProvider
import org.springframework.stereotype.Component
@Component
class CascMutationProvider(
private val cascLoadingService: CascLoadingService,
) : MutationProvider {
override val mutations: List<Mutation> = listOf(
object : Mutation {
override val name: String = "reloadCasc"
override val description: String = "Reload the configuration from the CasC files"
override fun inputFields(dictionary: MutableSet<GraphQLType>): List<GraphQLInputObjectField> = emptyList()
override val outputFields: List<GraphQLFieldDefinition> = emptyList()
override fun fetch(env: DataFetchingEnvironment): Any {
cascLoadingService.load()
return ""
}
}
)
} | mit | 57ea2d29026c1b768a7414063a043222 | 34.363636 | 118 | 0.738422 | 5.114035 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-stale/src/main/java/net/nemerosa/ontrack/extension/stale/StaleJobServiceImpl.kt | 1 | 4246 | package net.nemerosa.ontrack.extension.stale
import net.nemerosa.ontrack.common.getOrNull
import net.nemerosa.ontrack.extension.api.ExtensionManager
import net.nemerosa.ontrack.extension.stale.StaleBranchStatus.Companion.min
import net.nemerosa.ontrack.job.*
import net.nemerosa.ontrack.job.JobCategory.Companion.of
import net.nemerosa.ontrack.model.structure.Branch
import net.nemerosa.ontrack.model.structure.Build
import net.nemerosa.ontrack.model.structure.Project
import net.nemerosa.ontrack.model.structure.StructureService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.util.stream.Stream
@Component
class StaleJobServiceImpl(
extensionManager: ExtensionManager,
private val structureService: StructureService
) : StaleJobService {
private val logger: Logger = LoggerFactory.getLogger(StaleJobServiceImpl::class.java)
private val checks: Set<StaleBranchCheck> by lazy {
extensionManager.getExtensions(StaleBranchCheck::class.java).toSet()
}
override fun collectJobRegistrations(): Stream<JobRegistration> {
// Gets all projects...
return structureService.projectList
// ... which have a StaleProperty
.filter { project -> isProjectEligible(project) }
// ... and associates a job with them
.map { project -> createStaleJob(project) }
// ... as a stream
.stream()
}
private fun isProjectEligible(project: Project) = checks.any { it.isProjectEligible(project) }
protected fun createStaleJob(project: Project): JobRegistration = JobRegistration(
object : Job {
override fun getKey(): JobKey {
return getStaleJobKey(project)
}
override fun getTask(): JobRun {
return JobRun { runListener: JobRunListener -> detectAndManageStaleBranches(runListener, project) }
}
override fun getDescription(): String {
return "Detection and management of stale branches for " + project.name
}
override fun isDisabled(): Boolean {
return project.isDisabled
}
override fun isValid(): Boolean = isProjectEligible(project)
},
Schedule.EVERY_DAY
)
protected fun getStaleJobKey(project: Project): JobKey {
return STALE_BRANCH_JOB.getKey(project.id.toString())
}
override fun detectAndManageStaleBranches(runListener: JobRunListener, project: Project) {
if (isProjectEligible(project)) {
structureService.getBranchesForProject(project.id).forEach { branch ->
// Last build on this branch
val lastBuild: Build? = structureService.getLastBuild(branch.id).getOrNull()
detectAndManageStaleBranch(branch, lastBuild)
}
}
}
fun detectAndManageStaleBranch(branch: Branch, lastBuild: Build?) {
logger.debug("[{}] Scanning branch for staleness", branch.entityDisplayName)
// Gets all results
val status: StaleBranchStatus? = checks.fold<StaleBranchCheck, StaleBranchStatus?>(null) { acc: StaleBranchStatus?, check: StaleBranchCheck ->
when (acc) {
null -> check.getBranchStaleness(branch, lastBuild)
StaleBranchStatus.KEEP -> StaleBranchStatus.KEEP
else -> min(acc, check.getBranchStaleness(branch, lastBuild))
}
}
// Logging
logger.debug("[{}] Branch staleness status: {}", branch.entityDisplayName, status)
// Actions
when (status) {
StaleBranchStatus.DELETE -> structureService.deleteBranch(branch.id)
StaleBranchStatus.DISABLE -> if (!branch.isDisabled) {
structureService.disableBranch(branch)
}
// NUll or KEEP
else -> {
}
}
}
companion object {
val STALE_BRANCH_JOB: JobType = of("cleanup").withName("Cleanup")
.getType("stale-branches").withName("Stale branches cleanup")
}
} | mit | e32fe77077d1275a0ad055f522b4cd65 | 38.691589 | 150 | 0.641309 | 4.977726 | false | false | false | false |
aglne/mycollab | mycollab-dao/src/main/java/com/mycollab/db/arguments/SearchCriteria.kt | 3 | 2192 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.db.arguments
import java.io.Serializable
/**
* @author MyCollab Ltd.
* @since 1.0
*/
abstract class SearchCriteria : Serializable {
private var orderFields: MutableList<OrderField>? = null
var saccountid: NumberSearchField? = null
private var extraFields: MutableList<SearchField>? = null
init {
saccountid = NumberSearchField(GroupIdProvider.accountId)
}
fun getExtraFields(): List<SearchField>? {
return extraFields
}
fun setExtraFields(extraFields: MutableList<SearchField>) {
this.extraFields = extraFields
}
fun addExtraField(extraField: SearchField?): SearchCriteria {
if (extraField == null) {
return this
}
if (extraFields == null) {
extraFields = mutableListOf()
}
extraFields!!.add(extraField)
return this
}
fun addOrderField(orderField: OrderField) {
if (orderFields == null) {
orderFields = mutableListOf()
}
orderFields!!.add(orderField)
}
fun getOrderFields(): List<OrderField>? {
return orderFields
}
fun setOrderFields(orderFields: MutableList<OrderField>) {
this.orderFields = orderFields
}
class OrderField(val field: String, val direction: String = "ASC") : Serializable
companion object {
private const val serialVersionUID = 1L
const val ASC = "ASC"
const val DESC = "DESC"
}
}
| agpl-3.0 | 81aeb03225290b557c0c7bdd41520be9 | 27.089744 | 85 | 0.666362 | 4.462322 | false | false | false | false |
DankBots/Mega-Gnar | src/main/kotlin/com/jagrosh/jdautilities/menu/Paginator.kt | 1 | 5727 | package com.jagrosh.jdautilities.menu
import com.jagrosh.jdautilities.waiter.EventWaiter
import net.dv8tion.jda.api.EmbedBuilder
import net.dv8tion.jda.api.MessageBuilder
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.Message
import net.dv8tion.jda.api.entities.MessageEmbed
import net.dv8tion.jda.api.entities.TextChannel
import net.dv8tion.jda.api.entities.User
import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent
import net.dv8tion.jda.api.requests.RestAction
import java.awt.Color
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
class Paginator(
waiter: EventWaiter,
user: User?,
title: String?,
description: String?,
color: Color?,
fields: List<MessageEmbed.Field>,
val emptyMessage: String?,
val list: List<List<String>>,
timeout: Long,
unit: TimeUnit,
finally: (Message?) -> Unit
) : Menu(waiter, user, title, description, color, fields, timeout, unit, finally) {
val LEFT = "\u25C0"
val STOP = "\u23F9"
val RIGHT = "\u25B6"
private val menuPermissions = setOf(Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_ADD_REACTION, Permission.MESSAGE_MANAGE)
fun display(channel: TextChannel) {
if (!channel.guild.selfMember.hasPermission(channel, menuPermissions)) {
val joined = menuPermissions.joinToString("`, `", prefix = "`", postfix = "`")
channel.sendMessage("Error: The bot requires the permissions $joined for pagination menus.").queue()
return finally(null)
}
paginate(channel, 1)
}
fun display(message: Message) = display(message.textChannel)
fun paginate(channel: TextChannel, page: Int) {
if (list.isEmpty()) {
channel.sendMessage(renderEmptyPage()).queue()
return
}
val pageNum = page.coerceIn(1, list.size)
val msg = renderPage(page)
initialize(channel.sendMessage(msg), pageNum)
}
fun paginate(message: Message, page: Int) {
if (list.isEmpty()) {
message.editMessage(renderEmptyPage()).queue()
return
}
val pageNum = page.coerceIn(1, list.size)
val msg = renderPage(page)
initialize(message.editMessage(msg), pageNum)
}
private fun addButtons(message: Message, directions: Boolean): CompletableFuture<Void> {
return when (directions) {
true -> {
message.addReaction(LEFT).submit()
.thenCompose { message.addReaction(STOP).submit() }
.thenCompose { message.addReaction(RIGHT).submit() }
.thenAccept {}
}
false -> {
message.addReaction(STOP).submit()
.thenAccept {}
}
}
}
private fun initialize(action: RestAction<Message>, page: Int) {
action.submit()
.thenCompose { m ->
addButtons(m, list.size > 1)
.thenApply { m }
}
.thenAccept { message ->
waiter.waitFor(MessageReactionAddEvent::class.java) {
val pageNew = when (it.reactionEmote.name) {
LEFT -> page - 1
RIGHT -> page + 1
STOP -> {
finally(message)
return@waitFor
}
else -> {
finally(message)
error("Internal pagination error")
}
}
it.reaction.removeReaction(it.user!!).queue()
if (pageNew != page) {
message?.editMessage(renderPage(pageNew))?.queue {
paginate(it, pageNew)
}
}
}.predicate {
when {
it.messageIdLong != message?.idLong -> false
it.user!!.isBot -> false
user != null && it.user != user -> {
it.reaction.removeReaction(it.user!!).queue()
false
}
else -> when (it.reactionEmote.name) {
LEFT, STOP, RIGHT -> true
else -> false
}
}
}.timeout(timeout, unit) {
//finally(message)
}
}
}
private fun renderPage(page: Int): Message {
val pageNum = page.coerceIn(1, list.size)
val items = list[pageNum - 1]
val embedDescription = buildString {
description?.let { append(it).append('\n').append('\n') }
items.forEachIndexed { index, s ->
append('`').append(index + 1 + (pageNum - 1) * list[0].size).append("` ")
append(s).append('\n')
}
}
val embed = EmbedBuilder().apply {
setColor(color)
setTitle(title)
setDescription(embedDescription)
super.fields.forEach { addField(it) }
setFooter("Page $pageNum/${list.size}", null)
}.build()
return MessageBuilder().setEmbed(embed).build()
}
private fun renderEmptyPage(): Message {
val embed = EmbedBuilder().apply {
setColor(color)
emptyMessage?.let(this::setDescription)
super.fields.forEach { addField(it) }
}.build()
return MessageBuilder().setEmbed(embed).build()
}
}
| mit | 62053fd6835142e1f2e7ed0f1b08e546 | 33.920732 | 131 | 0.528549 | 4.788462 | false | false | false | false |
goodwinnk/intellij-community | plugins/configuration-script/src/RunConfigurationListReader.kt | 1 | 4055 | package com.intellij.configurationScript
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.ConfigurationType
import com.intellij.execution.configurations.RunConfigurationOptions
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.util.ReflectionUtil
import gnu.trove.THashMap
import org.yaml.snakeyaml.nodes.MappingNode
import org.yaml.snakeyaml.nodes.Node
import org.yaml.snakeyaml.nodes.ScalarNode
import org.yaml.snakeyaml.nodes.SequenceNode
internal class RunConfigurationListReader(private val processor: (factory: ConfigurationFactory, state: Any) -> Unit) {
// rc grouped by type
fun read(parentNode: MappingNode, isTemplatesOnly: Boolean) {
val keyToType = THashMap<String, ConfigurationType>()
processConfigurationTypes { configurationType, propertyName, _ ->
keyToType.put(propertyName.toString(), configurationType)
}
for (tuple in parentNode.value) {
val keyNode = tuple.keyNode
if (keyNode !is ScalarNode) {
LOG.warn("Unexpected keyNode type: ${keyNode.nodeId}")
continue
}
if (keyNode.value == Keys.templates) {
if (isTemplatesOnly) {
read(tuple.valueNode as? MappingNode ?: continue, false)
}
continue
}
val configurationType = keyToType.get(keyNode.value)
if (configurationType == null) {
LOG.warn("Unknown run configuration type: ${keyNode.value}")
continue
}
val factories = configurationType.configurationFactories
if (factories.isEmpty()) {
continue
}
val valueNode = tuple.valueNode
if (factories.size > 1) {
if (valueNode !is MappingNode) {
LOG.warn("Unexpected valueNode type: ${valueNode.nodeId}")
continue
}
readFactoryGroup(valueNode, configurationType)
}
else {
readRunConfigurationGroup(tuple.valueNode, factories.first())
}
}
}
// rc grouped by factory (nested group) if more than one factory
private fun readFactoryGroup(parentNode: MappingNode, type: ConfigurationType) {
for (tuple in parentNode.value) {
val keyNode = tuple.keyNode
if (keyNode !is ScalarNode) {
LOG.warn("Unexpected keyNode type: ${keyNode.nodeId}")
continue
}
val factoryKey = keyNode.value
val factory = type.configurationFactories.find { factory -> factoryKey == rcFactoryIdToPropertyName(factory) }
if (factory == null) {
LOG.warn("Unknown run configuration factory: ${keyNode.value}")
continue
}
readRunConfigurationGroup(tuple.valueNode, factory)
}
}
private fun readRunConfigurationGroup(node: Node, factory: ConfigurationFactory) {
val optionsClass = factory.optionsClass
if (optionsClass == null) {
LOG.debug { "Configuration factory \"${factory.name}\" is not described because options class not defined" }
return
}
if (node is MappingNode) {
// direct child
LOG.runAndLogException {
readRunConfiguration(optionsClass, node, factory)
}
}
else if (node is SequenceNode) {
// array of child
for (itemNode in node.value) {
@Suppress("IfThenToSafeAccess")
if (itemNode is MappingNode) {
readRunConfiguration(optionsClass, itemNode, factory)
}
}
}
}
private fun readRunConfiguration(optionsClass: Class<out BaseState>, node: MappingNode, factory: ConfigurationFactory) {
val instance = ReflectionUtil.newInstance(optionsClass)
if (instance is RunConfigurationOptions) {
// very important - set BEFORE read to ensure that user can set any value for isAllowRunningInParallel and it will be not overridden by us later
instance.isAllowRunningInParallel = factory.singletonPolicy.isAllowRunningInParallel
}
processor(factory, readObject(instance, node))
}
} | apache-2.0 | 6ebcf8acfcfeea44553079cb839cf3d0 | 33.666667 | 150 | 0.697411 | 4.915152 | false | true | false | false |
apixandru/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/ScreenshotOnFailure.kt | 1 | 2721 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.impl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.testGuiFramework.framework.IdeTestApplication
import org.fest.swing.core.BasicComponentPrinter
import org.fest.swing.exception.ComponentLookupException
import org.fest.swing.image.ScreenshotTaker
import org.junit.rules.TestWatcher
import org.junit.runner.Description
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.PrintStream
import java.text.SimpleDateFormat
import java.util.*
class ScreenshotOnFailure: TestWatcher() {
override fun failed(throwable: Throwable?, description: Description?) {
val screenshotName = "${description!!.testClass.simpleName}.${description.methodName}"
takeScreenshotOnFailure(throwable!!, screenshotName)
}
companion object {
private val LOG = Logger.getInstance(ScreenshotOnFailure::class.java)
private val myScreenshotTaker = ScreenshotTaker()
fun takeScreenshotOnFailure(e: Throwable, screenshotName: String) {
try {
var file = File(IdeTestApplication.getFailedTestScreenshotDirPath(), "$screenshotName.png")
if (file.exists())
file = File(IdeTestApplication.getFailedTestScreenshotDirPath(), "$screenshotName.${getDateAndTime()}.png")
file.delete()
if (e is ComponentLookupException)
LOG.error("${getHierarchy()} \n caused by:", e)
myScreenshotTaker.saveDesktopAsPng(file.path)
LOG.info("Screenshot: $file")
}
catch (t: Throwable) {
LOG.error("Screenshot failed. ${t.message}")
}
}
fun getHierarchy(): String {
val out = ByteArrayOutputStream()
val printStream = PrintStream(out, true)
val componentPrinter = BasicComponentPrinter.printerWithCurrentAwtHierarchy()
componentPrinter.printComponents(printStream)
printStream.flush()
return String(out.toByteArray())
}
private fun getDateAndTime(): String {
val dateFormat = SimpleDateFormat("yyyy_MM_dd.HH_mm_ss_SSS")
val date = Date()
return dateFormat.format(date) //2016/11/16 12:08:43
}
}
} | apache-2.0 | db9aa3d46a193832ed0d0f5548b7b812 | 34.815789 | 117 | 0.729879 | 4.3958 | false | true | false | false |
panpf/sketch | sketch/src/main/java/com/github/panpf/sketch/stateimage/IconStateImage.kt | 1 | 3044 | /*
* Copyright (C) 2022 panpf <[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.github.panpf.sketch.stateimage
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import androidx.annotation.DrawableRes
import com.github.panpf.sketch.Sketch
import com.github.panpf.sketch.drawable.internal.IconDrawable
import com.github.panpf.sketch.request.ImageRequest
import com.github.panpf.sketch.util.SketchException
/**
* Combines the given icon and background into a drawable with no fixed size to use as a state drawable.
*
* Icons are centered and always the same size
*/
class IconStateImage private constructor(
private val icon: DrawableFetcher,
private val bg: Any?,
) : StateImage {
constructor(icon: Drawable, bg: Drawable)
: this(RealDrawable(icon), RealDrawable(bg))
constructor(icon: Drawable, @DrawableRes bg: Int)
: this(RealDrawable(icon), ResDrawable(bg))
constructor(icon: Drawable, bg: ColorFetcher)
: this(RealDrawable(icon), bg)
constructor(icon: Drawable)
: this(RealDrawable(icon), null)
constructor(@DrawableRes icon: Int, bg: Drawable)
: this(ResDrawable(icon), RealDrawable(bg))
constructor(@DrawableRes icon: Int, @DrawableRes bg: Int)
: this(ResDrawable(icon), ResDrawable(bg))
constructor(@DrawableRes icon: Int, bg: ColorFetcher)
: this(ResDrawable(icon), bg)
constructor(@DrawableRes icon: Int)
: this(ResDrawable(icon), null)
override fun getDrawable(
sketch: Sketch,
request: ImageRequest,
exception: SketchException?
): Drawable {
val icon = icon.getDrawable(request.context)
val bgDrawable = when (bg) {
is DrawableFetcher -> bg.getDrawable(request.context)
is ColorFetcher -> ColorDrawable(bg.getColor(request.context))
else -> null
}
return IconDrawable(icon, bgDrawable)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is IconStateImage) return false
if (icon != other.icon) return false
if (bg != other.bg) return false
return true
}
override fun hashCode(): Int {
var result = icon.hashCode()
result = 31 * result + (bg?.hashCode() ?: 0)
return result
}
override fun toString(): String {
return "IconStateImage(icon=$icon, bg=$bg)"
}
} | apache-2.0 | 550f1677249acba224967e13d075255b | 32.461538 | 104 | 0.676084 | 4.311615 | false | false | false | false |
lare96/luna | plugins/world/player/skill/runecrafting/equipTiara/Tiara.kt | 1 | 968 | package world.player.skill.runecrafting.equipTiara
/**
* An enum representing headgear that can be used to enter an [Altar].
*/
enum class Tiara(val id: Int, val config: Int) {
AIR_TIARA(id = 5527,
config = 1),
MIND_TIARA(id = 5529,
config = 2),
WATER_TIARA(id = 5531,
config = 4),
EARTH_TIARA(id = 5535,
config = 8),
FIRE_TIARA(id = 5537,
config = 16),
BODY_TIARA(id = 5533,
config = 32),
COSMIC_TIARA(id = 5539,
config = 64),
LAW_TIARA(id = 5545,
config = 128),
NATURE_TIARA(id = 5541,
config = 256),
CHAOS_TIARA(id = 5543,
config = 512),
DEATH_TIARA(id = 5547,
config = 1024);
companion object {
/**
* Mappings of [Tiara.id] to [Tiara] instances.
*/
val ID_TO_TIARA = values().associateBy { it.id }
}
}
| mit | e9e3b748c90e66b59d38884558db4f3c | 25.162162 | 70 | 0.488636 | 3.248322 | false | true | false | false |
yiyocx/GitlabAndroid | app/src/main/kotlin/yiyo/gitlabandroid/ui/fragments/ProjectsFragment.kt | 2 | 2669 | package yiyo.gitlabandroid.ui.fragments
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_projects.*
import yiyo.gitlabandroid.R
import yiyo.gitlabandroid.model.entities.Project
import yiyo.gitlabandroid.mvp.presenters.ProjectsPresenter
import yiyo.gitlabandroid.mvp.views.HomeView
import yiyo.gitlabandroid.ui.activities.ProjectDetailActivity
import yiyo.gitlabandroid.ui.adapters.ProjectsAdapter
/**
* Created by yiyo on 25/08/15.
*/
public class ProjectsFragment(val owned: Boolean = false) : Fragment(), HomeView {
private val projectsPresenter by lazy(LazyThreadSafetyMode.NONE) { ProjectsPresenter(this@ProjectsFragment, owned) }
private val projectsAdapter by lazy(LazyThreadSafetyMode.NONE) {
ProjectsAdapter(getContext(), { project -> projectsPresenter.onProjectClicked(project) })
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.fragment_projects, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val linearLayoutManager = LinearLayoutManager(getContext())
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL)
recycler_repositories.setHasFixedSize(true)
recycler_repositories.setLayoutManager(linearLayoutManager)
recycler_repositories.setAdapter(projectsAdapter)
}
override fun onResume() {
super.onResume()
projectsPresenter.onResume()
}
override fun onPause() {
super.onPause()
projectsPresenter.onPause()
}
override fun showLoading() {
projects_progress.setVisibility(View.VISIBLE)
}
override fun hideLoading() {
projects_progress.setVisibility(View.GONE)
}
override fun showProjects(projectsReceived: List<Project>) {
projectsAdapter.projects = projectsReceived
}
override fun navigateToProjectDetail(projectId: Int, name: String, pathWithNamespace: String) {
val intent = Intent(getActivity(), ProjectDetailActivity::class.java)
intent.putExtra("projectId", projectId)
intent.putExtra("name", name)
intent.putExtra("pathWithNamespace", pathWithNamespace)
startActivity(intent)
}
override fun getContext(): Context = getActivity()
} | gpl-2.0 | b6fb0835d14a08947f2c6ff10a286341 | 35.081081 | 120 | 0.749344 | 4.715548 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/edit/summaries/EditSummaryHandler.kt | 1 | 1826 | package org.wikipedia.edit.summaries
import android.view.View
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.database.AppDatabase
import org.wikipedia.edit.db.EditSummary
import org.wikipedia.page.PageTitle
import org.wikipedia.util.L10nUtil.setConditionalTextDirection
class EditSummaryHandler(private val container: View,
private val summaryEdit: AutoCompleteTextView,
title: PageTitle) {
init {
container.setOnClickListener { summaryEdit.requestFocus() }
setConditionalTextDirection(summaryEdit, title.wikiSite.languageCode)
AppDatabase.instance.editSummaryDao().getEditSummaries()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { summaries ->
if (container.isAttachedToWindow) {
updateAutoCompleteList(summaries)
}
}
}
private fun updateAutoCompleteList(editSummaries: List<EditSummary>) {
val adapter = ArrayAdapter(container.context, android.R.layout.simple_list_item_1, editSummaries)
summaryEdit.setAdapter(adapter)
}
fun show() {
container.visibility = View.VISIBLE
}
fun persistSummary() {
AppDatabase.instance.editSummaryDao().insertEditSummary(EditSummary(summary = summaryEdit.text.toString()))
.subscribeOn(Schedulers.io())
.subscribe()
}
fun handleBackPressed(): Boolean {
if (container.visibility == View.VISIBLE) {
container.visibility = View.GONE
return true
}
return false
}
}
| apache-2.0 | 910a8994e15ec7f9135921ef309c3d9d | 33.45283 | 115 | 0.679628 | 5.016484 | false | false | false | false |
Popalay/Cardme | presentation/src/main/kotlin/com/popalay/cardme/presentation/screens/holderdetails/HolderDetailsViewModel.kt | 1 | 2181 | package com.popalay.cardme.presentation.screens.holderdetails
import android.databinding.ObservableBoolean
import android.databinding.ObservableField
import com.jakewharton.rxrelay2.PublishRelay
import com.popalay.cardme.domain.interactor.HolderInteractor
import com.popalay.cardme.domain.interactor.SettingsInteractor
import com.popalay.cardme.data.models.Card
import com.popalay.cardme.data.models.Holder
import com.popalay.cardme.presentation.base.BaseViewModel
import com.popalay.cardme.presentation.base.navigation.CustomRouter
import com.popalay.cardme.presentation.screens.SCREEN_CARD_DETAILS
import com.popalay.cardme.utils.extensions.applyThrottling
import com.stepango.rxdatabindings.setTo
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.addTo
import io.reactivex.rxkotlin.subscribeBy
import javax.inject.Inject
import javax.inject.Named
class HolderDetailsViewModel @Inject constructor(
private val router: CustomRouter,
@Named(HolderDetailsActivity.KEY_HOLDER_DETAILS) holderName: String,
holderInteractor: HolderInteractor,
settingsInteractor: SettingsInteractor
) : BaseViewModel(), HolderDetailsViewModelFacade {
val holder = ObservableField<Holder>()
val showImage = ObservableBoolean()
val cardClickPublisher: PublishRelay<Card> = PublishRelay.create<Card>()
init {
holderInteractor.get(holderName)
.observeOn(AndroidSchedulers.mainThread())
.setTo(holder)
.subscribeBy()
.addTo(disposables)
settingsInteractor.listenShowCardsBackground()
.observeOn(AndroidSchedulers.mainThread())
.setTo(showImage)
.subscribeBy()
.addTo(disposables)
cardClickPublisher
.applyThrottling()
.subscribe { router.navigateTo(SCREEN_CARD_DETAILS, it.number) }
.addTo(disposables)
}
override fun getPositionOfCard(number: String) = holder.get().cards.indexOfFirst { it.number == number }
}
interface HolderDetailsViewModelFacade {
fun getPositionOfCard(number: String): Int
}
| apache-2.0 | 58a2127b6bab5fc866aa5bbfe9e623ad | 34.754098 | 108 | 0.739569 | 4.825221 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/ctrl/ColonyFocusView.kt | 1 | 3187 | package au.com.codeka.warworlds.client.ctrl
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import android.widget.ProgressBar
import android.widget.TextView
import au.com.codeka.warworlds.client.R
import au.com.codeka.warworlds.common.proto.Colony
import com.squareup.wire.get
import java.util.*
import kotlin.math.abs
import kotlin.math.roundToInt
class ColonyFocusView(context: Context?, attrs: AttributeSet?) : FrameLayout(context!!, attrs) {
fun refresh(colony: Colony) {
var defence = (0.25 * colony.population * get(colony.defence_bonus, 1.0f)).toInt()
if (defence < 1) {
defence = 1
}
val defenceTextView = findViewById<View>(R.id.colony_defence) as TextView
defenceTextView.text = String.format(Locale.US, "Defence: %d", defence)
/*
ProgressBar populationFocus =
(ProgressBar) findViewById(R.id.solarsystem_colony_population_focus);
populationFocus.setProgress((int) (100.0f * colony.focus.population));
TextView populationValue = (TextView) findViewById(R.id.solarsystem_colony_population_value);
String deltaPopulation = String.format(Locale.US, "%s%d / hr",
(Wire.get(colony.delta_population, 0.0f) > 0 ? "+" : "-"),
Math.abs(Math.round(Wire.get(colony.delta_population, 0.0f))));
boolean isInCooldown = (colony.cooldown_end_time < new Date().getTime());
if (Wire.get(colony.delta_population, 0.0f) < 0 && colony.population < 110.0 && isInCooldown) {
deltaPopulation = "<font color=\"#ffff00\">" + deltaPopulation + "</font>";
}
populationValue.setText(Html.fromHtml(deltaPopulation));
*/
val farmingFocus = findViewById<View>(R.id.solarsystem_colony_farming_focus) as ProgressBar
farmingFocus.progress = (100.0f * colony.focus.farming).toInt()
val farmingValue = findViewById<View>(R.id.solarsystem_colony_farming_value) as TextView
farmingValue.text = String.format(Locale.US, "%s%d / hr",
if (get(colony.delta_goods, 0.0f) < 0) "-" else "+",
abs(get(colony.delta_goods, 0.0f).roundToInt())
)
val miningFocus = findViewById<View>(R.id.solarsystem_colony_mining_focus) as ProgressBar
miningFocus.progress = (100.0f * colony.focus.mining).toInt()
val miningValue = findViewById<View>(R.id.solarsystem_colony_mining_value) as TextView
miningValue.text = String.format(Locale.US, "%s%d / hr",
if (get(colony.delta_minerals, 0.0f) < 0) "-" else "+",
abs(get(colony.delta_minerals, 0.0f).roundToInt())
)
val constructionFocus = findViewById<View>(R.id.solarsystem_colony_construction_focus) as ProgressBar
constructionFocus.progress = (100.0f * colony.focus.construction).toInt()
val constructionValue = findViewById<View>(R.id.solarsystem_colony_construction_value) as TextView
val numBuildRequests = colony.build_requests.size
if (numBuildRequests == 0) {
constructionValue.text = context.getString(R.string.idle)
} else {
constructionValue.text = String.format(Locale.US, "Q: %d", numBuildRequests)
}
}
init {
addView(View.inflate(context, R.layout.ctrl_colony_focus_view, null))
}
} | mit | 5adcec746abda561ade0297b268a4330 | 47.30303 | 105 | 0.710386 | 3.49069 | false | false | false | false |
hannesa2/owncloud-android | owncloudApp/src/main/java/com/owncloud/android/usecases/RetryUploadFromContentUriUseCase.kt | 2 | 2643 | /**
* ownCloud Android client application
*
* @author Abel García de Prada
* Copyright (C) 2021 ownCloud GmbH.
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
* <p>
* 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.
* <p>
* 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.owncloud.android.usecases
import androidx.core.net.toUri
import androidx.work.WorkManager
import com.owncloud.android.MainApp
import com.owncloud.android.datamodel.UploadsStorageManager
import com.owncloud.android.domain.BaseUseCase
import com.owncloud.android.domain.camerauploads.model.FolderBackUpConfiguration.Behavior.COPY
import com.owncloud.android.domain.camerauploads.model.FolderBackUpConfiguration.Behavior.MOVE
import com.owncloud.android.files.services.FileUploader.LOCAL_BEHAVIOUR_MOVE
class RetryUploadFromContentUriUseCase(
private val workManager: WorkManager
) : BaseUseCase<Unit, RetryUploadFromContentUriUseCase.Params>() {
override fun run(params: Params) {
val uploadsStorageManager = UploadsStorageManager(MainApp.appContext.contentResolver)
val failedUploads = uploadsStorageManager.failedUploads
val filteredUploads = failedUploads.filter { it.uploadId == params.uploadIdInStorageManager }
val uploadToRetry = filteredUploads.firstOrNull()
uploadToRetry ?: return
UploadFileFromContentUriUseCase(workManager).execute(
UploadFileFromContentUriUseCase.Params(
accountName = uploadToRetry.accountName,
contentUri = uploadToRetry.localPath.toUri(),
lastModifiedInSeconds = (uploadToRetry.uploadEndTimestamp / 1000).toString(),
behavior = if (uploadToRetry.localAction == LOCAL_BEHAVIOUR_MOVE) MOVE.name else COPY.name,
uploadPath = uploadToRetry.remotePath,
uploadIdInStorageManager = uploadToRetry.uploadId,
wifiOnly = false,
chargingOnly = false
)
)
uploadsStorageManager.updateUpload(uploadToRetry.apply { uploadStatus = UploadsStorageManager.UploadStatus.UPLOAD_IN_PROGRESS })
}
data class Params(
val uploadIdInStorageManager: Long,
)
}
| gpl-2.0 | b9df85e9fe4eab33d539115f37c59ffd | 42.311475 | 136 | 0.736942 | 4.786232 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-api/src/main/kotlin/org/nd4j/samediff/frameworkimport/rule/attribute/NDArrayExtractScalarValue.kt | 1 | 3537 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.rule.attribute
import org.nd4j.ir.OpNamespace
import org.nd4j.linalg.factory.Nd4j
import org.nd4j.samediff.frameworkimport.ArgDescriptor
import org.nd4j.samediff.frameworkimport.context.MappingContext
import org.nd4j.samediff.frameworkimport.lookupIndexForArgDescriptor
import org.nd4j.samediff.frameworkimport.nameSpaceTensorFromNDarray
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
abstract class NDArrayExtractScalarValue<
GRAPH_DEF: GeneratedMessageV3,
OP_DEF_TYPE: GeneratedMessageV3,
NODE_TYPE: GeneratedMessageV3,
ATTR_DEF : GeneratedMessageV3,
ATTR_VALUE_TYPE : GeneratedMessageV3,
TENSOR_TYPE : GeneratedMessageV3, DATA_TYPE>(mappingNamesToPerform: Map<String, String>,
transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>>):
BaseAttributeExtractionRule<GRAPH_DEF, OP_DEF_TYPE, NODE_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, TENSOR_TYPE, DATA_TYPE>
(name = "ndarrayextractscalarvalue", mappingNamesToPerform = mappingNamesToPerform, transformerArgs = transformerArgs)
where DATA_TYPE: ProtocolMessageEnum {
override fun acceptsInputType(argDescriptorType: AttributeValueType): Boolean {
return argDescriptorType == AttributeValueType.TENSOR
}
override fun outputsType(argDescriptorType: List<OpNamespace.ArgDescriptor.ArgType>): Boolean {
return argDescriptorType.contains(OpNamespace.ArgDescriptor.ArgType.INPUT_TENSOR)
}
override fun convertAttributes(mappingCtx: MappingContext<GRAPH_DEF, NODE_TYPE, OP_DEF_TYPE, TENSOR_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, DATA_TYPE>): List<OpNamespace.ArgDescriptor> {
val ret = ArrayList<OpNamespace.ArgDescriptor>()
mappingNamesToPerform().forEach { (k, v) ->
val indexValueToAbstract = transformerArgs[k]!![0].int64Value
val ndarrayInput = mappingCtx.tensorInputFor(v).toNd4jNDArray()
val argDescriptor = ArgDescriptor {
name = k
argType = OpNamespace.ArgDescriptor.ArgType.INPUT_TENSOR
inputValue = nameSpaceTensorFromNDarray(Nd4j.scalar(ndarrayInput.getDouble(indexValueToAbstract)))
argIndex = lookupIndexForArgDescriptor(
argDescriptorName = k,
opDescriptorName = mappingCtx.nd4jOpName(),
argDescriptorType = OpNamespace.ArgDescriptor.ArgType.INPUT_TENSOR
)
}
ret.add(argDescriptor)
}
return ret
}
} | apache-2.0 | 3aa40833b3f83c91864c5a56f574d956 | 48.830986 | 183 | 0.676845 | 4.70972 | false | false | false | false |
mightyfrog/S4FD | app/src/main/java/org/mightyfrog/android/s4fd/comparemiscs/DataAdapter.kt | 1 | 3923 | package org.mightyfrog.android.s4fd.comparemiscs
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.raizlabs.android.dbflow.sql.language.Select
import com.raizlabs.android.dbflow.sql.queriable.StringQuery
import com.squareup.picasso.Picasso
import org.mightyfrog.android.s4fd.R
import org.mightyfrog.android.s4fd.data.KHCharacter
import org.mightyfrog.android.s4fd.data.KHCharacter_Table
import org.mightyfrog.android.s4fd.data.MiscAttribute
import org.mightyfrog.android.s4fd.util.Const
import java.util.*
/**
* @author Shigehiro Soejima
*/
class DataAdapter(var name: String, ownerId: Int, charToCompareId: Int) : RecyclerView.Adapter<DataAdapter.MiscViewHolder>() {
private val list: MutableList<Misc> = mutableListOf()
private val thumbnailUrlMap = SparseArray<String?>()
init {
setHasStableIds(true)
if (charToCompareId != 0) {
list.addAll(getMiscList(ownerId))
if (ownerId != charToCompareId) {
list.addAll(getMiscList(charToCompareId))
}
} else {
for (id in 1..Const.CHARACTER_COUNT) { // 1 to 58
list.addAll(getMiscList(id))
}
}
}
override fun getItemId(position: Int) = list[position].ownerId.toLong()
override fun getItemCount() = list.size
override fun onBindViewHolder(holder: MiscViewHolder, position: Int) {
holder.bind(list[position])
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int)
= MiscViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.vh_comparison, parent, false))
private fun getMiscList(id: Int): List<Misc> { // TODO: rewrite me :(
val miscList: ArrayList<Misc> = ArrayList(1)
val list: List<MiscAttribute> = StringQuery(MiscAttribute::class.java, "select a.id as \"id\", a.name as \"cName\", b.name as \"sName\", a.rank, a.ownerId, a.value from CharacterAttributeDatum a, SmashAttributeType b where a.smashAttributeTypeId = b.id and a.ownerId=$id and b.name='$name'").queryList()
val misc1 = Misc()
misc1.ownerId = id
misc1.name = list[0].sName
when (name) {
"AIRDODGE" -> misc1.displayName = "Air Dodge"
"ROLLS" -> misc1.displayName = "Forward/Back Roll"
"LEDGEROLL" -> misc1.displayName = "Ledge Roll"
"SPOTDODGE" -> misc1.displayName = "Spot Dodge"
}
misc1.intangibility = list[0].value
misc1.faf = list[1].value
miscList.add(misc1)
return miscList
}
inner class MiscViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val thumbnailIv = itemView.findViewById<ImageView>(R.id.thumbnail)
private val nameTv = itemView.findViewById<TextView>(R.id.name)
private val valueTv = itemView.findViewById<TextView>(R.id.value)
fun bind(datum: Misc) {
datum.apply {
val thumbnailUrl = thumbnailUrlMap.get(ownerId) ?: Select().from(KHCharacter::class.java).where(KHCharacter_Table.id.eq(ownerId)).querySingle()?.thumbnailUrl
thumbnailUrlMap.put(ownerId, thumbnailUrl)
Picasso.with(thumbnailIv.context)
.load(thumbnailUrl)
.placeholder(R.drawable.placeholder)
.into(thumbnailIv)
nameTv.text = displayName
valueTv.text = itemView.context.getString(R.string.misc_data, intangibility, faf)
}
}
}
class Misc {
var ownerId: Int = 0
var name: String? = "N/A"
var displayName: String? = "N/A"
var intangibility: String? = "N/A"
var faf: String? = "N/A"
}
} | apache-2.0 | 94d88d9f5f3327529b9d18f4a16aaaad | 38.636364 | 311 | 0.654856 | 3.962626 | false | false | false | false |
androidx/androidx | compose/desktop/desktop/samples/src/jvmMain/kotlin/androidx/compose/desktop/examples/swingexample/Main.jvm.kt | 3 | 8886 | /*
* 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.desktop.examples.swingexample
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.awt.ComposePanel
import androidx.compose.ui.awt.SwingPanel
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.ApplicationScope
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.launchApplication
import androidx.compose.ui.window.rememberWindowState
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import java.awt.BorderLayout
import java.awt.Color as awtColor
import java.awt.Component
import java.awt.GridLayout
import java.awt.Dimension
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.JButton
import javax.swing.JFrame
import javax.swing.JPanel
import javax.swing.SwingUtilities
import javax.swing.WindowConstants
val northClicks = mutableStateOf(0)
val westClicks = mutableStateOf(0)
val eastClicks = mutableStateOf(0)
fun main() = SwingUtilities.invokeLater {
SwingComposeWindow()
}
fun SwingComposeWindow() {
// creating ComposePanel
val composePanelTop = ComposePanel()
composePanelTop.setBackground(awtColor(55, 155, 55))
val composePanelBottom = ComposePanel()
composePanelBottom.setBackground(awtColor(55, 55, 155))
// setting the content
composePanelTop.setContent {
ComposeContent(background = Color(55, 155, 55))
DisposableEffect(Unit) {
onDispose {
println("Dispose composition")
}
}
}
composePanelBottom.setContent {
ComposeContent(background = Color(55, 55, 155))
DisposableEffect(Unit) {
onDispose {
println("Dispose composition")
}
}
}
val window = JFrame()
window.defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
window.title = "SwingComposeWindow"
val panel = JPanel()
panel.setLayout(GridLayout(2, 1))
window.contentPane.add(panel, BorderLayout.CENTER)
window.contentPane.add(actionButton("WEST", { westClicks.value++ }), BorderLayout.WEST)
window.contentPane.add(
actionButton(
text = "SOUTH/REMOVE COMPOSE",
size = IntSize(40, 40),
action = {
panel.remove(composePanelBottom)
}
),
BorderLayout.SOUTH
)
// addind ComposePanel on JFrame
panel.add(composePanelTop)
panel.add(composePanelBottom)
window.setSize(800, 600)
window.setVisible(true)
}
fun actionButton(
text: String,
action: (() -> Unit)? = null,
size: IntSize = IntSize(70, 70)
): JButton {
val button = JButton(text)
button.setToolTipText("Tooltip for $text button.")
button.setPreferredSize(Dimension(size.width, size.height))
button.addActionListener(object : ActionListener {
public override fun actionPerformed(e: ActionEvent) {
action?.invoke()
}
})
return button
}
@Composable
fun ComposeContent(background: Color = Color.White) {
Box(
modifier = Modifier.fillMaxSize().background(color = background),
contentAlignment = Alignment.Center
) {
Column {
Row(
modifier = Modifier.height(40.dp)
) {
Button(
modifier = Modifier.height(35.dp).padding(top = 3.dp),
onClick = {
@OptIn(DelicateCoroutinesApi::class)
GlobalScope.launchApplication {
Window(
onCloseRequest = ::exitApplication,
state = rememberWindowState(size = DpSize(400.dp, 250.dp))
) {
SecondWindowContent()
}
}
}
) {
Text("New window...", color = Color.White)
}
Spacer(modifier = Modifier.width(20.dp))
SwingPanel(
modifier = Modifier.size(200.dp, 39.dp),
factory = {
actionButton(
text = "JComponent",
action = {
westClicks.value++
northClicks.value++
eastClicks.value++
}
)
},
background = background
)
Spacer(modifier = Modifier.width(20.dp))
SwingPanel(
background = background,
modifier = Modifier.size(200.dp, 39.dp),
factory = { ComposableColoredPanel(Color.Red) }
)
}
Spacer(modifier = Modifier.height(50.dp))
Row {
Counter("West", westClicks)
Spacer(modifier = Modifier.width(25.dp))
Counter("North", northClicks)
Spacer(modifier = Modifier.width(25.dp))
Counter("East", eastClicks)
}
}
}
}
fun ComposableColoredPanel(color: Color): Component {
val composePanel = ComposePanel()
// setting the content
composePanel.setContent {
Box(
modifier = Modifier.fillMaxSize().background(color = color),
contentAlignment = Alignment.Center
) {
Text(text = "ColoredPanel")
}
}
return composePanel
}
@Composable
fun Counter(text: String, counter: MutableState<Int>) {
Surface(
modifier = Modifier.size(130.dp, 130.dp),
color = Color(180, 180, 180),
shape = RoundedCornerShape(4.dp)
) {
Column {
Box(
modifier = Modifier.height(30.dp).fillMaxWidth(),
contentAlignment = Alignment.Center
) {
Text(text = "${text}Clicks: ${counter.value}")
}
Spacer(modifier = Modifier.height(25.dp))
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Button(onClick = { counter.value++ }) {
Text(text = text, color = Color.White)
}
}
}
}
}
@Composable
fun ApplicationScope.SecondWindowContent() {
Box(
Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Column {
Box(
modifier = Modifier.height(30.dp).fillMaxWidth(),
contentAlignment = Alignment.Center
) {
Text(text = "Second Window", color = Color.White)
}
Spacer(modifier = Modifier.height(30.dp))
Box(
modifier = Modifier.height(30.dp).fillMaxWidth(),
contentAlignment = Alignment.Center
) {
Button(onClick = { exitApplication() }) {
Text("Close", color = Color.White)
}
}
}
}
} | apache-2.0 | 46c3dd540433f0ab0b92f270e7b8f787 | 31.793358 | 91 | 0.600945 | 4.882418 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/ty/Expressions.kt | 2 | 13891 | /*
* 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.ty
import com.intellij.openapi.util.Computable
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.Processor
import com.tang.intellij.lua.Constants
import com.tang.intellij.lua.ext.recursionGuard
import com.tang.intellij.lua.project.LuaSettings
import com.tang.intellij.lua.psi.*
import com.tang.intellij.lua.psi.impl.LuaNameExprMixin
import com.tang.intellij.lua.psi.search.LuaShortNamesManager
import com.tang.intellij.lua.search.GuardType
import com.tang.intellij.lua.search.SearchContext
fun inferExpr(expr: LuaExpr?, context: SearchContext): ITy {
if (expr == null)
return Ty.UNKNOWN
if (expr is LuaIndexExpr || expr is LuaNameExpr) {
val tree = LuaDeclarationTree.get(expr.containingFile)
val declaration = tree.find(expr)?.firstDeclaration?.psi
if (declaration != expr && declaration is LuaTypeGuessable) {
return declaration.guessType(context)
}
}
return inferExprInner(expr, context)
}
private fun inferExprInner(expr: LuaPsiElement, context: SearchContext): ITy {
return when (expr) {
is LuaUnaryExpr -> expr.infer(context)
is LuaBinaryExpr -> expr.infer(context)
is LuaCallExpr -> expr.infer(context)
is LuaClosureExpr -> infer(expr, context)
is LuaTableExpr -> expr.infer()
is LuaParenExpr -> infer(expr.expr, context)
is LuaNameExpr -> expr.infer(context)
is LuaLiteralExpr -> expr.infer()
is LuaIndexExpr -> expr.infer(context)
else -> Ty.UNKNOWN
}
}
private fun LuaUnaryExpr.infer(context: SearchContext): ITy {
val stub = stub
val operator = if (stub != null) stub.opType else unaryOp.node.firstChildNode.elementType
return when (operator) {
LuaTypes.MINUS -> infer(expr, context) // Negative something
LuaTypes.GETN -> Ty.NUMBER // Table length is a number
else -> Ty.UNKNOWN
}
}
private fun LuaBinaryExpr.infer(context: SearchContext): ITy {
val stub = stub
val operator = if (stub != null) stub.opType else {
val firstChild = firstChild
val nextVisibleLeaf = PsiTreeUtil.nextVisibleLeaf(firstChild)
nextVisibleLeaf?.node?.elementType
}
return operator.let {
when (it) {
//..
LuaTypes.CONCAT -> Ty.STRING
//<=, ==, <, ~=, >=, >
LuaTypes.LE, LuaTypes.EQ, LuaTypes.LT, LuaTypes.NE, LuaTypes.GE, LuaTypes.GT -> Ty.BOOLEAN
//and, or
LuaTypes.AND, LuaTypes.OR -> guessAndOrType(this, operator, context)
//&, <<, |, >>, ~, ^, +, -, *, /, //, %
LuaTypes.BIT_AND, LuaTypes.BIT_LTLT, LuaTypes.BIT_OR, LuaTypes.BIT_RTRT, LuaTypes.BIT_TILDE, LuaTypes.EXP,
LuaTypes.PLUS, LuaTypes.MINUS, LuaTypes.MULT, LuaTypes.DIV, LuaTypes.DOUBLE_DIV, LuaTypes.MOD -> guessBinaryOpType(this, context)
else -> Ty.UNKNOWN
}
}
}
private fun guessAndOrType(binaryExpr: LuaBinaryExpr, operator: IElementType?, context:SearchContext): ITy {
val rhs = binaryExpr.right
//and
if (operator == LuaTypes.AND)
return infer(rhs, context)
//or
val lhs = binaryExpr.left
val lty = infer(lhs, context)
return if (rhs != null) lty.union(infer(rhs, context)) else lty
}
private fun guessBinaryOpType(binaryExpr : LuaBinaryExpr, context:SearchContext): ITy {
val lhs = binaryExpr.left
// TODO: Search for operator overrides
return infer(lhs, context)
}
fun LuaCallExpr.createSubstitutor(sig: IFunSignature, context: SearchContext): ITySubstitutor? {
if (sig.isGeneric()) {
val list = mutableListOf<ITy>()
// self type
if (this.isMethodColonCall) {
this.prefixExpr?.let { prefix ->
list.add(prefix.guessType(context))
}
}
this.argList.map { list.add(it.guessType(context)) }
val map = mutableMapOf<String, ITy>()
var processedIndex = -1
sig.tyParameters.forEach { map[it.name] = Ty.UNKNOWN }
sig.processArgs { index, param ->
val arg = list.getOrNull(index)
if (arg != null) {
GenericAnalyzer(arg, param.ty).analyze(map)
}
processedIndex = index
true
}
// vararg
val varargTy = sig.varargTy
if (varargTy != null && processedIndex < list.lastIndex) {
val argTy = list[processedIndex + 1]
GenericAnalyzer(argTy, varargTy).analyze(map)
}
sig.tyParameters.forEach {
val superCls = it.superClassName
if (Ty.isInvalid(map[it.name]) && superCls != null) map[it.name] = Ty.create(superCls)
}
return object : TySubstitutor() {
override fun substitute(clazz: ITyClass): ITy {
return map.getOrElse(clazz.className) { clazz }
}
}
}
return null
}
private fun LuaCallExpr.getReturnTy(sig: IFunSignature, context: SearchContext): ITy? {
val substitutor = createSubstitutor(sig, context)
var returnTy = if (substitutor != null) sig.returnTy.substitute(substitutor) else sig.returnTy
returnTy = returnTy.substitute(TySelfSubstitutor(project, this))
return if (returnTy is TyTuple) {
if (context.guessTuple())
returnTy
else returnTy.list.getOrNull(context.index)
} else {
if (context.guessTuple() || context.index == 0)
returnTy
else null
}
}
private fun LuaCallExpr.infer(context: SearchContext): ITy {
val luaCallExpr = this
// xxx()
val expr = luaCallExpr.expr
// 从 require 'xxx' 中获取返回类型
if (expr is LuaNameExpr && LuaSettings.isRequireLikeFunctionName(expr.name)) {
var filePath: String? = null
val string = luaCallExpr.firstStringArg
if (string is LuaLiteralExpr) {
filePath = string.stringValue
}
var file: LuaPsiFile? = null
if (filePath != null)
file = resolveRequireFile(filePath, luaCallExpr.project)
if (file != null)
return file.guessType(context)
return Ty.UNKNOWN
}
var ret: ITy = Ty.UNKNOWN
val ty = infer(expr, context)//expr.guessType(context)
TyUnion.each(ty) {
when (it) {
is ITyFunction -> {
it.process(Processor { sig ->
val targetTy = getReturnTy(sig, context)
if (targetTy != null)
ret = ret.union(targetTy)
true
})
}
//constructor : Class table __call
is ITyClass -> ret = ret.union(it)
}
}
// xxx.new()
if (expr is LuaIndexExpr) {
val fnName = expr.name
if (fnName != null && LuaSettings.isConstructorName(fnName)) {
ret = ret.union(expr.guessParentType(context))
}
}
return ret
}
private fun LuaNameExpr.infer(context: SearchContext): ITy {
val set = recursionGuard(this, Computable {
var type:ITy = Ty.UNKNOWN
context.withRecursionGuard(this, GuardType.GlobalName) {
val multiResolve = multiResolve(this, context)
var maxTimes = 10
for (element in multiResolve) {
val set = getType(context, element)
type = type.union(set)
if (--maxTimes == 0)
break
}
type
}
/**
* fixme : optimize it.
* function xx:method()
* self.name = '123'
* end
*
* https://github.com/EmmyLua/IntelliJ-EmmyLua/issues/93
* the type of 'self' should be same of 'xx'
*/
if (Ty.isInvalid(type)) {
if (name == Constants.WORD_SELF) {
val methodDef = PsiTreeUtil.getStubOrPsiParentOfType(this, LuaClassMethodDef::class.java)
if (methodDef != null && !methodDef.isStatic) {
val methodName = methodDef.classMethodName
val expr = methodName.expr
type = expr.guessType(context)
}
}
}
if (Ty.isInvalid(type)) {
type = getType(context, this)
}
type
})
return set ?: Ty.UNKNOWN
}
private fun getType(context: SearchContext, def: PsiElement): ITy {
when (def) {
is LuaNameExpr -> {
//todo stub.module -> ty
val stub = def.stub
stub?.module?.let {
val memberType = createSerializedClass(it).findMemberType(def.name, context)
if (memberType != null && !Ty.isInvalid(memberType))
return memberType
}
var type: ITy = def.docTy ?: Ty.UNKNOWN
//guess from value expr
if (Ty.isInvalid(type) /*&& !context.forStub*/) {
val stat = def.assignStat
if (stat != null) {
val exprList = stat.valueExprList
if (exprList != null) {
type = context.withIndex(stat.getIndexFor(def)) {
exprList.guessTypeAt(context)
}
}
}
}
//Global
if (isGlobal(def) && type !is ITyPrimitive) {
//use globalClassTy to store class members, that's very important
type = type.union(TyClass.createGlobalType(def, context.forStub))
}
return type
}
is LuaTypeGuessable -> return def.guessType(context)
else -> return Ty.UNKNOWN
}
}
private fun isGlobal(nameExpr: LuaNameExpr):Boolean {
val minx = nameExpr as LuaNameExprMixin
val gs = minx.greenStub
return gs?.isGlobal ?: (resolveLocal(nameExpr, null) == null)
}
private fun LuaLiteralExpr.infer(): ITy {
return when (this.kind) {
LuaLiteralKind.Bool -> Ty.BOOLEAN
LuaLiteralKind.String -> Ty.STRING
LuaLiteralKind.Number -> Ty.NUMBER
LuaLiteralKind.Varargs -> {
val o = PsiTreeUtil.getParentOfType(this, LuaFuncBodyOwner::class.java)
o?.varargType ?: Ty.UNKNOWN
}
//LuaLiteralKind.Nil -> Ty.NIL
else -> Ty.UNKNOWN
}
}
private fun LuaIndexExpr.infer(context: SearchContext): ITy {
val retTy = recursionGuard(this, Computable {
val indexExpr = this
var parentTy: ITy? = null
// xxx[yyy] as an array element?
if (indexExpr.brack) {
val tySet = indexExpr.guessParentType(context)
var ty: ITy = Ty.UNKNOWN
// Type[]
TyUnion.each(tySet) {
if (it is ITyArray) ty = ty.union(it.base)
}
if (ty !is TyUnknown) return@Computable ty
// table<number, Type>
TyUnion.each(tySet) {
if (it is ITyGeneric) ty = ty.union(it.getParamTy(1))
}
if (ty !is TyUnknown) return@Computable ty
parentTy = tySet
}
//from @type annotation
val docTy = indexExpr.docTy
if (docTy != null)
return@Computable docTy
// xxx.yyy = zzz
//from value
var result: ITy = Ty.UNKNOWN
val assignStat = indexExpr.assignStat
if (assignStat != null) {
result = context.withIndex(assignStat.getIndexFor(indexExpr)) {
assignStat.valueExprList?.guessTypeAt(context) ?: Ty.UNKNOWN
}
}
//from other class member
val propName = indexExpr.name
if (propName != null) {
val prefixType = parentTy ?: indexExpr.guessParentType(context)
prefixType.eachTopClass(Processor { clazz ->
result = result.union(guessFieldType(propName, clazz, context))
true
})
// table<string, K> -> member type is K
prefixType.each { ty ->
if (ty is ITyGeneric && ty.getParamTy(0) == Ty.STRING)
result = result.union(ty.getParamTy(1))
}
}
result
})
return retTy ?: Ty.UNKNOWN
}
private fun guessFieldType(fieldName: String, type: ITyClass, context: SearchContext): ITy {
// _G.var = {} <==> var = {}
if (type.className == Constants.WORD_G)
return TyClass.createGlobalType(fieldName)
var set:ITy = Ty.UNKNOWN
LuaShortNamesManager.getInstance(context.project).processAllMembers(type, fieldName, context, Processor {
set = set.union(it.guessType(context))
true
})
return set
}
private fun LuaTableExpr.infer(): ITy {
val list = this.tableFieldList
if (list.size == 1) {
val valueExpr = list.first().valueExpr
if (valueExpr is LuaLiteralExpr && valueExpr.kind == LuaLiteralKind.Varargs) {
val func = PsiTreeUtil.getStubOrPsiParentOfType(this, LuaFuncBodyOwner::class.java)
val ty = func?.varargType
if (ty != null)
return TyArray(ty)
}
}
return TyTable(this)
} | apache-2.0 | 0460eeba3e2797295faf0b72b3765d0a | 33.17734 | 141 | 0.58782 | 4.22503 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/modules/award/contests/AwardContestsFragment.kt | 2 | 6122 | package ru.fantlab.android.ui.modules.award.contests
import android.content.Context
import android.os.Bundle
import androidx.annotation.StringRes
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import kotlinx.android.synthetic.main.micro_grid_refresh_list.*
import kotlinx.android.synthetic.main.state_layout.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.Award
import ru.fantlab.android.data.dao.model.Consts
import ru.fantlab.android.data.dao.model.ConstsParent
import ru.fantlab.android.helper.BundleConstant
import ru.fantlab.android.helper.BundleConstant.EXTRA_TWO
import ru.fantlab.android.helper.Bundler
import ru.fantlab.android.ui.adapter.viewholder.ConstsViewHolder
import ru.fantlab.android.ui.adapter.viewholder.ConstsWorkViewHolder
import ru.fantlab.android.ui.base.BaseFragment
import ru.fantlab.android.ui.modules.award.AwardPagerMvp
import ru.fantlab.android.ui.modules.work.WorkPagerActivity
import ru.fantlab.android.ui.widgets.recyclerview.layoutManager.StaggeredManager
import ru.fantlab.android.ui.widgets.treeview.TreeNode
import ru.fantlab.android.ui.widgets.treeview.TreeViewAdapter
import java.util.*
class AwardContestsFragment : BaseFragment<AwardContestsMvp.View, AwardContestsPresenter>(),
AwardContestsMvp.View {
private var countCallback: AwardPagerMvp.View? = null
private var workId: Int? = -1
override fun fragmentLayout() = R.layout.micro_grid_refresh_list
override fun providePresenter() = AwardContestsPresenter()
override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
workId = arguments?.getInt(EXTRA_TWO)
stateLayout.setEmptyText(R.string.no_contests)
stateLayout.setOnReloadListener(this)
refresh.setOnRefreshListener(this)
recycler.setEmptyView(stateLayout, refresh)
recycler.addDivider()
presenter.onFragmentCreated(arguments!!)
}
override fun onInitViews(contests: List<Award.Contest>?) {
hideProgress()
if (!contests.isNullOrEmpty()) {
onSetTabCount(contests.size)
initAdapter(contests)
} else {
stateLayout.showEmptyState()
}
}
private fun initAdapter(contests: List<Award.Contest>) {
val nodes = arrayListOf<TreeNode<*>>()
contests.forEachIndexed { subIndex, item ->
val title = item.nameyear
val app = TreeNode(ConstsParent(title, item.description))
nodes.add(app)
item.contestWorks?.forEach { contestsWork ->
var nameConsts = if (!contestsWork.workRusname.isNullOrEmpty()) {
if (!contestsWork.cwName.isNullOrEmpty()) {
String.format("%s / %s", contestsWork.workRusname, contestsWork.cwName)
} else {
contestsWork.workRusname
}
} else {
contestsWork.cwName
}
if (nameConsts.isNullOrEmpty()) {
nameConsts = if (contestsWork.autorRusname.isEmpty()) {
contestsWork.cwRusname
} else contestsWork.autorRusname
}
nameConsts = if (contestsWork.cwLinkId != null) {
StringBuilder()
.append("\"$nameConsts\"")
.append(", ")
.append(contestsWork.autorRusname)
.toString()
} else nameConsts
nodes[subIndex].addChild(TreeNode(Consts(nameConsts, contestsWork.nominationRusname, contestsWork.cwLinkId ?: 0)))
if (workId != -1) app.expandAll()
}
}
val adapter = TreeViewAdapter(nodes, Arrays.asList(ConstsWorkViewHolder(), ConstsViewHolder()))
if (recycler.adapter == null)
recycler.adapter = adapter
else
adapter.notifyDataSetChanged()
adapter.setOnTreeNodeListener(object : TreeViewAdapter.OnTreeNodeListener {
override fun onSelected(extra: Int, add: Boolean) {
}
override fun onClick(node: TreeNode<*>, holder: RecyclerView.ViewHolder): Boolean {
if (!node.isLeaf) {
onToggle(!node.isExpand, holder)
} else if (node.isLeaf && node.content is ConstsParent) {
return false
} else {
val itemWork = node.content as Consts
if (itemWork.workId != 0) {
WorkPagerActivity.startActivity(context!!, itemWork.workId, itemWork.title)
}
}
return false
}
override fun onToggle(isExpand: Boolean, holder: RecyclerView.ViewHolder) {
val dirViewHolder = holder as ConstsViewHolder.ViewHolder
val ivArrow = dirViewHolder.ivArrow
val rotateDegree = if (isExpand) 90.0f else -90.0f
ivArrow.animate().rotationBy(rotateDegree)
.start()
}
})
if (workId != -1) {
var position = 0
var success = false
nodes.forEachIndexed { index, treeNode ->
if (success) return
val works = treeNode.childList
works.forEach { workNode ->
val work = workNode.content as Consts
if (work.workId == workId) {
val lm: StaggeredManager = recycler.layoutManager as StaggeredManager
lm.scrollToPosition(position)
success = true
return@forEachIndexed
}
position++
}
position++
}
}
fastScroller.attachRecyclerView(recycler)
}
override fun showProgress(@StringRes resId: Int, cancelable: Boolean) {
refresh.isRefreshing = true
stateLayout.showProgress()
}
override fun hideProgress() {
refresh.isRefreshing = false
stateLayout.showReload(recycler.adapter?.itemCount ?: 0)
}
override fun showErrorMessage(msgRes: String?) {
hideProgress()
super.showErrorMessage(msgRes)
}
override fun showMessage(titleRes: Int, msgRes: Int) {
hideProgress()
super.showMessage(titleRes, msgRes)
}
companion object {
fun newInstance(awardId: Int, workId: Int): AwardContestsFragment {
val view = AwardContestsFragment()
view.arguments = Bundler.start()
.put(BundleConstant.EXTRA, awardId)
.put(BundleConstant.EXTRA_TWO, workId)
.end()
return view
}
}
override fun onRefresh() {
presenter.getContests(true)
}
override fun onClick(v: View?) {
onRefresh()
}
override fun onSetTabCount(allCount: Int) {
countCallback?.onSetBadge(1, allCount)
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is AwardPagerMvp.View) {
countCallback = context
}
}
override fun onDetach() {
countCallback = null
super.onDetach()
}
override fun onItemClicked(item: Award.Contest, position: Int) {
}
} | gpl-3.0 | e507114b8cc60ddafa9bebd082319370 | 28.57971 | 118 | 0.73146 | 3.690175 | false | true | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/vfs/TarGzFile.kt | 1 | 4270 | package org.jetbrains.haskell.vfs
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileSystem
import java.io.OutputStream
import java.io.InputStream
import org.apache.commons.compress.archivers.ArchiveEntry
import java.io.FileInputStream
import java.io.BufferedInputStream
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
import java.io.ByteArrayInputStream
import org.apache.commons.compress.archivers.tar.TarArchiveEntry
import java.io.ByteArrayOutputStream
import java.util.ArrayList
import java.io.File
/**
* Created by atsky on 09/05/14.
*/
public class TarGzFile(val archiveFile: VirtualFile,
val myPath: String) : VirtualFile() {
var isInit = false;
var myData: ByteArray? = null
val myChildren = ArrayList<String>()
fun doInit(): Boolean {
if (isInit) {
return true
}
val archiveIns = archiveFile.getInputStream()
val bin = BufferedInputStream(archiveIns)
val gzIn = GzipCompressorInputStream(bin);
val tarArchiveInputStream = TarArchiveInputStream(gzIn)
while (true) {
val entry = tarArchiveInputStream.getNextTarEntry();
if (entry == null) {
break
}
val entryName = entry.getName() ?: ""
if (myPath == entryName) {
myData = readToArray(tarArchiveInputStream)
} else if (entryName.startsWith(myPath)) {
val name = entryName.substring(myPath.length())
if (!name.substring(0, name.length() - 1).contains("/")) {
myChildren.add(name)
}
}
}
gzIn.close()
isInit = true
return (myData != null)
}
fun readToArray(ins: InputStream): ByteArray {
val buffer = ByteArrayOutputStream()
var nRead: Int
val data = ByteArray(16384)
while (true) {
nRead = ins.read(data, 0, data.size())
if (nRead == -1) {
break;
}
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer.toByteArray();
}
override fun getName(): String {
val str = if (isDirectory()) {
myPath.substring(0, myPath.length() - 1)
} else {
myPath
}
val indexOf = str.lastIndexOf('/')
return myPath.substring(indexOf + 1)
}
override fun getFileSystem(): VirtualFileSystem = CabalVirtualFileSystem.INSTANCE
override fun getPath(): String =
archiveFile.getPath() + "!" + myPath
override fun isWritable() = false
override fun isDirectory() = myPath.last() == '/'
override fun isValid() = true
override fun getParent(): VirtualFile? {
val str = if (isDirectory()) {
myPath.substring(0, myPath.length() - 1)
} else {
myPath
}
val indexOf = str.lastIndexOf('/')
if (indexOf == -1) {
return null
}
return TarGzFile(archiveFile, str.substring(0, indexOf + 1))
}
override fun getChildren(): Array<VirtualFile>? {
doInit()
val files : List<VirtualFile> = myChildren.map { TarGzFile(archiveFile, myPath + it) }
return files.toTypedArray()
}
override fun getOutputStream(requestor: Any?, newModificationStamp: Long, newTimeStamp: Long): OutputStream {
throw UnsupportedOperationException()
}
override fun contentsToByteArray(): ByteArray {
doInit()
return myData!!;
}
override fun getTimeStamp(): Long {
return archiveFile.getTimeStamp()
}
override fun getModificationStamp(): Long {
return archiveFile.getModificationStamp()
}
override fun getLength(): Long {
doInit()
return myData!!.size().toLong()
}
override fun refresh(asynchronous: Boolean, recursive: Boolean, postRunnable: Runnable?) {
throw UnsupportedOperationException()
}
override fun getInputStream(): InputStream? {
doInit()
return ByteArrayInputStream(myData!!)
}
} | apache-2.0 | 8507d3af7fc2f79bd2e1bac24be4e4b4 | 27.66443 | 113 | 0.608899 | 4.819413 | false | false | false | false |
inorichi/tachiyomi-extensions | src/all/dragonball_multiverse/src/eu/kanade/tachiyomi/extension/all/dragonball_multiverse/DbMultiverse.kt | 1 | 4453 | package eu.kanade.tachiyomi.extension.all.dragonball_multiverse
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import rx.Observable
abstract class DbMultiverse(override val lang: String, private val internalLang: String) : ParsedHttpSource() {
override val name =
if (internalLang.endsWith("_PA")) "Dragon Ball Multiverse Parody"
else "Dragon Ball Multiverse"
override val baseUrl = "https://www.dragonball-multiverse.com"
override val supportsLatest = false
private fun chapterFromElement(element: Element, name: String): SChapter {
val chapter = SChapter.create()
chapter.setUrlWithoutDomain(element.attr("abs:href"))
chapter.name = name + element.text().let { num ->
if (num.contains("-")) {
"Pages $num"
} else {
"Page $num"
}
}
return chapter
}
override fun chapterListSelector(): String = "div.cadrelect.chapters a[href*=page-]"
override fun chapterListParse(response: Response): List<SChapter> {
val chapters = mutableListOf<SChapter>()
val document = response.asJsoup()
document.select("div[ch]").forEach { container ->
container.select(chapterListSelector()).mapIndexed { i, chapter ->
// Each page is its own chapter, add chapter name when a first page is mapped
val name = if (i == 0) container.select("h4").text() + " - " else ""
chapters.add(chapterFromElement(chapter, name))
}
}
return chapters.reversed()
}
override fun pageListParse(document: Document): List<Page> {
return document.select("div#h_read img").mapIndexed { index, element ->
Page(index, "", element.attr("abs:src"))
}
}
override fun mangaDetailsParse(document: Document): SManga = createManga(document)
override fun fetchPopularManga(page: Int): Observable<MangasPage> {
return Observable.just(MangasPage(listOf(createManga(null)), hasNextPage = false))
}
private fun createManga(document: Document?) = SManga.create().apply {
title = name
status = SManga.ONGOING
url = "/$internalLang/chapters.html"
description = "Dragon Ball Multiverse (DBM) is a free online comic, made by a whole team of fans. It's our personal sequel to DBZ."
thumbnail_url = document?.select("div[ch=\"1\"] img")?.attr("abs:src")
}
override fun chapterFromElement(element: Element): SChapter = throw UnsupportedOperationException()
override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException()
override fun popularMangaFromElement(element: Element): SManga = throw UnsupportedOperationException()
override fun popularMangaRequest(page: Int): Request = throw UnsupportedOperationException()
override fun popularMangaSelector(): String = throw UnsupportedOperationException()
override fun popularMangaNextPageSelector(): String? = throw UnsupportedOperationException()
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> = Observable.just(MangasPage(emptyList(), false))
override fun searchMangaFromElement(element: Element): SManga = throw UnsupportedOperationException()
override fun searchMangaNextPageSelector(): String? = throw UnsupportedOperationException()
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = throw UnsupportedOperationException()
override fun searchMangaSelector(): String = throw UnsupportedOperationException()
override fun latestUpdatesFromElement(element: Element): SManga = throw UnsupportedOperationException()
override fun latestUpdatesNextPageSelector(): String? = throw UnsupportedOperationException()
override fun latestUpdatesRequest(page: Int): Request = throw UnsupportedOperationException()
override fun latestUpdatesSelector(): String = throw UnsupportedOperationException()
}
| apache-2.0 | 57ec06e07c52e96e25f152f284b07d1b | 42.23301 | 154 | 0.713676 | 5.100802 | false | false | false | false |
stfalcon-studio/uaroads_android | app/src/main/java/com/stfalcon/new_uaroads_android/features/record/managers/Point.kt | 1 | 1784 | /*
* Copyright (c) 2017 stfalcon.com
*
* 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.stfalcon.new_uaroads_android.features.record.managers
/*
* Created by Anton Bevza on 4/24/17.
*/
class Point {
companion object {
const val POINT_TYPE_CP = "cp"
const val POINT_TYPE_PIT = "origin"
fun createCheckpoint(lat: Double, lng: Double, time: Long, accuracy: Float, speed: Float)
= Point(lat, lng, time, accuracy, speed)
fun createPit(pit: Double, time: Long) =
Point(pit, time)
}
val pit: Double
val time: Long
val type: String
val lat: Double
val lng: Double
val accuracy: Float
val speed: Float
private constructor(lat: Double, lng: Double, time: Long, accuracy: Float, speed: Float) {
this.lat = lat
this.lng = lng
this.accuracy = accuracy
this.speed = speed
this.pit = 0.0
this.time = time
this.type = POINT_TYPE_CP
}
private constructor(pit: Double, time: Long) {
this.pit = pit
this.time = time
this.lat = 0.0
this.lng = 0.0
this.accuracy = 0f
this.speed = 0f
this.type = POINT_TYPE_PIT
}
} | apache-2.0 | 3b3a9e238751f06b7baed4b3d0808006 | 26.461538 | 97 | 0.618274 | 3.77167 | false | false | false | false |
ligi/SCR | android/src/main/java/org/ligi/scr/ListActivity.kt | 1 | 4194 | package org.ligi.scr
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_list.*
import org.joda.time.DateTime
import org.joda.time.format.ISODateTimeFormat
import org.ligi.scr.model.Event
import org.ligi.scr.model.decorated.EventDecorator
import java.util.*
class ListActivity : AppCompatActivity() {
private val recyclers = ArrayList<RecyclerView>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list)
supportActionBar?.setDisplayShowHomeEnabled(true)
supportActionBar?.setDisplayShowCustomEnabled(true)
supportActionBar?.customView = DaySelector(this)
supportActionBar?.subtitle = "Schedule Conflict Resolver"
var earliestEventTime = DateTime.parse(App.conference.days[0].date).plusDays(1)
var latestEventTime = DateTime.parse(App.conference.days[0].date)
for (day in App.conference.days) {
for (events in day.rooms.values) {
for (event in events) {
val dateTime = DateTime(event.date)
if (dateTime.isBefore(earliestEventTime)) {
earliestEventTime = dateTime
}
if (dateTime.isAfter(latestEventTime)) {
latestEventTime = dateTime
}
}
}
}
val roomToAllEvents = HashMap<String, ArrayList<Event>>()
val rooms = App.conference.days[0].rooms.keys
for (room in rooms) {
var act_time = earliestEventTime
val newEventList = ArrayList<Event>()
for (day in App.conference.days) {
day.rooms[room]?.forEach {
val eventDecorator = EventDecorator(it)
if (act_time.isBefore(eventDecorator.start)) {
val breakEvent = Event()
breakEvent.title = "break"
breakEvent.date = act_time.toString(ISODateTimeFormat.dateTime())
val eventDecorator1 = EventDecorator(breakEvent)
eventDecorator1.end = eventDecorator.start
newEventList.add(breakEvent)
}
act_time = eventDecorator.end
newEventList.add(it)
}
}
if (DateTime.parse(newEventList.last().date).isBefore(latestEventTime)) {
val event = Event()
event.title = "end"
event.date = DateTime.parse(newEventList.last().date).toString(ISODateTimeFormat.dateTime())
EventDecorator(event).end = latestEventTime
newEventList.add(event)
}
roomToAllEvents.put(room, newEventList)
}
recyclers.clear()
for (i in rooms.indices) {
val layoutManager1 = GridLayoutManager(this, 1)
val recycler = layoutInflater.inflate(R.layout.recycler, list_host, false) as RecyclerView
recycler.layoutManager = layoutManager1
recycler.adapter = EventAdapter(roomToAllEvents.values.elementAt(i))
recyclers.add(recycler)
recycler.setOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
if (recyclerView!!.getTag(R.id.tag_scroll_sync) != null) {
return
}
for (recyclerView1 in recyclers) {
if (recyclerView1 != recyclerView) {
recyclerView1.setTag(R.id.tag_scroll_sync, true)
recyclerView1.scrollBy(dx, dy)
recyclerView1.setTag(R.id.tag_scroll_sync, null)
}
}
}
})
list_host!!.addView(recycler)
}
}
} | gpl-3.0 | bcff999c9b8211c3dde3aa8a20a7b025 | 36.455357 | 108 | 0.571531 | 5.046931 | false | false | false | false |
saki4510t/libcommon | app/src/main/java/com/serenegiant/libcommon/ProgressFragment.kt | 1 | 2181 | package com.serenegiant.libcommon
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2022 saki [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.
*/
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.serenegiant.widget.ProgressView
class ProgressFragment : BaseFragment() {
private var mProgress1: ProgressView? = null
private var mProgress2: ProgressView? = null
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (DEBUG) Log.v(TAG, "onCreateView:")
return inflater.inflate(R.layout.fragment_progress_view, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initView(view)
}
override fun onAttach(context: Context) {
super.onAttach(context)
requireActivity().title = getString(R.string.title_progress_view)
}
override fun onDestroy() {
if (DEBUG) Log.v(TAG, "onDestroy:")
super.onDestroy()
}
//--------------------------------------------------------------------------------
private fun initView(rootView: View) {
if (DEBUG) Log.v(TAG, "initView:")
mProgress1 = rootView.findViewById(R.id.progressView1)
mProgress2 = rootView.findViewById(R.id.progressView2)
}
//--------------------------------------------------------------------------------
companion object {
private const val DEBUG = true // TODO set false on release
private val TAG = ProgressFragment::class.java.simpleName
}
}
| apache-2.0 | ffd038b2b72554248895e45fa80beac2 | 31.073529 | 82 | 0.695094 | 4.016575 | false | false | false | false |
campos20/tnoodle | webscrambles/src/main/kotlin/org/worldcubeassociation/tnoodle/server/webscrambles/pdf/FmcScrambleCutoutSheet.kt | 1 | 4521 | package org.worldcubeassociation.tnoodle.server.webscrambles.pdf
import com.itextpdf.text.*
import com.itextpdf.text.pdf.PdfWriter
import org.worldcubeassociation.tnoodle.server.webscrambles.Translate
import org.worldcubeassociation.tnoodle.server.webscrambles.pdf.util.PdfDrawUtil.drawDashedLine
import org.worldcubeassociation.tnoodle.server.webscrambles.pdf.util.PdfDrawUtil.renderSvgToPDF
import org.worldcubeassociation.tnoodle.server.webscrambles.pdf.util.PdfDrawUtil.populateRect
import org.worldcubeassociation.tnoodle.server.webscrambles.pdf.util.FontUtil
import org.worldcubeassociation.tnoodle.server.webscrambles.wcif.model.*
import java.util.*
class FmcScrambleCutoutSheet(scrambleSet: ScrambleSet, activityCode: ActivityCode, competitionTitle: String, locale: Locale, hasGroupID: Boolean) : FmcSheet(scrambleSet, activityCode, competitionTitle, locale, hasGroupID) {
override fun PdfWriter.writeContents(document: Document) {
for (i in scrambleSet.scrambles.indices) {
addFmcScrambleCutoutSheet(document, i)
document.newPage()
}
}
private fun PdfWriter.addFmcScrambleCutoutSheet(document: Document, index: Int) {
val pageSize = document.pageSize
val scrambleModel = scrambleSet.scrambles[index]
val scramble = scrambleModel.allScrambleStrings.single() // we assume FMC only has one scramble
val right = (pageSize.width - LEFT).toInt()
val top = (pageSize.height - BOTTOM).toInt()
val height = top - BOTTOM
val width = right - LEFT
val availableScrambleHeight = height / SCRAMBLES_PER_SHEET
val availableScrambleWidth = (width * .45).toInt()
val availablePaddedScrambleHeight = availableScrambleHeight - 2 * SCRAMBLE_IMAGE_PADDING
val dim = scramblingPuzzle.getPreferredSize(availableScrambleWidth, availablePaddedScrambleHeight)
val svg = scramblingPuzzle.drawScramble(scramble, null)
val tp = directContent.renderSvgToPDF(svg, dim)
val substitutions = mapOf(
"scrambleIndex" to (index + 1).toString(),
"scrambleCount" to expectedAttemptNum.toString()
)
val scrambleSuffix = Translate.translate("fmc.scrambleXofY", locale, substitutions)
.takeIf { expectedAttemptNum > 1 } ?: ""
val eventTitle = Translate.translate("fmc.event", locale)
val attemptDetails = activityCode.compileTitleString(locale, includeEvent = false, includeGroupID = hasGroupID)
val attemptTitle = "$eventTitle $attemptDetails".trim()
val title = "$attemptTitle $scrambleSuffix"
val font = Font(BASE_FONT, FONT_SIZE / 2)
val localBaseFont = FontUtil.getFontForLocale(locale)
val localFont = Font(localBaseFont, FONT_SIZE)
// empty strings for space above and below
val textList = listOf(
"" to font,
competitionTitle to font,
title to localFont,
scramble to localFont,
"" to font)
val alignList = List(textList.size) { Element.ALIGN_LEFT }
val paddedTitleItems = textList.zipTriple(alignList)
for (i in 0 until SCRAMBLES_PER_SHEET) {
val rect = Rectangle(LEFT.toFloat(), (top - i * availableScrambleHeight).toFloat(), (right - dim.width - SPACE_SCRAMBLE_IMAGE).toFloat(), (top - (i + 1) * availableScrambleHeight).toFloat())
directContent.populateRect(rect, paddedTitleItems)
directContent.addImage(Image.getInstance(tp), dim.width.toDouble(), 0.0, 0.0, dim.height.toDouble(), (right - dim.width).toDouble(), top.toDouble() - (i + 1) * availableScrambleHeight + (availableScrambleHeight - dim.getHeight()) / 2)
directContent.drawDashedLine(LEFT, right, top - i * availableScrambleHeight)
}
directContent.drawDashedLine(LEFT, right, top - SCRAMBLES_PER_SHEET * availableScrambleHeight)
}
companion object {
val BASE_FONT = FontUtil.getFontForLocale(Translate.DEFAULT_LOCALE)
val BOTTOM = 10
val LEFT = 20
val SPACE_SCRAMBLE_IMAGE = 5 // scramble image won't touch the scramble
val SCRAMBLE_IMAGE_PADDING = 8 // scramble image won't touch the dashed lines
val FONT_SIZE = 20f
val SCRAMBLES_PER_SHEET = 8
private fun <A,B,C> Iterable<Pair<A,B>>.zipTriple(other: Iterable<C>): List<Triple<A,B,C>> {
return zip(other).map { Triple(it.first.first, it.first.second, it.second) }
}
}
}
| gpl-3.0 | 56db20f25200b987318b51b5fbd7f99d | 43.762376 | 246 | 0.694315 | 4.189991 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/baby_changing_table/AddBabyChangingTable.kt | 1 | 1320 | package de.westnordost.streetcomplete.quests.baby_changing_table
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.SimpleOverpassQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddBabyChangingTable(o: OverpassMapDataDao) : SimpleOverpassQuestType<Boolean>(o) {
override val tagFilters = """
nodes, ways with (((amenity ~ restaurant|cafe|fuel|fast_food or shop ~ mall|department_store)
and name and toilets=yes) or amenity=toilets) and !diaper
"""
override val commitMessage = "Add baby changing table"
override val defaultDisabledMessage = R.string.default_disabled_msg_go_inside
override val icon = R.drawable.ic_quest_baby
override fun getTitle(tags: Map<String, String>) =
if (tags.containsKey("name"))
R.string.quest_baby_changing_table_title
else
R.string.quest_baby_changing_table_toilets_title
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("diaper", if(answer) "yes" else "no")
}
}
| gpl-3.0 | 7f124ca5673d62d6de5ac4ff3c1002ee | 43 | 101 | 0.752273 | 4.4 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-basex/main/uk/co/reecedunn/intellij/plugin/basex/lang/BaseX.kt | 1 | 2875 | /*
* Copyright (C) 2020 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.basex.lang
import com.intellij.navigation.ItemPresentation
import uk.co.reecedunn.intellij.plugin.basex.resources.BaseXIcons
import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmProductType
import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmProductVersion
import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSchemaFile
import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmVendorType
import java.io.File
import javax.swing.Icon
object BaseX : ItemPresentation, XpmVendorType, XpmProductType {
// region ItemPresentation
override fun getPresentableText(): String = "BaseX"
override fun getLocationString(): String? = null
override fun getIcon(unused: Boolean): Icon = BaseXIcons.Product
// endregion
// region XpmVendorType / XpmProductType
override val id: String = "basex"
override val presentation: ItemPresentation
get() = this
// endregion
// region XpmVendorType
private val basexJar = listOf(
"BaseX.jar",
"basex.jar",
"BaseX6.jar"
)
override fun isValidInstallDir(installDir: String): Boolean {
return basexJar.find { File("$installDir/$it").exists() } != null
}
override val modulePath: String? = null
override fun schemaFiles(path: String): Sequence<XpmSchemaFile> = sequenceOf()
// endregion
// region Language Versions
val VERSION_6_1: XpmProductVersion = BaseXVersion(this, 6, 1, "Update Facility, Full Text, fuzzy")
val VERSION_7_7: XpmProductVersion = BaseXVersion(this, 7, 7, "XQuery 3.0 REC")
val VERSION_7_8: XpmProductVersion = BaseXVersion(this, 7, 8, "update")
val VERSION_8_4: XpmProductVersion = BaseXVersion(this, 8, 4, "non-deterministic")
val VERSION_8_5: XpmProductVersion = BaseXVersion(this, 8, 5, "update {}, transform with")
val VERSION_8_6: XpmProductVersion = BaseXVersion(this, 8, 6, "XQuery 3.1 REC")
val VERSION_9_1: XpmProductVersion = BaseXVersion(this, 9, 1, "ternary if, ?:, if without else")
@Suppress("unused")
val languageVersions: List<XpmProductVersion> = listOf(
VERSION_6_1,
VERSION_7_7,
VERSION_7_8,
VERSION_8_4,
VERSION_8_5,
VERSION_8_6,
VERSION_9_1
)
// endregion
}
| apache-2.0 | e0fc012c9d58e8ec56aa6581ad700abb | 33.22619 | 102 | 0.704 | 3.879892 | false | false | false | false |
GLodi/GitNav | app/src/main/java/giuliolodi/gitnav/ui/commit/CommitActivity.kt | 1 | 1790 | /*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.commit
import android.content.Context
import android.content.Intent
import android.os.Bundle
import giuliolodi.gitnav.R
import giuliolodi.gitnav.ui.base.BaseActivity
/**
* Created by giulio on 20/12/2017.
*/
class CommitActivity : BaseActivity() {
private val COMMIT_FRAGMENT_TAG = "COMMIT_FRAGMENT_TAG"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.commit_activity)
var commitFragment: CommitFragment? = supportFragmentManager.findFragmentByTag(COMMIT_FRAGMENT_TAG) as CommitFragment?
if (commitFragment == null) {
commitFragment = CommitFragment()
supportFragmentManager
.beginTransaction()
.replace(R.id.commit_activity_frame, commitFragment, COMMIT_FRAGMENT_TAG)
.commit()
}
}
override fun onBackPressed() {
super.onBackPressed()
overridePendingTransition(0,0)
}
companion object {
fun getIntent(context: Context): Intent {
return Intent(context, CommitActivity::class.java)
}
}
} | apache-2.0 | 2e8edcf7a84aa30d28d0873743aeb212 | 30.421053 | 126 | 0.683799 | 4.601542 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android | search_presentation/src/main/java/com/vmenon/mpo/search/presentation/viewmodel/ShowSearchResultsViewModel.kt | 1 | 2280 | package com.vmenon.mpo.search.presentation.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.DiffUtil
import com.vmenon.mpo.common.domain.ContentEvent
import com.vmenon.mpo.search.presentation.mvi.ShowSearchViewEvent
import com.vmenon.mpo.search.presentation.mvi.ShowSearchViewState
import com.vmenon.mpo.search.usecases.SearchInteractors
import com.vmenon.mpo.search.presentation.adapter.diff.ShowSearchResultsDiff
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
class ShowSearchResultsViewModel : ViewModel() {
@Inject
lateinit var searchInteractors: SearchInteractors
private val initialState = ShowSearchViewState(
previousResults = emptyList(),
currentResults = emptyList(),
loading = true
)
private val states = MutableLiveData(ContentEvent(initialState))
private var currentState: ShowSearchViewState
get() = states.value?.anyContent() ?: initialState
set(value) {
states.postValue(ContentEvent(value))
}
fun states(): LiveData<ContentEvent<ShowSearchViewState>> = states
fun send(event: ShowSearchViewEvent) {
viewModelScope.launch {
when (event) {
is ShowSearchViewEvent.SearchRequestedEvent -> searchShows(event.keyword)
}
}
}
fun clearState() {
states.value = ContentEvent(initialState)
}
private suspend fun searchShows(keyword: String) {
val newResults = searchInteractors.searchForShows(keyword) ?: emptyList()
val diffResult = getDiff(
ShowSearchResultsDiff(currentState.currentResults, newResults)
)
currentState = currentState.copy(
previousResults = currentState.currentResults,
currentResults = newResults,
diffResult = diffResult,
loading = false
)
}
private suspend fun getDiff(callback: DiffUtil.Callback): DiffUtil.DiffResult =
withContext(Dispatchers.Default) {
DiffUtil.calculateDiff(callback)
}
} | apache-2.0 | 6fc167005637036f37ba2cb30e40c939 | 32.057971 | 89 | 0.716667 | 5.066667 | false | false | false | false |
farmerbb/Notepad | app/src/main/java/com/farmerbb/notepad/ui/components/AlertDialogs.kt | 1 | 4100 | /* Copyright 2021 Braden Farmer
*
* 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.farmerbb.notepad.ui.components
import androidx.compose.material.AlertDialog
import androidx.compose.runtime.Composable
import androidx.compose.ui.window.DialogProperties
import com.farmerbb.notepad.BuildConfig
import com.farmerbb.notepad.R
import java.util.Calendar
import java.util.TimeZone
private val buildYear: Int get() {
val calendar = Calendar.getInstance(TimeZone.getTimeZone("America/Denver")).apply {
timeInMillis = BuildConfig.TIMESTAMP
}
return calendar.get(Calendar.YEAR)
}
@Composable
fun DeleteDialog(
isMultiple: Boolean = false,
onConfirm: () -> Unit,
onDismiss: () -> Unit
) {
val title = if (isMultiple) {
R.string.dialog_delete_button_title_plural
} else {
R.string.dialog_delete_button_title
}
AlertDialog(
onDismissRequest = onDismiss,
title = { DialogTitle(id = title) },
text = { DialogText(id = R.string.dialog_are_you_sure) },
confirmButton = {
DialogButton(
onClick = onConfirm,
id = R.string.action_delete
)
},
dismissButton = {
DialogButton(
onClick = onDismiss,
id = R.string.action_cancel
)
}
)
}
@Composable
fun AboutDialog(
onDismiss: () -> Unit,
checkForUpdates: () -> Unit
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { DialogTitle(id = R.string.dialog_about_title) },
text = { DialogText(id = R.string.dialog_about_message, buildYear) },
confirmButton = {
DialogButton(
onClick = onDismiss, // dismissing the dialog is the primary action
id = R.string.action_close
)
},
dismissButton = {
DialogButton(
onClick = checkForUpdates,
id = R.string.check_for_updates
)
}
)
}
@Composable
fun SaveDialog(
onConfirm: () -> Unit,
onDiscard: () -> Unit,
onDismiss: () -> Unit
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { DialogTitle(id = R.string.dialog_save_button_title) },
text = { DialogText(id = R.string.dialog_save_changes) },
confirmButton = {
DialogButton(
onClick = onConfirm,
id = R.string.action_save
)
},
dismissButton = {
DialogButton(
onClick = onDiscard,
id = R.string.action_discard
)
}
)
}
@Composable
fun FirstRunDialog(
onDismiss: () -> Unit
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { DialogTitle(id = R.string.app_name) },
text = { DialogText(id = R.string.first_run) },
confirmButton = {
DialogButton(
onClick = onDismiss,
id = R.string.action_close
)
},
properties = DialogProperties(
dismissOnBackPress = false,
dismissOnClickOutside = false
)
)
}
@Composable
fun FirstViewDialog(
onDismiss: () -> Unit
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { DialogTitle(id = R.string.app_name) },
text = { DialogText(id = R.string.first_view) },
confirmButton = {
DialogButton(
onClick = onDismiss,
id = R.string.action_close
)
}
)
} | apache-2.0 | 0d1e2217bfe8dc99b45b1c4c5c7ed8d4 | 26.34 | 87 | 0.580244 | 4.427646 | false | false | false | false |
savvasdalkitsis/gameframe | workspace/src/main/java/com/savvasdalkitsis/gameframe/feature/workspace/element/layer/view/LayerSettingsView.kt | 1 | 4048 | /**
* Copyright 2017 Savvas Dalkitsis
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.feature.workspace.element.layer.view
import android.content.Context
import android.support.v7.app.AlertDialog
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.*
import com.savvasdalkitsis.gameframe.feature.workspace.R
import com.savvasdalkitsis.gameframe.feature.composition.model.AvailableBlendMode
import com.savvasdalkitsis.gameframe.feature.composition.model.AvailablePorterDuffOperator
import com.savvasdalkitsis.gameframe.feature.workspace.element.layer.model.Layer
import com.savvasdalkitsis.gameframe.feature.workspace.element.layer.model.LayerSettings
import com.savvasdalkitsis.gameframe.kotlin.visible
class LayerSettingsView : LinearLayout {
private lateinit var title: EditText
private lateinit var blendMode: Spinner
private lateinit var porterDuff: Spinner
private lateinit var alpha: SeekBar
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun onFinishInflate() {
super.onFinishInflate()
title = findViewById(R.id.view_layer_title)
alpha = findViewById(R.id.view_layer_alpha)
blendMode = findViewById(R.id.view_layer_blend_mode)
blendMode.adapter = adapter(AvailableBlendMode.values())
porterDuff = findViewById(R.id.view_layer_porter_duff)
porterDuff.adapter = adapter(AvailablePorterDuffOperator.values())
}
fun bindTo(layer: Layer) {
title.setText(layer.layerSettings.title)
alpha.progress = (layer.layerSettings.alpha * 100).toInt()
blendMode.visible()
blendMode.setSelection(AvailableBlendMode.indexOf(layer.layerSettings.blendMode))
porterDuff.setSelection(AvailablePorterDuffOperator.indexOf(layer.layerSettings.porterDuffOperator))
porterDuff.visible()
}
private fun <T> adapter(values: Array<T>) = ArrayAdapter(context, android.R.layout.simple_spinner_item, values).apply {
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
}
val layerSettings: LayerSettings
get() = LayerSettings(
title = title.text.toString(),
alpha = alpha.progress / 100f,
blendMode = AvailableBlendMode.values()[blendMode.selectedItemPosition],
porterDuffOperator = AvailablePorterDuffOperator.values()[porterDuff.selectedItemPosition]
)
companion object {
internal fun show(context: Context, layer: Layer, root: ViewGroup, layerSettingsSetListener: LayerSettingsSetListener) {
val settingsView = LayoutInflater.from(context).inflate(R.layout.view_layer_settings, root, false) as LayerSettingsView
settingsView.bindTo(layer)
AlertDialog.Builder(context, R.style.AppTheme_Dialog)
.setTitle(R.string.layer_settings)
.setView(settingsView)
.setPositiveButton(android.R.string.ok) { _, _ -> layerSettingsSetListener.onLayerSettingsSet(settingsView.layerSettings) }
.setNegativeButton(android.R.string.cancel) { _, _ -> }
.create()
.show()
}
}
}
| apache-2.0 | 9f7e6cd14f2fc594610acd8586411b4f | 43.977778 | 143 | 0.723073 | 4.631579 | false | false | false | false |
google/filament | android/samples/sample-hello-camera/src/main/java/com/google/android/filament/hellocam/MainActivity.kt | 1 | 16461 | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.filament.hellocam
import android.animation.ValueAnimator
import android.app.Activity
import android.opengl.Matrix
import android.os.Bundle
import android.view.Choreographer
import android.view.Surface
import android.view.SurfaceView
import android.view.animation.LinearInterpolator
import androidx.core.app.ActivityCompat
import com.google.android.filament.*
import com.google.android.filament.RenderableManager.*
import com.google.android.filament.VertexBuffer.*
import com.google.android.filament.android.DisplayHelper
import com.google.android.filament.android.UiHelper
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.channels.Channels
import kotlin.math.*
class MainActivity : Activity(), ActivityCompat.OnRequestPermissionsResultCallback {
companion object {
init {
Filament.init()
}
}
private lateinit var surfaceView: SurfaceView
private lateinit var uiHelper: UiHelper
private lateinit var displayHelper: DisplayHelper
private lateinit var choreographer: Choreographer
private lateinit var engine: Engine
private lateinit var renderer: Renderer
private lateinit var scene: Scene
private lateinit var view: View
// This helper wraps the Android camera2 API and connects it to a Filament material.
private lateinit var cameraHelper: CameraHelper
// This is the Filament camera, not the phone camera. :)
private lateinit var camera: Camera
// Other Filament objects:
private lateinit var material: Material
private lateinit var materialInstance: MaterialInstance
private lateinit var vertexBuffer: VertexBuffer
private lateinit var indexBuffer: IndexBuffer
// Filament entity representing a renderable object
@Entity private var renderable = 0
@Entity private var light = 0
// A swap chain is Filament's representation of a surface
private var swapChain: SwapChain? = null
// Performs the rendering and schedules new frames
private val frameScheduler = FrameCallback()
private val animator = ValueAnimator.ofFloat(0.0f, 50.0f)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
surfaceView = SurfaceView(this)
setContentView(surfaceView)
choreographer = Choreographer.getInstance()
displayHelper = DisplayHelper(this)
setupSurfaceView()
setupFilament()
setupView()
setupScene()
cameraHelper = CameraHelper(this, engine, materialInstance)
cameraHelper.openCamera()
}
private fun setupSurfaceView() {
uiHelper = UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK)
uiHelper.renderCallback = SurfaceCallback()
uiHelper.attachTo(surfaceView)
}
private fun setupFilament() {
engine = Engine.create()
renderer = engine.createRenderer()
scene = engine.createScene()
view = engine.createView()
camera = engine.createCamera(engine.entityManager.create())
}
private fun setupView() {
scene.skybox = Skybox.Builder().color(0.035f, 0.035f, 0.035f, 1.0f).build(engine)
view.camera = camera
view.scene = scene
}
private fun setupScene() {
loadMaterial()
setupMaterial()
createMesh()
// To create a renderable we first create a generic entity
renderable = EntityManager.get().create()
// We then create a renderable component on that entity
// A renderable is made of several primitives; in this case we declare only 1
// If we wanted each face of the cube to have a different material, we could
// declare 6 primitives (1 per face) and give each of them a different material
// instance, setup with different parameters
RenderableManager.Builder(1)
// Overall bounding box of the renderable
.boundingBox(Box(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f))
// Sets the mesh data of the first primitive, 6 faces of 6 indices each
.geometry(0, PrimitiveType.TRIANGLES, vertexBuffer, indexBuffer, 0, 6 * 6)
// Sets the material of the first primitive
.material(0, materialInstance)
.build(engine, renderable)
// Add the entity to the scene to render it
scene.addEntity(renderable)
// We now need a light, let's create a directional light
light = EntityManager.get().create()
// Create a color from a temperature (5,500K)
val (r, g, b) = Colors.cct(5_500.0f)
LightManager.Builder(LightManager.Type.DIRECTIONAL)
.color(r, g, b)
// Intensity of the sun in lux on a clear day
.intensity(110_000.0f)
// The direction is normalized on our behalf
.direction(0.0f, -0.5f, -1.0f)
.castShadows(true)
.build(engine, light)
// Add the entity to the scene to light it
scene.addEntity(light)
// Set the exposure on the camera, this exposure follows the sunny f/16 rule
// Since we've defined a light that has the same intensity as the sun, it
// guarantees a proper exposure
camera.setExposure(16.0f, 1.0f / 125.0f, 100.0f)
// Move the camera back to see the object
camera.lookAt(0.0, 0.0, 6.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)
startAnimation()
}
private fun loadMaterial() {
readUncompressedAsset("materials/lit.filamat").let {
material = Material.Builder().payload(it, it.remaining()).build(engine)
}
}
private fun setupMaterial() {
materialInstance = material.createInstance()
materialInstance.setParameter("baseColor", Colors.RgbType.SRGB, 1.0f, 0.85f, 0.57f)
materialInstance.setParameter("roughness", 0.3f)
}
private fun createMesh() {
val floatSize = 4
val shortSize = 2
// A vertex is a position + a tangent frame:
// 3 floats for XYZ position, 4 floats for normal+tangents (quaternion)
val vertexSize = 3 * floatSize + 4 * floatSize
// Define a vertex and a function to put a vertex in a ByteBuffer
@Suppress("ArrayInDataClass")
data class Vertex(val x: Float, val y: Float, val z: Float, val tangents: FloatArray)
fun ByteBuffer.put(v: Vertex): ByteBuffer {
putFloat(v.x)
putFloat(v.y)
putFloat(v.z)
v.tangents.forEach { putFloat(it) }
return this
}
// 6 faces, 4 vertices per face
val vertexCount = 6 * 4
// Create tangent frames, one per face
val tfPX = FloatArray(4)
val tfNX = FloatArray(4)
val tfPY = FloatArray(4)
val tfNY = FloatArray(4)
val tfPZ = FloatArray(4)
val tfNZ = FloatArray(4)
MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, tfPX)
MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, -1.0f, 0.0f, 0.0f, tfNX)
MathUtils.packTangentFrame(-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, tfPY)
MathUtils.packTangentFrame(-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, tfNY)
MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, tfPZ)
MathUtils.packTangentFrame( 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, tfNZ)
val vertexData = ByteBuffer.allocate(vertexCount * vertexSize)
// It is important to respect the native byte order
.order(ByteOrder.nativeOrder())
// Face -Z
.put(Vertex(-1.5f, -1.5f, -1.0f, tfNZ))
.put(Vertex(-1.5f, 1.5f, -1.0f, tfNZ))
.put(Vertex( 1.5f, 1.5f, -1.0f, tfNZ))
.put(Vertex( 1.5f, -1.5f, -1.0f, tfNZ))
// Face +X
.put(Vertex( 1.5f, -1.5f, -1.0f, tfPX))
.put(Vertex( 1.5f, 1.5f, -1.0f, tfPX))
.put(Vertex( 1.0f, 1.0f, 1.0f, tfPX))
.put(Vertex( 1.0f, -1.0f, 1.0f, tfPX))
// Face +Z
.put(Vertex(-1.0f, -1.0f, 1.0f, tfPZ))
.put(Vertex( 1.0f, -1.0f, 1.0f, tfPZ))
.put(Vertex( 1.0f, 1.0f, 1.0f, tfPZ))
.put(Vertex(-1.0f, 1.0f, 1.0f, tfPZ))
// Face -X
.put(Vertex(-1.0f, -1.0f, 1.0f, tfNX))
.put(Vertex(-1.0f, 1.0f, 1.0f, tfNX))
.put(Vertex(-1.5f, 1.5f, -1.0f, tfNX))
.put(Vertex(-1.5f, -1.5f, -1.0f, tfNX))
// Face -Y
.put(Vertex(-1.0f, -1.0f, 1.0f, tfNY))
.put(Vertex(-1.5f, -1.5f, -1.0f, tfNY))
.put(Vertex( 1.5f, -1.5f, -1.0f, tfNY))
.put(Vertex( 1.0f, -1.0f, 1.0f, tfNY))
// Face +Y
.put(Vertex(-1.5f, 1.5f, -1.0f, tfPY))
.put(Vertex(-1.0f, 1.0f, 1.0f, tfPY))
.put(Vertex( 1.0f, 1.0f, 1.0f, tfPY))
.put(Vertex( 1.5f, 1.5f, -1.0f, tfPY))
// Make sure the cursor is pointing in the right place in the byte buffer
.flip()
// Declare the layout of our mesh
vertexBuffer = VertexBuffer.Builder()
.bufferCount(1)
.vertexCount(vertexCount)
// Because we interleave position and color data we must specify offset and stride
// We could use de-interleaved data by declaring two buffers and giving each
// attribute a different buffer index
.attribute(VertexAttribute.POSITION, 0, AttributeType.FLOAT3, 0, vertexSize)
.attribute(VertexAttribute.TANGENTS, 0, AttributeType.FLOAT4, 3 * floatSize, vertexSize)
.build(engine)
// Feed the vertex data to the mesh
// We only set 1 buffer because the data is interleaved
vertexBuffer.setBufferAt(engine, 0, vertexData)
// Create the indices
val indexData = ByteBuffer.allocate(6 * 2 * 3 * shortSize)
.order(ByteOrder.nativeOrder())
repeat(6) {
val i = (it * 4).toShort()
indexData
.putShort(i).putShort((i + 1).toShort()).putShort((i + 2).toShort())
.putShort(i).putShort((i + 2).toShort()).putShort((i + 3).toShort())
}
indexData.flip()
// 6 faces, 2 triangles per face,
indexBuffer = IndexBuffer.Builder()
.indexCount(vertexCount * 2)
.bufferType(IndexBuffer.Builder.IndexType.USHORT)
.build(engine)
indexBuffer.setBuffer(engine, indexData)
}
private fun startAnimation() {
// Animate the triangle
animator.interpolator = LinearInterpolator()
animator.duration = 6000
animator.repeatMode = ValueAnimator.RESTART
animator.repeatCount = ValueAnimator.INFINITE
animator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener {
val transformMatrix = FloatArray(16)
override fun onAnimationUpdate(animator: ValueAnimator) {
val t = animator.animatedValue as Float
val radians = sin(t) * 3.0f * PI.toFloat()
Matrix.setRotateM(transformMatrix, 0, radians, 0.0f, 1.0f, 0.0f)
val tcm = engine.transformManager
tcm.setTransform(tcm.getInstance(renderable), transformMatrix)
}
})
animator.start()
}
override fun onResume() {
super.onResume()
choreographer.postFrameCallback(frameScheduler)
animator.start()
cameraHelper.onResume()
}
override fun onPause() {
super.onPause()
choreographer.removeFrameCallback(frameScheduler)
animator.cancel()
cameraHelper.onPause()
}
override fun onDestroy() {
super.onDestroy()
// Stop the animation and any pending frame
choreographer.removeFrameCallback(frameScheduler)
animator.cancel()
// Always detach the surface before destroying the engine
uiHelper.detach()
// Cleanup all resources
engine.destroyEntity(light)
engine.destroyEntity(renderable)
engine.destroyRenderer(renderer)
engine.destroyVertexBuffer(vertexBuffer)
engine.destroyIndexBuffer(indexBuffer)
engine.destroyMaterialInstance(materialInstance)
engine.destroyMaterial(material)
engine.destroyView(view)
engine.destroyScene(scene)
engine.destroyCameraComponent(camera.entity)
// Engine.destroyEntity() destroys Filament related resources only
// (components), not the entity itself
val entityManager = EntityManager.get()
entityManager.destroy(light)
entityManager.destroy(renderable)
entityManager.destroy(camera.entity)
// Destroying the engine will free up any resource you may have forgotten
// to destroy, but it's recommended to do the cleanup properly
engine.destroy()
}
inner class FrameCallback : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
// Schedule the next frame
choreographer.postFrameCallback(this)
// This check guarantees that we have a swap chain
if (uiHelper.isReadyToRender) {
cameraHelper.pushExternalImageToFilament()
// If beginFrame() returns false you should skip the frame
// This means you are sending frames too quickly to the GPU
if (renderer.beginFrame(swapChain!!, frameTimeNanos)) {
renderer.render(view)
renderer.endFrame()
}
}
}
}
inner class SurfaceCallback : UiHelper.RendererCallback {
override fun onNativeWindowChanged(surface: Surface) {
swapChain?.let { engine.destroySwapChain(it) }
swapChain = engine.createSwapChain(surface)
displayHelper.attach(renderer, surfaceView.display)
}
override fun onDetachedFromSurface() {
displayHelper.detach()
swapChain?.let {
engine.destroySwapChain(it)
// Required to ensure we don't return before Filament is done executing the
// destroySwapChain command, otherwise Android might destroy the Surface
// too early
engine.flushAndWait()
swapChain = null
}
}
override fun onResized(width: Int, height: Int) {
val aspect = width.toDouble() / height.toDouble()
camera.setProjection(45.0, aspect, 0.1, 20.0, Camera.Fov.VERTICAL)
view.viewport = Viewport(0, 0, width, height)
}
}
private fun readUncompressedAsset(@Suppress("SameParameterValue") assetName: String): ByteBuffer {
assets.openFd(assetName).use { fd ->
val input = fd.createInputStream()
val dst = ByteBuffer.allocate(fd.length.toInt())
val src = Channels.newChannel(input)
src.read(dst)
src.close()
return dst.apply { rewind() }
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (!cameraHelper.onRequestPermissionsResult(requestCode, grantResults)) {
this.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
}
| apache-2.0 | 21a50901d4325975293fcd84a0fd88a3 | 37.640845 | 115 | 0.61023 | 4.215365 | false | false | false | false |
MaTriXy/material-dialogs | core/src/main/java/com/afollestad/materialdialogs/internal/button/DialogActionButton.kt | 2 | 3835 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.materialdialogs.internal.button
import android.content.Context
import android.content.res.ColorStateList.valueOf
import android.graphics.drawable.RippleDrawable
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.LOLLIPOP
import android.util.AttributeSet
import android.view.Gravity.CENTER
import androidx.annotation.ColorInt
import androidx.appcompat.widget.AppCompatButton
import com.afollestad.materialdialogs.R
import com.afollestad.materialdialogs.inferThemeIsLight
import com.afollestad.materialdialogs.utils.MDUtil.ifNotZero
import com.afollestad.materialdialogs.utils.MDUtil.resolveColor
import com.afollestad.materialdialogs.utils.MDUtil.resolveDrawable
import com.afollestad.materialdialogs.utils.MDUtil.resolveInt
import com.afollestad.materialdialogs.utils.adjustAlpha
import com.afollestad.materialdialogs.utils.setGravityEndCompat
/**
* Represents an action button in a dialog, positive, negative, or neutral. Handles switching
* out its selector, padding, and text alignment based on whether buttons are in stacked mode or not.
*
* @author Aidan Follestad (afollestad)
*/
class DialogActionButton(
context: Context,
attrs: AttributeSet? = null
) : AppCompatButton(context, attrs) {
companion object {
private const val CASING_UPPER = 1
}
private var enabledColor: Int = 0
private var disabledColor: Int = 0
private var enabledColorOverride: Int? = null
init {
isClickable = true
isFocusable = true
}
internal fun update(
baseContext: Context,
appContext: Context,
stacked: Boolean
) {
// Casing
val casing = resolveInt(
context = appContext,
attr = R.attr.md_button_casing,
defaultValue = CASING_UPPER
)
setSupportAllCaps(casing == CASING_UPPER)
// Text color
val isLightTheme = inferThemeIsLight(appContext)
enabledColor = resolveColor(appContext, attr = R.attr.md_color_button_text) {
resolveColor(appContext, attr = R.attr.colorPrimary)
}
val disabledColorRes =
if (isLightTheme) R.color.md_disabled_text_light_theme
else R.color.md_disabled_text_dark_theme
disabledColor = resolveColor(baseContext, res = disabledColorRes)
setTextColor(enabledColorOverride ?: enabledColor)
// Selector
val bgDrawable = resolveDrawable(baseContext, attr = R.attr.md_button_selector)
if (SDK_INT >= LOLLIPOP && bgDrawable is RippleDrawable) {
resolveColor(context = baseContext, attr = R.attr.md_ripple_color) {
resolveColor(appContext, attr = R.attr.colorPrimary).adjustAlpha(.12f)
}.ifNotZero {
bgDrawable.setColor(valueOf(it))
}
}
background = bgDrawable
// Text alignment
if (stacked) setGravityEndCompat()
else gravity = CENTER
// Invalidate in case enabled state was changed before this method executed
isEnabled = isEnabled
}
fun updateTextColor(@ColorInt color: Int) {
enabledColor = color
enabledColorOverride = color
isEnabled = isEnabled
}
override fun setEnabled(enabled: Boolean) {
super.setEnabled(enabled)
setTextColor(if (enabled) enabledColorOverride ?: enabledColor else disabledColor)
}
}
| apache-2.0 | 6d5f9aa26cc3dbb6f78932a56bab8491 | 33.241071 | 101 | 0.746284 | 4.348073 | false | false | false | false |
Heiner1/AndroidAPS | automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt | 1 | 2351 | package info.nightscout.androidaps.plugins.general.automation.triggers
import android.widget.LinearLayout
import com.google.common.base.Optional
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.automation.R
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.general.automation.elements.InputDateTime
import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder
import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel
import info.nightscout.androidaps.utils.JsonHelper
import info.nightscout.androidaps.utils.T
import org.json.JSONObject
class TriggerTime(injector: HasAndroidInjector) : Trigger(injector) {
var time = InputDateTime(rh, dateUtil)
constructor(injector: HasAndroidInjector, runAt: Long) : this(injector) {
this.time.value = runAt
}
@Suppress("unused")
constructor(injector: HasAndroidInjector, triggerTime: TriggerTime) : this(injector) {
this.time.value = triggerTime.time.value
}
fun runAt(time: Long): TriggerTime {
this.time.value = time
return this
}
override fun shouldRun(): Boolean {
val now = dateUtil.now()
if (now >= time.value && now - time.value < T.mins(5).msecs()) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())
return true
}
aapsLogger.debug(LTag.AUTOMATION, "NOT ready for execution: " + friendlyDescription())
return false
}
override fun dataJSON(): JSONObject =
JSONObject()
.put("runAt", time.value)
override fun fromJSON(data: String): Trigger {
val o = JSONObject(data)
time.value = JsonHelper.safeGetLong(o, "runAt")
return this
}
override fun friendlyName(): Int = R.string.time
override fun friendlyDescription(): String =
rh.gs(R.string.atspecifiedtime, dateUtil.dateAndTimeString(time.value))
override fun icon(): Optional<Int> = Optional.of(R.drawable.ic_access_alarm_24dp)
override fun duplicate(): Trigger = TriggerTime(injector, time.value)
override fun generateDialog(root: LinearLayout) {
LayoutBuilder()
.add(StaticLabel(rh, R.string.time, this))
.add(time)
.build(root)
}
} | agpl-3.0 | b6e919c74500effedaa424dc964bd901 | 33.588235 | 94 | 0.700128 | 4.297989 | false | false | false | false |
Heiner1/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketReviewBolusAvg.kt | 1 | 1865 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.danars.encryption.BleEncryption
class DanaRSPacketReviewBolusAvg(
injector: HasAndroidInjector
) : DanaRSPacket(injector) {
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__BOLUS_AVG
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
var dataIndex = DATA_START
var dataSize = 2
val bolusAvg03 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
val bolusAvg07 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
val bolusAvg14 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
val bolusAvg21 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
val bolusAvg28 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
val required = ((1 and 0x000000FF shl 8) + (1 and 0x000000FF)) / 100.0
if (bolusAvg03 == bolusAvg07 && bolusAvg07 == bolusAvg14 && bolusAvg14 == bolusAvg21 && bolusAvg21 == bolusAvg28 && bolusAvg28 == required) failed = true
aapsLogger.debug(LTag.PUMPCOMM, "Bolus average 3d: $bolusAvg03 U")
aapsLogger.debug(LTag.PUMPCOMM, "Bolus average 7d: $bolusAvg07 U")
aapsLogger.debug(LTag.PUMPCOMM, "Bolus average 14d: $bolusAvg14 U")
aapsLogger.debug(LTag.PUMPCOMM, "Bolus average 21d: $bolusAvg21 U")
aapsLogger.debug(LTag.PUMPCOMM, "Bolus average 28d: $bolusAvg28 U")
}
override val friendlyName: String = "REVIEW__BOLUS_AVG"
} | agpl-3.0 | 1b114b5970afe536bbedc1f5ebcb513a | 43.428571 | 161 | 0.685791 | 4.153675 | false | false | false | false |
abigpotostew/easypolitics | ui/src/main/kotlin/bz/stew/bracken/ui/service/AbstractService.kt | 1 | 888 | package bz.stew.bracken.ui.service
import bz.stew.bracken.ui.util.JsonUtil
abstract class AbstractService<T> : Service<T> {
override fun sendRequest(requestUrl: ServiceEndpoint, parser: Parser<T>, onDownload: (ServiceResponse<T>) -> Unit) {
ServerRequestDispatcher().sendRequest(
requestUrl.getUrl(),
object : RequestCallback() {
override fun onLoad(response: String) {
var parsed = try {
val json = JsonUtil.parse(response)
parser.parse(json)
} catch (e: Exception) {
null
}
if (parsed == null) {
parsed = emptyList()
}
onDownload(ServiceResponse(parsed, response))
}
}
)
}
} | apache-2.0 | 66e6f632d702993d7b8422bb06eff71b | 31.925926 | 120 | 0.48536 | 5.285714 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/uast/uast-kotlin-fir/src/org/jetbrains/uast/kotlin/FirKotlinUastResolveProviderService.kt | 2 | 25637 | // 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.uast.kotlin
import com.intellij.psi.*
import com.intellij.psi.impl.compiled.ClsMemberImpl
import com.intellij.psi.impl.file.PsiPackageImpl
import com.intellij.util.SmartList
import org.jetbrains.kotlin.analysis.api.KtTypeArgumentWithVariance
import org.jetbrains.kotlin.analysis.api.base.KtConstantValue
import org.jetbrains.kotlin.analysis.api.calls.*
import org.jetbrains.kotlin.analysis.api.components.KtConstantEvaluationMode
import org.jetbrains.kotlin.analysis.api.components.buildClassType
import org.jetbrains.kotlin.analysis.api.components.buildTypeParameterType
import org.jetbrains.kotlin.analysis.api.symbols.KtConstructorSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtPropertySymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtSamConstructorSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtValueParameterSymbol
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtNamedSymbol
import org.jetbrains.kotlin.analysis.api.types.*
import org.jetbrains.kotlin.analysis.project.structure.KtLibraryModule
import org.jetbrains.kotlin.analysis.project.structure.KtSourceModule
import org.jetbrains.kotlin.analysis.project.structure.getKtModule
import org.jetbrains.kotlin.asJava.toLightAnnotation
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.types.typeUtil.TypeNullability
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.internal.*
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameterBase
interface FirKotlinUastResolveProviderService : BaseKotlinUastResolveProviderService {
override val languagePlugin: UastLanguagePlugin
get() = firKotlinUastPlugin
override val baseKotlinConverter: BaseKotlinConverter
get() = FirKotlinConverter
private val KtExpression.parentValueArgument: ValueArgument?
get() = parents.firstOrNull { it is ValueArgument } as? ValueArgument
override fun convertToPsiAnnotation(ktElement: KtElement): PsiAnnotation? {
return ktElement.toLightAnnotation()
}
override fun convertValueArguments(ktCallElement: KtCallElement, parent: UElement): List<UNamedExpression>? {
analyzeForUast(ktCallElement) {
val argumentMapping = ktCallElement.resolveCall().singleFunctionCallOrNull()?.argumentMapping ?: return null
val handledParameters = mutableSetOf<KtValueParameterSymbol>()
val valueArguments = SmartList<UNamedExpression>()
// NB: we need a loop over call element's value arguments to preserve their order.
ktCallElement.valueArguments.forEach {
val parameter = argumentMapping[it.getArgumentExpression()]?.symbol ?: return@forEach
if (!handledParameters.add(parameter)) return@forEach
val arguments = argumentMapping.entries
.filter { (_, param) -> param.symbol == parameter }
.mapNotNull { (arg, _) -> arg.parentValueArgument }
val name = parameter.name.asString()
when {
arguments.size == 1 ->
KotlinUNamedExpression.create(name, arguments.first(), parent)
arguments.size > 1 ->
KotlinUNamedExpression.create(name, arguments, parent)
else -> null
}?.let { valueArgument -> valueArguments.add(valueArgument) }
}
return valueArguments.ifEmpty { null }
}
}
override fun findAttributeValueExpression(uAnnotation: KotlinUAnnotation, arg: ValueArgument): UExpression? {
val annotationEntry = uAnnotation.sourcePsi
analyzeForUast(annotationEntry) {
val resolvedAnnotationCall = annotationEntry.resolveCall().singleCallOrNull<KtAnnotationCall>() ?: return null
val parameter = resolvedAnnotationCall.argumentMapping[arg.getArgumentExpression()]?.symbol ?: return null
val namedExpression = uAnnotation.attributeValues.find { it.name == parameter.name.asString() }
return namedExpression?.expression as? KotlinUVarargExpression ?: namedExpression
}
}
override fun findDefaultValueForAnnotationAttribute(ktCallElement: KtCallElement, name: String): KtExpression? {
analyzeForUast(ktCallElement) {
val resolvedAnnotationConstructorSymbol =
ktCallElement.resolveCall().singleConstructorCallOrNull()?.symbol ?: return null
val parameter = resolvedAnnotationConstructorSymbol.valueParameters.find { it.name.asString() == name } ?: return null
return (parameter.psi as? KtParameter)?.defaultValue
}
}
override fun getArgumentForParameter(ktCallElement: KtCallElement, index: Int, parent: UElement): UExpression? {
analyzeForUast(ktCallElement) {
val resolvedFunctionCall = ktCallElement.resolveCall().singleFunctionCallOrNull()
val resolvedFunctionLikeSymbol =
resolvedFunctionCall?.symbol ?: return null
val parameter = resolvedFunctionLikeSymbol.valueParameters.getOrNull(index) ?: return null
val arguments = resolvedFunctionCall.argumentMapping.entries
.filter { (_, param) -> param.symbol == parameter }
.mapNotNull { (arg, _) -> arg.parentValueArgument }
return when {
arguments.isEmpty() -> null
arguments.size == 1 -> {
val argument = arguments.single()
if (parameter.isVararg && argument.getSpreadElement() == null)
baseKotlinConverter.createVarargsHolder(arguments, parent)
else
baseKotlinConverter.convertOrEmpty(argument.getArgumentExpression(), parent)
}
else ->
baseKotlinConverter.createVarargsHolder(arguments, parent)
}
}
}
override fun getImplicitReturn(ktLambdaExpression: KtLambdaExpression, parent: UElement): KotlinUImplicitReturnExpression? {
val lastExpression = ktLambdaExpression.bodyExpression?.statements?.lastOrNull() ?: return null
// Skip _explicit_ return.
if (lastExpression is KtReturnExpression) return null
analyzeForUast(ktLambdaExpression) {
// TODO: Should check an explicit, expected return type as well
// e.g., val y: () -> Unit = { 1 } // the lambda return type is Int, but we won't add an implicit return here.
val returnType = ktLambdaExpression.functionLiteral.getAnonymousFunctionSymbol().returnType
val returnUnitOrNothing = returnType.isUnit || returnType.isNothing
return if (returnUnitOrNothing) null else
KotlinUImplicitReturnExpression(parent).apply {
returnExpression = baseKotlinConverter.convertOrEmpty(lastExpression, this)
}
}
}
override fun getImplicitParameters(
ktLambdaExpression: KtLambdaExpression,
parent: UElement,
includeExplicitParameters: Boolean
): List<KotlinUParameter> {
// TODO receiver parameter, dispatch parameter like in org.jetbrains.uast.kotlin.KotlinUastResolveProviderService.getImplicitParameters
analyzeForUast(ktLambdaExpression) {
return ktLambdaExpression.functionLiteral.getAnonymousFunctionSymbol().valueParameters.map { p ->
val psiType = p.returnType.asPsiType(
ktLambdaExpression,
KtTypeMappingMode.DEFAULT_UAST,
isAnnotationMethod = false
) ?: UastErrorType
KotlinUParameter(
UastKotlinPsiParameterBase(
name = p.name.asString(),
type = psiType,
parent = ktLambdaExpression,
ktOrigin = ktLambdaExpression,
language = ktLambdaExpression.language,
isVarArgs = p.isVararg,
ktDefaultValue = null
),
null,
parent
)
}
}
}
override fun getPsiAnnotations(psiElement: PsiModifierListOwner): Array<PsiAnnotation> {
return psiElement.annotations
}
override fun resolveBitwiseOperators(ktBinaryExpression: KtBinaryExpression): UastBinaryOperator {
val other = UastBinaryOperator.OTHER
analyzeForUast(ktBinaryExpression) {
val resolvedCall = ktBinaryExpression.resolveCall()?.singleFunctionCallOrNull() ?: return other
val operatorName = resolvedCall.symbol.callableIdIfNonLocal?.callableName?.asString() ?: return other
return KotlinUBinaryExpression.BITWISE_OPERATORS[operatorName] ?: other
}
}
override fun resolveCall(ktElement: KtElement): PsiMethod? {
return analyzeForUast(ktElement) {
ktElement.resolveCall()?.singleFunctionCallOrNull()?.symbol?.let { toPsiMethod(it, ktElement) }
}
}
override fun resolveAccessorCall(ktSimpleNameExpression: KtSimpleNameExpression): PsiMethod? {
return analyzeForUast(ktSimpleNameExpression) {
val variableAccessCall = ktSimpleNameExpression.resolveCall()?.singleCallOrNull<KtSimpleVariableAccessCall>() ?: return null
val propertySymbol = variableAccessCall.symbol as? KtPropertySymbol ?: return null
when (variableAccessCall.simpleAccess) {
is KtSimpleVariableAccess.Read ->
toPsiMethod(propertySymbol.getter ?: return null, ktSimpleNameExpression)
is KtSimpleVariableAccess.Write ->
toPsiMethod(propertySymbol.setter ?: return null, ktSimpleNameExpression)
}
}
}
override fun isResolvedToExtension(ktCallElement: KtCallElement): Boolean {
analyzeForUast(ktCallElement) {
val resolvedFunctionLikeSymbol = ktCallElement.resolveCall().singleFunctionCallOrNull()?.symbol ?: return false
return resolvedFunctionLikeSymbol.isExtension
}
}
override fun resolvedFunctionName(ktCallElement: KtCallElement): String? {
analyzeForUast(ktCallElement) {
val resolvedFunctionLikeSymbol = ktCallElement.resolveCall().singleFunctionCallOrNull()?.symbol ?: return null
return (resolvedFunctionLikeSymbol as? KtNamedSymbol)?.name?.identifierOrNullIfSpecial
?: (resolvedFunctionLikeSymbol as? KtConstructorSymbol)?.let { SpecialNames.INIT.asString() }
}
}
override fun qualifiedAnnotationName(ktCallElement: KtCallElement): String? {
analyzeForUast(ktCallElement) {
val resolvedAnnotationConstructorSymbol =
ktCallElement.resolveCall().singleConstructorCallOrNull()?.symbol ?: return null
return resolvedAnnotationConstructorSymbol.containingClassIdIfNonLocal
?.asSingleFqName()
?.toString()
}
}
override fun callKind(ktCallElement: KtCallElement): UastCallKind {
analyzeForUast(ktCallElement) {
val resolvedFunctionLikeSymbol =
ktCallElement.resolveCall().singleFunctionCallOrNull()?.symbol ?: return UastCallKind.METHOD_CALL
val fqName = resolvedFunctionLikeSymbol.callableIdIfNonLocal?.asSingleFqName()
return when {
resolvedFunctionLikeSymbol is KtConstructorSymbol -> UastCallKind.CONSTRUCTOR_CALL
fqName != null && isAnnotationArgumentArrayInitializer(ktCallElement, fqName) -> UastCallKind.NESTED_ARRAY_INITIALIZER
else -> UastCallKind.METHOD_CALL
}
}
}
override fun isAnnotationConstructorCall(ktCallElement: KtCallElement): Boolean {
analyzeForUast(ktCallElement) {
val resolvedAnnotationConstructorSymbol =
ktCallElement.resolveCall().singleConstructorCallOrNull()?.symbol ?: return false
val ktType = resolvedAnnotationConstructorSymbol.returnType
val context = containingKtClass(resolvedAnnotationConstructorSymbol) ?: ktCallElement
val psiClass = toPsiClass(ktType, null, context, ktCallElement.typeOwnerKind) ?: return false
return psiClass.isAnnotationType
}
}
override fun resolveToClassIfConstructorCall(ktCallElement: KtCallElement, source: UElement): PsiClass? {
analyzeForUast(ktCallElement) {
val resolvedFunctionLikeSymbol = ktCallElement.resolveCall().singleFunctionCallOrNull()?.symbol ?: return null
return when (resolvedFunctionLikeSymbol) {
is KtConstructorSymbol -> {
val context = containingKtClass(resolvedFunctionLikeSymbol) ?: ktCallElement
toPsiClass(resolvedFunctionLikeSymbol.returnType, source, context, ktCallElement.typeOwnerKind)
}
is KtSamConstructorSymbol -> {
toPsiClass(resolvedFunctionLikeSymbol.returnType, source, ktCallElement, ktCallElement.typeOwnerKind)
}
else -> null
}
}
}
override fun resolveToClass(ktAnnotationEntry: KtAnnotationEntry, source: UElement): PsiClass? {
analyzeForUast(ktAnnotationEntry) {
val resolvedAnnotationCall = ktAnnotationEntry.resolveCall().singleCallOrNull<KtAnnotationCall>() ?: return null
val resolvedAnnotationConstructorSymbol = resolvedAnnotationCall.symbol
val ktType = resolvedAnnotationConstructorSymbol.returnType
val context = containingKtClass(resolvedAnnotationConstructorSymbol) ?: ktAnnotationEntry
return toPsiClass(ktType, source, context, ktAnnotationEntry.typeOwnerKind)
}
}
override fun resolveToDeclaration(ktExpression: KtExpression): PsiElement? {
val resolvedTargetSymbol = when (ktExpression) {
is KtExpressionWithLabel -> {
analyzeForUast(ktExpression) {
ktExpression.getTargetLabel()?.mainReference?.resolveToSymbol()
}
}
is KtCallExpression -> {
resolveCall(ktExpression)?.let { return it }
}
is KtReferenceExpression -> {
analyzeForUast(ktExpression) {
ktExpression.mainReference.resolveToSymbol()
}
}
else -> null
} ?: return null
val resolvedTargetElement = resolvedTargetSymbol.psiForUast(ktExpression.project)
// Shortcut: if the resolution target is compiled class/member, package info, or pure Java declarations,
// we can return it early here (to avoid expensive follow-up steps: module retrieval and light element conversion).
if (resolvedTargetElement is ClsMemberImpl<*> ||
resolvedTargetElement is PsiPackageImpl ||
!isKotlin(resolvedTargetElement)
) {
return resolvedTargetElement
}
when ((resolvedTargetElement as? KtDeclaration)?.getKtModule(ktExpression.project)) {
is KtSourceModule -> {
// `getMaybeLightElement` tries light element conversion first, and then something else for local declarations.
resolvedTargetElement?.getMaybeLightElement(ktExpression)?.let { return it }
}
is KtLibraryModule -> {
// For decompiled declarations, we can try light element conversion (only).
(resolvedTargetElement as? KtDeclaration)?.toLightElements()?.singleOrNull()?.let { return it }
}
else -> {}
}
fun resolveToPsiClassOrEnumEntry(classOrObject: KtClassOrObject): PsiElement? {
analyzeForUast(ktExpression) {
val ktType = when (classOrObject) {
is KtEnumEntry ->
classOrObject.getEnumEntrySymbol().containingEnumClassIdIfNonLocal?.let { enumClassId ->
buildClassType(enumClassId)
}
else ->
buildClassType(classOrObject.getClassOrObjectSymbol())
} ?: return null
val psiClass = toPsiClass(ktType, source = null, classOrObject, classOrObject.typeOwnerKind)
return when (classOrObject) {
is KtEnumEntry -> psiClass?.findFieldByName(classOrObject.name, false)
else -> psiClass
}
}
}
when (resolvedTargetElement) {
is KtClassOrObject -> {
resolveToPsiClassOrEnumEntry(resolvedTargetElement)?.let { return it }
}
is KtConstructor<*> -> {
resolveToPsiClassOrEnumEntry(resolvedTargetElement.getContainingClassOrObject())?.let { return it }
}
is KtTypeAlias -> {
analyzeForUast(ktExpression) {
val ktType = resolvedTargetElement.getTypeAliasSymbol().expandedType
toPsiClass(
ktType,
source = null,
resolvedTargetElement,
resolvedTargetElement.typeOwnerKind
)?.let { return it }
}
}
is KtTypeParameter -> {
analyzeForUast(ktExpression) {
val ktType = buildTypeParameterType(resolvedTargetElement.getTypeParameterSymbol())
toPsiClass(
ktType,
ktExpression.toUElement(),
resolvedTargetElement,
resolvedTargetElement.typeOwnerKind
)?.let { return it }
}
}
is KtFunctionLiteral -> {
// Implicit lambda parameter `it`
if ((resolvedTargetSymbol as? KtValueParameterSymbol)?.isImplicitLambdaParameter == true) {
// From its containing lambda (of function literal), build ULambdaExpression
val lambda = resolvedTargetElement.toUElementOfType<ULambdaExpression>()
// and return javaPsi of the corresponding lambda implicit parameter
lambda?.valueParameters?.singleOrNull()?.javaPsi?.let { return it }
}
}
}
// TODO: need to handle resolved target to library source
return resolvedTargetElement
}
override fun resolveToType(ktTypeReference: KtTypeReference, source: UElement, boxed: Boolean): PsiType? {
analyzeForUast(ktTypeReference) {
val ktType = ktTypeReference.getKtType()
if (ktType is KtClassErrorType) return null
return toPsiType(ktType, source, ktTypeReference, ktTypeReference.typeOwnerKind, boxed)
}
}
override fun resolveToType(ktTypeReference: KtTypeReference, containingLightDeclaration: PsiModifierListOwner?): PsiType? {
analyzeForUast(ktTypeReference) {
val ktType = ktTypeReference.getKtType()
if (ktType is KtClassErrorType) return null
return toPsiType(ktType, containingLightDeclaration, ktTypeReference, ktTypeReference.typeOwnerKind)
}
}
override fun getReceiverType(ktCallElement: KtCallElement, source: UElement): PsiType? {
analyzeForUast(ktCallElement) {
val ktCall = ktCallElement.resolveCall().singleFunctionCallOrNull() ?: return null
val ktType = ktCall.partiallyAppliedSymbol.signature.receiverType ?: return null
if (ktType is KtClassErrorType) return null
return toPsiType(ktType, source, ktCallElement, ktCallElement.typeOwnerKind, boxed = true)
}
}
override fun getAccessorReceiverType(ktSimpleNameExpression: KtSimpleNameExpression, source: UElement): PsiType? {
analyzeForUast(ktSimpleNameExpression) {
val ktCall = ktSimpleNameExpression.resolveCall()?.singleCallOrNull<KtVariableAccessCall>() ?: return null
val ktType = ktCall.partiallyAppliedSymbol.signature.receiverType ?: return null
if (ktType is KtClassErrorType) return null
return toPsiType(ktType, source, ktSimpleNameExpression, ktSimpleNameExpression.typeOwnerKind, boxed = true)
}
}
override fun getDoubleColonReceiverType(ktDoubleColonExpression: KtDoubleColonExpression, source: UElement): PsiType? {
analyzeForUast(ktDoubleColonExpression) {
val receiverKtType = ktDoubleColonExpression.getReceiverKtType() ?: return null
return toPsiType(receiverKtType, source, ktDoubleColonExpression, ktDoubleColonExpression.typeOwnerKind, boxed = true)
}
}
override fun getCommonSupertype(left: KtExpression, right: KtExpression, uExpression: UExpression): PsiType? {
val ktElement = uExpression.sourcePsi as? KtExpression ?: return null
analyzeForUast(ktElement) {
val leftType = left.getKtType() ?: return null
val rightType = right.getKtType() ?: return null
val commonSuperType = commonSuperType(listOf(leftType, rightType)) ?: return null
return toPsiType(commonSuperType, uExpression, ktElement, ktElement.typeOwnerKind)
}
}
override fun getType(ktExpression: KtExpression, source: UElement): PsiType? {
analyzeForUast(ktExpression) {
val ktType = ktExpression.getKtType() ?: return null
return toPsiType(ktType, source, ktExpression, ktExpression.typeOwnerKind)
}
}
override fun getType(ktDeclaration: KtDeclaration, source: UElement): PsiType? {
analyzeForUast(ktDeclaration) {
return toPsiType(ktDeclaration.getReturnKtType(), source, ktDeclaration, ktDeclaration.typeOwnerKind)
}
}
override fun getType(ktDeclaration: KtDeclaration, containingLightDeclaration: PsiModifierListOwner?): PsiType? {
analyzeForUast(ktDeclaration) {
return toPsiType(ktDeclaration.getReturnKtType(), containingLightDeclaration, ktDeclaration, ktDeclaration.typeOwnerKind)
}
}
override fun getFunctionType(ktFunction: KtFunction, source: UElement): PsiType? {
analyzeForUast(ktFunction) {
return toPsiType(ktFunction.getFunctionalType(), source, ktFunction, ktFunction.typeOwnerKind)
}
}
override fun getFunctionalInterfaceType(uLambdaExpression: KotlinULambdaExpression): PsiType? {
val sourcePsi = uLambdaExpression.sourcePsi
analyzeForUast(sourcePsi) {
val samType = sourcePsi.getExpectedType()
?.takeIf { it !is KtClassErrorType && it.isFunctionalInterfaceType }
?.lowerBoundIfFlexible()
?: return null
return toPsiType(samType, uLambdaExpression, sourcePsi, sourcePsi.typeOwnerKind)
}
}
override fun nullability(psiElement: PsiElement): TypeNullability? {
if (psiElement is KtTypeReference) {
analyzeForUast(psiElement) {
nullability(psiElement.getKtType())?.let { return it }
}
}
if (psiElement is KtCallableDeclaration) {
psiElement.typeReference?.let { typeReference ->
analyzeForUast(typeReference) {
nullability(typeReference.getKtType())?.let { return it }
}
}
}
if (psiElement is KtProperty) {
psiElement.initializer?.let { propertyInitializer ->
analyzeForUast(propertyInitializer) {
nullability(propertyInitializer.getKtType())?.let { return it }
}
}
psiElement.delegateExpression?.let { delegatedExpression ->
analyzeForUast(delegatedExpression) {
val typeArgument = (delegatedExpression.getKtType() as? KtNonErrorClassType)?.typeArguments?.firstOrNull()
nullability((typeArgument as? KtTypeArgumentWithVariance)?.type)?.let { return it }
}
}
}
psiElement.getParentOfType<KtProperty>(false)?.let { property ->
property.typeReference?.let { typeReference ->
analyzeForUast(typeReference) {
nullability(typeReference.getKtType())
}
} ?:
property.initializer?.let { propertyInitializer ->
analyzeForUast(propertyInitializer) {
nullability(propertyInitializer.getKtType())
}
}
}?.let { return it }
return null
}
override fun evaluate(uExpression: UExpression): Any? {
val ktExpression = uExpression.sourcePsi as? KtExpression ?: return null
analyzeForUast(ktExpression) {
return ktExpression.evaluate(KtConstantEvaluationMode.CONSTANT_LIKE_EXPRESSION_EVALUATION)
?.takeUnless { it is KtConstantValue.KtErrorConstantValue }?.value
}
}
}
| apache-2.0 | f599bac2ae84036a6c7a0deb57e7f52b | 49.268627 | 143 | 0.654328 | 6.386896 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/fragment/TableBuilder.kt | 1 | 7054 | package org.hexworks.zircon.api.builder.fragment
import org.hexworks.cobalt.databinding.api.collection.ObservableList
import org.hexworks.cobalt.databinding.api.value.ObservableValue
import org.hexworks.zircon.api.Beta
import org.hexworks.zircon.api.component.Component
import org.hexworks.zircon.api.component.HBox
import org.hexworks.zircon.api.component.Icon
import org.hexworks.zircon.api.component.Label
import org.hexworks.zircon.api.component.renderer.ComponentRenderer
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.dsl.component.buildIcon
import org.hexworks.zircon.api.dsl.component.buildLabel
import org.hexworks.zircon.api.fragment.Table
import org.hexworks.zircon.api.fragment.builder.FragmentBuilder
import org.hexworks.zircon.internal.component.renderer.DefaultHBoxRenderer
import org.hexworks.zircon.internal.dsl.ZirconDsl
import org.hexworks.zircon.internal.fragment.impl.DefaultTable
import org.hexworks.zircon.internal.fragment.impl.TableColumn
import kotlin.jvm.JvmStatic
@ZirconDsl
@Beta
class TableBuilder<T : Any> private constructor(
var data: ObservableList<T>? = null,
var columns: List<TableColumn<T, *, *>> = listOf(),
var height: Int = 2,
var rowSpacing: Int = 0,
var colSpacing: Int = 0,
var position: Position = Position.zero(),
var addHeader: Boolean = true,
var selectedRowRenderer: ComponentRenderer<HBox> = DefaultHBoxRenderer(),
) : FragmentBuilder<Table<T>, TableBuilder<T>> {
fun <V : Any, C : Component> TableBuilder<T>.column(init: TableColumnBuilder<T, V, C>.() -> Unit) {
columns = columns + TableColumnBuilder.newBuilder<T, V, C>().apply(init).build()
}
/**
* Creates a column that will render a [Label] that will contain the [String] you provide.
* In order for this to work what you'll need to set is
* - [TableColumnBuilder.valueProvider]
* - [TableColumnBuilder.width]
* The rest will be set for you.
*/
fun TableBuilder<T>.textColumn(init: TableColumnBuilder<T, String, Label>.() -> Unit) {
columns = columns + TableColumnBuilder.newBuilder<T, String, Label>()
.apply(init)
.also { builder ->
builder.cellRenderer = {
buildLabel {
+it
preferredSize = Size.create(builder.width, 1)
}
}
}
.build()
}
/**
* Creates a column that will render a [Label] that will contain the [Number] you provide.
* In order for this to work what you'll need to set is
* - [TableColumnBuilder.valueProvider]
* - [TableColumnBuilder.width]
* The rest will be set for you.
*/
fun TableBuilder<T>.numberColumn(init: TableColumnBuilder<T, Number, Label>.() -> Unit) {
columns = columns + TableColumnBuilder.newBuilder<T, Number, Label>()
.apply(init)
.also { builder ->
builder.cellRenderer = { number ->
buildLabel {
+number.toString()
preferredSize = Size.create(builder.width, 1)
}
}
}
.build()
}
/**
* Creates a column that will render an [Label] and bind its value to the obserable value
* you provide. In order for this to work what you'll need to set is
* - a [TableColumnBuilder.valueProvider]
* The rest will be set for you.
*/
fun TableBuilder<T>.observableTextColumn(init: TableColumnBuilder<T, ObservableValue<String>, Label>.() -> Unit) {
columns = columns + TableColumnBuilder.newBuilder<T, ObservableValue<String>, Label>()
.apply(init)
.also { builder ->
builder.cellRenderer = { value ->
buildLabel {
textProperty.updateFrom(value)
preferredSize = Size.create(builder.width, 1)
}
}
}
.build()
}
/**
* Creates a column that will render an [Icon]. In order for this to work
* what you'll need to set is
* - a [TableColumnBuilder.valueProvider]
* The rest will be set for you.
*/
fun TableBuilder<T>.iconColumn(init: TableColumnBuilder<T, Tile, Icon>.() -> Unit) {
columns = columns +
TableColumnBuilder.newBuilder<T, Tile, Icon>()
.apply(init).also { builder ->
builder.width = 1
builder.cellRenderer = { tile ->
buildIcon {
iconTile = tile
}
}
}
.build()
}
fun withHeight(height: Int) = also {
this.height = height
}
fun withData(data: ObservableList<T>) = also {
this.data = data
}
fun withColumns(columns: List<TableColumn<T, *, *>>) = also {
this.columns = columns
}
fun withRowSpacing(spacing: Int) = also {
rowSpacing = spacing
}
fun withColumnSpacing(spacing: Int) = also {
colSpacing = spacing
}
fun withAddHeader(addHeader: Boolean) = also {
this.addHeader = addHeader
}
fun withSelectedRowRenderer(rowRenderer: ComponentRenderer<HBox>) = also {
this.selectedRowRenderer = rowRenderer
}
override fun build(): Table<T> {
val minHeight = 2
require(height >= minHeight) {
"A table requires a height of at least $minHeight."
}
require(columns.isNotEmpty()) {
"A table must have at least one column."
}
require(rowSpacing >= 0) {
"Row spacing must be greater than equal to 0. Current value is $rowSpacing"
}
require(colSpacing >= 0) {
"Col spacing must be greater than equal to 0. Current value is $colSpacing"
}
return DefaultTable(
position = position,
data = data ?: error("A table must have an observable list of data associated with its columns"),
height = data!!.size + 1,
columns = columns,
rowSpacing = rowSpacing,
colSpacing = colSpacing,
addHeader = addHeader,
selectedRowRenderer = selectedRowRenderer
)
}
override fun withPosition(position: Position): TableBuilder<T> = also {
this.position = position
}
override fun createCopy() = TableBuilder(
data = data,
columns = columns,
height = (data?.size ?: 0) + 1,
rowSpacing = rowSpacing,
colSpacing = colSpacing,
position = position,
addHeader = addHeader,
selectedRowRenderer = selectedRowRenderer
)
companion object {
@JvmStatic
fun <T : Any> newBuilder() = TableBuilder<T>()
}
}
| apache-2.0 | d65f3ac919f967359e378ec40dc6f7a4 | 34.807107 | 118 | 0.597392 | 4.586476 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/jetpack/java/org/wordpress/android/ui/accounts/login/components/PrimaryButton.kt | 1 | 1754 | package org.wordpress.android.ui.accounts.login.components
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import org.wordpress.android.R
import org.wordpress.android.ui.compose.unit.Margin
@Composable
fun PrimaryButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
Button(
onClick = onClick,
elevation = ButtonDefaults.elevation(
defaultElevation = 0.dp,
pressedElevation = 0.dp,
),
colors = ButtonDefaults.buttonColors(
backgroundColor = colorResource(R.color.bg_jetpack_login_splash_primary_button),
contentColor = colorResource(R.color.text_color_jetpack_login_splash_primary_button),
),
modifier = modifier
.padding(horizontal = dimensionResource(R.dimen.login_prologue_revamped_buttons_padding))
.padding(top = Margin.ExtraLarge.value)
.fillMaxWidth(),
) {
Text(
text = stringResource(R.string.continue_with_wpcom_no_signup),
style = TextStyle(
fontWeight = FontWeight.SemiBold,
),
)
}
}
| gpl-2.0 | 392f2b12c9afe627dddf882432df6aae | 37.130435 | 109 | 0.668757 | 4.591623 | false | false | false | false |
y20k/transistor | app/src/main/java/org/y20k/transistor/Keys.kt | 1 | 9585 | /*
* Keys.kt
* Implements the keys used throughout the app
* This object hosts all keys used to control Transistor state
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package org.y20k.transistor
import java.util.*
/*
* Keys object
*/
object Keys {
// application name
const val APPLICATION_NAME: String = "Transistor"
// version numbers
const val CURRENT_COLLECTION_CLASS_VERSION_NUMBER: Int = 0
// time values
const val UPDATE_REPEAT_INTERVAL: Long = 4L // every 4 hours
const val MINIMUM_TIME_BETWEEN_UPDATES: Long = 180000L // 3 minutes in milliseconds
const val SLEEP_TIMER_DURATION: Long = 900000L // 15 minutes in milliseconds
const val SLEEP_TIMER_INTERVAL: Long = 1000L // 1 second in milliseconds
// ranges
val PLAYBACK_SPEEDS = arrayOf(1.0f, 1.2f, 1.4f, 1.6f, 1.8f, 2.0f)
// notification
const val NOW_PLAYING_NOTIFICATION_ID: Int = 42
const val NOW_PLAYING_NOTIFICATION_CHANNEL_ID: String = "notificationChannelIdPlaybackChannel"
// intent actions
const val ACTION_SHOW_PLAYER: String = "org.y20k.transistor.action.SHOW_PLAYER"
const val ACTION_START_PLAYER_SERVICE: String = "org.y20k.transistor.action.START_PLAYER_SERVICE"
const val ACTION_COLLECTION_CHANGED: String = "org.y20k.transistor.action.COLLECTION_CHANGED"
const val ACTION_START: String = "org.y20k.transistor.action.START"
const val ACTION_STOP: String = "org.y20k.transistor.action.STOP"
// intent extras
const val EXTRA_COLLECTION_MODIFICATION_DATE: String = "COLLECTION_MODIFICATION_DATE"
const val EXTRA_STATION_UUID: String = "STATION_UUID"
const val EXTRA_STREAM_URI: String = "STREAM_URI"
const val EXTRA_START_LAST_PLAYED_STATION: String = "START_LAST_PLAYED_STATION"
// arguments
const val ARG_UPDATE_COLLECTION: String = "ArgUpdateCollection"
const val ARG_UPDATE_IMAGES: String = "ArgUpdateImages"
const val ARG_RESTORE_COLLECTION: String = "ArgRestoreCollection"
// keys
const val KEY_DOWNLOAD_WORK_REQUEST: String = "DOWNLOAD_WORK_REQUEST"
const val KEY_SAVE_INSTANCE_STATE_STATION_LIST: String = "SAVE_INSTANCE_STATE_STATION_LIST"
const val KEY_STREAM_URI: String = "STREAM_URI"
// custom MediaController commands
const val CMD_RELOAD_PLAYER_STATE: String = "RELOAD_PLAYER_STATE"
const val CMD_REQUEST_PROGRESS_UPDATE: String = "REQUEST_PROGRESS_UPDATE"
const val CMD_START_SLEEP_TIMER: String = "START_SLEEP_TIMER"
const val CMD_CANCEL_SLEEP_TIMER: String = "CANCEL_SLEEP_TIMER"
const val CMD_PLAY_STREAM: String = "PLAY_STREAM"
// preferences
const val PREF_RADIO_BROWSER_API: String = "RADIO_BROWSER_API"
const val PREF_ONE_TIME_HOUSEKEEPING_NECESSARY: String = "ONE_TIME_HOUSEKEEPING_NECESSARY_VERSIONCODE_72" // increment to current app version code to trigger housekeeping that runs only once
const val PREF_THEME_SELECTION: String= "THEME_SELECTION"
const val PREF_LAST_UPDATE_COLLECTION: String = "LAST_UPDATE_COLLECTION"
const val PREF_COLLECTION_SIZE: String = "COLLECTION_SIZE"
const val PREF_COLLECTION_MODIFICATION_DATE: String = "COLLECTION_MODIFICATION_DATE"
const val PREF_CURRENT_PLAYBACK_STATE: String = "CURRENT_PLAYBACK_STATE"
const val PREF_ACTIVE_DOWNLOADS: String = "ACTIVE_DOWNLOADS"
const val PREF_DOWNLOAD_OVER_MOBILE: String = "DOWNLOAD_OVER_MOBILE"
const val PREF_KEEP_DEBUG_LOG: String = "KEEP_DEBUG_LOG"
const val PREF_STATION_LIST_EXPANDED_UUID = "STATION_LIST_EXPANDED_UUID"
const val PREF_PLAYER_STATE_STATION_UUID: String = "PLAYER_STATE_STATION_UUID"
const val PREF_PLAYER_STATE_PLAYBACK_STATE: String = "PLAYER_STATE_PLAYBACK_STATE"
const val PREF_PLAYER_STATE_PLAYBACK_SPEED: String = "PLAYER_STATE_PLAYBACK_SPEED"
const val PREF_PLAYER_STATE_BOTTOM_SHEET_STATE: String = "PLAYER_STATE_BOTTOM_SHEET_STATE"
const val PREF_PLAYER_STATE_SLEEP_TIMER_STATE: String = "PLAYER_STATE_SLEEP_TIMER_STATE"
const val PREF_PLAYER_METADATA_HISTORY: String = "PLAYER_METADATA_HISTORY"
const val PREF_EDIT_STATIONS: String = "EDIT_STATIONS"
const val PREF_EDIT_STREAMS_URIS: String = "EDIT_STREAMS_URIS"
// states
const val STATE_SLEEP_TIMER_STOPPED: Int = 0
// default const values
const val DEFAULT_SIZE_OF_METADATA_HISTORY: Int = 25
const val DEFAULT_MAX_LENGTH_OF_METADATA_ENTRY: Int = 127
const val DEFAULT_DOWNLOAD_OVER_MOBILE: Boolean = false
const val ACTIVE_DOWNLOADS_EMPTY: String = "zero"
// media browser
const val MEDIA_BROWSER_ROOT = "__ROOT__"
const val MEDIA_BROWSER_ROOT_RECENT = "__RECENT__"
const val MEDIA_BROWSER_ROOT_EMPTY = "@empty@"
// view types
const val VIEW_TYPE_ADD_NEW: Int = 1
const val VIEW_TYPE_STATION: Int = 2
// view holder update types
const val HOLDER_UPDATE_COVER: Int = 0
const val HOLDER_UPDATE_NAME: Int = 1
const val HOLDER_UPDATE_PLAYBACK_STATE: Int = 2
const val HOLDER_UPDATE_DOWNLOAD_STATE: Int = 3
const val HOLDER_UPDATE_PLAYBACK_PROGRESS: Int = 4
// dialog types
const val DIALOG_UPDATE_COLLECTION: Int = 1
const val DIALOG_REMOVE_STATION: Int = 2
const val DIALOG_DELETE_DOWNLOADS: Int = 3
const val DIALOG_UPDATE_STATION_IMAGES: Int = 4
const val DIALOG_RESTORE_COLLECTION: Int = 5
// dialog results
const val DIALOG_RESULT_DEFAULT: Int = -1
const val DIALOG_EMPTY_PAYLOAD_STRING: String = ""
const val DIALOG_EMPTY_PAYLOAD_INT: Int = -1
// search types
const val SEARCH_TYPE_BY_KEYWORD = 0
const val SEARCH_TYPE_BY_UUID = 1
// file types
const val FILE_TYPE_DEFAULT: Int = 0
const val FILE_TYPE_PLAYLIST: Int = 10
const val FILE_TYPE_AUDIO: Int = 20
const val FILE_TYPE_IMAGE: Int = 3
// mime types and charsets and file extensions
const val CHARSET_UNDEFINDED = "undefined"
const val MIME_TYPE_JPG = "image/jpeg"
const val MIME_TYPE_PNG = "image/png"
const val MIME_TYPE_MPEG = "audio/mpeg"
const val MIME_TYPE_HLS = "application/vnd.apple.mpegurl.audio"
const val MIME_TYPE_M3U = "audio/x-mpegurl"
const val MIME_TYPE_PLS = "audio/x-scpls"
const val MIME_TYPE_XML = "text/xml"
const val MIME_TYPE_ZIP = "application/zip"
const val MIME_TYPE_OCTET_STREAM = "application/octet-stream"
const val MIME_TYPE_UNSUPPORTED = "unsupported"
val MIME_TYPES_M3U = arrayOf("application/mpegurl", "application/x-mpegurl", "audio/mpegurl", "audio/x-mpegurl")
val MIME_TYPES_PLS = arrayOf("audio/x-scpls", "application/pls+xml")
val MIME_TYPES_HLS = arrayOf("application/vnd.apple.mpegurl", "application/vnd.apple.mpegurl.audio")
val MIME_TYPES_MPEG = arrayOf("audio/mpeg")
val MIME_TYPES_OGG = arrayOf("audio/ogg", "application/ogg", "audio/opus")
val MIME_TYPES_AAC = arrayOf("audio/aac", "audio/aacp")
val MIME_TYPES_IMAGE = arrayOf("image/png", "image/jpeg")
val MIME_TYPES_FAVICON = arrayOf("image/x-icon", "image/vnd.microsoft.icon")
val MIME_TYPES_ZIP = arrayOf("application/zip", "application/x-zip-compressed", "multipart/x-zip")
// folder names
const val FOLDER_COLLECTION: String = "collection"
const val FOLDER_AUDIO: String = "audio"
const val FOLDER_IMAGES: String = "images"
const val FOLDER_TEMP: String = "temp"
const val TRANSISTOR_LEGACY_FOLDER_COLLECTION: String = "Collection"
// file names and extensions
const val COLLECTION_FILE: String = "collection.json"
const val COLLECTION_M3U_FILE: String = "collection.m3u"
const val COLLECTION_BACKUP_FILE: String = "transistor-backup.zip"
const val STATION_IMAGE_FILE: String = "station-image.jpg"
const val STATION_SMALL_IMAGE_FILE: String = "station-image-small.jpg"
const val DEBUG_LOG_FILE: String = "log-can-be-deleted.txt"
const val TRANSISTOR_LEGACY_STATION_FILE_EXTENSION: String = ".m3u"
// server addresses
const val RADIO_BROWSER_API_BASE: String = "all.api.radio-browser.info"
const val RADIO_BROWSER_API_DEFAULT: String = "de1.api.radio-browser.info"
// locations
const val LOCATION_DEFAULT_STATION_IMAGE: String = "android.resource://org.y20k.transistor/drawable/ic_default_station_image_24dp"
// sizes (in dp)
const val SIZE_COVER_NOTIFICATION_LARGE_ICON: Int = 256
const val SIZE_COVER_LOCK_SCREEN: Int = 320
const val SIZE_STATION_IMAGE_CARD: Int = 72 // todo adjust according to layout
const val SIZE_STATION_IMAGE_MAXIMUM: Int = 640
const val SIZE_STATION_IMAGE_LOCK_SCREEN: Int = 320
const val BOTTOM_SHEET_PEEK_HEIGHT: Int = 72
// default values
val DEFAULT_DATE: Date = Date(0L)
const val DEFAULT_RFC2822_DATE: String = "Thu, 01 Jan 1970 01:00:00 +0100" // --> Date(0)
const val EMPTY_STRING_RESOURCE: Int = 0
// requests
const val REQUEST_UPDATE_COLLECTION: Int = 2
// results
const val RESULT_DATA_SLEEP_TIMER_REMAINING: String = "DATA_SLEEP_TIMER_REMAINING"
const val RESULT_CODE_PERIODIC_PROGRESS_UPDATE: Int = 1
const val RESULT_DATA_METADATA: String = "DATA_PLAYBACK_PROGRESS"
// theme states
const val STATE_THEME_FOLLOW_SYSTEM: String = "stateFollowSystem"
const val STATE_THEME_LIGHT_MODE: String = "stateLightMode"
const val STATE_THEME_DARK_MODE: String = "stateDarkMode"
// unique names
const val NAME_PERIODIC_COLLECTION_UPDATE_WORK: String = "PERIODIC_COLLECTION_UPDATE_WORK"
}
| mit | c35e4d8118fe6685d6f0f57f59ca1bf0 | 43.170507 | 194 | 0.70579 | 3.603383 | false | false | false | false |
mdaniel/intellij-community | platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarRunConfigurationsAction.kt | 1 | 11543 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.runToolbar
import com.intellij.execution.*
import com.intellij.execution.actions.RunConfigurationsComboBoxAction
import com.intellij.execution.impl.EditConfigurationsDialog
import com.intellij.execution.runToolbar.components.ComboBoxArrowComponent
import com.intellij.execution.runToolbar.components.MouseListenerHelper
import com.intellij.execution.runToolbar.components.TrimmedMiddleLabel
import com.intellij.ide.DataManager
import com.intellij.ide.HelpTooltip
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl.DO_NOT_ADD_CUSTOMIZATION_HANDLER
import com.intellij.openapi.actionSystem.impl.segmentedActionBar.SegmentedCustomPanel
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.Gray
import com.intellij.ui.JBColor
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import net.miginfocom.swing.MigLayout
import org.jetbrains.annotations.Nls
import java.awt.Color
import java.awt.Dimension
import java.awt.Font
import java.awt.Point
import java.beans.PropertyChangeEvent
import javax.swing.*
open class RunToolbarRunConfigurationsAction : RunConfigurationsComboBoxAction(), RTRunConfiguration {
companion object {
private val PROP_ACTIVE_TARGET = Key<ExecutionTarget?>("PROP_ACTIVE_TARGET")
private val PROP_TARGETS = Key<List<ExecutionTarget>>("PROP_TARGETS")
fun doRightClick(dataContext: DataContext) {
ActionManager.getInstance().getAction("RunToolbarSlotContextMenuGroup")?.let {
if (it is ActionGroup) {
SwingUtilities.invokeLater {
val popup = JBPopupFactory.getInstance().createActionGroupPopup(
null, it, dataContext, false, false, false, null, 5, null)
popup.showInBestPositionFor(dataContext)
}
}
}
}
}
override fun addTargetGroup(project: Project?, allActionsGroup: DefaultActionGroup?) {
}
open fun trace(e: AnActionEvent, add: String? = null) {
}
override fun getEditRunConfigurationAction(): AnAction? {
return ActionManager.getInstance().getAction(RunToolbarEditConfigurationAction.ACTION_ID)
}
override fun createFinalAction(configuration: RunnerAndConfigurationSettings, project: Project): AnAction {
return RunToolbarSelectConfigAction(configuration, project)
}
override fun getSelectedConfiguration(e: AnActionEvent): RunnerAndConfigurationSettings? {
return e.configuration() ?: e.project?.let {
val value = RunManager.getInstance(it).selectedConfiguration
e.setConfiguration(value)
value
}
}
override fun checkMainSlotVisibility(state: RunToolbarMainSlotState): Boolean {
return false
}
override fun update(e: AnActionEvent) {
super.update(e)
if(!e.presentation.isVisible) return
e.presentation.isVisible = !e.isActiveProcess()
if (!RunToolbarProcess.isExperimentalUpdatingEnabled) {
e.mainState()?.let {
e.presentation.isVisible = e.presentation.isVisible && checkMainSlotVisibility(it)
}
}
e.presentation.description = e.runToolbarData()?.let {
RunToolbarData.prepareDescription(e.presentation.text,
ActionsBundle.message("action.RunToolbarShowHidePopupAction.click.to.open.combo.text"))
}
var targetList = emptyList<ExecutionTarget>()
e.project?.let {project ->
val targetManager = ExecutionTargetManager.getInstance(project)
e.configuration()?.configuration?.let { config->
val name = Executor.shortenNameIfNeeded(config.name)
e.presentation.setText(name, false)
targetList = targetManager.getTargetsFor(config)
}
}
e.presentation.putClientProperty(PROP_TARGETS, targetList)
e.presentation.putClientProperty(PROP_ACTIVE_TARGET, e.executionTarget())
}
override fun createCustomComponent(presentation: Presentation, place: String): JComponent {
return object : SegmentedCustomPanel(presentation) {
init {
layout = MigLayout("ins 0, gap 0, fill, hidemode 3", "[grow][pref!]")
val configComponent = RunToolbarConfigComponent(presentation)
add(configComponent, "grow")
val targetComponent =
object : JPanel(MigLayout("ins 0, fill", "[min!][grow]")){
override fun getPreferredSize(): Dimension {
val d = super.getPreferredSize()
d.width = FixWidthSegmentedActionToolbarComponent.RUN_TARGET_WIDTH
return d
}
}.apply {
add(JPanel(MigLayout("ins 0")).apply {
val s = JBDimension(1, 24)
preferredSize = s
minimumSize = s
maximumSize = s
background = UIManager.getColor("Separator.separatorColor")
}, "w min!")
add(object : DraggablePane(){
init {
setListener(object : DragListener {
override fun dragStarted(locationOnScreen: Point) {
}
override fun dragged(locationOnScreen: Point, offset: Dimension) {
}
override fun dragStopped(locationOnScreen: Point, offset: Dimension) {
}
})
}
}.apply {
isOpaque = false
}, "pos 0 0")
add(RunToolbarTargetComponent(presentation), "grow")
isOpaque = false
}
add(targetComponent, "w pref")
background = JBColor.namedColor("ComboBoxButton.background", Gray.xDF)
}
override fun getPreferredSize(): Dimension {
val d = super.getPreferredSize()
d.width = FixWidthSegmentedActionToolbarComponent.RUN_CONFIG_WIDTH
return d
}
}
}
private inner class RunToolbarTargetComponent(presentation: Presentation) : RunToolbarComboboxComponent(presentation) {
override fun presentationChanged(event: PropertyChangeEvent) {
parent.isVisible = presentation.getClientProperty(PROP_ACTIVE_TARGET)?.let {
if (it !== DefaultExecutionTarget.INSTANCE && !it.isExternallyManaged) {
updateView(it.displayName, true, it.icon, presentation.description)
true
}
else false
} ?: run {
false
}
}
override fun createPopup(onDispose: Runnable): JBPopup {
val group = DefaultActionGroup()
presentation.getClientProperty(PROP_TARGETS)?.forEach { target ->
group.add(object : AnAction({ target.displayName }, target.icon) {
override fun actionPerformed(e: AnActionEvent) {
e.setExecutionTarget(target)
}
})
}
return createActionPopup(group, ActionToolbar.getDataContextFor(this), onDispose)
}
override fun getPreferredSize(): Dimension {
val d = super.getPreferredSize()
d.width = FixWidthSegmentedActionToolbarComponent.RUN_TARGET_WIDTH
return d
}
}
private inner class RunToolbarConfigComponent(presentation: Presentation) : RunToolbarComboboxComponent(presentation) {
override fun presentationChanged(event: PropertyChangeEvent) {
updateView(presentation.text, presentation.isEnabled, presentation.icon, presentation.description)
}
override fun doRightClick() {
doRightClick(ActionToolbar.getDataContextFor(this))
}
override fun createPopup(onDispose: Runnable): JBPopup {
return createActionPopup(ActionToolbar.getDataContextFor(this), this, onDispose)
}
override fun doShiftClick() {
val context = DataManager.getInstance().getDataContext(this)
val project = CommonDataKeys.PROJECT.getData(context)
if (project != null && !ActionUtil.isDumbMode(project)) {
EditConfigurationsDialog(project).show()
return
}
}
}
private abstract class RunToolbarComboboxComponent(presentation: Presentation) : SegmentedCustomPanel(presentation) {
protected val setting = object : TrimmedMiddleLabel() {
override fun getFont(): Font {
return UIUtil.getToolbarFont()
}
override fun getForeground(): Color {
return UIUtil.getLabelForeground()
}
}
protected val arrow = ComboBoxArrowComponent().getView()
init {
MouseListenerHelper.addListener(this, { doClick() }, { doShiftClick() }, { doRightClick() })
fill()
putClientProperty(DO_NOT_ADD_CUSTOMIZATION_HANDLER, true)
isOpaque = false
}
private fun fill() {
layout = MigLayout("ins 0 0 0 3, novisualpadding, gap 0, fill, hidemode 3", "4[][min!]")
add(setting, "ay center, growx, wmin 10")
add(arrow, "w min!")
setting.border = JBUI.Borders.empty()
}
protected fun updateView(@Nls text: String, enable: Boolean, icon: Icon? = null, @Nls toolTipText: String? = null) {
setting.icon = icon
setting.text = text
setting.putClientProperty(DO_NOT_ADD_CUSTOMIZATION_HANDLER, true)
setting.isEnabled = enable
arrow.isVisible = enable
setting.toolTipText = toolTipText
arrow.toolTipText = toolTipText
}
protected open fun doRightClick() {}
protected open fun doClick() {
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown { showPopup() }
}
private fun showPopup() {
val popup: JBPopup = createPopup() {}
if (Registry.`is`("ide.helptooltip.enabled")) {
HelpTooltip.setMasterPopup(this, popup)
}
popup.showUnderneathOf(this)
}
abstract fun createPopup(onDispose: Runnable): JBPopup
protected open fun doShiftClick() {}
}
private class RunToolbarSelectConfigAction(val configuration: RunnerAndConfigurationSettings,
val project: Project) : DumbAwareAction() {
init {
var name = Executor.shortenNameIfNeeded(configuration.name)
if (name.isEmpty()) {
name = " "
}
val presentation = templatePresentation
presentation.setText(name, false)
presentation.description = ExecutionBundle.message("select.0.1", configuration.type.configurationTypeDescription, name)
updateIcon(presentation)
}
private fun updateIcon(presentation: Presentation) {
setConfigurationIcon(presentation, configuration, project)
}
override fun actionPerformed(e: AnActionEvent) {
e.project?.let {
e.runToolbarData()?.clear()
e.setConfiguration(configuration)
e.id()?.let { id ->
RunToolbarSlotManager.getInstance(it).configurationChanged(id, configuration)
}
}
}
override fun update(e: AnActionEvent) {
super.update(e)
updateIcon(e.presentation)
updatePresentation(ExecutionTargetManager.getActiveTarget(project),
configuration,
project,
e.presentation,
e.place)
}
}
}
| apache-2.0 | 7c0c28a9324426d6c732bb19a1897287 | 33.150888 | 158 | 0.681365 | 4.977577 | false | true | false | false |
DroidSmith/TirePressureGuide | tireguide/src/test/java/com/droidsmith/tireguide/calcengine/CalculatorTest.kt | 1 | 5318 | package com.droidsmith.tireguide.calcengine
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import kotlin.math.roundToInt
@RunWith(Parameterized::class)
class CalculatorTest(private val loadWeight: Double, private val tireWidth: String, private val psi: Double) {
private var calculator: Calculator = Calculator()
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{index}: Test with loadWeight={0}, tireWidth={1}, psi: {2}")
fun data(): Collection<Array<Any>> {
return listOf(
arrayOf(0.0, "20", -11),
arrayOf(8.0, "20", 0),
arrayOf(50.0, "20", 57),
arrayOf(100.0, "20", 125),
arrayOf(63.9, "20", 76),
arrayOf(77.4, "20", 95),
arrayOf(84.15, "20", 104),
arrayOf(85.2, "20", 105),
arrayOf(91.8, "20", 114),
arrayOf(102.6, "20", 129),
arrayOf(103.2, "20", 130),
arrayOf(105.3, "20", 133),
arrayOf(112.2, "20", 142),
arrayOf(122.4, "20", 156),
arrayOf(136.9, "20", 176),
arrayOf(140.4, "20", 180),
arrayOf(0.0, "21", 0),
arrayOf(50.0, "21", 59),
arrayOf(100.0, "21", 118),
arrayOf(63.9, "21", 76),
arrayOf(77.4, "21", 91),
arrayOf(84.15, "21", 99),
arrayOf(85.2, "21", 101),
arrayOf(91.8, "21", 108),
arrayOf(102.6, "21", 121),
arrayOf(103.2, "21", 122),
arrayOf(105.3, "21", 124),
arrayOf(112.2, "21", 133),
arrayOf(122.4, "21", 145),
arrayOf(136.9, "21", 162),
arrayOf(140.4, "21", 166),
arrayOf(0.0, "22", -6),
arrayOf(5.0, "22", 0),
arrayOf(50.0, "22", 52),
arrayOf(100.0, "22", 111),
arrayOf(63.9, "22", 68),
arrayOf(77.4, "22", 84),
arrayOf(84.15, "22", 92),
arrayOf(85.2, "22", 93),
arrayOf(91.8, "22", 101),
arrayOf(102.6, "22", 114),
arrayOf(103.2, "22", 114),
arrayOf(105.3, "22", 117),
arrayOf(112.2, "22", 125),
arrayOf(122.4, "22", 137),
arrayOf(136.9, "22", 154),
arrayOf(140.4, "22", 158),
arrayOf(0.0, "23", -9),
arrayOf(8.0, "23", 0),
arrayOf(50.0, "23", 47),
arrayOf(100.0, "23", 104),
arrayOf(63.9, "23", 63),
arrayOf(77.4, "23", 78),
arrayOf(84.15, "23", 86),
arrayOf(85.2, "23", 87),
arrayOf(91.8, "23", 95),
arrayOf(102.6, "23", 107),
arrayOf(103.2, "23", 108),
arrayOf(105.3, "23", 110),
arrayOf(112.2, "23", 118),
arrayOf(122.4, "23", 130),
arrayOf(136.9, "23", 146),
arrayOf(140.4, "23", 150),
arrayOf(0.0, "24", -10),
arrayOf(10.0, "24", 0),
arrayOf(50.0, "24", 42),
arrayOf(100.0, "24", 95),
arrayOf(63.9, "24", 57),
arrayOf(77.4, "24", 71),
arrayOf(84.15, "24", 78),
arrayOf(85.2, "24", 79),
arrayOf(91.8, "24", 86),
arrayOf(102.6, "24", 98),
arrayOf(103.2, "24", 98),
arrayOf(105.3, "24", 101),
arrayOf(112.2, "24", 108),
arrayOf(122.4, "24", 119),
arrayOf(136.9, "24", 134),
arrayOf(140.4, "24", 138),
arrayOf(0.0, "25", -13),
arrayOf(13.0, "25", 0),
arrayOf(50.0, "25", 37),
arrayOf(100.0, "25", 87),
arrayOf(63.9, "25", 51),
arrayOf(77.4, "25", 64),
arrayOf(84.15, "25", 71),
arrayOf(85.2, "25", 72),
arrayOf(91.8, "25", 79),
arrayOf(102.6, "25", 90),
arrayOf(103.2, "25", 90),
arrayOf(105.3, "25", 92),
arrayOf(112.2, "25", 99),
arrayOf(122.4, "25", 109),
arrayOf(136.9, "25", 124),
arrayOf(140.4, "25", 127),
arrayOf(0.0, "26", -13),
arrayOf(13.0, "26", 0),
arrayOf(50.0, "26", 35),
arrayOf(100.0, "26", 83),
arrayOf(63.9, "26", 48),
arrayOf(77.4, "26", 61),
arrayOf(84.15, "26", 68),
arrayOf(85.2, "26", 69),
arrayOf(91.8, "26", 75),
arrayOf(102.6, "26", 85),
arrayOf(103.2, "26", 86),
arrayOf(105.3, "26", 88),
arrayOf(112.2, "26", 94),
arrayOf(122.4, "26", 104),
arrayOf(136.9, "26", 118),
arrayOf(140.4, "26", 121),
arrayOf(0.0, "27", -8),
arrayOf(10.0, "27", 0),
arrayOf(50.0, "27", 36),
arrayOf(100.0, "27", 80),
arrayOf(63.9, "27", 48),
arrayOf(77.4, "27", 60),
arrayOf(84.15, "27", 66),
arrayOf(85.2, "27", 67),
arrayOf(91.8, "27", 73),
arrayOf(102.6, "27", 82),
arrayOf(103.2, "27", 83),
arrayOf(105.3, "27", 85),
arrayOf(112.2, "27", 91),
arrayOf(122.4, "27", 100),
arrayOf(136.9, "27", 113),
arrayOf(140.4, "27", 116),
arrayOf(0.0, "28", -6),
arrayOf(8.0, "28", 0),
arrayOf(50.0, "28", 34),
arrayOf(100.0, "28", 74),
arrayOf(63.9, "28", 45),
arrayOf(77.4, "28", 56),
arrayOf(84.15, "28", 61),
arrayOf(85.2, "28", 62),
arrayOf(91.8, "28", 67),
arrayOf(102.6, "28", 76),
arrayOf(103.2, "28", 76),
arrayOf(105.3, "28", 78),
arrayOf(112.2, "28", 84),
arrayOf(122.4, "28", 92),
arrayOf(136.9, "28", 103),
arrayOf(140.4, "28", 106),
arrayOf(0.0, "", 0),
arrayOf(50.0, "", 0),
arrayOf(100.0, "", 0),
arrayOf(0.0, "29", 0),
arrayOf(50.0, "29", 0),
arrayOf(100.0, "29", 0)
)
}
}
@Test
fun whenCalculatingTirePressure_WithValidInput_ThenCorrectPressureIsGiven() {
assertTrue(arePsiEqual(psi, calculator.psi(loadWeight, tireWidth)))
}
private fun arePsiEqual(expectedPsi: Double, testPsi: Double): Boolean {
return expectedPsi.roundToInt().toDouble() == testPsi
}
}
| apache-2.0 | e995812886b9627b25a59b0bf7874124 | 28.709497 | 110 | 0.539112 | 2.426095 | false | false | false | false |
androidstarters/androidstarters.com | templates/buffer-clean-architecture-components-kotlin/domain/src/main/java/org/buffer/android/boilerplate/domain/interactor/FlowableUseCase.kt | 1 | 1632 | package <%= appPackage %>.domain.interactor
import io.reactivex.Flowable
import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subscribers.DisposableSubscriber
import <%= appPackage %>.domain.executor.PostExecutionThread
import <%= appPackage %>.domain.executor.ThreadExecutor
/**
* Abstract class for a UseCase that returns an instance of a [Single].
*/
abstract class FlowableUseCase<T, in Params> constructor(
private val threadExecutor: ThreadExecutor,
private val postExecutionThread: PostExecutionThread) {
private val disposables = CompositeDisposable()
/**
* Builds a [Single] which will be used when the current [FlowableUseCase] is executed.
*/
protected abstract fun buildUseCaseObservable(params: Params? = null): Flowable<T>
/**
* Executes the current use case.
*/
open fun execute(observer: DisposableSubscriber<T>, params: Params? = null) {
val observable = this.buildUseCaseObservable(params)
.subscribeOn(Schedulers.from(threadExecutor))
.observeOn(postExecutionThread.scheduler) as Flowable<T>
addDisposable(observable.subscribeWith(observer))
}
/**
* Dispose from current [CompositeDisposable].
*/
fun dispose() {
if (!disposables.isDisposed) disposables.dispose()
}
/**
* Dispose from current [CompositeDisposable].
*/
private fun addDisposable(disposable: Disposable) {
disposables.add(disposable)
}
} | mit | 53e7708acc753bd249fcb5fcc76aea0a | 30.403846 | 91 | 0.709559 | 5.1 | false | false | false | false |
hermantai/samples | kotlin/udacity-kotlin-bootcamp/HelloKotlin/src/playgeneric.kt | 1 | 773 | open class BaseBuildingMaterial() {
open val numberNeeded = 1
}
class Wood : BaseBuildingMaterial() {
override val numberNeeded = 4
}
class Brick : BaseBuildingMaterial() {
override val numberNeeded = 8
}
class Building<T: BaseBuildingMaterial>(val buildingMaterial: T) {
val baseMaterialsNeeded = 100
val actualMaterialsNeeded = buildingMaterial.numberNeeded * baseMaterialsNeeded
fun build() {
println(" $actualMaterialsNeeded ${buildingMaterial::class.simpleName} required")
}
}
open class Stuff {
open val value = 1
}
class Pencil : Stuff() {
override val value = 2
}
class DoStuff(val stuff : Stuff) {
fun doIt() {
println(stuff.value)
}
}
fun main(args: Array<String>) {
Building(Wood()).build()
DoStuff(Pencil()).doIt()
}
| apache-2.0 | 6d19841e199f185100723af2f8d24152 | 17.853659 | 85 | 0.706339 | 3.629108 | false | false | false | false |
SneakSpeak/sp-android | app/src/main/kotlin/io/sneakspeak/sneakspeak/adapters/ChannelListAdapter.kt | 1 | 5665 | package io.sneakspeak.sneakspeak.adapters
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import android.text.InputType
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import io.sneakspeak.sneakspeak.R
import io.sneakspeak.sneakspeak.activities.ChatActivity
import io.sneakspeak.sneakspeak.data.Channel
import io.sneakspeak.sneakspeak.data.User
import io.sneakspeak.sneakspeak.managers.DatabaseManager
import io.sneakspeak.sneakspeak.managers.HttpManager
import kotlinx.android.synthetic.main.item_channel.view.*
import kotlinx.android.synthetic.main.item_header.view.*
import org.jetbrains.anko.*
import org.jetbrains.anko.support.v4.indeterminateProgressDialog
import org.jetbrains.anko.support.v4.toast
import java.util.*
class ChannelListAdapter(ctx: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>(),
View.OnClickListener {
val TAG = "ChannelListAdapter"
val TYPE_HEADER = 0
val TYPE_ITEM = 1
val context = ctx
class ItemViewHolder(channelView: View) : RecyclerView.ViewHolder(channelView) {
val channelName = channelView.channelName
}
class HeaderViewHolder(headerView: View) : RecyclerView.ViewHolder(headerView) {
val header = headerView.header
}
private var joinedChannels = ArrayList<Channel>()
private var publicChannels = ArrayList<Channel>()
fun setChannels(public: List<Channel>, joined: List<Channel>) {
joinedChannels = ArrayList(joined)
Log.d(TAG, "Joined: $joinedChannels")
publicChannels = ArrayList(public.filter { !joinedChannels.contains(it) })
Log.d(TAG, "Public: $publicChannels")
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val context = parent.context
val inflater = LayoutInflater.from(context)
// Inflate the custom layout
if (viewType == TYPE_HEADER) {
val headerItem = inflater.inflate(R.layout.item_header, parent, false)
return ChannelListAdapter.HeaderViewHolder(headerItem)
} else {
val channelItem = inflater.inflate(R.layout.item_channel, parent, false)
channelItem.setOnClickListener(this)
return ChannelListAdapter.ItemViewHolder(channelItem)
}
}
override fun getItemViewType(position: Int) = when (position) {
0, joinedChannels.size + 1 -> TYPE_HEADER
else -> TYPE_ITEM
}
// Involves populating data into the item through holder
override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
if (viewHolder is ChannelListAdapter.HeaderViewHolder) {
if (position == 0) viewHolder.header.text = "Joined channels"
else viewHolder.header.text = "Public channels"
}
else if (viewHolder is ChannelListAdapter.ItemViewHolder) {
if (position <= joinedChannels.size) {
val item = joinedChannels[position-1]
viewHolder.channelName.text = item.name
}
else {
val item = publicChannels[position- 2 - joinedChannels.size]
viewHolder.channelName.text = item.name
}
}
}
override fun getItemCount() = 2 + publicChannels.size + joinedChannels.size
override fun onClick(view: View?) {
val name = view?.channelName?.text?.toString() ?: return
val channel = publicChannels.find { it.name == name }
?: joinedChannels.find { it.name == name}
?: return
Log.d(TAG, "Channel selected: $channel")
if (channel in publicChannels) {
val alertDialog = AlertDialogBuilder(context)
alertDialog.title("Joining channel")
alertDialog.message("Do you want to join channel ${channel.name}")
alertDialog.positiveButton {
val server = DatabaseManager.getCurrentServer()
if (server == null) {
context.toast("Something is wrong.")
return@positiveButton
}
val dialog = context.indeterminateProgressDialog("Joining channel ${channel.name}...")
dialog.show()
async() {
val joinedChannel = HttpManager.joinOrCreateChannel(server, channel.name, true)
if (joinedChannel == null) {
uiThread { dialog.dismiss() }
return@async
}
addJoinedChannel(joinedChannel)
uiThread {
notifyDataSetChanged()
dialog.dismiss()
}
val intent = Intent(context, ChatActivity::class.java)
val bundle = Bundle()
bundle.putSerializable("channel", channel)
intent.putExtras(bundle)
context.startActivity(intent)
}
}
alertDialog.negativeButton("Cancel")
alertDialog.show()
return
}
val intent = Intent(context, ChatActivity::class.java)
val bundle = Bundle()
bundle.putSerializable("channel", channel)
intent.putExtras(bundle)
context.startActivity(intent)
}
fun addJoinedChannel(channel: Channel) {
joinedChannels.add(channel)
publicChannels.remove(channel)
}
} | mit | f9bc7e0a01edce85b97fe275d27019d5 | 32.329412 | 102 | 0.631244 | 5.026619 | false | false | false | false |
JetBrains/kotlin-spec | build-utils/src/org/jetbrains/kotlin/spec/markSentencesFilter.kt | 1 | 3374 | package org.jetbrains.kotlin.spec
import ru.spbstu.pandoc.*
private const val SENTENCE_CLASS = "sentence"
private const val PARAGRAPH_CLASS = "paragraph"
private fun <T> Iterable<T>.breakBy(f : (T) -> Boolean): Pair<MutableList<T>, MutableList<T>> {
val it = iterator()
val before: MutableList<T> = mutableListOf()
val after: MutableList<T> = mutableListOf()
for(t in it) {
if(f(t)) {
after += t
break
}
before += t
}
after.addAll(it.asSequence())
return before to after
}
private fun <T> MutableList<T>.unconsed() = first() to subList(1, lastIndex + 1)
private val stopList = setOf(
"e.g.", "i.e.", "w.r.t.", "ca.",
"cca.", "etc.", "f.", "ff.",
"i.a.", "Ph.D.", "Q.E.D.", "vs."
) // et.al. is commonly at the end of sentence => not here
private fun breakSentence(inlines: List<Inline>): Pair<List<Inline>, List<Inline>> {
fun isEndLine(i: Inline): Boolean = when {
i is Inline.Str
&& (i.text.endsWith(".") || i.text.endsWith("?") || i.text.endsWith("!"))
&& i.text !in stopList ->
true
i is Inline.LineBreak -> true
else -> false
}
val (ac, bc) = inlines.breakBy(::isEndLine)
if(bc.isEmpty()) return ac to emptyList()
if(bc.size == 1) return inlines to emptyList()
val (h, t_) = bc.unconsed()
val (h2, tail) = t_.unconsed()
when {
h2 is Inline.Space
|| h2 is Inline.SoftBreak
|| (h2 is Inline.Span && SENTENCE_CLASS in h2.attr.classes)
|| (h == Inline.Str(".")) && h2 is Inline.Str && h2.text.startsWith(")") -> {
ac += h
ac += h2
return ac to tail
}
(h is Inline.Str) && h.text.startsWith(".)")
|| (h is Inline.LineBreak) && h2 is Inline.Str && h2.text.startsWith(".") -> {
ac += h
tail.add(0, h2)
return ac to tail
}
else -> {
tail.add(0, h2)
val (dc, ec) = breakSentence(tail)
return (ac + h + dc) to ec
}
}
}
private fun splitSentences(inlines: List<Inline>): MutableList<List<Inline>> {
if(inlines.isEmpty()) return mutableListOf()
var (sent, rest) = breakSentence(inlines)
val res = mutableListOf(sent)
while(rest.isNotEmpty()) {
val (sent_, rest_) = breakSentence(rest)
rest = rest_
res += sent_
}
return res
}
private fun process(inlines: List<Inline>): List<Inline> =
splitSentences(inlines).map { Inline.Span(Attr(classes = listOf(SENTENCE_CLASS)), it) }
private object SpecSentencesFilterVisitor : PandocVisitor() {
override fun visit(b: Block.Para): Block {
return Block.Div(
Attr(classes = listOf(PARAGRAPH_CLASS)),
listOf(b.copy(inlines = process(b.inlines)))
)
}
override fun visit(b: Block.Plain): Block {
return b.copy(inlines = process(b.inlines))
}
override fun visit(b: Block.Div): Block {
if(PARAGRAPH_CLASS in b.attr.classes) return b;
return super.visit(b)
}
override fun visit(i: Inline.Span): Inline {
if(SENTENCE_CLASS in i.attr.classes) return i
return super.visit(i)
}
}
fun main() = makeFilter(SpecSentencesFilterVisitor)
| apache-2.0 | 08bee4d431aa107855625a17dc3e2f3c | 29.396396 | 95 | 0.554535 | 3.577943 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ui/dsl/builder/components/SegmentedButtonComponent.kt | 3 | 9498 | // 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.ui.dsl.builder.components
import com.intellij.ide.ui.laf.darcula.DarculaUIUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.ActionButtonWithText
import com.intellij.openapi.actionSystem.impl.PresentationFactory
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.observable.properties.ObservableMutableProperty
import com.intellij.openapi.observable.util.addMouseListener
import com.intellij.openapi.observable.util.lockOrSkip
import com.intellij.openapi.observable.util.whenDisposed
import com.intellij.openapi.observable.util.whenKeyReleased
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.NlsActions
import com.intellij.ui.dsl.builder.DslComponentProperty
import com.intellij.ui.dsl.builder.EmptySpacingConfiguration
import com.intellij.ui.dsl.builder.SpacingConfiguration
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.ui.dsl.gridLayout.GridLayout
import com.intellij.ui.dsl.gridLayout.builders.RowsGridBuilder
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import org.jetbrains.annotations.ApiStatus
import java.awt.*
import java.awt.event.FocusEvent
import java.awt.event.FocusListener
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import javax.swing.JPanel
private const val PLACE = "SegmentedButton"
@ApiStatus.Internal
internal class SegmentedButtonComponent<T>(items: Collection<T>, private val renderer: (T) -> String) : JPanel(GridLayout()) {
var spacing: SpacingConfiguration = EmptySpacingConfiguration()
set(value) {
field = value
// Rebuild buttons with correct spacing
rebuild()
}
var selectedItem: T? = null
set(value) {
if (field != value) {
setSelectedState(field, false)
setSelectedState(value, true)
field = value
for (listener in listenerList.getListeners(ModelListener::class.java)) {
listener.onItemSelected()
}
repaint()
}
}
var items: Collection<T> = emptyList()
set(value) {
field = value
rebuild()
}
init {
isFocusable = true
border = SegmentedButtonBorder()
putClientProperty(DslComponentProperty.VISUAL_PADDINGS, Gaps(size = DarculaUIUtil.BW.get()))
this.items = items
addFocusListener(object : FocusListener {
override fun focusGained(e: FocusEvent?) {
repaint()
}
override fun focusLost(e: FocusEvent?) {
repaint()
}
})
val actionLeft = DumbAwareAction.create { moveSelection(-1) }
actionLeft.registerCustomShortcutSet(ActionUtil.getShortcutSet("SegmentedButton-left"), this)
val actionRight = DumbAwareAction.create { moveSelection(1) }
actionRight.registerCustomShortcutSet(ActionUtil.getShortcutSet("SegmentedButton-right"), this)
}
fun addModelListener(l: ModelListener) {
listenerList.add(ModelListener::class.java, l)
}
fun removeModelListener(l: ModelListener) {
listenerList.remove(ModelListener::class.java, l)
}
override fun setEnabled(enabled: Boolean) {
super.setEnabled(enabled)
for (component in components) {
component.isEnabled = enabled
}
}
override fun paint(g: Graphics) {
super.paint(g)
// Paint selected button frame over all children
val g2 = g.create() as Graphics2D
try {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE)
g2.paint = getSegmentedButtonBorderPaint(this, true)
val selectedButton = components.getOrNull(items.indexOf(selectedItem))
if (selectedButton != null) {
val r = selectedButton.bounds
JBInsets.addTo(r, JBUI.insets(DarculaUIUtil.LW.unscaled.toInt()))
paintBorder(g2, r)
}
}
finally {
g2.dispose()
}
}
private fun rebuild() {
removeAll()
val presentationFactory = PresentationFactory()
val builder = RowsGridBuilder(this)
for (item in items) {
val action = SegmentedButtonAction(this, item, renderer.invoke(item))
val button = SegmentedButton(action, presentationFactory.getPresentation(action), spacing)
builder.cell(button)
}
for (listener in listenerList.getListeners(ModelListener::class.java)) {
listener.onRebuild()
}
}
private fun setSelectedState(item: T?, selectedState: Boolean) {
val componentIndex = items.indexOf(item)
val segmentedButton = components.getOrNull(componentIndex) as? SegmentedButton<*>
segmentedButton?.selectedState = selectedState
}
private fun moveSelection(step: Int) {
if (items.isEmpty()) {
return
}
val selectedIndex = items.indexOf(selectedItem)
val newSelectedIndex = if (selectedIndex < 0) 0 else (selectedIndex + step).coerceIn(0, items.size - 1)
selectedItem = items.elementAt(newSelectedIndex)
}
companion object {
fun <T> SegmentedButtonComponent<T>.bind(property: ObservableMutableProperty<T>) {
val mutex = AtomicBoolean()
property.afterChange {
mutex.lockOrSkip {
selectedItem = it
}
}
whenItemSelected {
mutex.lockOrSkip {
property.set(it)
}
}
}
fun <T> SegmentedButtonComponent<T>.whenItemSelected(parentDisposable: Disposable? = null, listener: (T) -> Unit) {
addModelListener(parentDisposable, object : ModelListener {
override fun onItemSelected() {
selectedItem?.let(listener)
}
})
}
private fun SegmentedButtonComponent<*>.whenRebuild(parentDisposable: Disposable?, listener: () -> Unit) {
addModelListener(parentDisposable, object : ModelListener {
override fun onRebuild() = listener()
})
}
fun <T> SegmentedButtonComponent<T>.addModelListener(parentDisposable: Disposable? = null, listener: ModelListener) {
addModelListener(listener)
parentDisposable?.whenDisposed {
removeModelListener(listener)
}
}
@ApiStatus.Experimental
fun <T> SegmentedButtonComponent<T>.whenItemSelectedFromUi(parentDisposable: Disposable? = null, listener: (T) -> Unit) {
whenKeyReleased(parentDisposable) {
fireItemSelectedFromUi(listener)
}
whenButtonsTouchedFromUi(parentDisposable) {
fireItemSelectedFromUi(listener)
}
whenRebuild(parentDisposable) {
whenButtonsTouchedFromUi(parentDisposable) {
fireItemSelectedFromUi(listener)
}
}
}
private fun <T> SegmentedButtonComponent<T>.fireItemSelectedFromUi(listener: (T) -> Unit) {
invokeLater(ModalityState.stateForComponent(this)) {
selectedItem?.let(listener)
}
}
private fun SegmentedButtonComponent<*>.whenButtonsTouchedFromUi(parentDisposable: Disposable?, listener: () -> Unit) {
for (button in components) {
whenButtonTouchedFromUi(button, parentDisposable, listener)
}
}
private fun SegmentedButtonComponent<*>.whenButtonTouchedFromUi(
button: Component,
parentDisposable: Disposable?,
listener: () -> Unit
) {
val mouseListener = object : MouseAdapter() {
override fun mouseReleased(e: MouseEvent) = listener()
}
button.addMouseListener(parentDisposable, mouseListener)
whenRebuild(parentDisposable) {
button.removeMouseListener(mouseListener)
}
}
}
@ApiStatus.Internal
internal interface ModelListener : EventListener {
fun onItemSelected() {}
fun onRebuild() {}
}
}
private class SegmentedButtonAction<T>(val parent: SegmentedButtonComponent<T>, val item: T, @NlsActions.ActionText itemText: String)
: ToggleAction(itemText, null, null), DumbAware {
override fun isSelected(e: AnActionEvent): Boolean {
return parent.selectedItem == item
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
if (state) {
parent.selectedItem = item
}
}
}
private class SegmentedButton<T>(
private val action: SegmentedButtonAction<T>,
presentation: Presentation,
private val spacing: SpacingConfiguration
) : ActionButtonWithText(action, presentation, PLACE, Dimension(0, 0)) {
var selectedState: Boolean
get() = Toggleable.isSelected(myPresentation)
set(value) {
Toggleable.setSelected(myPresentation, value)
}
init {
setLook(SegmentedButtonLook)
}
override fun getPreferredSize(): Dimension {
val preferredSize = super.getPreferredSize()
return Dimension(preferredSize.width + spacing.segmentedButtonHorizontalGap * 2,
preferredSize.height + spacing.segmentedButtonVerticalGap * 2)
}
override fun actionPerformed(event: AnActionEvent) {
super.actionPerformed(event)
// Restore toggle action if selected button pressed again
selectedState = action.parent.selectedItem == action.item
}
}
| apache-2.0 | a89622a2f512b7624607593bde613119 | 31.416382 | 133 | 0.716361 | 4.642229 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findPropertyUsages/kotlinPrivatePropertyUsages4.0.kt | 7 | 349 | // FIR_IGNORE
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtParameter
// OPTIONS: usages
package server
public open class Server(private val <caret>foo: String = "foo") {
open fun processRequest() = foo
}
public class ServerEx() : Server(foo = "!") {
private val foo = "f"
override fun processRequest() = "foo" + foo
}
// FIR_COMPARISON
| apache-2.0 | 139ba65a8e3f20874106cdce6b48d204 | 22.266667 | 66 | 0.673352 | 3.49 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/rebase/interactive/dialog/GitRebaseCommitsTableView.kt | 2 | 11982 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.rebase.interactive.dialog
import com.intellij.icons.AllIcons
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.ui.CommitIconTableCellRenderer
import com.intellij.ui.ColoredTableCellRenderer
import com.intellij.ui.JBColor
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.TableSpeedSearch
import com.intellij.ui.scale.JBUIScale
import com.intellij.ui.speedSearch.SpeedSearchUtil
import com.intellij.ui.table.JBTable
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.vcs.log.data.index.IndexedDetails
import com.intellij.vcs.log.paint.PaintParameters
import git4idea.rebase.interactive.GitRebaseTodoModel
import git4idea.rebase.interactive.dialog.GitRebaseCommitsTableView.Companion.DEFAULT_CELL_HEIGHT
import git4idea.rebase.interactive.dialog.GitRebaseCommitsTableView.Companion.GRAPH_COLOR
import git4idea.rebase.interactive.dialog.GitRebaseCommitsTableView.Companion.GRAPH_LINE_WIDTH
import git4idea.rebase.interactive.dialog.GitRebaseCommitsTableView.Companion.GRAPH_NODE_WIDTH
import git4idea.rebase.interactive.dialog.view.CommitMessageCellEditor
import java.awt.*
import javax.swing.DefaultListSelectionModel
import javax.swing.JTable
import javax.swing.ListSelectionModel
import javax.swing.event.ChangeEvent
import javax.swing.table.TableCellEditor
internal open class GitRebaseCommitsTableView(
val project: Project,
val model: GitRebaseCommitsTableModel<*>,
private val disposable: Disposable
) : JBTable(model) {
companion object {
val GRAPH_LINE_WIDTH: Float
get() = JBUIScale.scale(1.5f)
val GRAPH_NODE_WIDTH: Int
get() = JBUI.scale(8)
val DEFAULT_CELL_HEIGHT: Int
get() = JBUI.scale(PaintParameters.ROW_HEIGHT)
val GRAPH_COLOR = JBColor.namedColor("VersionControl.GitCommits.graphColor", JBColor(Color(174, 185, 192), Color(135, 146, 154)))
}
init {
setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)
columnModel.selectionModel = object : DefaultListSelectionModel() {
override fun setSelectionInterval(index0: Int, index1: Int) {
val indexToForce = [email protected](GitRebaseCommitsTableModel.SUBJECT_COLUMN)
super.setSelectionInterval(indexToForce, indexToForce)
}
}
intercellSpacing = JBUI.emptySize()
tableHeader = null
installSpeedSearch()
prepareCommitIconColumn()
prepareSubjectColumn()
installUndoRedoActions()
}
private fun installUndoRedoActions() {
installAnActionWithShortcut(UndoAction(this), IdeActions.ACTION_UNDO)
installAnActionWithShortcut(RedoAction(this), IdeActions.ACTION_REDO)
}
private fun installAnActionWithShortcut(action: AnAction, shortcutActionId: String) {
action.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts(shortcutActionId), this)
}
final override fun setSelectionMode(selectionMode: Int) {
super.setSelectionMode(selectionMode)
}
private fun installSpeedSearch() {
TableSpeedSearch(this) { o, cell -> o.toString().takeIf { cell.column == GitRebaseCommitsTableModel.SUBJECT_COLUMN } }
}
private fun prepareCommitIconColumn() {
val commitIconColumn = columnModel.getColumn(GitRebaseCommitsTableModel.COMMIT_ICON_COLUMN)
commitIconColumn.cellRenderer = GitRebaseCommitIconTableCellRenderer()
adjustCommitIconColumnWidth()
}
private fun adjustCommitIconColumnWidth() {
val contentWidth = 2 * GRAPH_NODE_WIDTH + UIUtil.DEFAULT_HGAP
val column = columnModel.getColumn(GitRebaseCommitsTableModel.COMMIT_ICON_COLUMN)
column.maxWidth = contentWidth
column.preferredWidth = contentWidth
}
override fun prepareEditor(editor: TableCellEditor?, row: Int, column: Int): Component {
onEditorCreate()
return super.prepareEditor(editor, row, column)
}
protected open fun onEditorCreate() {}
override fun removeEditor() {
onEditorRemove()
if (editingRow in 0 until rowCount) {
setRowHeight(editingRow, DEFAULT_CELL_HEIGHT)
}
super.removeEditor()
}
override fun columnMarginChanged(e: ChangeEvent) {
// same as JTable#columnMarginChanged except for it doesn't stop editing
val tableHeader = getTableHeader()
val resizingColumn = tableHeader?.resizingColumn
if (resizingColumn != null && autoResizeMode == JTable.AUTO_RESIZE_OFF) {
resizingColumn.preferredWidth = resizingColumn.width
}
resizeAndRepaint()
}
protected open fun onEditorRemove() {}
private fun prepareSubjectColumn() {
val subjectColumn = columnModel.getColumn(GitRebaseCommitsTableModel.SUBJECT_COLUMN)
subjectColumn.cellRenderer = SubjectRenderer()
subjectColumn.cellEditor = CommitMessageCellEditor(project, this, disposable)
}
internal fun getDrawNodeType(row: Int): NodeType = when {
model.getElement(row).type == GitRebaseTodoModel.Type.NonUnite.KeepCommit.Edit -> NodeType.EDIT
model.getElement(row).type !is GitRebaseTodoModel.Type.NonUnite.KeepCommit -> NodeType.NO_NODE
model.getElement(row) is GitRebaseTodoModel.Element.UniteRoot -> NodeType.DOUBLE_NODE
else -> NodeType.SIMPLE_NODE
}
private abstract class DisabledDuringRewordAction(protected val table: GitRebaseCommitsTableView) : DumbAwareAction() {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun update(e: AnActionEvent) {
super.update(e)
val presentation = e.presentation
presentation.isEnabledAndVisible = true
if (table.editingRow != -1) {
presentation.isEnabledAndVisible = false
}
}
}
private class UndoAction(table: GitRebaseCommitsTableView) : DisabledDuringRewordAction(table) {
override fun actionPerformed(e: AnActionEvent) {
table.model.undo()
}
}
private class RedoAction(table: GitRebaseCommitsTableView) : DisabledDuringRewordAction(table) {
override fun actionPerformed(e: AnActionEvent) {
table.model.redo()
}
}
}
private class SubjectRenderer : ColoredTableCellRenderer() {
companion object {
private const val GRAPH_WIDTH = 20
private const val CONNECTION_CENTER_X = GRAPH_WIDTH / 4
}
private var graphType: GraphType = GraphType.NoGraph
private var rowHeight: Int = DEFAULT_CELL_HEIGHT
private val connectionCenterY: Int
get() = rowHeight / 2
override fun paint(g: Graphics?) {
super.paint(g)
(g as Graphics2D).paintFixupGraph()
}
private fun Graphics2D.paintFixupGraph() {
when (val type = graphType) {
is GraphType.NoGraph -> {
}
is GraphType.FixupGraph -> {
setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
color = GRAPH_COLOR
stroke = BasicStroke(GRAPH_LINE_WIDTH, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL)
drawCenterLine()
drawUpLine(type.isFirst)
if (!type.isLast) {
drawDownLine()
}
}
}
}
private fun Graphics2D.drawCenterLine() {
val gap = GRAPH_WIDTH / 5
val xRight = GRAPH_WIDTH - gap
drawLine(CONNECTION_CENTER_X, connectionCenterY, xRight, connectionCenterY)
}
private fun Graphics2D.drawDownLine() {
drawLine(CONNECTION_CENTER_X, connectionCenterY, CONNECTION_CENTER_X, rowHeight)
}
private fun Graphics2D.drawUpLine(withArrow: Boolean) {
val triangleSide = JBUI.scale(8)
val triangleBottomY = triangleSide / 2
val triangleBottomXDiff = triangleSide / 2
val upLineY = if (withArrow) triangleBottomY else 0
drawLine(CONNECTION_CENTER_X, connectionCenterY, CONNECTION_CENTER_X, upLineY)
if (withArrow) {
val xPoints = intArrayOf(CONNECTION_CENTER_X, CONNECTION_CENTER_X - triangleBottomXDiff, CONNECTION_CENTER_X + triangleBottomXDiff)
val yPoints = intArrayOf(0, triangleBottomY, triangleBottomY)
fillPolygon(xPoints, yPoints, xPoints.size)
}
}
private fun getRowGraphType(table: GitRebaseCommitsTableView, row: Int): GraphType {
val element = table.model.getElement(row)
return if (element is GitRebaseTodoModel.Element.UniteChild<*>) {
GraphType.FixupGraph(table.model.isFirstFixup(element), table.model.isLastFixup(element))
}
else {
GraphType.NoGraph
}
}
override fun customizeCellRenderer(table: JTable, value: Any?, selected: Boolean, hasFocus: Boolean, row: Int, column: Int) {
if (value != null) {
border = null
isOpaque = false
val commitsTable = table as GitRebaseCommitsTableView
graphType = getRowGraphType(commitsTable, row)
rowHeight = table.getRowHeight(row)
var attributes = SimpleTextAttributes.REGULAR_ATTRIBUTES
val element = commitsTable.model.rebaseTodoModel.elements[row]
when (element.type) {
GitRebaseTodoModel.Type.NonUnite.Drop -> {
attributes = SimpleTextAttributes(SimpleTextAttributes.STYLE_STRIKEOUT, null)
}
is GitRebaseTodoModel.Type.NonUnite.KeepCommit.Reword -> {
attributes = SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, JBColor.BLUE)
}
GitRebaseTodoModel.Type.Unite -> {
append("")
appendTextPadding(GRAPH_WIDTH)
}
else -> {
}
}
append(IndexedDetails.getSubject(commitsTable.model.getCommitMessage(row)), attributes, true)
SpeedSearchUtil.applySpeedSearchHighlighting(table, this, true, selected)
}
}
private sealed class GraphType {
object NoGraph : GraphType()
class FixupGraph(val isFirst: Boolean, val isLast: Boolean) : GraphType()
}
}
private class GitRebaseCommitIconTableCellRenderer : CommitIconTableCellRenderer({ GRAPH_COLOR }, DEFAULT_CELL_HEIGHT, GRAPH_LINE_WIDTH) {
override val nodeWidth: Int
get() = GRAPH_NODE_WIDTH
private var isHead = false
private var nodeType = NodeType.SIMPLE_NODE
override fun customizeRenderer(table: JTable?, value: Any?, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int) {
if (table != null && table is GitRebaseCommitsTableView) {
nodeType = table.getDrawNodeType(row)
isHead = row == table.rowCount - 1
}
}
override fun drawCommitIcon(g: Graphics2D) {
val tableRowHeight = rowHeight
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
when (nodeType) {
NodeType.SIMPLE_NODE -> {
drawNode(g)
}
NodeType.DOUBLE_NODE -> {
drawDoubleNode(g)
}
NodeType.NO_NODE -> {
}
NodeType.EDIT -> {
drawEditNode(g)
}
}
if (nodeType != NodeType.EDIT) {
drawEdge(g, tableRowHeight, false)
if (!isHead) {
drawEdge(g, tableRowHeight, true)
}
}
}
private fun drawDoubleNode(g: Graphics2D) {
val circleRadius = nodeWidth / 2
val backgroundCircleRadius = circleRadius + 1
val leftCircleX0 = nodeCenterX
val y0 = nodeCenterY
val rightCircleX0 = leftCircleX0 + circleRadius
// right circle
drawCircle(g, rightCircleX0, y0)
// distance between circles
drawCircle(g, leftCircleX0, y0, backgroundCircleRadius, background)
// left circle
drawCircle(g, leftCircleX0, y0)
}
private fun drawEditNode(g: Graphics2D) {
val icon = AllIcons.Actions.Pause
icon.paintIcon(null, g, nodeCenterX - icon.iconWidth / 2, nodeCenterY - icon.iconHeight / 2)
}
}
internal enum class NodeType {
NO_NODE, SIMPLE_NODE, DOUBLE_NODE, EDIT
}
| apache-2.0 | 1ac047796654527febd381633a045320 | 34.981982 | 140 | 0.73552 | 4.245925 | false | false | false | false |
jk1/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/statistics/SvnWorkingCopyFormatUsagesCollector.kt | 4 | 1136 | // 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.svn.statistics
import com.intellij.internal.statistic.beans.UsageDescriptor
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.openapi.project.Project
import org.jetbrains.idea.svn.NestedCopyType
import org.jetbrains.idea.svn.SvnVcs
class SvnWorkingCopyFormatUsagesCollector : ProjectUsagesCollector() {
override fun getGroupId() = "statistics.vcs.svn.format"
override fun getUsages(project: Project): Set<UsageDescriptor> {
val vcs = SvnVcs.getInstance(project)
// do not track roots with errors (SvnFileUrlMapping.getErrorRoots()) as they are "not usable" until errors are resolved
// skip externals and switched directories as they will have the same format
val roots = vcs.svnFileUrlMapping.allWcInfos.filter { it.type == null || it.type == NestedCopyType.inner }
return roots.groupingBy { it.format }.eachCount().map { UsageDescriptor(it.key.toString(), it.value) }.toSet()
}
}
| apache-2.0 | f4f876730d4c69cde4a722209255a367 | 50.636364 | 140 | 0.77993 | 4.130909 | false | false | false | false |
roylanceMichael/yaclib | core/src/main/java/org/roylance/yaclib/core/services/typescript/HttpExecuteServiceBuilder.kt | 1 | 986 | package org.roylance.yaclib.core.services.typescript
import org.roylance.common.service.IBuilder
import org.roylance.yaclib.YaclibModel
import org.roylance.yaclib.core.enums.CommonTokens
class HttpExecuteServiceBuilder : IBuilder<YaclibModel.File> {
private val InitialTemplate = """${CommonTokens.AutoGeneratedAlteringOkay}
export interface $FileName {
performPost(url:string, data:any, onSuccess:(data) => void, onError:(data) => void)
}
"""
override fun build(): YaclibModel.File {
val returnFile = YaclibModel.File.newBuilder()
.setFileToWrite(InitialTemplate.trim())
.setFileExtension(YaclibModel.FileExtension.TS_EXT)
.setFileUpdateType(YaclibModel.FileUpdateType.WRITE_IF_NOT_EXISTS)
.setFileName(FileName)
.setFullDirectoryLocation("")
.build()
return returnFile
}
companion object {
const val FileName = CommonTokens.HttpExecute
const val VariableName = CommonTokens.HttpExecuteVariableName
}
} | mit | b1cdbbe5a43dcb27b6652984321c2d83 | 31.9 | 87 | 0.747465 | 4.421525 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/opengles/src/templates/kotlin/opengles/GLESBinding.kt | 4 | 10150 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengles
import org.lwjgl.generator.*
import org.lwjgl.generator.Generator.Companion.register
import java.io.*
val NativeClass.capName: String
get() = if (templateName.startsWith(prefixTemplate)) templateName else "${prefixTemplate}_$templateName"
private const val CAPABILITIES_CLASS = "GLESCapabilities"
private val GLESBinding = register(object : APIBinding(
Module.OPENGLES,
CAPABILITIES_CLASS,
APICapabilities.JNI_CAPABILITIES
) {
private val classes by lazy { super.getClasses("GLES") }
private val functions by lazy { classes.getFunctionPointers() }
private val functionOrdinals by lazy {
LinkedHashMap<String, Int>().also { functionOrdinals ->
classes.asSequence()
.filter { it.hasNativeFunctions }
.forEach {
it.functions.asSequence()
.forEach { cmd ->
if (!cmd.has<Macro>() && !functionOrdinals.contains(cmd.name)) {
functionOrdinals[cmd.name] = functionOrdinals.size
}
}
}
}
}
override fun getFunctionOrdinal(function: Func) = functionOrdinals[function.name]!!
override fun printCustomJavadoc(writer: PrintWriter, function: Func, documentation: String): Boolean {
if (function.nativeClass.templateName.startsWith("GLES")) {
writer.printOpenGLJavaDoc(documentation, function.nativeName)
return true
}
return false
}
private val VECTOR_SUFFIX = "^gl(\\w+?)[ILP]?(?:Matrix)?\\d+(x\\d+)?N?u?(?:[bsifd]|i64)_?v?$".toRegex()
private val VECTOR_SUFFIX2 = "^gl(?:(Get)n?)?(\\w+?)[ILP]?\\d*N?u?(?:[bsifd]|i64)v$".toRegex()
private val NAMED = "^gl(\\w+?)?Named([A-Z]\\w*)$".toRegex()
private fun PrintWriter.printOpenGLJavaDoc(documentation: String, function: String) {
val page = VECTOR_SUFFIX.find(function).let {
if (it == null)
function
else
"gl${it.groupValues[1]}"
}.let { page ->
VECTOR_SUFFIX2.find(page).let {
if (it == null)
page
else
"gl${it.groupValues[1]}${it.groupValues[2]}"
}
}.let { page ->
NAMED.find(page).let {
if (it == null)
page
else
"gl${it.groupValues[1]}${it.groupValues[2]}"
}
}
val link = url("http://docs.gl/es3/$page", "Reference Page")
if (documentation.isEmpty())
println("$t/** $link */")
else {
if (documentation.indexOf('\n') == -1) {
println("$t/**")
print("$t * ")
print(documentation.substring("$t/** ".length, documentation.length - " */".length))
} else {
print(documentation.substring(0, documentation.length - "\n$t */".length))
}
print("\n$t * ")
print("\n$t * @see $link")
println("\n$t */")
}
}
override fun shouldCheckFunctionAddress(function: Func): Boolean = function.nativeClass.templateName != "GLES20"
override fun generateFunctionAddress(writer: PrintWriter, function: Func) {
writer.println("$t${t}long $FUNCTION_ADDRESS = GLES.getICD().${function.name};")
}
private val EXTENSION_NAME = "[A-Za-z0-9_]+".toRegex()
private fun getFunctionDependencyExpression(func: Func) = func.get<DependsOn>()
.reference
.let { expression ->
if (EXTENSION_NAME.matches(expression))
"ext.contains(\"$expression\")"
else
expression
}
private fun PrintWriter.printCheckFunctions(
nativeClass: NativeClass,
dependencies: LinkedHashMap<String, Int>,
filter: (Func) -> Boolean
) {
print("checkFunctions(provider, caps, new int[] {")
nativeClass.printPointers(this, { func ->
val index = functionOrdinals[func.name]
if (func.has<DependsOn>()) {
"flag${dependencies[getFunctionDependencyExpression(func)]} + $index"
} else{
index.toString()
}
}, filter)
print("},")
nativeClass.printPointers(this, { "\"${it.name}\"" }, filter)
print(")")
}
private fun PrintWriter.checkExtensionFunctions(nativeClass: NativeClass) {
val capName = nativeClass.capName
print("""
private static boolean check_${nativeClass.templateName}(FunctionProvider provider, PointerBuffer caps, Set<String> ext) {
if (!ext.contains("$capName")) {
return false;
}""")
val dependencies = nativeClass.functions
.filter { it.has<DependsOn>() }
.map(::getFunctionDependencyExpression)
.foldIndexed(LinkedHashMap<String, Int>()) { index, map, expression ->
if (!map.containsKey(expression)) {
map[expression] = index
}
map
}
if (dependencies.isNotEmpty()) {
println()
dependencies.forEach { (expression, index) ->
print("\n$t${t}int flag$index = $expression ? 0 : Integer.MIN_VALUE;")
}
}
print("\n\n$t${t}return ")
printCheckFunctions(nativeClass, dependencies) { it-> !it.has(IgnoreMissing) }
println(" || reportMissing(\"GLES\", \"$capName\");")
println("$t}")
}
init {
javaImport(
"org.lwjgl.*",
"java.util.function.IntFunction",
"static org.lwjgl.system.APIUtil.*",
"static org.lwjgl.system.Checks.*"
)
documentation = "Defines the capabilities of an OpenGL ES context."
}
override fun PrintWriter.generateJava() {
generateJavaPreamble()
println("""public final class $CAPABILITIES_CLASS {
static final int ADDRESS_BUFFER_SIZE = ${functions.size};""")
val functionSet = LinkedHashSet<String>()
classes.asSequence()
.filter { it.hasNativeFunctions }
.forEach {
val functions = it.functions.asSequence()
.filter { cmd ->
if (!cmd.has<Macro>()) {
if (functionSet.add(cmd.name)) {
return@filter true
}
}
false
}
.joinToString(",\n$t$t") { cmd -> cmd.name }
if (functions.isNotEmpty()) {
println("\n$t// ${it.templateName}")
println("${t}public final long")
println("$t$t$functions;")
}
}
println()
classes.forEach {
println(it.getCapabilityJavadoc())
println("${t}public final boolean ${it.capName};")
}
print("""
/** Off-heap array of the above function addresses. */
final PointerBuffer addresses;
$CAPABILITIES_CLASS(FunctionProvider provider, Set<String> ext, IntFunction<PointerBuffer> bufferFactory) {
PointerBuffer caps = bufferFactory.apply(ADDRESS_BUFFER_SIZE);
""")
for (extension in classes) {
val capName = extension.capName
print(
if (extension.hasNativeFunctions)
"\n$t$t$capName = check_${extension.templateName}(provider, caps, ext);"
else
"\n$t$t$capName = ext.contains(\"$capName\");"
)
}
println()
functionOrdinals.forEach { (it, index) ->
print("\n$t$t$it = caps.get($index);")
}
print("""
addresses = ThreadLocalUtil.setupAddressBuffer(caps);
}
/** Returns the buffer of OpenGL ES function pointers. */
public PointerBuffer getAddressBuffer() {
return addresses;
}
""")
for (extension in classes) {
if (!extension.hasNativeFunctions) {
continue
}
checkExtensionFunctions(extension)
}
println("""
private static boolean hasDSA(Set<String> ext) {
return ext.contains("GL_ARB_direct_state_access") || ext.contains("GL_EXT_direct_state_access");
}
}""")
}
})
fun String.nativeClassGLES(
templateName: String,
nativeSubPath: String = "",
prefix: String = "GL",
prefixMethod: String = prefix.lowercase(),
postfix: String = "",
init: NativeClass.() -> Unit
) = nativeClass(
Module.OPENGLES,
templateName,
nativeSubPath = nativeSubPath,
prefix = prefix,
prefixMethod = prefixMethod,
postfix = postfix,
binding = GLESBinding,
init = {
init()
if (!skipNative) {
nativeImport("opengles.h")
}
}
)
val NativeClass.capLink: String get() = "{@link $CAPABILITIES_CLASS\\#$capName $templateName}"
private val REGISTRY_PATTERN = "([A-Z]+)_\\w+".toRegex()
val NativeClass.registryLink: String
get() = url("https://www.khronos.org/registry/OpenGL/extensions/${if (postfix.isNotEmpty()) postfix else {
(REGISTRY_PATTERN.matchEntire(templateName) ?: throw IllegalStateException("Non-standard extension name: $templateName")).groups[1]!!.value
}}/$templateName.txt", templateName)
fun NativeClass.registryLink(spec: String): String =
url("https://www.khronos.org/registry/OpenGL/extensions/$postfix/$spec.txt", templateName)
fun registryLinkTo(group: String, name: String): String = "${group}_$name".let {
url("https://www.khronos.org/registry/OpenGL/extensions/$group/$it.txt", it)
}
val NativeClass.core: String get() = "{@link ${this.className} GLES ${this.className[4]}.${this.className[5]}}"
val NativeClass.promoted: String get() = "Promoted to core in ${this.core}." | bsd-3-clause | c1e063612cfd22a09997574463b29389 | 33.063758 | 147 | 0.553695 | 4.643184 | false | false | false | false |
google/android-fhir | engine/src/main/java/com/google/android/fhir/db/impl/DatabaseImpl.kt | 1 | 10644 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.db.impl
import android.content.Context
import androidx.annotation.VisibleForTesting
import androidx.room.Room
import androidx.room.withTransaction
import androidx.sqlite.db.SimpleSQLiteQuery
import ca.uhn.fhir.parser.IParser
import com.google.android.fhir.DatabaseErrorStrategy
import com.google.android.fhir.db.ResourceNotFoundException
import com.google.android.fhir.db.impl.DatabaseImpl.Companion.UNENCRYPTED_DATABASE_NAME
import com.google.android.fhir.db.impl.dao.LocalChangeToken
import com.google.android.fhir.db.impl.dao.LocalChangeUtils
import com.google.android.fhir.db.impl.dao.SquashedLocalChange
import com.google.android.fhir.db.impl.entities.LocalChangeEntity
import com.google.android.fhir.db.impl.entities.ResourceEntity
import com.google.android.fhir.db.impl.entities.SyncedResourceEntity
import com.google.android.fhir.logicalId
import com.google.android.fhir.search.SearchQuery
import java.lang.IllegalStateException
import java.time.Instant
import org.hl7.fhir.r4.model.Resource
import org.hl7.fhir.r4.model.ResourceType
/**
* The implementation for the persistence layer using Room. See docs for
* [com.google.android.fhir.db.Database] for the API docs.
*/
@Suppress("UNCHECKED_CAST")
internal class DatabaseImpl(
private val context: Context,
private val iParser: IParser,
databaseConfig: DatabaseConfig
) : com.google.android.fhir.db.Database {
val db: ResourceDatabase
init {
val enableEncryption =
databaseConfig.enableEncryption &&
DatabaseEncryptionKeyProvider.isDatabaseEncryptionSupported()
// The detection of unintentional switching of database encryption across releases can't be
// placed inside withTransaction because the database is opened within withTransaction. The
// default handling of corruption upon open in the room database is to re-create the database,
// which is undesirable.
val unexpectedDatabaseName =
if (enableEncryption) {
UNENCRYPTED_DATABASE_NAME
} else {
ENCRYPTED_DATABASE_NAME
}
check(!context.getDatabasePath(unexpectedDatabaseName).exists()) {
"Unexpected database, $unexpectedDatabaseName, has already existed. " +
"Check if you have accidentally enabled / disabled database encryption across releases."
}
@SuppressWarnings("NewApi")
db =
// Initializes builder with the database file name
when {
databaseConfig.inMemory ->
Room.inMemoryDatabaseBuilder(context, ResourceDatabase::class.java)
enableEncryption ->
Room.databaseBuilder(context, ResourceDatabase::class.java, ENCRYPTED_DATABASE_NAME)
else ->
Room.databaseBuilder(context, ResourceDatabase::class.java, UNENCRYPTED_DATABASE_NAME)
}
.apply {
// Provide the SupportSQLiteOpenHelper which enables the encryption.
if (enableEncryption) {
openHelperFactory {
SQLCipherSupportHelper(
it,
databaseErrorStrategy = databaseConfig.databaseErrorStrategy
) { DatabaseEncryptionKeyProvider.getOrCreatePassphrase(DATABASE_PASSPHRASE_NAME) }
}
}
}
.build()
}
private val resourceDao by lazy { db.resourceDao().also { it.iParser = iParser } }
private val syncedResourceDao = db.syncedResourceDao()
private val localChangeDao = db.localChangeDao().also { it.iParser = iParser }
override suspend fun <R : Resource> insert(vararg resource: R): List<String> {
val logicalIds = mutableListOf<String>()
db.withTransaction {
logicalIds.addAll(resourceDao.insertAll(resource.toList()))
localChangeDao.addInsertAll(resource.toList())
}
return logicalIds
}
override suspend fun <R : Resource> insertRemote(vararg resource: R) {
db.withTransaction { resourceDao.insertAll(resource.toList()) }
}
override suspend fun update(vararg resources: Resource) {
db.withTransaction {
resources.forEach {
val oldResourceEntity = selectEntity(it.resourceType, it.logicalId)
resourceDao.update(it)
localChangeDao.addUpdate(oldResourceEntity, it)
}
}
}
override suspend fun updateVersionIdAndLastUpdated(
resourceId: String,
resourceType: ResourceType,
versionId: String,
lastUpdated: Instant
) {
db.withTransaction {
resourceDao.updateRemoteVersionIdAndLastUpdate(
resourceId,
resourceType,
versionId,
lastUpdated
)
}
}
override suspend fun select(type: ResourceType, id: String): Resource {
return db.withTransaction {
resourceDao.getResource(resourceId = id, resourceType = type)?.let {
iParser.parseResource(it)
}
?: throw ResourceNotFoundException(type.name, id)
} as
Resource
}
override suspend fun lastUpdate(resourceType: ResourceType): String? {
return db.withTransaction { syncedResourceDao.getLastUpdate(resourceType) }
}
override suspend fun insertSyncedResources(
syncedResources: List<SyncedResourceEntity>,
resources: List<Resource>
) {
db.withTransaction {
syncedResourceDao.insertAll(syncedResources)
insertRemote(*resources.toTypedArray())
}
}
override suspend fun delete(type: ResourceType, id: String) {
db.withTransaction {
val remoteVersionId: String? =
try {
selectEntity(type, id).versionId
} catch (e: ResourceNotFoundException) {
null
}
val rowsDeleted = resourceDao.deleteResource(resourceId = id, resourceType = type)
if (rowsDeleted > 0)
localChangeDao.addDelete(
resourceId = id,
resourceType = type,
remoteVersionId = remoteVersionId
)
}
}
override suspend fun <R : Resource> search(query: SearchQuery): List<R> {
return db.withTransaction {
resourceDao
.getResources(SimpleSQLiteQuery(query.query, query.args.toTypedArray()))
.map { iParser.parseResource(it) as R }
.distinctBy { it.id }
}
}
override suspend fun count(query: SearchQuery): Long {
return db.withTransaction {
resourceDao.countResources(SimpleSQLiteQuery(query.query, query.args.toTypedArray()))
}
}
/**
* @returns a list of pairs. Each pair is a token + squashed local change. Each token is a list of
* [LocalChangeEntity.id] s of rows of the [LocalChangeEntity].
*/
override suspend fun getAllLocalChanges(): List<SquashedLocalChange> {
return db.withTransaction {
localChangeDao.getAllLocalChanges().groupBy { it.resourceId to it.resourceType }.values.map {
SquashedLocalChange(LocalChangeToken(it.map { it.id }), LocalChangeUtils.squash(it))
}
}
}
override suspend fun deleteUpdates(token: LocalChangeToken) {
db.withTransaction { localChangeDao.discardLocalChanges(token) }
}
override suspend fun selectEntity(type: ResourceType, id: String): ResourceEntity {
return db.withTransaction {
resourceDao.getResourceEntity(resourceId = id, resourceType = type)
?: throw ResourceNotFoundException(type.name, id)
}
}
override suspend fun withTransaction(block: suspend () -> Unit) {
db.withTransaction(block)
}
override suspend fun deleteUpdates(resources: List<Resource>) {
localChangeDao.discardLocalChanges(resources)
}
override fun close() {
db.close()
}
override suspend fun clearDatabase() {
db.clearAllTables()
}
override suspend fun getLocalChange(type: ResourceType, id: String): SquashedLocalChange? {
return db.withTransaction {
val localChangeEntityList =
localChangeDao.getLocalChanges(resourceType = type, resourceId = id)
if (localChangeEntityList.isEmpty()) {
return@withTransaction null
}
SquashedLocalChange(
LocalChangeToken(localChangeEntityList.map { it.id }),
LocalChangeUtils.squash(localChangeEntityList)
)
}
}
override suspend fun purge(type: ResourceType, id: String, forcePurge: Boolean) {
db.withTransaction {
// To check resource is present in DB else throw ResourceNotFoundException()
selectEntity(type, id)
val localChangeEntityList = localChangeDao.getLocalChanges(type, id)
// If local change is not available simply delete resource
if (localChangeEntityList.isEmpty()) {
resourceDao.deleteResource(resourceId = id, resourceType = type)
} else {
// local change is available with FORCE_PURGE the delete resource and discard changes from
// localChangeEntity table
if (forcePurge) {
resourceDao.deleteResource(resourceId = id, resourceType = type)
localChangeDao.discardLocalChanges(
token = LocalChangeToken(localChangeEntityList.map { it.id })
)
} else {
// local change is available but FORCE_PURGE = false then throw exception
throw IllegalStateException(
"Resource with type $type and id $id has local changes, either sync with server or FORCE_PURGE required"
)
}
}
}
}
companion object {
/**
* The name for unencrypted database.
*
* We use a separate name for unencrypted & encrypted database in order to detect any
* unintentional switching of database encryption across releases. When this happens, we throw
* [IllegalStateException] so that app developers have a chance to fix the issue.
*/
const val UNENCRYPTED_DATABASE_NAME = "resources.db"
/**
* The name for encrypted database.
*
* See [UNENCRYPTED_DATABASE_NAME] for the reason we use a separate name.
*/
const val ENCRYPTED_DATABASE_NAME = "resources_encrypted.db"
@VisibleForTesting const val DATABASE_PASSPHRASE_NAME = "fhirEngineDbPassphrase"
}
}
data class DatabaseConfig(
val inMemory: Boolean,
val enableEncryption: Boolean,
val databaseErrorStrategy: DatabaseErrorStrategy
)
| apache-2.0 | 32f419486f90702702d57bef0d862739 | 34.128713 | 116 | 0.704622 | 4.63993 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/insight/ListenerEventAnnotator.kt | 1 | 3955 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.insight
import com.demonwav.mcdev.MinecraftSettings
import com.demonwav.mcdev.facet.MinecraftFacet
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiIdentifier
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiModifier
import com.intellij.psi.impl.source.PsiClassReferenceType
class ListenerEventAnnotator : Annotator {
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
if (!MinecraftSettings.instance.isShowEventListenerGutterIcons) {
return
}
// Since we want to line up with the method declaration, not the annotation
// declaration, we need to target identifiers, not just PsiMethods.
if (!(element is PsiIdentifier && element.getParent() is PsiMethod)) {
return
}
// The PsiIdentifier is going to be a method of course!
val method = element.getParent() as PsiMethod
if (method.hasModifierProperty(PsiModifier.ABSTRACT)) {
// I don't think any implementation allows for abstract
return
}
val modifierList = method.modifierList
val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return
val instance = MinecraftFacet.getInstance(module) ?: return
// Since each platform has their own valid listener annotations,
// some platforms may have multiple allowed annotations for various cases
val moduleTypes = instance.types
var contains = false
for (moduleType in moduleTypes) {
val listenerAnnotations = moduleType.listenerAnnotations
for (listenerAnnotation in listenerAnnotations) {
if (modifierList.findAnnotation(listenerAnnotation) != null) {
contains = true
break
}
}
}
if (!contains) {
return
}
val parameters = method.parameterList.parameters
if (parameters.isEmpty()) {
return
}
val eventParameter = parameters[0] ?: // Listeners must have at least a single parameter
return
// Get the type of the parameter so we can start resolving it
val psiEventElement = eventParameter.typeElement ?: return
val type = psiEventElement.type as? PsiClassReferenceType ?: return
// Validate that it is a class reference type
// And again, make sure that we can at least resolve the type, otherwise it's not a valid
// class reference.
val eventClass = type.resolve() ?: return
if (instance.isEventClassValid(eventClass, method)) {
return
}
if (!instance.isStaticListenerSupported(method) && method.hasModifierProperty(PsiModifier.STATIC)) {
if (method.nameIdentifier != null) {
holder.createErrorAnnotation(method.nameIdentifier!!, "Event listener method must not be static")
}
}
if (!isSuperEventListenerAllowed(eventClass, method, instance)) {
holder.createErrorAnnotation(eventParameter, instance.writeErrorMessageForEvent(eventClass, method))
}
}
private fun isSuperEventListenerAllowed(eventClass: PsiClass, method: PsiMethod, facet: MinecraftFacet): Boolean {
val supers = eventClass.supers
for (aSuper in supers) {
if (facet.isEventClassValid(aSuper, method)) {
return true
}
if (isSuperEventListenerAllowed(aSuper, method, facet)) {
return true
}
}
return false
}
}
| mit | 1e1bb50206fc116f8c48f5ddb8604cfd | 37.028846 | 118 | 0.65512 | 5.245358 | false | false | false | false |
zhoucong1020/cohttp | src/test/java/net/winsion/cohttp/API.kt | 1 | 911 | package net.winsion.cohttp
import net.winsion.cohttp.markers.*
interface API {
@GET("/v2/book/{id}")
suspend fun book(@Path("id") id: String): Book
@GET("/v2/book/{id}")
fun bookCancelableRequest(@Path("id") id: String): CancelableRequest<Book>
@GET("/mobile-api/q/train/getTodaySchedule")
fun getTodaySchedule(@Query("stationId") stationId: String): CancelableRequest<ResponseData<List<Train>>>
@FormUrlEncoded
@POST("/v3/dynamic/getCurrentTrainMessage")
fun getCurrentTrainMessageV3Cancelable(): CancelableRequest<ResponseData<CurrentTrainMessage>>
class Book {
var pubdate: String = ""
}
class ResponseData<T> {
var success: Boolean = false
var code: Int = 0
var message: String = ""
var data: T? = null
}
class Train {
var trainNumber: String = ""
}
class CurrentTrainMessage {
}
} | apache-2.0 | 515207942b752ef29d2e233fb2428556 | 23.648649 | 109 | 0.646542 | 4.048889 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/feed/news/NewsFragment.kt | 1 | 7068 | package org.wikipedia.feed.news
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityOptionsCompat
import androidx.core.os.bundleOf
import androidx.core.util.Pair
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.appbar.AppBarLayout.OnOffsetChangedListener
import org.wikipedia.Constants
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.R
import org.wikipedia.databinding.FragmentNewsBinding
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.feed.model.Card
import org.wikipedia.feed.view.ListCardItemView
import org.wikipedia.history.HistoryEntry
import org.wikipedia.json.GsonMarshaller
import org.wikipedia.json.GsonUnmarshaller
import org.wikipedia.page.ExclusiveBottomSheetPresenter
import org.wikipedia.page.PageActivity
import org.wikipedia.readinglist.AddToReadingListDialog
import org.wikipedia.readinglist.MoveToReadingListDialog
import org.wikipedia.readinglist.ReadingListBehaviorsUtil
import org.wikipedia.richtext.RichTextUtil
import org.wikipedia.util.*
import org.wikipedia.util.DeviceUtil
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.TabUtil
import org.wikipedia.views.DefaultRecyclerAdapter
import org.wikipedia.views.DefaultViewHolder
import org.wikipedia.views.DrawableItemDecoration
class NewsFragment : Fragment() {
private var _binding: FragmentNewsBinding? = null
private val binding get() = _binding!!
private val bottomSheetPresenter = ExclusiveBottomSheetPresenter()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
super.onCreateView(inflater, container, savedInstanceState)
_binding = FragmentNewsBinding.inflate(inflater, container, false)
appCompatActivity.setSupportActionBar(binding.toolbar)
appCompatActivity.supportActionBar?.setDisplayHomeAsUpEnabled(true)
appCompatActivity.supportActionBar?.title = ""
val item = GsonUnmarshaller.unmarshal(NewsItem::class.java,
requireActivity().intent.getStringExtra(NewsActivity.EXTRA_NEWS_ITEM))
val wiki = GsonUnmarshaller.unmarshal(WikiSite::class.java,
requireActivity().intent.getStringExtra(NewsActivity.EXTRA_WIKI))
L10nUtil.setConditionalLayoutDirection(binding.root, wiki.languageCode())
binding.gradientView.background = GradientUtil.getPowerGradient(R.color.black54, Gravity.TOP)
val imageUri = item.thumb()
if (imageUri == null) {
binding.appBarLayout.setExpanded(false, false)
}
binding.headerImageView.loadImage(imageUri)
DeviceUtil.updateStatusBarTheme(requireActivity(), binding.toolbar, true)
binding.appBarLayout.addOnOffsetChangedListener(OnOffsetChangedListener { layout, offset ->
DeviceUtil.updateStatusBarTheme(requireActivity(), binding.toolbar,
layout.totalScrollRange + offset > layout.totalScrollRange / 2)
(requireActivity() as NewsActivity).updateNavigationBarColor()
})
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
binding.toolbarContainer.setStatusBarScrimColor(ResourceUtil.getThemedColor(requireContext(), R.attr.paper_color))
}
binding.storyTextView.text = RichTextUtil.stripHtml(item.story())
binding.linksRecyclerView.layoutManager = LinearLayoutManager(requireContext())
binding.linksRecyclerView.addItemDecoration(DrawableItemDecoration(requireContext(),
R.attr.list_separator_drawable))
binding.linksRecyclerView.isNestedScrollingEnabled = false
binding.linksRecyclerView.adapter = RecyclerAdapter(item.linkCards(wiki), Callback())
return binding.root
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
private val appCompatActivity get() = requireActivity() as AppCompatActivity
private class RecyclerAdapter constructor(items: List<NewsLinkCard>, private val callback: Callback) :
DefaultRecyclerAdapter<NewsLinkCard, ListCardItemView>(items) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DefaultViewHolder<ListCardItemView> {
return DefaultViewHolder(ListCardItemView(parent.context))
}
override fun onBindViewHolder(holder: DefaultViewHolder<ListCardItemView>, position: Int) {
val card = item(position)
holder.view.setCard(card)
.setHistoryEntry(HistoryEntry(card.pageTitle(), HistoryEntry.SOURCE_NEWS))
.setCallback(callback)
}
}
private inner class Callback : ListCardItemView.Callback {
override fun onSelectPage(card: Card, entry: HistoryEntry, openInNewBackgroundTab: Boolean) {
if (openInNewBackgroundTab) {
TabUtil.openInNewBackgroundTab(entry)
FeedbackUtil.showMessage(requireActivity(), R.string.article_opened_in_background_tab)
} else {
startActivity(PageActivity.newIntentForNewTab(requireContext(), entry, entry.title))
}
}
override fun onSelectPage(card: Card, entry: HistoryEntry, sharedElements: Array<Pair<View, String>>) {
val options = ActivityOptionsCompat.makeSceneTransitionAnimation(requireActivity(), *sharedElements)
val intent = PageActivity.newIntentForNewTab(requireContext(), entry, entry.title)
if (sharedElements.isNotEmpty()) {
intent.putExtra(Constants.INTENT_EXTRA_HAS_TRANSITION_ANIM, true)
}
startActivity(intent, if (DimenUtil.isLandscape(requireContext()) || sharedElements.isEmpty()) null else options.toBundle())
}
override fun onAddPageToList(entry: HistoryEntry, addToDefault: Boolean) {
if (addToDefault) {
ReadingListBehaviorsUtil.addToDefaultList(requireActivity(), entry.title, InvokeSource.NEWS_ACTIVITY) { readingListId -> onMovePageToList(readingListId, entry) }
} else {
bottomSheetPresenter.show(childFragmentManager, AddToReadingListDialog.newInstance(entry.title, InvokeSource.NEWS_ACTIVITY))
}
}
override fun onMovePageToList(sourceReadingListId: Long, entry: HistoryEntry) {
bottomSheetPresenter.show(childFragmentManager, MoveToReadingListDialog.newInstance(sourceReadingListId, entry.title, InvokeSource.NEWS_ACTIVITY))
}
}
companion object {
fun newInstance(item: NewsItem, wiki: WikiSite): NewsFragment {
return NewsFragment().apply {
arguments = bundleOf(NewsActivity.EXTRA_NEWS_ITEM to GsonMarshaller.marshal(item),
NewsActivity.EXTRA_WIKI to GsonMarshaller.marshal(wiki))
}
}
}
}
| apache-2.0 | 8b5d3b5871e6eca658eda6f09f12a60f | 46.436242 | 177 | 0.735286 | 5.159124 | false | false | false | false |
AshishKayastha/Movie-Guide | app/src/main/kotlin/com/ashish/movieguide/ui/multisearch/fragment/MultiSearchFragment.kt | 1 | 3647 | package com.ashish.movieguide.ui.multisearch.fragment
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.ashish.movieguide.R
import com.ashish.movieguide.data.models.Movie
import com.ashish.movieguide.data.models.MultiSearch
import com.ashish.movieguide.data.models.Person
import com.ashish.movieguide.data.models.TVShow
import com.ashish.movieguide.di.modules.FragmentModule
import com.ashish.movieguide.di.multibindings.fragment.FragmentComponentBuilderHost
import com.ashish.movieguide.ui.base.recyclerview.BaseRecyclerViewFragment
import com.ashish.movieguide.ui.base.recyclerview.BaseRecyclerViewMvpView
import com.ashish.movieguide.ui.movie.detail.MovieDetailActivity
import com.ashish.movieguide.ui.people.detail.PersonDetailActivity
import com.ashish.movieguide.ui.tvshow.detail.TVShowDetailActivity
import com.ashish.movieguide.utils.Constants.ADAPTER_TYPE_MULTI_SEARCH
import com.ashish.movieguide.utils.Constants.MEDIA_TYPE_MOVIE
import com.ashish.movieguide.utils.Constants.MEDIA_TYPE_PERSON
import com.ashish.movieguide.utils.Constants.MEDIA_TYPE_TV
/**
* Created by Ashish on Jan 05.
*/
class MultiSearchFragment : BaseRecyclerViewFragment<MultiSearch,
BaseRecyclerViewMvpView<MultiSearch>, MultiSearchPresenter>() {
companion object {
@JvmStatic fun newInstance() = MultiSearchFragment()
}
override fun injectDependencies(builderHost: FragmentComponentBuilderHost) {
builderHost.getFragmentComponentBuilder(MultiSearchFragment::class.java,
MultiSearchFragmentComponent.Builder::class.java)
.withModule(FragmentModule(activity))
.build()
.inject(this)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
swipeRefreshLayout.isEnabled = false
}
override fun loadData() {
// no-op
}
fun searchQuery(query: String) {
recyclerViewAdapter.clearAll()
presenter?.setSearchQuery(query)
presenter?.loadFreshData(null)
}
override fun getAdapterType() = ADAPTER_TYPE_MULTI_SEARCH
override fun getEmptyTextId() = R.string.no_results_available
override fun getEmptyImageId() = R.drawable.ic_search_white_100dp
override fun getTransitionNameId(position: Int): Int {
val multiSearch = recyclerViewAdapter.getItem<MultiSearch>(position)
with(multiSearch) {
if (mediaType == MEDIA_TYPE_TV) {
return R.string.transition_tv_poster
} else if (mediaType == MEDIA_TYPE_PERSON) {
return R.string.transition_person_profile
} else {
return R.string.transition_movie_poster
}
}
}
override fun getDetailIntent(position: Int): Intent? {
val multiSearch = recyclerViewAdapter.getItem<MultiSearch>(position)
with(multiSearch) {
if (mediaType == MEDIA_TYPE_MOVIE) {
val movie = Movie(id, title, posterPath = posterPath)
return MovieDetailActivity.createIntent(activity, movie)
} else if (mediaType == MEDIA_TYPE_TV) {
val tvShow = TVShow(id, name, posterPath = posterPath)
return TVShowDetailActivity.createIntent(activity, tvShow)
} else if (mediaType == MEDIA_TYPE_PERSON) {
val people = Person(id, name, profilePath = profilePath)
return PersonDetailActivity.createIntent(activity, people)
} else {
return null
}
}
}
} | apache-2.0 | 8e915d67f855ef9c47ec11390cb57c8e | 37.4 | 83 | 0.698656 | 4.628173 | false | false | false | false |
Mark-Kovalyov/CardRaytracerBenchmark | kotlin-native/src/nativeMain/kotlin/app.kt | 1 | 7290 | import kotlinx.cinterop.alloc
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.ptr
import platform.posix.ceil
import platform.posix.exit
import platform.posix.gettimeofday
import platform.posix.pow
import platform.posix.sqrt
import platform.posix.timeval
fun main(args: Array<String?>) {
val start = now()
CardRaytracer().process()
// if (args.size == 0) {
// CardRaytracer().process()
// println("Elapsed time : ${(now() - start) / 1000} sec")
// exit(1)
// } else if (args.size == 1) {
// val os: OutputStream = Files.newOutputStream(Paths.get(args[0]))
// CardRaytracer(os).process()
// println("Elapsed time : ${(now() - start) / 1000} sec")
// exit(2)
// } else if (args.size == 3) {
// val os: OutputStream = Files.newOutputStream(Paths.get(args[0]))
// CardRaytracer(args[1]?.toInt(), args[2]?.toInt()).process()
// println("Elapsed time : ${(now() - start) / 1000} sec")
// exit(2)
// }
exit(0)
}
class VectorBox(var value: Vector)
class DoubleBox(var value: Double)
class Vector(val x: Double, val y: Double, val z: Double) {
fun sum(r: Vector): Vector {
return Vector(x + r.x, y + r.y, z + r.z)
}
fun sum(ax: Double, ay: Double, az: Double): Vector {
return Vector(x + ax, y + ay, z + az)
}
fun prod(r: Double): Vector {
return Vector(x * r, y * r, z * r)
}
fun sprod(r: Vector): Double {
return x * r.x + y * r.y + z * r.z
}
fun vprod(r: Vector): Vector {
return Vector(y * r.z - z * r.y,
z * r.x - x * r.z,
x * r.y - y * r.x)
}
fun norm(): Vector {
// return *this * (1 / sqrt(*this % *this));
return prod(1.0 / sqrt(sprod(this)))
}
}
class CardRaytracer {
var width = WIDTH
var height = HEIGHT
var oldI = 12357
fun Random(): Double {
oldI = (oldI * J + 1) % M
return oldI.toDouble() / M
}
fun tracer(o: Vector, d: Vector, t: DoubleBox, n: VectorBox): Int {
t.value = 1e9
var m = 0
val p = -o.z / d.z
if (0.01 < p) {
t.value = p
n.value = Z_ORTHO_VECTOR
m = 1
}
for (k in 18 downTo 0) {
for (j in 8 downTo 0) {
// if (G[j] & 1 << k)
if (G[j] and 1 shl k != 0) {
// Vector p = o + Vector(-k, 0, -j - 4);
val _p = o.sum(-k.toDouble(), 0.0, -j - 4.0)
// double b = p % d;
val b = _p.sprod(d)
// double c = p % p - 1;
val c = _p.sprod(_p) - 1.0
// double q = b * b - c;
val q = b * b - c
if (q > 0) {
val s: Double = -b - sqrt(q)
if (s < t.value && s > 0.01) {
t.value = s
// n = !(p + d * t);
n.value = _p.sum(d.prod(t.value)).norm()
m = 2
}
}
}
}
}
return m
}
/**
*
* @param o
* @param d
* @return Color of sample
*/
fun sampler(o: Vector, d: Vector): Vector {
val t: DoubleBox = DoubleBox(0.0)
val n: VectorBox = VectorBox(ZERO_VECTOR)
val m = tracer(o, d, t, n)
if (m == 0) {
// return Vector(.7, .6, 1) * pow(1 - d.z, 4);
return COLOR_SKY.prod(pow(1.0 - d.z, 4.0))
}
// Vector h = o + d * t;
var h = o.sum(d.prod(t.value))
// Vector l = !(Vector(9 + Random(), 9 + Random(), 16) + h * -1);
val l = Vector(9.0 + Random(), 9.0 + Random(), 16.0).sum(h.prod(-1.0)).norm()
// Vector r = d + n * (n % d * -2);
val r = d.sum(n.value.prod(n.value.sprod(d) * -2.0))
// double b = l % n;
var b = l.sprod(n.value)
if (b < 0 || tracer(h, l, t, n) != 0) {
b = 0.0
}
// double p = pow(l % r * (b > 0), 99);
val p: Double = pow(l.sprod(r) * if (b > 0) 1.0 else 0.0, 99.0)
if (m and 1 != 0) {
// h = h * .2;
h = h.prod(0.2)
// return ((int) (ceil(h.x) + ceil(h.y)) & 1 ?
// Vector(3, 1, 1) :
// Vector(3, 3, 3)) * (b * .2 + .1);
return (if ((ceil(h.x) + ceil(h.y)).toInt() and 1 != 0) COLOR_CELL1_VECTOR else COLOR_CELL2_VECTOR).prod(b * 0.2 + 0.1)
}
// return Vector(p, p, p) + sampler(h, r) * .5;
return Vector(p, p, p).sum(sampler(h, r).prod(0.5))
}
constructor(width: Int, height: Int) {
this.width = width
this.height = height
}
constructor()
fun process() {
// Vector g = !Vector(-6, -16, 0);
val g = CAMERA_DEST_VECTOR.norm()
// Vector a = !(Vector(0, 0, 1) ^ g) * .002;
val a = Z_ORTHO_VECTOR.vprod(g).norm().prod(0.002)
// Vector b = !(g ^ a) * .002;
val b = g.vprod(a).norm().prod(0.002)
// Vector c = (a + b) * -256 + g;
val c = a.sum(b).prod(-256.0).sum(g)
for (y in height - 1 downTo 0) {
for (x in width - 1 downTo 0) {
var p = COLOR_DARK_GRAY_VECTOR
for (r in 0 until SUB_SAMPLES) {
//Vector t = a * (Random() - .5) * 99 + b * (Random() - .5) * 99;
val t = a.prod(Random() - 0.5).prod(99.0).sum(b.prod(Random() - 0.5).prod(99.0))
//p = sampler(Vector(17, 16, 8) + t,
// !(t * -1 + (a * (Random() + x) + b * (y + Random()) + c) * 16)) * 3.5 + p;
p = sampler(CAMERA_ASPECT_VECTOR.sum(t),
t.prod(-1.0).sum(a.prod(Random() + x).sum(b.prod(Random() + y)).sum(c).prod(16.0)).norm()
).prod(3.5).sum(p)
}
val R = p.x.toInt()
val G = p.y.toInt()
val B = p.z.toInt()
}
}
}
companion object {
const val WIDTH = 512
const val HEIGHT = 512
const val SUB_SAMPLES = 64
// Position vectors:
val ZERO_VECTOR = Vector(0.0, 0.0, 0.0)
val Z_ORTHO_VECTOR = Vector(0.0, 0.0, 1.0)
val CAMERA_ASPECT_VECTOR = Vector(17.0, 16.0, 8.0)
val CAMERA_DEST_VECTOR = Vector(-6.0, -16.0, 0.0)
// Color vectors:
val COLOR_CELL1_VECTOR = Vector(3.0, 1.0, 1.0)
val COLOR_CELL2_VECTOR = Vector(3.0, 3.0, 3.0)
val COLOR_DARK_GRAY_VECTOR = Vector(13.0, 13.0, 13.0)
val COLOR_SKY = Vector(0.7, 0.6, 1.0)
val G = intArrayOf(
247570,
280596,
280600,
249748,
18578,
18577,
231184,
16,
16
)
const val M = 1048576 // 2^20
const val J = 2045
}
}
fun now() = memScoped {
val timeVal = alloc<timeval>()
gettimeofday(timeVal.ptr, null)
val sec = timeVal.tv_sec
val usec = timeVal.tv_usec
(sec * 1_000L) + (usec / 1_000L)
} | gpl-3.0 | d0dc6670248142786837e30c2b2efb95 | 31.695067 | 131 | 0.434431 | 3.140888 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/settings/NotificationSettingsPreferenceLoader.kt | 1 | 2474 | package org.wikipedia.settings
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.preference.PreferenceFragmentCompat
import org.wikipedia.R
import org.wikipedia.util.ResourceUtil.getThemedColor
internal class NotificationSettingsPreferenceLoader(fragment: PreferenceFragmentCompat) : BasePreferenceLoader(fragment) {
override fun loadPreferences() {
loadPreferences(R.xml.preferences_notifications)
var drawable = AppCompatResources.getDrawable(activity, R.drawable.ic_speech_bubbles)
DrawableCompat.setTint(drawable!!, getThemedColor(activity, R.attr.colorAccent))
findPreference(R.string.preference_key_notification_system_enable).icon = drawable
drawable = AppCompatResources.getDrawable(activity, R.drawable.ic_edit_progressive)
DrawableCompat.setTint(drawable!!, getThemedColor(activity, R.attr.colorAccent))
findPreference(R.string.preference_key_notification_milestone_enable).icon = drawable
drawable = AppCompatResources.getDrawable(activity, R.drawable.ic_user_talk)
DrawableCompat.setTint(drawable!!, ContextCompat.getColor(activity, R.color.green50))
findPreference(R.string.preference_key_notification_thanks_enable).icon = drawable
drawable = AppCompatResources.getDrawable(activity, R.drawable.ic_revert)
DrawableCompat.setTint(drawable!!, getThemedColor(activity, R.attr.material_theme_secondary_color))
findPreference(R.string.preference_key_notification_revert_enable).icon = drawable
drawable = AppCompatResources.getDrawable(activity, R.drawable.ic_mention)
DrawableCompat.setTint(drawable!!, getThemedColor(activity, R.attr.colorAccent))
findPreference(R.string.preference_key_notification_mention_enable).icon = drawable
drawable = AppCompatResources.getDrawable(activity, R.drawable.ic_user_avatar)
DrawableCompat.setTint(drawable!!, getThemedColor(activity, R.attr.material_theme_secondary_color))
findPreference(R.string.preference_key_notification_login_fail_enable).icon = drawable
drawable = AppCompatResources.getDrawable(activity, R.drawable.ic_edit_user_talk)
DrawableCompat.setTint(drawable!!, getThemedColor(activity, R.attr.colorAccent))
findPreference(R.string.preference_key_notification_user_talk_enable).icon = drawable
}
}
| apache-2.0 | e9c2359e33c82249be7605a809ad6ea9 | 59.341463 | 122 | 0.778901 | 4.730402 | false | false | false | false |
cdietze/klay | tripleklay/src/main/kotlin/tripleklay/ui/Scroller.kt | 1 | 26367 | package tripleklay.ui
import euklid.f.Dimension
import euklid.f.IDimension
import euklid.f.Point
import klay.core.*
import klay.scene.GroupLayer
import klay.scene.Interaction
import klay.scene.Layer
import klay.scene.Mouse
import react.Closeable
import react.Connection
import react.Signal
import tripleklay.ui.Scroller.Clippable
import tripleklay.ui.layout.AxisLayout
import tripleklay.ui.util.XYFlicker
import tripleklay.util.Colors
import tripleklay.util.Layers
import kotlin.reflect.KClass
/**
* A composite element that manages horizontal and vertical scrolling of a single content element.
* As shown below, the content can be thought of as moving around behind the scroll group, which is
* clipped to create a "view" to the content. Methods [.xpos] and [.ypos] allow reading
* the current position of the view. The view position can be set with [.scroll]. The view
* size and content size are available via [.viewSize] and [.contentSize].
* <pre>`Scrolled view (xpos,ypos>0) View unscrolled (xpos,ypos=0)
* --------------------------- ---------------------------
* | : | | Scroll | |
* | content : ypos | | Group | |
* | : | | "view" | |
* | ----------- | |---------- |
* | | Scroll | | | |
* |---xpos--->| Group | | | |
* | | "view" | | | content |
* | ----------- | | |
* --------------------------- ---------------------------
`</pre> *
*
* Scroll bars are configurable via the [.BAR_TYPE] style.
*
* NOTE: `Scroller` is a composite container, so callers can't add to or remove from it.
* To "add" elements, callers should set [.content] to a `Group` and add things to it
* instead.
*
* NOTE: scrolling is done by pointer events; there are two ways to provide interactive
* (clickable) content.
* * The first way is to pass `bubble=true` to [Pointer.Dispatcher]'s
* constructor. This allows any descendants within the content to be clicked normally. With this
* approach, after the pointer has been dragged more than a minimum distance, the `Scroller`
* calls [Interaction.capture], which will cancel all other pointer interactions, including
* clickable descendants. For buttons or toggles, this causes the element to be deselected,
* corresponding to popular mobile OS conventions.
* * The second way is to use the [.contentClicked] signal. This is more lightweight but
* only emits after the pointer is released less than a minimum distance away from its starting
* position.
* TODO: some way to handle keyboard events (complicated by lack of a focus element)
* TODO: more fine-grained setPropagateEvents (add a flag to klay Layer?)
* TODO: temporarily allow drags past the min/max scroll positions and bounce back
*/
class Scroller
/**
* Creates a new scroller containing the given content and with [Scroller.Behavior.BOTH].
*
* If the content is an instance of [Clippable], then translation will occur via that
* interface. Otherwise, the content's layer translation will be set directly. Graphics level
* clipping is always performed.
*/
(content: Element<*>) : Composite<Scroller>() {
/**
* Interface for customizing how content is clipped and translated.
* @see Scroller.Scroller
*/
interface Clippable {
/**
* Sets the size of the area the content should clip to. In the default clipping, this
* has no effect (it relies solely on the clipped group surrounding the content).
* This will always be called prior to `setPosition`.
*/
fun setViewArea(width: Float, height: Float)
/**
* Sets the translation of the content, based on scroll bar positions. Both numbers will
* be non-positive, up to the maximum position of the content such that its right or
* bottom edge aligns with the width or height of the view area, respectively. For the
* default clipping, this just sets the translation of the content's layer.
*/
fun setPosition(x: Float, y: Float)
}
/**
* Handles creating the scroll bars.
*/
abstract class BarType {
/**
* Creates the scroll bars.
*/
abstract fun createBars(scroller: Scroller): Bars
}
/**
* Listens for changes to the scrolling area or offset.
*/
interface Listener {
/**
* Notifies this listener of changes to the content size or scroll size. Normally this
* happens when either the content or scroll group is validated.
* @param contentSize the new size of the content
* *
* @param scrollSize the new size of the viewable area
*/
fun viewChanged(contentSize: IDimension, scrollSize: IDimension)
/**
* Notifies this listener of changes to the content offset. Note the offset values are
* positive numbers, so correspond to the position of the view area over the content.
* @param xpos the horizontal amount by which the view is offset
* *
* @param ypos the vertical amount by which the view is offset
*/
fun positionChanged(xpos: Float, ypos: Float)
}
/**
* Defines the directions available for scrolling.
*/
enum class Behavior {
HORIZONTAL, VERTICAL, BOTH;
fun hasHorizontal(): Boolean {
return this == HORIZONTAL || this == BOTH
}
fun hasVertical(): Boolean {
return this == VERTICAL || this == BOTH
}
}
/**
* A range along an axis for representing scroll bars. Using the content and view extent,
* calculates the relative sizes.
*/
class Range {
/**
* Returns the maximum value that this range can have, in content offset coordinates.
*/
fun max(): Float {
return _max
}
/**
* Tests if the range is currently active. A range is inactive if it's turned off
* explicitly or if the view size is larger than the content size.
*/
fun active(): Boolean {
return _max != 0f
}
/** Gets the size of the content along this range's axis. */
fun contentSize(): Float {
return if (_on) _csize else _size
}
/** Gets the size of the view along this scroll bar's axis. */
fun viewSize(): Float {
return _size
}
/** Gets the current content offset. */
fun contentPos(): Float {
return _cpos
}
fun setOn(on: Boolean) {
_on = on
}
fun on(): Boolean {
return _on
}
/** Set the view size and content size along this range's axis. */
fun setRange(viewSize: Float, contentSize: Float): Float {
_size = viewSize
_csize = contentSize
if (!_on || _size >= _csize) {
// no need to render, clear fields
_cpos = 0f
_pos = _cpos
_extent = _pos
_max = _extent
return 0f
} else {
// prepare rendering fields
_max = _csize - _size
_extent = _size * _size / _csize
_pos = minOf(_pos, _size - _extent)
_cpos = _pos / (_size - _extent) * _max
return _cpos
}
}
/** Sets the position of the content along this range's axis. */
fun set(cpos: Float): Boolean {
if (cpos == _cpos) return false
_cpos = cpos
_pos = if (_max == 0f) 0f else cpos / _max * (_size - _extent)
return true
}
/** During size computation, extends the provided hint. */
fun extendHint(hint: Float): Float {
// we want the content to take up as much space as it wants if this bar is on
// TODO: use Float.MAX? that may cause trouble in other layout code
return if (_on) 100000f else hint
}
/** If this range is in use. Set according to [Scroller.Behavior]. */
private var _on = true
/** View size. */
var _size: Float = 0.toFloat()
/** Content size. */
private var _csize: Float = 0.toFloat()
/** Bar offset. */
var _pos: Float = 0.toFloat()
/** Content offset. */
var _cpos: Float = 0.toFloat()
/** Thumb size. */
var _extent: Float = 0.toFloat()
/** The maximum position the content can have. */
var _max: Float = 0.toFloat()
}
/**
* Handles the appearance and animation of scroll bars.
*/
abstract class Bars
/**
* Creates new bars for the given `Scroller`.
*/
protected constructor(protected val _scroller: Scroller) : Closeable {
/**
* Updates the scroll bars to match the current view and content size. This will be
* called during layout, prior to the call to [.layer].
*/
fun updateView() {}
/**
* Gets the layer to display the scroll bars. It gets added to the same parent as the
* content's.
*/
abstract fun layer(): Layer
/**
* Updates the scroll bars' time based animation, if any, after the given time delta.
*/
open fun update(dt: Float) {}
/**
* Updates the scroll bars' positions. Not necessary for immediate layer bars.
*/
open fun updatePosition() {}
/**
* Destroys the resources created by the bars.
*/
override fun close() {
layer().close()
}
/**
* Space consumed by active scroll bars.
*/
fun size(): Float {
return 0f
}
}
/**
* Plain rectangle scroll bars that overlay the content area, consume no additional screen
* space, and fade out after inactivity. Ideal for drag scrolling on a mobile device.
*/
class TouchBars(scroller: Scroller, private var _color: Int, private var _size: Float,
private var _topAlpha: Float, private var _fadeSpeed: Float) : Bars(scroller) {
private var _alpha: Float = 0.toFloat()
private var _layer: Layer
init {
_layer = object : Layer() {
override fun paintImpl(surface: Surface) {
surface.saveTx()
surface.setFillColor(_color)
val h = _scroller.hrange
val v = _scroller.vrange
if (h.active()) drawBar(surface, h._pos, v._size - _size, h._extent, _size)
if (v.active()) drawBar(surface, h._size - _size, v._pos, _size, v._extent)
surface.restoreTx()
}
}
}
override fun update(delta: Float) {
// fade out the bars
if (_alpha > 0 && _fadeSpeed > 0) setBarAlpha(_alpha - _fadeSpeed * delta)
}
override fun updatePosition() {
// whenever the position changes, update to full visibility
setBarAlpha(_topAlpha)
}
override fun layer(): Layer {
return _layer
}
private fun setBarAlpha(alpha: Float) {
_alpha = minOf(_topAlpha, maxOf(0f, alpha))
_layer.setAlpha(minOf(_alpha, 1f))
_layer.setVisible(_alpha > 0)
}
private fun drawBar(surface: Surface, x: Float, y: Float, w: Float, h: Float) {
surface.fillRect(x, y, w, h)
}
}
/** The content contained in the scroller. */
val content: Element<*>
/** Scroll ranges. */
val hrange = createRange()
val vrange = createRange()
private val _scroller: Group
private val _flicker: XYFlicker
private val _clippable: Clippable
private val _contentSize = Dimension()
private var _upconn: Connection? = null
private var _queuedScroll: Point? = null
private var _lners: MutableList<Listener>? = null
/** Scroll bar type, used to determine if the bars need to be recreated. */
private var _barType: BarType? = null
/** Scroll bars, created during layout, based on the [BarType]. */
private var _bars: Bars? = null
/** Region around elements when updating visibility. */
private var _elementBuffer: IDimension? = null
init {
layout = AxisLayout.horizontal().stretchByDefault().offStretch().gap(0)
// our only immediate child is the _scroller, and that contains the content
_scroller = object : Group(ScrollLayout()) {
override fun createLayer(): GroupLayer {
// use 1, 1 so we don't crash. the real size is set on validation
return GroupLayer(1f, 1f)
}
override fun layout() {
super.layout()
// do this after children have validated their bounding boxes
updateVisibility()
}
}
initChildren(_scroller)
this.content = content
_scroller.add(this.content)
// use the content's clipping method if it is Clippable
if (content is Clippable) {
_clippable = content
} else {
// otherwise, clip using layer translation
_clippable = object : Clippable {
override fun setViewArea(width: Float, height: Float) { /* noop */
}
override fun setPosition(x: Float, y: Float) {
[email protected](x, y)
}
}
}
// absorb clicks so that pointer drag can always scroll
set(Element.Flag.HIT_ABSORB, true)
// handle mouse wheel
layer.events().connect(object : Mouse.Listener {
override fun onWheel(event: klay.core.Mouse.WheelEvent, iact: Mouse.Interaction) {
// scale so each wheel notch is 1/4 the screen dimension
val delta = event.velocity * .25f
if (vrange.active())
scrollY(ypos() + (delta * viewSize().height) as Int)
else
scrollX(xpos() + (delta * viewSize().width) as Int)
}
})
// handle drag scrolling
_flicker = XYFlicker()
layer.events().connect(_flicker)
}
/**
* Sets the behavior of this scroller.
*/
fun setBehavior(beh: Behavior): Scroller {
hrange.setOn(beh.hasHorizontal())
vrange.setOn(beh.hasVertical())
invalidate()
return this
}
/**
* Adds a listener to be notified of this scroller's changes.
*/
fun addListener(lner: Listener) {
if (_lners == null) _lners = ArrayList<Listener>()
_lners!!.add(lner)
}
/**
* Removes a previously added listener from this scroller.
*/
fun removeListener(lner: Listener) {
if (_lners != null) _lners!!.remove(lner)
}
/**
* Returns the offset of the left edge of the view area relative to that of the content.
*/
fun xpos(): Float {
return hrange._cpos
}
/**
* Returns the offset of the top edge of the view area relative to that of the content.
*/
fun ypos(): Float {
return vrange._cpos
}
/**
* Sets the left edge of the view area relative to that of the content. The value is clipped
* to be within its valid range.
*/
fun scrollX(x: Float) {
scroll(x, ypos())
}
/**
* Sets the top edge of the view area relative to that of the content. The value is clipped
* to be within its valid range.
*/
fun scrollY(y: Float) {
scroll(xpos(), y)
}
/**
* Sets the left and top of the view area relative to that of the content. The values are
* clipped to be within their respective valid ranges.
*/
fun scroll(x: Float, y: Float) {
var x = x
var y = y
x = maxOf(0f, minOf(x, hrange._max))
y = maxOf(0f, minOf(y, vrange._max))
_flicker.positionChanged(x, y)
}
/**
* Sets the left and top of the view area relative to that of the content the next time the
* container is laid out. This is needed if the caller invalidates the content and needs
* to then set a scroll position which may be out of range for the old size.
*/
fun queueScroll(x: Float, y: Float) {
_queuedScroll = Point(x, y)
}
/**
* Gets the size of the content that we are responsible for scrolling. Scrolling is active for
* a given axis when this is larger than [.viewSize] along that axis.
*/
fun contentSize(): IDimension {
return _contentSize
}
/**
* Gets the size of the view which renders some portion of the content.
*/
fun viewSize(): IDimension {
return _scroller.size()
}
/**
* Gets the signal dispatched when a pointer click occurs in the scroller. This happens
* only when the drag was not far enough to cause appreciable scrolling.
*/
fun contentClicked(): Signal<Pointer.Event> {
return _flicker.clicked
}
/** Prepares the scroller for the next frame, at t = t + delta. */
private fun update(delta: Float) {
_flicker.update(delta)
update(false)
if (_bars != null) _bars!!.update(delta)
}
/** Updates the position of the content to match the flicker. If force is set, then the
* relevant values will be updated even if there was no change. */
private fun update(force: Boolean) {
val pos = _flicker.position()
val dx = hrange.set(pos.x)
val dy = vrange.set(pos.y)
if (dx || dy || force) {
_clippable.setPosition(-pos.x, -pos.y)
// now check the child elements for visibility
if (!force) updateVisibility()
firePositionChange()
if (_bars != null) _bars!!.updatePosition()
}
}
/**
* A method for creating our `Range` instances. This is called once each for `hrange` and `vrange` at creation time. Overriding this method will allow subclasses
* to customize `Range` behavior.
*/
private fun createRange(): Range {
return Range()
}
/** Extends the usual layout with scroll bar setup. */
private inner class BarsLayoutData : LayoutData() {
val barType = resolveStyle(BAR_TYPE)
}
override fun createLayoutData(hintX: Float, hintY: Float): LayoutData {
return BarsLayoutData()
}
override val styleClass: KClass<*>
get() = Scroller::class
override fun wasAdded() {
super.wasAdded()
_upconn = root()!!.iface.frame.connect({ clock: Clock ->
update(clock.dt.toFloat())
})
invalidate()
}
override fun wasRemoved() {
_upconn?.close()
updateBars(null) // make sure bars get destroyed in case we don't get added again
super.wasRemoved()
}
/** Hides the layers of any children of the content that are currently visible but outside
* the clipping area. */
// TODO: can we get the performance win without being so intrusive?
private fun updateVisibility() {
// only Container can participate, others must implement Clippable and do something else
if (content !is Container<*>) {
return
}
// hide the layer of any child of content that isn't in bounds
val x = hrange._cpos
val y = vrange._cpos
val wid = hrange._size
val hei = vrange._size
val bx = _elementBuffer!!.width
val by = _elementBuffer!!.height
for (child in content) {
val size = child.size()
if (child.isVisible)
child.layer.setVisible(
child.x() - bx < x + wid && child.x() + size.width + bx > x &&
child.y() - by < y + hei && child.y() + size.height + by > y)
}
}
/** Dispatches a [Listener.viewChanged] to listeners. */
private fun fireViewChanged() {
if (_lners == null) return
val csize = contentSize()
val ssize = viewSize()
for (lner in _lners!!) {
lner.viewChanged(csize, ssize)
}
}
/** Dispatches a [Listener.positionChanged] to listeners. */
private fun firePositionChange() {
if (_lners == null) return
for (lner in _lners!!) {
lner.positionChanged(xpos(), ypos())
}
}
private fun updateBars(barType: BarType?) {
if (_bars != null) {
if (_barType === barType) return
_bars!!.close()
_bars = null
}
_barType = barType
if (_barType != null) _bars = _barType!!.createBars(this)
}
override fun layout(ldata: LayoutData, left: Float, top: Float,
width: Float, height: Float) {
// set the bars and element buffer first so the ScrollLayout can use them
_elementBuffer = resolveStyle(ELEMENT_BUFFER)
updateBars((ldata as BarsLayoutData).barType)
super.layout(ldata, left, top, width, height)
if (_bars != null) layer.add(_bars!!.layer().setDepth(1f).setTranslation(left, top))
}
/** Lays out the internal scroller group that contains the content. Performs all the jiggery
* pokery necessary to make the content think it is in a large area and update the outer
* `Scroller` instance. */
private inner class ScrollLayout : Layout() {
override fun computeSize(elems: Container<*>, hintX: Float, hintY: Float): Dimension {
// the content is always the 1st child, get the preferred size with extended hints
assert(elems.childCount() == 1 && elems.childAt(0) === content)
_contentSize.setSize(preferredSize(elems.childAt(0),
hrange.extendHint(hintX), vrange.extendHint(hintY)))
return Dimension(_contentSize)
}
override fun layout(elems: Container<*>, left: Float, top: Float, width: Float,
height: Float) {
var left = left
var top = top
var width = width
var height = height
assert(elems.childCount() == 1 && elems.childAt(0) === content)
// if we're going to have H or V scrolling, make room on the bottom and/or right
if (hrange.on() && _contentSize.width > width) height -= _bars!!.size()
if (vrange.on() && _contentSize.height > height) width -= _bars!!.size()
// reset ranges
left = hrange.setRange(width, _contentSize.width)
top = vrange.setRange(height, _contentSize.height)
// let the bars know about the range change
if (_bars != null) _bars!!.updateView()
// set the content bounds to the large virtual area starting at 0, 0
setBounds(content, 0f, 0f, hrange.contentSize(), vrange.contentSize())
// clip the content in its own special way
_clippable.setViewArea(width, height)
// clip the scroller layer too, can't hurt
_scroller.layer.setSize(width, height)
// reset the flicker (it retains its current position)
_flicker.reset(hrange.max(), vrange.max())
// scroll the content
if (_queuedScroll != null) {
scroll(_queuedScroll!!.x, _queuedScroll!!.y)
_queuedScroll = null
} else {
scroll(left, top)
}
// force an update so the scroll bars have properly aligned positions
update(true)
// notify listeners of a view change
fireViewChanged()
}
}
companion object {
/** The type of bars to use. By default, uses an instance of [TouchBars]. */
val BAR_TYPE = Style.newStyle<BarType>(true, object : BarType() {
override fun createBars(scroller: Scroller): Bars {
return TouchBars(scroller, Color.withAlpha(Colors.BLACK, 128), 5f, 3f, 1.5f / 1000)
}
})
/** The buffer around a child element when updating visibility ([.updateVisibility].
* The default value (0x0) causes any elements whose exact bounds lie outside the clipped
* area to be culled. If elements are liable to have overhanging layers, the value can be set
* larger appropriately. */
val ELEMENT_BUFFER = Style.newStyle<IDimension>(true, Dimension(0f, 0f))
/**
* Finds the closest ancestor of the given element that is a `Scroller`, or null if
* there isn't one. This uses the tripleplay ui hierarchy.
*/
fun findScrollParent(elem: Element<*>?): Scroller? {
var elem = elem
while (elem != null && elem !is Scroller) {
elem = elem.parent()
}
return elem as Scroller?
}
/**
* Attempts to scroll the given element into view.
* @return true if successful
*/
fun makeVisible(elem: Element<*>): Boolean {
val scroller = findScrollParent(elem) ?: return false
// the element in question may have been added and then immediately scrolled to, which
// means it hasn't been laid out yet and does not have its proper position; in that case
// defer this process a tick to allow it to be laid out
if (!scroller.isSet(Element.Flag.VALID)) {
elem.root()!!.iface.frame.connect({
makeVisible(elem)
}).once()
return true
}
val offset = Layers.transform(Point(0f, 0f), elem.layer, scroller.content.layer)
scroller.scroll(offset.x, offset.y)
return true
}
}
}
| apache-2.0 | 2f25b8d2ac0f2f74d9e9407a5214d1ac | 34.202937 | 165 | 0.568514 | 4.487236 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/data/InstalledPackagesUtils.kt | 2 | 12997 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.data
import com.intellij.buildsystem.model.unified.UnifiedCoordinates
import com.intellij.buildsystem.model.unified.UnifiedDependency
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.io.DigestUtil
import com.jetbrains.packagesearch.intellij.plugin.PluginEnvironment
import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyDeclarationIndexes
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleOperationProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.asDependency
import com.jetbrains.packagesearch.intellij.plugin.extensibility.key
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.DependencyUsageInfo
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.InstalledDependency
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ProjectDataProvider
import com.jetbrains.packagesearch.intellij.plugin.util.TraceInfo
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import com.jetbrains.packagesearch.intellij.plugin.util.logError
import com.jetbrains.packagesearch.intellij.plugin.util.packageVersionNormalizer
import com.jetbrains.packagesearch.intellij.plugin.util.parallelMap
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.yield
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.descriptors.element
import kotlinx.serialization.encodeToString
import kotlinx.serialization.encoding.CompositeDecoder.Companion.DECODE_DONE
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.encoding.decodeStructure
import kotlinx.serialization.encoding.encodeStructure
import kotlinx.serialization.json.Json
import java.io.File
import java.nio.file.Path
import kotlin.io.path.absolutePathString
internal suspend fun installedPackages(
dependenciesByModule: Map<ProjectModule, List<ResolvedUnifiedDependency>>,
project: Project,
dataProvider: ProjectDataProvider,
traceInfo: TraceInfo
): List<PackageModel.Installed> {
val usageInfoByDependency = mutableMapOf<UnifiedDependency, MutableList<DependencyUsageInfo>>()
for (module in dependenciesByModule.keys) {
dependenciesByModule[module]?.forEach { (dependency, resolvedVersion, declarationIndexInBuildFile) ->
yield()
val usageInfo = DependencyUsageInfo(
projectModule = module,
declaredVersion = PackageVersion.from(dependency.coordinates.version),
resolvedVersion = PackageVersion.from(resolvedVersion),
scope = PackageScope.from(dependency.scope),
userDefinedScopes = module.moduleType.userDefinedScopes(project)
.map { rawScope -> PackageScope.from(rawScope) },
declarationIndexInBuildFile = declarationIndexInBuildFile
)
val usageInfoList = usageInfoByDependency.getOrPut(dependency) { mutableListOf() }
usageInfoList.add(usageInfo)
}
}
val installedDependencies = dependenciesByModule.values.flatten()
.mapNotNull { InstalledDependency.from(it.dependency) }
val dependencyRemoteInfoMap = dataProvider.fetchInfoFor(installedDependencies, traceInfo)
return usageInfoByDependency.parallelMap { (dependency, usageInfo) ->
val installedDependency = InstalledDependency.from(dependency)
val remoteInfo = if (installedDependency != null) {
dependencyRemoteInfoMap[installedDependency]
} else {
null
}
PackageModel.fromInstalledDependency(
unifiedDependency = dependency,
usageInfo = usageInfo,
remoteInfo = remoteInfo,
normalizer = packageVersionNormalizer
)
}.filterNotNull().sortedBy { it.sortKey }
}
internal suspend fun fetchProjectDependencies(
modules: List<ProjectModule>,
cacheDirectory: Path,
json: Json
) = coroutineScope {
modules.associateWith { module -> async { module.installedDependencies(cacheDirectory, json) } }
.mapValues { (_, value) -> value.await() }
}
internal suspend fun ProjectModule.installedDependencies(cacheDirectory: Path, json: Json) = coroutineScope {
val fileHashCode = buildFile.hashCode()
val cacheFile = File(cacheDirectory.absolutePathString(), "$fileHashCode.json")
if (!cacheFile.exists()) withContext(Dispatchers.IO) {
cacheFile.apply { parentFile.mkdirs() }.createNewFile()
}
val sha256Deferred: Deferred<String> = async(AppExecutorUtil.getAppExecutorService().asCoroutineDispatcher()) {
StringUtil.toHexString(DigestUtil.sha256().digest(buildFile.contentsToByteArray()))
}
val cachedContents = withContext(Dispatchers.IO) { kotlin.runCatching { cacheFile.readText() } }
.onFailure { logDebug("installedDependencies", it) { "Someone messed with our cache file UGH ${cacheFile.absolutePath}" } }
.getOrNull()
?.takeIf { it.isNotBlank() }
val cache = if (cachedContents != null) {
// TODO: consider invalidating when ancillary files change (e.g., gradle.properties)
runCatching { json.decodeFromString<InstalledDependenciesCache>(cachedContents) }
.onFailure { logDebug("installedDependencies", it) { "Dependency JSON cache file read failed for ${buildFile.path}" } }
.getOrNull()
} else {
null
}
val sha256 = sha256Deferred.await()
if (
cache?.sha256 == sha256
&& cache.fileHashCode == fileHashCode
&& cache.cacheVersion == PluginEnvironment.Caches.version
// if dependencies are empty it could be because build APIs have previously failed
&& (cache.dependencies.isNotEmpty() || cache.parsingAttempts >= PluginEnvironment.Caches.maxAttempts)
) {
return@coroutineScope cache.dependencies
}
val declaredDependencies =
runCatching { ProjectModuleOperationProvider.forProjectModuleType(moduleType)?.declaredDependenciesInModule(this@installedDependencies) }
.onFailure { logDebug("installedDependencies", it) { "Unable to list dependencies in module $name" } }
.getOrNull()
?.toList()
?: emptyList()
val scopes = declaredDependencies.mapNotNull { it.scope }.toSet()
val resolvedDependenciesMapJob = async {
runCatching {
ProjectModuleOperationProvider.forProjectModuleType(moduleType)
?.resolvedDependenciesInModule(this@installedDependencies, scopes)
?.mapNotNull { dep -> dep.key?.let { it to dep.coordinates.version } }
?.toMap()
?: emptyMap()
}.onFailure { logError("Error while evaluating resolvedDependenciesInModule for $name", it) }
.getOrElse { emptyMap() }
}
val dependenciesLocationMap = declaredDependencies
.mapNotNull {
it.asDependency()
?.let { dependencyDeclarationCallback(it) }
?.let { location -> it to location }
}
.toMap()
val resolvedDependenciesMap = resolvedDependenciesMapJob.await()
val dependencies: List<ResolvedUnifiedDependency> =
declaredDependencies.map { ResolvedUnifiedDependency(it, resolvedDependenciesMap[it.key], dependenciesLocationMap[it]) }
nativeModule.project.lifecycleScope.launch {
val jsonText = json.encodeToString(
value = InstalledDependenciesCache(
cacheVersion = PluginEnvironment.Caches.version,
fileHashCode = fileHashCode,
sha256 = sha256,
parsingAttempts = cache?.parsingAttempts?.let { it + 1 } ?: 1,
projectName = name,
dependencies = dependencies
)
)
cacheFile.writeText(jsonText)
}
dependencies
}
@Serializable
internal data class InstalledDependenciesCache(
val cacheVersion: Int,
val fileHashCode: Int,
val sha256: String,
val parsingAttempts: Int = 0,
val projectName: String,
val dependencies: List<ResolvedUnifiedDependency>
)
@Serializable
data class ResolvedUnifiedDependency(
val dependency: @Serializable(with = UnifiedDependencySerializer::class) UnifiedDependency,
val resolvedVersion: String? = null,
val declarationIndexes: DependencyDeclarationIndexes?
)
internal object UnifiedCoordinatesSerializer : KSerializer<UnifiedCoordinates> {
override val descriptor = buildClassSerialDescriptor(UnifiedCoordinates::class.qualifiedName!!) {
element<String>("groupId", isOptional = true)
element<String>("artifactId", isOptional = true)
element<String>("version", isOptional = true)
}
override fun deserialize(decoder: Decoder) = decoder.decodeStructure(descriptor) {
var groupId: String? = null
var artifactId: String? = null
var version: String? = null
loop@ while (true) {
when (val index = decodeElementIndex(descriptor)) {
DECODE_DONE -> break@loop
0 -> groupId = decodeStringElement(descriptor, 0)
1 -> artifactId = decodeStringElement(descriptor, 1)
2 -> version = decodeStringElement(descriptor, 2)
else -> throw SerializationException("Unexpected index $index")
}
}
UnifiedCoordinates(groupId, artifactId, version)
}
override fun serialize(encoder: Encoder, value: UnifiedCoordinates) = encoder.encodeStructure(descriptor) {
value.groupId?.let { encodeStringElement(descriptor, 0, it) }
value.artifactId?.let { encodeStringElement(descriptor, 1, it) }
value.version?.let { encodeStringElement(descriptor, 2, it) }
}
}
internal object UnifiedDependencySerializer : KSerializer<UnifiedDependency> {
override val descriptor = buildClassSerialDescriptor(UnifiedDependency::class.qualifiedName!!) {
element("coordinates", UnifiedCoordinatesSerializer.descriptor)
element<String>("scope", isOptional = true)
}
override fun deserialize(decoder: Decoder) = decoder.decodeStructure(descriptor) {
var coordinates: UnifiedCoordinates? = null
var scope: String? = null
loop@ while (true) {
when (val index = decodeElementIndex(descriptor)) {
DECODE_DONE -> break@loop
0 -> coordinates = decodeSerializableElement(descriptor, 0, UnifiedCoordinatesSerializer)
1 -> scope = decodeStringElement(descriptor, 1)
else -> throw SerializationException("Unexpected index $index")
}
}
UnifiedDependency(
coordinates = requireNotNull(coordinates) { "coordinates property missing while deserializing ${UnifiedDependency::class.qualifiedName}" },
scope = scope
)
}
override fun serialize(encoder: Encoder, value: UnifiedDependency) = encoder.encodeStructure(descriptor) {
encodeSerializableElement(descriptor, 0, UnifiedCoordinatesSerializer, value.coordinates)
value.scope?.let { encodeStringElement(descriptor, 1, it) }
}
} | apache-2.0 | 1246ca457b6c28424945ec85ccfc4f46 | 44.131944 | 151 | 0.714319 | 5.253436 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/sns/src/main/kotlin/com/kotlin/sns/ListTags.kt | 1 | 1697 | // snippet-sourcedescription:[ListTags.kt demonstrates how to retrieve tags from an Amazon Simple Notification Service (Amazon SNS) topic.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-keyword:[Amazon Simple Notification Service]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.sns
// snippet-start:[sns.kotlin.list_tags.import]
import aws.sdk.kotlin.services.sns.SnsClient
import aws.sdk.kotlin.services.sns.model.ListTagsForResourceRequest
import kotlin.system.exitProcess
// snippet-end:[sns.kotlin.list_tags.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage: <topicArn>
Where:
topicArn - The ARN of the topic from which tags are listed.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val topicArn = args[0]
listTopicTags(topicArn)
}
// snippet-start:[sns.kotlin.list_tags.main]
suspend fun listTopicTags(topicArn: String?) {
val tagsForResourceRequest = ListTagsForResourceRequest {
resourceArn = topicArn
}
SnsClient { region = "us-east-1" }.use { snsClient ->
val response = snsClient.listTagsForResource(tagsForResourceRequest)
println("Tags for topic $topicArn are " + response.tags)
}
}
// snippet-end:[sns.kotlin.list_tags.main]
| apache-2.0 | 14f9c0504fd4f893e2c5b6e5fead1ad4 | 28.854545 | 139 | 0.687684 | 3.77951 | false | false | false | false |
android/location-samples | ForegroundLocationUpdates/app/src/main/java/com/google/android/gms/location/sample/foregroundlocation/ForegroundLocationService.kt | 1 | 10155 | /*
* Copyright (C) 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.gms.location.sample.foregroundlocation
import android.Manifest.permission
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.location.Location
import android.os.Binder
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import com.google.android.gms.location.sample.foregroundlocation.ForegroundLocationService.LocalBinder
import com.google.android.gms.location.sample.foregroundlocation.data.LocationPreferences
import com.google.android.gms.location.sample.foregroundlocation.data.LocationRepository
import com.google.android.gms.location.sample.foregroundlocation.ui.hasPermission
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* Service which manages turning location updates on and off. UI clients should bind to this service
* to access this functionality.
*
* This service can be started the usual way (i.e. startService), but it will also start itself when
* the first client binds to it. Thereafter it will manage its own lifetime as follows:
* - While there are any bound clients, the service remains started in the background. If it was
* in the foreground, it will exit the foreground, cancelling any ongoing notification.
* - When there are no bound clients and location updates are on, the service moves to the
* foreground and shows an ongoing notification with the latest location.
* - When there are no bound clients and location updates are off, the service stops itself.
*/
@AndroidEntryPoint
class ForegroundLocationService : LifecycleService() {
@Inject
lateinit var locationRepository: LocationRepository
@Inject
lateinit var locationPreferences: LocationPreferences
private val localBinder = LocalBinder()
private var bindCount = 0
private var started = false
private var isForeground = false
private fun isBound() = bindCount > 0
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
// This action comes from our ongoing notification. The user requested to stop updates.
if (intent?.action == ACTION_STOP_UPDATES) {
stopLocationUpdates()
lifecycleScope.launch {
locationPreferences.setLocationTurnedOn(false)
}
}
// Startup tasks only happen once.
if (!started) {
started = true
// Check if we should turn on location updates.
lifecycleScope.launch {
if (locationPreferences.isLocationTurnedOn.first()) {
// If the service is restarted for any reason, we may have lost permission to
// access location since last time. In that case we won't turn updates on here,
// and the service will stop when we manage its lifetime below. Then the user
// will have to open the app to turn updates on again.
if (hasPermission(permission.ACCESS_FINE_LOCATION) ||
hasPermission(permission.ACCESS_COARSE_LOCATION)
) {
locationRepository.startLocationUpdates()
}
}
}
// Update any foreground notification when we receive location updates.
lifecycleScope.launch {
locationRepository.lastLocation.collect(::showNotification)
}
}
// Decide whether to remain in the background, promote to the foreground, or stop.
manageLifetime()
// In case we are stopped by the system, have the system restart this service so we can
// manage our lifetime appropriately.
return START_STICKY
}
override fun onBind(intent: Intent): IBinder {
super.onBind(intent)
handleBind()
return localBinder
}
override fun onRebind(intent: Intent?) {
handleBind()
}
private fun handleBind() {
bindCount++
// Start ourself. This will let us manage our lifetime separately from bound clients.
startService(Intent(this, this::class.java))
}
override fun onUnbind(intent: Intent?): Boolean {
bindCount--
lifecycleScope.launch {
// UI client can unbind because it went through a configuration change, in which case it
// will be recreated and bind again shortly. Wait a few seconds, and if still not bound,
// manage our lifetime accordingly.
delay(UNBIND_DELAY_MILLIS)
manageLifetime()
}
// Allow clients to rebind, in which case onRebind will be called.
return true
}
private fun manageLifetime() {
when {
// We should not be in the foreground while UI clients are bound.
isBound() -> exitForeground()
// Location updates were started.
locationRepository.isReceivingLocationUpdates.value -> enterForeground()
// Nothing to do, so we can stop.
else -> stopSelf()
}
}
private fun exitForeground() {
if (isForeground) {
isForeground = false
stopForeground(true)
}
}
private fun enterForeground() {
if (!isForeground) {
isForeground = true
// Show notification with the latest location.
showNotification(locationRepository.lastLocation.value)
}
}
private fun showNotification(location: Location?) {
if (!isForeground) {
return
}
createNotificationChannel()
startForeground(NOTIFICATION_ID, buildNotification(location))
}
private fun createNotificationChannel() {
if (VERSION.SDK_INT >= VERSION_CODES.O) {
val notificationChannel = NotificationChannel(
NOTIFICATION_CHANNEL_ID,
getString(R.string.notification_channel_name),
NotificationManager.IMPORTANCE_DEFAULT
)
val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(notificationChannel)
}
}
private fun buildNotification(location: Location?) : Notification {
// Tapping the notification opens the app.
val pendingIntent = PendingIntent.getActivity(
this,
0,
packageManager.getLaunchIntentForPackage(this.packageName),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
// Include an action to stop location updates without going through the app UI.
val stopIntent = PendingIntent.getService(
this,
0,
Intent(this, this::class.java).setAction(ACTION_STOP_UPDATES),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val contentText = if (location != null) {
getString(R.string.location_lat_lng, location.latitude, location.longitude)
} else {
getString(R.string.waiting_for_location)
}
return NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setContentTitle(getString(R.string.notification_title))
.setContentText(contentText)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_location)
.addAction(R.drawable.ic_stop, getString(R.string.stop), stopIntent)
.setOngoing(true)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.build()
}
// Methods for clients.
fun startLocationUpdates() {
locationRepository.startLocationUpdates()
}
fun stopLocationUpdates() {
locationRepository.stopLocationUpdates()
}
/** Binder which provides clients access to the service. */
internal inner class LocalBinder : Binder() {
fun getService(): ForegroundLocationService = this@ForegroundLocationService
}
private companion object {
const val UNBIND_DELAY_MILLIS = 2000.toLong() // 2 seconds
const val NOTIFICATION_ID = 1
const val NOTIFICATION_CHANNEL_ID = "LocationUpdates"
const val ACTION_STOP_UPDATES = BuildConfig.APPLICATION_ID + ".ACTION_STOP_UPDATES"
}
}
/**
* ServiceConnection that provides access to a [ForegroundLocationService].
*/
class ForegroundLocationServiceConnection @Inject constructor() : ServiceConnection {
var service: ForegroundLocationService? = null
private set
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
service = (binder as LocalBinder).getService()
}
override fun onServiceDisconnected(name: ComponentName) {
// Note: this should never be called since the service is in the same process.
service = null
}
}
| apache-2.0 | f36dc54f5ecf9f99890f7082b6766a76 | 36.750929 | 102 | 0.673264 | 5.160061 | false | false | false | false |
paplorinc/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/DeduplicateVisitorsSupplier.kt | 4 | 1628 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project.manage
import com.intellij.openapi.externalSystem.model.Key
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.LibraryData
import com.intellij.openapi.externalSystem.model.project.LibraryDependencyData
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.model.project.ModuleDependencyData
import com.intellij.util.containers.Interner
import java.util.function.Function
class DeduplicateVisitorsSupplier {
private val myModuleData: Interner<ModuleData> = Interner()
private val myLibraryData: Interner<LibraryData> = Interner()
fun getVisitor(key: Key<*>): Function<*,*>? = when (key) {
ProjectKeys.LIBRARY_DEPENDENCY -> Function { dep: LibraryDependencyData? -> visit(dep) }
ProjectKeys.MODULE_DEPENDENCY -> Function { dep: ModuleDependencyData? -> visit(dep) }
else -> null
}
fun visit(data: LibraryDependencyData?): LibraryDependencyData? {
if (data == null) {
return null
}
data.ownerModule = myModuleData.intern(data.ownerModule)
data.target = myLibraryData.intern(data.target)
return data
}
fun visit(data: ModuleDependencyData?): ModuleDependencyData? {
if (data == null) {
return null
}
data.ownerModule = myModuleData.intern(data.ownerModule)
data.target = myModuleData.intern(data.target)
return data
}
}
| apache-2.0 | add4c928978cb0cc3485ac8845213f03 | 37.761905 | 140 | 0.763514 | 4.250653 | false | false | false | false |
noboru-i/SlideViewer | app/src/main/java/hm/orz/chaos114/android/slideviewer/widget/PickPageDialog.kt | 1 | 1884 | package hm.orz.chaos114.android.slideviewer.widget
import android.content.Context
import android.databinding.DataBindingUtil
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.widget.SeekBar
import hm.orz.chaos114.android.slideviewer.R
import hm.orz.chaos114.android.slideviewer.databinding.DialogPickPageBinding
import java.util.Locale
/**
* Show dialog for pick page.
*/
object PickPageDialog {
fun show(context: Context, currentPage: Int, maxPage: Int, listener: OnPickPageListener) {
val binding = DataBindingUtil.inflate<DialogPickPageBinding>(LayoutInflater.from(context), R.layout.dialog_pick_page, null, false)
binding.maxPageView.text = String.format(Locale.getDefault(), "%d / %d", currentPage + 1, maxPage)
binding.seekBar.max = maxPage - 1
binding.seekBar.progress = currentPage
binding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
if (!fromUser) {
return
}
binding.maxPageView.text = String.format(Locale.getDefault(), "%d / %d", progress + 1, maxPage)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
}
})
AlertDialog.Builder(context)
.setTitle("Select page")
.setPositiveButton(android.R.string.ok) { _, _ -> listener.onPickPage(binding.seekBar.progress) }
.setNegativeButton(android.R.string.cancel, null)
.setCancelable(true)
.setView(binding.root)
.show()
}
interface OnPickPageListener {
fun onPickPage(page: Int)
}
}
| mit | d4f0db54f309b873441ee3d2b0794969 | 36.68 | 138 | 0.657643 | 4.550725 | false | false | false | false |
google/intellij-community | jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/junit/JUnitIgnoredTestInspection.kt | 3 | 2402 | // 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.codeInspection.test.junit
import com.intellij.analysis.JvmAnalysisBundle
import com.intellij.codeInspection.*
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel
import com.intellij.codeInspection.util.InspectionMessage
import com.intellij.psi.PsiElementVisitor
import com.intellij.uast.UastHintedVisitorAdapter
import com.siyeh.ig.junit.JUnitCommonClassNames.*
import org.jetbrains.uast.*
import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor
import javax.swing.JComponent
class JUnitIgnoredTestInspection : AbstractBaseUastLocalInspectionTool() {
@JvmField
var onlyReportWithoutReason = true
override fun createOptionsPanel(): JComponent = SingleCheckboxOptionsPanel(
JvmAnalysisBundle.message("jvm.inspections.junit.ignored.test.ignore.reason.option"), this, "onlyReportWithoutReason"
)
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor =
UastHintedVisitorAdapter.create(
holder.file.language,
JUnitIgnoredTestVisitor(holder, onlyReportWithoutReason),
arrayOf(UClass::class.java, UMethod::class.java),
directOnly = true
)
}
private class JUnitIgnoredTestVisitor(
private val holder: ProblemsHolder,
private val onlyReportWithoutReason: Boolean
) : AbstractUastNonRecursiveVisitor() {
val withoutReasonChoice = if (onlyReportWithoutReason) 2 else 1
override fun visitClass(node: UClass): Boolean = checkIgnoreOrDisabled(
node, JvmAnalysisBundle.message("jvm.inspections.junit.ignored.test.class.problem.descriptor", node.javaPsi.name, withoutReasonChoice)
)
override fun visitMethod(node: UMethod): Boolean = checkIgnoreOrDisabled(
node, JvmAnalysisBundle.message("jvm.inspections.junit.ignored.test.method.problem.descriptor", node.name, withoutReasonChoice)
)
private fun checkIgnoreOrDisabled(node: UDeclaration, message: @InspectionMessage String): Boolean {
val annotations = node.findAnnotations(ORG_JUNIT_IGNORE, ORG_JUNIT_JUPITER_API_DISABLED)
if (annotations.isEmpty()) return true
if (onlyReportWithoutReason && annotations.any { it.findDeclaredAttributeValue("value") != null }) return true
holder.registerUProblem(node, message)
return true
}
} | apache-2.0 | 7c0849a159f7d7c505cb95028bc1e027 | 44.339623 | 138 | 0.802248 | 4.700587 | false | true | false | false |
google/intellij-community | python/src/com/jetbrains/python/newProject/PythonNewProjectWizard.kt | 3 | 9906 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.newProject
import com.intellij.ide.highlighter.ModuleFileType
import com.intellij.ide.projectWizard.NewProjectWizardConstants.Language.PYTHON
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.ide.wizard.*
import com.intellij.openapi.Disposable
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil
import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.ui.dsl.builder.Panel
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.jetbrains.python.PyBundle
import com.jetbrains.python.PythonModuleTypeBase
import com.jetbrains.python.newProject.steps.ProjectSpecificSettingsStep
import com.jetbrains.python.newProject.steps.PyAddExistingSdkPanel
import com.jetbrains.python.sdk.PySdkProvider
import com.jetbrains.python.sdk.PySdkSettings
import com.jetbrains.python.sdk.add.PyAddNewCondaEnvPanel
import com.jetbrains.python.sdk.add.PyAddNewVirtualEnvPanel
import com.jetbrains.python.sdk.add.PyAddSdkPanel
import com.jetbrains.python.sdk.pythonSdk
import java.nio.file.Path
/**
* A wizard for creating new pure-Python projects in IntelliJ.
*
* It suggests creating a new Python virtual environment for your new project to follow Python best practices.
*/
class PythonNewProjectWizard : LanguageNewProjectWizard {
override val name = PYTHON
override val ordinal = 600
override fun createStep(parent: NewProjectWizardLanguageStep): NewProjectWizardStep = NewPythonProjectStep(parent)
}
/**
* Data for sharing among the steps of the new Python project wizard.
*/
interface NewProjectWizardPythonData : NewProjectWizardBaseData {
/**
* A property for tracking changes in [pythonSdk].
*/
val pythonSdkProperty: GraphProperty<Sdk?>
/**
* The Python SDK for the new Python project or module.
*
* During [NewProjectWizardStep.setupUI] it reflects the selected Python SDK (it may be `null` for a new environment or if there is no
* Python installed on the machine). After [PythonSdkStep] gets or creates the actual SDK for the new project in its
* [NewProjectWizardStep.setupProject], the attribute contains the actual SDK.
*/
var pythonSdk: Sdk?
/**
* The Python module after it has been created during [NewProjectWizardStep.setupProject].
*/
val module: Module?
companion object {
val KEY = Key.create<NewProjectWizardPythonData>(NewProjectWizardPythonData::class.java.name)
val NewProjectWizardStep.pythonData get() = data.getUserData(KEY)!!
val NewProjectWizardStep.pythonSdkProperty get() = pythonData.pythonSdkProperty
val NewProjectWizardStep.pythonSdk get() = pythonData.pythonSdk
val NewProjectWizardStep.module get() = pythonData.module
}
}
/**
* A new Python project wizard step that allows you to either create a new Python environment or select an existing Python interpreter.
*
* It works for both PyCharm (where the *.iml file resides in .idea/ directory and the SDK is set for the project) and other
* IntelliJ-based IDEs (where the *.iml file resides in the module directory and the SDK is set for the module).
*/
class NewPythonProjectStep<P>(parent: P)
: AbstractNewProjectWizardStep(parent),
NewProjectWizardBaseData by parent,
NewProjectWizardPythonData
where P : NewProjectWizardStep, P : NewProjectWizardBaseData {
override val pythonSdkProperty = propertyGraph.property<Sdk?>(null)
override var pythonSdk by pythonSdkProperty
override val module: Module?
get() = intellijModule ?: context.project?.let { ModuleManager.getInstance(it).modules.firstOrNull() }
private var intellijModule: Module? = null
private val sdkStep: PythonSdkStep<NewPythonProjectStep<P>> by lazy { PythonSdkStep(this) }
override fun setupUI(builder: Panel) {
sdkStep.setupUI(builder)
}
override fun setupProject(project: Project) {
commitIntellijModule(project)
sdkStep.setupProject(project)
setupSdk(project)
}
private fun commitIntellijModule(project: Project) {
val moduleName = name
val projectPath = Path.of(path, name)
val moduleBuilder = PythonModuleTypeBase.getInstance().createModuleBuilder().apply {
name = moduleName
contentEntryPath = projectPath.toString()
moduleFilePath = projectPath.resolve(moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION).toString()
}
intellijModule = moduleBuilder.commit(project)?.firstOrNull()
}
private fun setupSdk(project: Project) {
var sdk = pythonSdk ?: return
val existingSdk = ProjectJdkTable.getInstance().findJdk(sdk.name)
if (existingSdk != null) {
pythonSdk = existingSdk
sdk = existingSdk
}
else {
SdkConfigurationUtil.addSdk(sdk)
}
val module = intellijModule
if (module != null) {
module.pythonSdk = sdk
}
else {
SdkConfigurationUtil.setDirectoryProjectSdk(project, sdk)
}
}
init {
data.putUserData(NewProjectWizardPythonData.KEY, this)
}
}
/**
* A new Python project wizard step that allows you to get or create a Python SDK for your [path]/[name].
*
* The resulting SDK is available as [pythonSdk]. The SDK may have not been saved to the project JDK table yet.
*/
class PythonSdkStep<P>(parent: P)
: AbstractNewProjectWizardMultiStepBase(parent),
NewProjectWizardPythonData by parent
where P : NewProjectWizardStep, P : NewProjectWizardPythonData {
override val label: String = PyBundle.message("python.sdk.new.project.environment")
override fun initSteps(): Map<String, NewProjectWizardStep> {
val existingSdkPanel = PyAddExistingSdkPanel(null, null, existingSdks(context), "$path/$name", null)
return mapOf(
"New" to NewEnvironmentStep(this),
// TODO: Handle remote project creation for remote SDKs
"Existing" to PythonSdkPanelAdapterStep(this, existingSdkPanel),
)
}
override fun setupUI(builder: Panel) {
super.setupUI(builder)
step = if (PySdkSettings.instance.useNewEnvironmentForNewProject) "New" else "Existing"
}
override fun setupProject(project: Project) {
super.setupProject(project)
PySdkSettings.instance.useNewEnvironmentForNewProject = step == "New"
}
}
/**
* A new Python project wizard step that allows you to create a new Python environment of various types.
*
* The following environment types are supported:
*
* * Virtualenv
* * Conda
* * Pipenv
*
* as well as other environments offered by third-party plugins via [PySdkProvider.createNewEnvironmentPanel].
*
* The suggested new environment path for some types of Python environments depends on the path of your new project.
*/
private class NewEnvironmentStep<P>(parent: P)
: AbstractNewProjectWizardMultiStepBase(parent),
NewProjectWizardPythonData by parent
where P : NewProjectWizardStep, P : NewProjectWizardPythonData {
override val label: String = PyBundle.message("python.sdk.new.project.environment.type")
override fun initSteps(): Map<String, PythonSdkPanelAdapterStep<NewEnvironmentStep<P>>> {
val sdks = existingSdks(context)
val newProjectPath = "$path/$name"
val basePanels = listOf(
PyAddNewVirtualEnvPanel(null, null, sdks, newProjectPath, context),
PyAddNewCondaEnvPanel(null, null, sdks, newProjectPath),
)
val providedPanels = PySdkProvider.EP_NAME.extensionList.map { it.createNewEnvironmentPanel(null, null, sdks, newProjectPath, context) }
val panels = basePanels + providedPanels
return panels
.associateBy { it.envName }
.mapValues { (_, v) -> PythonSdkPanelAdapterStep(this, v) }
}
override fun setupUI(builder: Panel) {
super.setupUI(builder)
val preferred = PySdkSettings.instance.preferredEnvironmentType
step = if (preferred != null && preferred in steps.keys) preferred else steps.keys.first()
}
override fun setupProject(project: Project) {
super.setupProject(project)
PySdkSettings.instance.preferredEnvironmentType = step
}
}
/**
* A new Python project wizard step that allows you to get or create a Python environment via its [PyAddSdkPanel].
*/
private class PythonSdkPanelAdapterStep<P>(parent: P, val panel: PyAddSdkPanel)
: AbstractNewProjectWizardStep(parent),
NewProjectWizardPythonData by parent
where P : NewProjectWizardStep, P : NewProjectWizardPythonData {
override fun setupUI(builder: Panel) {
with(builder) {
row {
cell(panel)
.validationRequestor { panel.addChangeListener(it) }
.horizontalAlign(HorizontalAlign.FILL)
.validationOnInput { panel.validateAll().firstOrNull() }
.validationOnApply { panel.validateAll().firstOrNull() }
}
}
panel.addChangeListener {
pythonSdk = panel.sdk
}
nameProperty.afterChange { updateNewProjectPath() }
pathProperty.afterChange { updateNewProjectPath() }
}
override fun setupProject(project: Project) {
pythonSdk = panel.getOrCreateSdk()
}
private fun updateNewProjectPath() {
panel.newProjectPath = "$path/$name"
}
}
/**
* Return the list of already configured Python SDKs.
*/
private fun existingSdks(context: WizardContext): List<Sdk> {
val sdksModel = ProjectSdksModel().apply {
reset(context.project)
Disposer.register(context.disposable, Disposable {
disposeUIResources()
})
}
return ProjectSpecificSettingsStep.getValidPythonSdks(sdksModel.sdks.toList())
}
| apache-2.0 | bed9caeb0d843608188034099895f2a3 | 35.825279 | 140 | 0.754189 | 4.464173 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.