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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mcdimus/mate-wp | src/main/kotlin/ee/mcdimus/matewp/command/UpdateCommand.kt | 1 | 2031 | package ee.mcdimus.matewp.command
import ee.mcdimus.matewp.service.BingPhotoOfTheDayService
import ee.mcdimus.matewp.service.FileSystemService
import ee.mcdimus.matewp.service.ImageService
import ee.mcdimus.matewp.service.OpSysService
import ee.mcdimus.matewp.service.OpSysServiceFactory
import java.io.File
import java.io.IOException
import java.nio.file.Files
import javax.imageio.ImageIO
import kotlin.system.exitProcess
class UpdateCommand : Command {
private val bingPhotoOfTheDayService: BingPhotoOfTheDayService by lazy { BingPhotoOfTheDayService() }
private val fileSystemService: FileSystemService by lazy { FileSystemService() }
private val opSystemService: OpSysService by lazy { OpSysServiceFactory.get() }
private val imageService: ImageService by lazy { ImageService() }
override fun execute() {
// get image data
val imageData = bingPhotoOfTheDayService.getData()
println(imageData)
val imagesDir = fileSystemService.getImagesDirectory()
val imagePropertiesPath = imagesDir.resolve("${imageData.startDate}.properties")
if (Files.notExists(imagePropertiesPath)) {
SaveCommand("previous").execute()
fileSystemService.saveProperties(imagePropertiesPath, linkedMapOf(
"startDate" to imageData.startDate,
"urlBase" to imageData.urlBase,
"copyright" to imageData.copyright
))
// download image
var imageFile: File? = null
try {
val image = imageService.download(imageData.downloadURL)
val imageWithText = imageService.addText(image!!, imageData.copyright)
imageFile = File(imagesDir.toFile(), imageData.filename)
ImageIO.write(imageWithText, "jpg", imageFile)
} catch (ignored: IOException) {
System.err.println(imageFile?.absolutePath)
exitProcess(1)
}
opSystemService.setAsWallpaper(imageFile.toPath())
} else {
val imageFile = imagesDir.resolve(imageData.filename)
opSystemService.setAsWallpaper(imageFile)
}
}
}
| mit | 2c27c799cd83a690d3a200d36db416c9 | 34.017241 | 103 | 0.73806 | 4.358369 | false | false | false | false |
spotify/heroic | heroic-core/src/main/java/com/spotify/heroic/shell/task/parameters/DataMigrateParameters.kt | 1 | 2231 | /*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.shell.task.parameters
import org.kohsuke.args4j.Argument
import org.kohsuke.args4j.Option
import java.util.*
internal class DataMigrateParameters : KeyspaceBase() {
@Option(name = "-f", aliases = ["--from"], usage = "Backend group to load data from", metaVar = "<group>")
val from = Optional.empty<String>()
@Option(name = "-t", aliases = ["--to"], usage = "Backend group to load data to", metaVar = "<group>")
val to = Optional.empty<String>()
@Option(name = "--page-limit", usage = "Limit the number metadata entries to fetch per page (default: 100)")
val pageLimit = 100
@Option(name = "--keys-paged", usage = "Use the high-level paging mechanism when streaming keys")
val keysPaged = false
@Option(name = "--keys-page-size", usage = "Use the given page-size when paging keys")
val keysPageSize = 10
@Option(name = "--fetch-size", usage = "Use the given fetch size")
val fetchSize = Optional.empty<Int>()
@Option(name = "--tracing", usage = "Trace the queries for more debugging when things go wrong")
val tracing = false
@Option(name = "--parallelism", usage = "The number of migration requests to send in parallel (default: 100)", metaVar = "<number>")
val parallelism = Runtime.getRuntime().availableProcessors() * 4
@Argument
override val query = ArrayList<String>()
}
| apache-2.0 | 8bcf506827faf45a88865a7ad29602b6 | 39.563636 | 136 | 0.700583 | 4.093578 | false | false | false | false |
sreich/ore-infinium | core/src/com/ore/infinium/systems/client/ClientBlockDiggingSystem.kt | 1 | 9250 | /**
MIT License
Copyright (c) 2016 Shaun Reich <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.ore.infinium.systems.client
import com.artemis.BaseSystem
import com.artemis.annotations.Wire
import com.artemis.managers.TagManager
import com.ore.infinium.OreBlock
import com.ore.infinium.OreClient
import com.ore.infinium.OreWorld
import com.ore.infinium.components.PlayerComponent
import com.ore.infinium.components.ToolComponent
import com.ore.infinium.systems.GameTickSystem
import com.ore.infinium.util.isInvalidEntity
import com.ore.infinium.util.mapper
import com.ore.infinium.util.opt
import com.ore.infinium.util.system
import mu.KLogging
@Wire(failOnNull = false)
class ClientBlockDiggingSystem(private val oreWorld: OreWorld, private val client: OreClient) : BaseSystem() {
companion object : KLogging()
private val mPlayer by mapper<PlayerComponent>()
private val mTool by mapper<ToolComponent>()
private val gameTickSystem by system<GameTickSystem>()
private val clientNetworkSystem by system<ClientNetworkSystem>()
private val soundSystem by system<SoundSystem>()
private val tagManager by system<TagManager>()
/**
* the client only uses this to ensure it doesn't send a dig
* begin/finish more than once per block..
*/
class BlockToDig {
internal var x: Int = 0
internal var y: Int = 0
/**
* the tick when the dig request for this block was started
*/
internal var digStartTick: Long = 0
/**
* indicates we've already sent a packet to the server
* saying that we think we've finished digging this block.
* the server can (and may) do nothing with the request.
*/
internal var finishSent: Boolean = false
/**
* current health of a block that is getting damaged.
*/
var damagedBlockHealth = -1f
var totalBlockHealth = -1f
//hack
var ticksTook: Int = 0
}
private val blocksToDig = mutableListOf<BlockToDig>()
override fun processSystem() {
if (!clientNetworkSystem.connected) {
return
}
val mouse = oreWorld.mousePositionWorldCoords()
//todo check if block is null
val blockX = mouse.x.toInt()
val blockY = mouse.y.toInt()
if (ableToDigAtIndex(blockX, blockY)) {
dig()
}
blocksToDig.removeAll { blockToDig -> expireOldDigRequests(blockToDig) }
}
/**
* @return true if it was expired, false if ignored/persisted
*/
private fun expireOldDigRequests(blockToDig: BlockToDig): Boolean {
val player = tagManager.getEntity(OreWorld.s_mainPlayer).id
val cPlayer = mPlayer.get(player)
val itemEntity = cPlayer.equippedPrimaryItem
val cTool = mTool.opt(itemEntity)
if (cTool == null) {
//switched tools, expire it.
return true
}
//final short totalBlockHealth = OreWorld.blockAttributes.get(block.type).blockTotalHealth;
if (!ableToDigAtIndex(blockToDig.x, blockToDig.y)) {
//not even a thing that can dig, or they are no longer digging
//remove the request
return true
}
val damagePerTick = cTool.blockDamage * getWorld().getDelta()
//this many ticks after start tick, it should have already been destroyed
val expectedTickEnd = blockToDig.digStartTick + (blockToDig.totalBlockHealth / damagePerTick).toInt()
//when actual ticks surpass our expected ticks, by so much
//we assume this request times out
if (gameTickSystem.ticks > expectedTickEnd + 10) {
return true
}
return false
}
/**
*
*
* checks if an item that can dig blocks is equipped and able
* to pick the bloxk at the given block indices
* @param x
* *
* @param y
* *
* *
* @return
*/
fun ableToDigAtIndex(x: Int, y: Int): Boolean {
if (!client.leftMouseDown) {
return false
}
val player = tagManager.getEntity(OreWorld.s_mainPlayer).id
//FIXME make this receive a vector, look at block at position,
//see if he has the right drill type etc to even ATTEMPT a block dig
val cPlayer = mPlayer.get(player)
val itemEntity = cPlayer.equippedPrimaryItem
if (isInvalidEntity(itemEntity)) {
return false
}
val cTool = mTool.opt(itemEntity) ?: return false
if (cTool.type != ToolComponent.ToolType.Drill) {
return false
}
val blockType = oreWorld.blockType(x, y)
if (blockType == OreBlock.BlockType.Air.oreValue) {
return false
}
return true
}
/**
* dig at the player mouse position.
* does not verify if it can or should be done,
* but does handle telling the server it will be/is finished digging
*/
fun dig() {
val player = tagManager.getEntity(OreWorld.s_mainPlayer).id
val cPlayer = mPlayer.get(player)
val itemEntity = cPlayer.equippedPrimaryItem
val mouse = oreWorld.mousePositionWorldCoords()
//guaranteed to have a tool, we already check that in the method call before this
val cTool = mTool.get(itemEntity)
val blockX = mouse.x.toInt()
val blockY = mouse.y.toInt()
val blockType = oreWorld.blockType(blockX, blockY)
//if any of these blocks is what we're trying to dig
//then we need to continue digging them
var found = false
for (blockToDig in blocksToDig) {
//block.destroy();
if (blockToDig.x == blockX || blockToDig.y == blockY) {
found = true
}
var attacked = false
//only decrement block health if it has some
if (blockToDig.damagedBlockHealth > 0) {
blockToDig.damagedBlockHealth -= getWorld().getDelta() * cTool.blockDamage
blockToDig.ticksTook += 1
attacked = true
}
// only send dig finish packet once per block
if (blockToDig.damagedBlockHealth <= 0 && !blockToDig.finishSent) {
blockToDig.finishSent = true
//we killed the block
clientNetworkSystem.sendBlockDigFinish(blockX, blockY)
playBlockDugSound(blockType)
logger.debug { "processSystem finish! tick taken: ${blockToDig.ticksTook}"}
return
}
if (attacked) {
playBlockAttackSound(blockType)
}
}
if (!found) {
//inform server we're beginning to dig this block. it will track our time.
//we will too, but mostly just so we know not to send these requests again
clientNetworkSystem.sendBlockDigBegin(blockX, blockY)
val totalBlockHealth = OreBlock.blockAttributes[blockType]!!.blockTotalHealth
val blockToDig = BlockToDig().apply {
damagedBlockHealth = totalBlockHealth
this.totalBlockHealth = totalBlockHealth
digStartTick = gameTickSystem.ticks
x = blockX
y = blockY
}
blocksToDig.add(blockToDig)
}
}
private fun playBlockDugSound(blockType: Byte) {
when (blockType) {
OreBlock.BlockType.Dirt.oreValue ->
soundSystem.playDirtAttackFinish()
OreBlock.BlockType.Stone.oreValue ->
soundSystem.playStoneAttackFinish()
}
}
private fun playBlockAttackSound(blockType: Byte) {
when (blockType) {
OreBlock.BlockType.Dirt.oreValue -> soundSystem.playDirtAttack()
OreBlock.BlockType.Stone.oreValue -> soundSystem.playDrillAttack()
}
}
fun blockHealthAtIndex(x: Int, y: Int): Float {
for (blockToDig in blocksToDig) {
if (blockToDig.x == x && blockToDig.y == y) {
return blockToDig.damagedBlockHealth
}
}
return -1f
}
}
| mit | 895f5e7fb3e65167d9c7d5ffa98e21c3 | 31.118056 | 110 | 0.633838 | 4.425837 | false | false | false | false |
Killian-LeClainche/Java-Base-Application-Engine | src/polaris/okapi/render/Font.kt | 1 | 4713 | package polaris.okapi.render
import jdk.nashorn.internal.objects.NativeArray.forEach
import org.lwjgl.opengl.GL11.*
import org.lwjgl.stb.STBTTAlignedQuad
import org.lwjgl.stb.STBTTBakedChar
import org.lwjgl.stb.STBTTFontinfo
import org.lwjgl.stb.STBTTPackedchar
import org.lwjgl.stb.STBTruetype.*
import org.lwjgl.system.MemoryStack
import org.lwjgl.system.MemoryStack.stackPush
import org.lwjgl.system.rpmalloc.RPmalloc
import org.lwjgl.system.rpmalloc.RPmalloc.rpfree
import java.nio.ByteBuffer
import polaris.okapi.util.scale
import java.awt.SystemColor.text
/**
* Created by Killian Le Clainche on 12/12/2017.
*/
data class Font @JvmOverloads constructor(val name: String, val info: STBTTFontinfo, val width: Int, val height: Int, val oversample: Int, val bitmap: ByteBuffer, var id: Int = glGenTextures()) {
var ascent: Int = 0
private set
var descent: Int = 0
private set
var lineGap: Int = 0
private set
val chardata: STBTTPackedchar.Buffer = STBTTPackedchar.malloc(96)
init {
stackPush().use {
val fontAscent = it.mallocInt(1)
val fontDescent = it.mallocInt(1)
val fontLineGap = it.mallocInt(1)
stbtt_GetFontVMetrics(info, fontAscent, fontDescent, fontLineGap)
ascent = fontAscent[0]
descent = fontDescent[0]
lineGap = fontLineGap[0]
}
}
fun bind() = glBindTexture(GL_TEXTURE_2D, id)
fun getWidth(text: String, scale: Float): Float = getWidth(text) * scale
fun getWidth(text: String): Float {
var length = 0f
text.chars().forEach {
length += chardata[it - 32].xadvance()
}
return length
}
fun destroy() {
if(id != 0)
glDeleteTextures(id)
id = 0
}
fun close() {
destroy()
info.free()
chardata.free()
rpfree(bitmap)
}
/*fun draw(text: String, x: Float, y: Float, z: Float, scale: Float): VBO? {
var x = x
//int bufferSize = text.length() * 6 * 5;
//VBOBuffer vboBuffer = new VBOBuffer(bufferSize);
//IBOBuffer iboBuffer = new IBOBuffer(bufferSize);
val quad = STBTTAlignedQuad.malloc()
//VBO vbo;
xBuffer.put(0, 0f)
yBuffer.put(0, 0f)
GL11.glPushMatrix()
GL11.glTranslated(x.toDouble(), y.toDouble(), z.toDouble())
GL11.glBegin(GL11.GL_QUADS)
var c: Char
var x0: Float
var y0: Float
var x1: Float
var y1: Float
for (i in 0 until text.length) {
c = text[i]
if (c == '\n') {
xBuffer.put(0, 0f)
yBuffer.put(0, yBuffer.get(0) + size)
continue
}
x = xBuffer.get(0)
stbtt_GetBakedQuad(fontChardata, fontWidth, fontHeight, c.toInt() - 32, xBuffer, yBuffer, quad, true)
x0 = quad.x0()
y0 = quad.y0()
x1 = quad.x1()
y1 = quad.y1()
x1 = x0 + (x1 - x0) * scale
y0 = y1 + (y0 - y1) * scale
xBuffer.put(0, x + (xBuffer.get(0) - x) * scale)
GL11.glTexCoord2d(quad.s0().toDouble(), quad.t1().toDouble())
GL11.glVertex3d(x0.toDouble(), y1.toDouble(), z.toDouble())
GL11.glTexCoord2d(quad.s1().toDouble(), quad.t1().toDouble())
GL11.glVertex3d(x1.toDouble(), y1.toDouble(), z.toDouble())
GL11.glTexCoord2d(quad.s1().toDouble(), quad.t0().toDouble())
GL11.glVertex3d(x1.toDouble(), y0.toDouble(), z.toDouble())
GL11.glTexCoord2d(quad.s0().toDouble(), quad.t0().toDouble())
GL11.glVertex3d(x0.toDouble(), y0.toDouble(), z.toDouble())
/*vboBuffer.addVertex(x0, y1, z);
vboBuffer.addVertex(x1, y1, z);
vboBuffer.addVertex(x0, y0, z);
vboBuffer.addVertex(x0, y0, z);
vboBuffer.addVertex(x1, y1, z);
vboBuffer.addVertex(x1, y0, z);*/
/*vboBuffer.addTextureVertex(x0, y1, z, quad.s0(), quad.t1());
vboBuffer.addTextureVertex(x1, y1, z, quad.s1(), quad.t1());
vboBuffer.addTextureVertex(x0, y0, z, quad.s0(), quad.t0());
vboBuffer.addTextureVertex(x0, y0, z, quad.s0(), quad.t0());
vboBuffer.addTextureVertex(x1, y1, z, quad.s1(), quad.t1());
vboBuffer.addTextureVertex(x1, y0, z, quad.s1(), quad.t0());*/
}
GL11.glEnd()
GL11.glPopMatrix()
quad.free()
//iboBuffer.shrinkVBO(vboBuffer, VBO.POS_TEXTURE_STRIDE);
//vbo = VBO.createStaticVBO(GL11.GL_TRIANGLES, VBO.POS_TEXTURE, VBO.POS_TEXTURE_STRIDE, VBO.POS_TEXTURE_OFFSET, vboBuffer);
//return vbo;
return null
}*/
} | gpl-2.0 | 80444cf91c724dd135c51b58120da242 | 30.218543 | 195 | 0.591555 | 3.239175 | false | false | false | false |
sreich/ore-infinium | core/src/com/ore/infinium/systems/client/SpriteRenderSystem.kt | 1 | 10169 | /**
MIT License
Copyright (c) 2016 Shaun Reich <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.ore.infinium.systems.client
import aurelienribon.tweenengine.Timeline
import aurelienribon.tweenengine.Tween
import aurelienribon.tweenengine.TweenEquations
import aurelienribon.tweenengine.TweenManager
import aurelienribon.tweenengine.equations.Sine
import com.artemis.BaseSystem
import com.artemis.annotations.Wire
import com.artemis.managers.TagManager
import com.artemis.utils.IntBag
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.g2d.Sprite
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.glutils.ShaderProgram
import com.ore.infinium.OreWorld
import com.ore.infinium.SpriteTween
import com.ore.infinium.components.ItemComponent
import com.ore.infinium.components.SpriteComponent
import com.ore.infinium.util.*
import ktx.assets.file
@Wire
class SpriteRenderSystem(private val oreWorld: OreWorld,
private val camera: OrthographicCamera)
: BaseSystem(), RenderSystemMarker {
private lateinit var batch: SpriteBatch
private val mSprite by mapper<SpriteComponent>()
private val mItem by mapper<ItemComponent>()
private val tagManager by system<TagManager>()
private val tileRenderSystem by system<TileRenderSystem>()
private lateinit var tweenManager: TweenManager
private lateinit var defaultShader: ShaderProgram
private lateinit var spriteLightMapBlendShader: ShaderProgram
override fun initialize() {
//fixme hack this should be in init i think and everything else changed from lateinit to val
batch = SpriteBatch()
defaultShader = batch.shader
val tileLightMapBlendVertex = file("shaders/spriteLightMapBlend.vert").readString()
val tileLightMapBlendFrag = file("shaders/spriteLightMapBlend.frag").readString()
spriteLightMapBlendShader = ShaderProgram(tileLightMapBlendVertex, tileLightMapBlendFrag)
check(spriteLightMapBlendShader.isCompiled) { "tileLightMapBlendShader compile failed: ${spriteLightMapBlendShader.log}" }
spriteLightMapBlendShader.setUniformi("u_lightmap", 1)
spriteLightMapBlendShader.use {
spriteLightMapBlendShader.setUniformi("u_lightmap", 1)
}
tweenManager = TweenManager()
Tween.registerAccessor(Sprite::class.java, SpriteTween())
//default is 3, but color requires 4 (rgba)
Tween.setCombinedAttributesLimit(4)
world.aspectSubscriptionManager.get(allOf(SpriteComponent::class)).addSubscriptionListener(
SpriteEntityListener())
}
override fun dispose() {
batch.dispose()
}
override fun begin() {
batch.projectionMatrix = camera.combined
// batch.begin();
}
override fun processSystem() {
// batch.setProjectionMatrix(oreWorld.camera.combined);
tweenManager.update(world.getDelta())
batch.shader = spriteLightMapBlendShader
Gdx.gl20.glActiveTexture(GL20.GL_TEXTURE0 + 1)
tileRenderSystem.tileLightMapFbo.colorBufferTexture.bind(1)
Gdx.gl20.glActiveTexture(GL20.GL_TEXTURE0)
batch.begin()
renderEntities(world.getDelta())
batch.end()
batch.shader = defaultShader
batch.begin()
renderDroppedEntities(world.getDelta())
batch.end()
//restore color
batch.color = Color.WHITE
}
override fun end() {
// batch.end();
}
//fixme probably also droppedblocks?
private fun renderDroppedEntities(delta: Float) {
//fixme obviously this is very inefficient...but dunno if it'll ever be an issue.
val entities = world.entities(allOf(SpriteComponent::class))
var cItem: ItemComponent?
for (i in entities.indices) {
cItem = mItem.opt(entities.get(i))
//don't draw in-inventory or not dropped items
if (cItem == null || cItem.state != ItemComponent.State.DroppedInWorld) {
continue
}
val cSprite = mSprite.get(entities.get(i))
glowDroppedSprite(cSprite.sprite)
/*
batch.draw(cSprite.sprite,
cSprite.sprite.getX() - (cSprite.sprite.getWidth() * 0.5f),
cSprite.sprite.getY() + (cSprite.sprite.getHeight() * 0.5f),
cSprite.sprite.getWidth(), -cSprite.sprite.getHeight());
*/
batch.color = cSprite.sprite.color
val x = cSprite.sprite.x - cSprite.sprite.width * 0.5f
val y = cSprite.sprite.y + cSprite.sprite.height * 0.5f
//flip the sprite when drawn, by using negative height
val scaleX = cSprite.sprite.scaleX
val scaleY = cSprite.sprite.scaleY
val width = cSprite.sprite.width
val height = -cSprite.sprite.height
val originX = width * 0.5f
val originY = height * 0.5f
// cSprite.sprite.setScale(Interpolation.bounce.apply(0.0f, 0.5f, scaleX));
batch.draw(cSprite.sprite, (x * 16.0f).floor() / 16.0f,
(y * 16.0f).floor() / 16.0f, originX, originY, width, height, scaleX, scaleY,
rotation)
}
}
private fun glowDroppedSprite(sprite: Sprite) {
if (!tweenManager.containsTarget(sprite)) {
Timeline.createSequence().push(
Tween.to(sprite, SpriteTween.SCALE, 2.8f).target(0.2f, 0.2f).ease(
Sine.IN)).push(
Tween.to(sprite, SpriteTween.SCALE, 2.8f).target(.5f, .5f).ease(
Sine.OUT)).repeatYoyo(Tween.INFINITY, 0.0f).start(tweenManager)
val glowColor = Color.GOLDENROD
Tween.to(sprite, SpriteTween.COLOR, 2.8f).target(glowColor.r, glowColor.g, glowColor.b, 1f).ease(
TweenEquations.easeInOutSine).repeatYoyo(Tween.INFINITY, 0.0f).start(tweenManager)
}
}
private fun renderEntities(delta: Float) {
//todo need to exclude blocks?
val entities = world.entities(allOf(SpriteComponent::class))
var cSprite: SpriteComponent
for (i in entities.indices) {
val entity = entities.get(i)
val cItem = mItem.opt(entity)
//don't draw in-inventory or dropped items
if (cItem != null && cItem.state != ItemComponent.State.InWorldState) {
//hack
continue
}
cSprite = mSprite.get(entity)
if (!cSprite.visible) {
continue
}
//assert(cSprite.sprite != null) { "sprite is null" }
assert(cSprite.sprite.texture != null) { "sprite has null texture" }
var placementGhost = false
val tag = tagManager.opt(entity)
if (tag != null && tag == "itemPlacementOverlay") {
placementGhost = true
if (cSprite.placementValid) {
batch.setColor(0f, 1f, 0f, 0.6f)
} else {
batch.setColor(1f, 0f, 0f, 0.6f)
}
}
val x = cSprite.sprite.rect.x
val y = cSprite.sprite.y + cSprite.sprite.height * 0.5f
//flip the sprite when drawn, by using negative height
val scaleX = 1f
val scaleY = 1f
val width = cSprite.sprite.width
val height = -cSprite.sprite.height
val originX = width * 0.5f
val originY = height * 0.5f
//this prevents some jiggling of static items when player is moving, when the objects pos is
// not rounded to a reasonable flat number,
//but for the player it means they jiggle on all movement.
//batch.draw(cSprite.sprite, MathUtils.floor(x * 16.0f) / 16.0f, MathUtils.floor(y * 16.0f) /
// 16.0f,
// originX, originY, width, height, scaleX, scaleY, rotation);
batch.draw(cSprite.sprite, x, y, originX, originY, width, height, scaleX, scaleY, rotation)
//reset color for next run
if (placementGhost) {
batch.setColor(1f, 1f, 1f, 1f)
}
}
}
inner class SpriteEntityListener : OreEntitySubscriptionListener {
override fun inserted(entities: IntBag) {
super.inserted(entities)
entities.toMutableList().forEach {
mSprite.get(it).sprite.apply {
// color = Color.WHITE
//fixme for some reason seems sprites get an alpha of like 0.9967 or so...
//which is weird, because i'm not aware of changing that *anywhere*
}
}
}
}
companion object {
var spriteCount: Int = 0
internal var rotation: Float = 0f
}
}
| mit | d44b05fbb0e0f71af1872803d6554647 | 35.579137 | 130 | 0.634477 | 4.33092 | false | false | false | false |
Jay-Y/yframework | yframework-android/framework/src/main/java/org/yframework/android/util/WindowManagerUtil.kt | 1 | 1190 | package org.yframework.android.util
import android.app.Activity
import android.util.DisplayMetrics
import android.view.WindowManager
/**
* Description: DisplayMetricsUtil<br>
* Comments Name: DisplayMetricsUtil<br>
* Date: 2019-09-22 18:50<br>
* Author: ysj<br>
* EditorDate: 2019-09-22 18:50<br>
* Editor: ysj
*/
class WindowManagerUtil private constructor(windowManager: WindowManager) {
companion object {
private var INSTANCE: WindowManagerUtil? = null
fun with(activity: Activity): WindowManagerUtil {
if (INSTANCE == null) {
synchronized(this)
{
if (INSTANCE == null) {
INSTANCE =
WindowManagerUtil(activity.windowManager)
}
}
}
return INSTANCE!!
}
}
private val displayMetrics = DisplayMetrics()
private val rotation: Int
init {
val display = windowManager.defaultDisplay
display.getMetrics(displayMetrics)
rotation = display.rotation
}
fun getDisplayMetrics(): DisplayMetrics {
return displayMetrics
}
} | apache-2.0 | 085c58f65fcf864993f11e2ea7d03ce9 | 24.340426 | 75 | 0.59916 | 5 | false | false | false | false |
phylame/jem | commons/src/main/kotlin/jclp/xml/XmlExtend.kt | 1 | 6067 | /*
* Copyright 2015-2017 Peng Wan <[email protected]>
*
* This file is part of Jem.
*
* 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 jclp.xml
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import org.xmlpull.v1.XmlSerializer
import java.io.Flushable
import java.io.OutputStream
import java.io.Writer
const val SERIALIZER_INDENTATION_KEY = "http://xmlpull.org/v1/doc/properties.html#serializer-indentation"
const val SERIALIZER_LINE_SEPARATOR_KEY = "http://xmlpull.org/v1/doc/properties.html#serializer-line-separator"
var XmlSerializer.indentation: String?
inline get() = getProperty(SERIALIZER_INDENTATION_KEY) as? String
inline set(value) = setProperty(SERIALIZER_INDENTATION_KEY, value)
var XmlSerializer.lineSeparator: String?
inline get() = getProperty(SERIALIZER_LINE_SEPARATOR_KEY) as? String
inline set(value) = setProperty(SERIALIZER_LINE_SEPARATOR_KEY, value)
fun XmlSerializer.init(output: Writer, indent: String = " ", newLine: String = System.lineSeparator()) {
setOutput(output)
lineSeparator = newLine
indentation = indent
}
fun XmlSerializer.init(output: OutputStream, encoding: String = "UTF-8", indent: String = " ", newLine: String = System.lineSeparator()) {
setOutput(output, encoding)
lineSeparator = newLine
indentation = indent
}
fun XmlSerializer.startDocument(encoding: String = "UTF-8") {
startDocument(encoding, true)
text(lineSeparator)
}
fun XmlSerializer.doctype(root: String) {
docdecl(" $root")
text(lineSeparator)
}
fun XmlSerializer.docdecl(root: String, id: String, uri: String) {
docdecl(" $root PUBLIC \"$id\" \"$uri\"")
text(lineSeparator)
}
fun XmlSerializer.startTag(name: String) {
startTag(null, name)
}
fun XmlSerializer.startTag(prefix: String, namespace: String, name: String) {
setPrefix(prefix, namespace)
startTag(null, name)
}
fun XmlSerializer.attribute(name: String, value: String) {
attribute(null, name, value)
}
fun XmlSerializer.lang(lang: String) {
attribute("xml:lang", lang)
}
fun XmlSerializer.comm(text: String) {
val ln = lineSeparator
val indent = indentation ?: ""
text(ln)
text(indent.repeat(depth))
comment(text)
text(ln)
text(indent.repeat(depth))
}
fun XmlSerializer.endTag() {
endTag(namespace, name)
}
fun xmlSerializer(output: Writer, indent: String = " ", newLine: String = System.lineSeparator()): XmlSerializer =
XmlPullParserFactory.newInstance().newSerializer().apply { init(output, indent, newLine) }
fun xmlSerializer(output: OutputStream, encoding: String = "UTF-8", indent: String = " ", newLine: String = System.lineSeparator()): XmlSerializer =
XmlPullParserFactory.newInstance().newSerializer().apply { init(output, encoding, indent, newLine) }
fun XmlPullParser.getAttribute(name: String): String = getAttributeValue(null, name)
class XML(val output: Appendable, val indent: String, val lineSeparator: String) {
fun doctype(root: String, scope: String = "", dtd: String = "", uri: String = "") {
with(output) {
append("<!DOCTYPE $root")
if (scope.isNotEmpty()) append(" $scope")
if (dtd.isNotEmpty()) append(" \"$dtd\"")
if (uri.isNotEmpty()) append(" \"$uri\"")
append(">").append(lineSeparator)
}
}
inline fun tag(name: String, block: Tag.() -> Unit) {
Tag(name).apply(block).renderTo(output, indent, lineSeparator)
}
}
class Tag(val name: String, text: String = "") {
var depth = 0
val attr = linkedMapOf<String, String>()
val children = arrayListOf<Tag>()
val text = StringBuilder(text)
operator fun CharSequence.unaryPlus() {
text.append(this)
}
fun tag(name: String) {
children += Tag(name)
}
fun tag(name: String, text: String) {
children += Tag(name, text).also { it.depth = depth + 1 }
}
inline fun tag(name: String, block: Tag.() -> Unit) {
children += Tag(name).also { it.depth = depth + 1 }.apply(block)
}
fun renderTo(output: Appendable, indent: String, lineSeparator: String) {
with(output) {
val prefix = indent.repeat(depth)
append(prefix).append("<$name")
if (attr.isNotEmpty()) {
for (entry in attr) {
append(' ').append("${entry.key}=\"${entry.value}\"")
}
}
var hasContent = false
if (text.isNotEmpty()) {
append('>').append(text)
hasContent = true
}
if (children.isNotEmpty()) {
append('>').append(lineSeparator)
for (tag in children) {
tag.renderTo(this, indent, lineSeparator)
append(lineSeparator)
}
append(prefix)
hasContent = true
}
if (hasContent) {
append("</$name>")
} else {
append(" />")
}
}
}
}
inline fun Appendable.xml(
indent: String = "",
lineSeparator: String = System.lineSeparator(),
encoding: String = "utf-8",
standalone: Boolean = true,
block: XML.() -> Unit) {
append("<?xml version=\"1.0\" encoding=\"$encoding\"")
if (!standalone) append(" standalone=\"no\"")
append("?>").append(lineSeparator)
XML(this, indent, lineSeparator).apply(block)
(this as? Flushable)?.flush()
}
| apache-2.0 | b053e45428cfaa9956b7c09f364cb6b7 | 31.100529 | 149 | 0.631778 | 4.096556 | false | false | false | false |
jmfayard/skripts | kotlin/nearby.kt | 1 | 6892 | #!/usr/bin/env kotlin-script.sh
package p2p
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.selects.select
import java.util.Random
import kotlin.coroutines.CoroutineContext
data class Msg(val id: Int, val value: Int)
fun main() = runBlocking {
val streamToSend = Channel<Msg>()
val streamSent = Channel<Msg>()
val streamError = Channel<Msg>()
val nearby = FakeNearby("tx42", true, "sender23", streamToSend, streamSent, streamError, coroutineContext)
val launchNearbyJob = launch {
// withTimeout(30, TimeUnit.SECONDS) {
nearby.orchestrateNearby()
// }
}
val sendMessagesJob = launch {
for (id in 1..10) {
val msg = Msg(id = id, value = id * id)
println("Please send $msg")
streamToSend.send(msg)
delay(200)
}
}
val replayErrorsJob = launch {
for (msg in streamError) {
println("Message error $msg - please retry it")
streamToSend.send(msg)
}
}
val msgsOkJob = launch {
for (msg in streamSent) {
println("Msg $msg was correctly sent")
}
}
// wait for all jobs to complete
listOf(launchNearbyJob, sendMessagesJob, replayErrorsJob, msgsOkJob)
.forEach { job -> job.join() }
}
class FakeNearby(
val transaction: String,
val isSender: Boolean,
var peer: String,
val inputChannel: ReceiveChannel<Msg>,
val outputOkChannel: SendChannel<Msg>,
val outputErrorChannel: SendChannel<Msg>,
override val coroutineContext: CoroutineContext
) : CoroutineScope {
val canSendChannel = Channel<Boolean>()
suspend fun orchestrateNearby() {
val success = connectGoogleClient()
if (!success) println("Google Play Services is not setup")
val lifecycleEvents = appLifecycleEvents()
val randomEvents = randomNetworkErrors()
var shouldContinue = true
while (true) {
select<Unit> {
canSendChannel.onReceiveOrNull { canSend ->
println("Select: canSend=$canSend")
if (canSend == true) {
startSendingMessages()
}
}
lifecycleEvents.onReceiveOrNull { value ->
// canSendChannel.send(false)
if (value == "START") {
println("Select: lifecycleEvents=$value start")
startNearby()
} else { // "STOP"
println("Stopping")
}
}
randomEvents.onReceiveOrNull { msg ->
println("Select: randomEvents=$msg")
canSendChannel.send(false)
if (msg == "DISCONNECT") {
shouldContinue = false
startNearby()
} else { // "FAIL"
disconnectGoogleClient()
}
}
}
if (!shouldContinue) {
break
}
}
println("Nearby interrupted, you may want to retry it")
}
suspend fun startNearby() {
println("start nearby")
// canSendChannel.send(false)
if (isSender) {
val connectionRequests = advertise()
for (id in connectionRequests) {
println("Advertise: $id")
if (id != peer) continue
val success = tryConnect()
if (success) {
println("Connect success")
// canSendChannel.send(true)
} else {
println("Error while connecting")
}
}
} else {
val endpointsFound = discover()
for (id in endpointsFound) {
println("Discover: $id")
if (id != peer) continue
val success = tryConnect()
if (success) {
println("Connect success")
// canSendChannel.send(true)
} else {
println("Error while connecting")
}
}
}
}
suspend fun startSendingMessages() {
inputChannel.consumeEach { msg ->
println("Sending msg $msg")
delay(500)
if (badLuck(20)) {
println("Message has not been sent successfully, you will have to resend it")
outputErrorChannel.send(msg)
} else {
println("Message $msg sent successfully")
outputOkChannel.send(msg)
}
}
}
suspend fun appLifecycleEvents() = produce {
println("START")
send("START")
delay(10000)
println("STOP")
send("STOP")
delay(20000)
println("START")
send("START")
println("STOP")
send("STOP")
}
suspend fun randomNetworkErrors() = produce {
while (true) {
delay(1000)
if (badLuck(10)) send("DISCONNECT")
if (badLuck(10)) send("FAIL")
}
}
suspend fun connectGoogleClient(): Boolean {
delay(100)
return badLuck(10)
}
suspend fun disconnectGoogleClient() {
delay(10)
}
suspend fun discover() = advertise()
suspend fun advertise() = produce {
when (random.nextInt(100)) {
in 0..30 -> { // Best case scenario, we discover our peer, only once, no error
delay(100)
send(peer)
}
in 30..50 -> { // We get our peer multiple times
repeat(3) {
delay(100)
send(peer)
}
}
in 50..90 -> { // we discover someone but not my peer
delay(100)
send("notmypeer")
delay(100)
send(peer)
}
in 90..100 -> { // we don't discovery my peer
send("notmypeer")
delay(300)
}
}
}
suspend fun tryConnect(): Boolean {
delay(100)
return badLuck(40)
}
val random = Random()
fun badLuck(probability: Int): Boolean {
check(probability in 0..100) { "Probability $probability invalid, should be in 0..100" }
return random.nextInt() <= probability
}
}
| apache-2.0 | 1733423958ce283a4652fb23d8528026 | 28.706897 | 110 | 0.515961 | 4.908832 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinImplicitThisToParameterUsage.kt | 2 | 2816 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages
import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet
import org.jetbrains.kotlin.idea.core.ShortenReferences.Options
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinParameterInfo
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.resolve.DescriptorUtils
abstract class KotlinImplicitReceiverUsage(callElement: KtElement) : KotlinUsageInfo<KtElement>(callElement) {
protected abstract fun getNewReceiverText(): String
protected open fun processReplacedElement(element: KtElement) {
}
override fun processUsage(changeInfo: KotlinChangeInfo, element: KtElement, allUsages: Array<out UsageInfo>): Boolean {
val newQualifiedCall = KtPsiFactory(element.project).createExpression(
"${getNewReceiverText()}.${element.text}"
) as KtQualifiedExpression
processReplacedElement(element.replace(newQualifiedCall) as KtElement)
return false
}
}
class KotlinImplicitThisToParameterUsage(
callElement: KtElement,
val parameterInfo: KotlinParameterInfo,
val containingCallable: KotlinCallableDefinitionUsage<*>
) : KotlinImplicitReceiverUsage(callElement) {
override fun getNewReceiverText(): String = parameterInfo.getInheritedName(containingCallable)
override fun processReplacedElement(element: KtElement) {
element.addToShorteningWaitSet(Options(removeThisLabels = true))
}
}
class KotlinImplicitThisUsage(
callElement: KtElement,
val targetDescriptor: DeclarationDescriptor
) : KotlinImplicitReceiverUsage(callElement) {
override fun getNewReceiverText() = explicateReceiverOf(targetDescriptor)
override fun processReplacedElement(element: KtElement) {
element.addToShorteningWaitSet(Options(removeThisLabels = true, removeThis = true))
}
}
fun explicateReceiverOf(descriptor: DeclarationDescriptor): String {
val name = descriptor.name
return when {
name.isSpecial -> "this"
DescriptorUtils.isCompanionObject(descriptor) -> IdeDescriptorRenderers.SOURCE_CODE
.renderClassifierName(descriptor as ClassifierDescriptor)
else -> "this@${name.asString()}"
}
} | apache-2.0 | 3fd498d4220f2a3f48ead9181f60137c | 42.338462 | 158 | 0.791548 | 5.205176 | false | false | false | false |
bradylangdale/IntrepidClient | Client Files/IntrepidClient/src/main/kotlin/org/abendigo/csgo/offsets/NetVarOffset.kt | 1 | 3070 | package org.abendigo.csgo.offsets
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap
import java.util.*
import kotlin.LazyThreadSafetyMode.NONE
import kotlin.reflect.KProperty
data class NetVarOffset(val className: String, val varName: String, val offset: Int) {
override fun toString() = "$className $varName = 0x${Integer.toHexString(offset).toUpperCase()}"
}
val netVars by lazy(NONE) {
val map = Int2ObjectArrayMap<NetVarOffset>(20000) // Have us covered for a while with 20K
var clientClass = ClientClass(firstClass)
while (clientClass.readable()) {
val table = RecvTable(clientClass.table)
if (!table.readable()) {
clientClass = ClientClass(clientClass.next)
continue
}
scanTable(map, table, 0, table.tableName)
clientClass = ClientClass(clientClass.next)
}
// dumps to file
//val builder = StringBuilder()
//for ((hash, nv) in map) builder.append("$nv\n")
//Files.write(File("netvars.txt").toPath(), builder.toString().toByteArray())
Collections.unmodifiableMap(map)
}
class NetVarDelegate(val className: String, var varName: String?, val offset: Int, val index: Int = -1) {
operator fun getValue(thisRef: Any?, property: KProperty<*>): Int {
if (varName == null) varName = property.name + if (index < 0) "" else "[$index]"
return netVars[hashClassAndVar(className, varName!!)]!!.offset + offset
}
}
fun netVar(className: String, varName: String? = null, offset: Int = 0, index: Int = -1)
= NetVarDelegate(className, if (varName != null && index >= 0) "$varName[$index]" else varName, offset, index)
fun bpNetVar(varName: String? = null, offset: Int = 0, index: Int = -1)
= netVar("DT_BasePlayer", varName, offset, index)
fun beNetVar(varName: String? = null, offset: Int = 0, index: Int = -1)
= netVar("DT_BaseEntity", varName, offset, index)
fun cspNetVar(varName: String? = null, offset: Int = 0, index: Int = -1)
= netVar("DT_CSPlayer", varName, offset, index)
fun bcwNetVar(varName: String? = null, offset: Int = 0, index: Int = -1)
= netVar("DT_BaseCombatWeapon", varName, offset, index)
fun wepNetVar(varName: String? = null, offset: Int = 0, index: Int = -1)
= netVar("DT_WeaponCSBase", varName, offset, index)
internal fun scanTable(netVars: MutableMap<Int, NetVarOffset>, table: RecvTable, offset: Int, name: String) {
for (i in 0..table.propCount - 1) {
val prop = RecvProp(table.propForId(i), offset)
if (!Character.isDigit(prop.name[0])) {
if (!prop.name.contains("baseclass")) {
val netVar = NetVarOffset(name, prop.name, prop.offset)
netVars.put(hashNetVar(netVar), netVar)
}
val child = prop.table
if (child != 0) scanTable(netVars, RecvTable(child), prop.offset, name)
}
}
}
internal fun nvString(bytes: ByteArray): String {
for (i in 0..bytes.size - 1) if (bytes[i].toInt() == 0) bytes[i] = 32
return String(bytes).split(" ")[0].trim()
}
private fun hashClassAndVar(className: String, varName: String) = className.hashCode() xor varName.hashCode()
private fun hashNetVar(netVar: NetVarOffset) = hashClassAndVar(netVar.className, netVar.varName) | gpl-3.0 | fc1fb717f8cbc5ed3c29963b1b74d73c | 35.129412 | 112 | 0.702932 | 3.207941 | false | false | false | false |
google/intellij-community | tools/ideTestingFramework/intellij.tools.ide.starter/src/com/intellij/ide/starter/models/VMOptions.kt | 1 | 9092 | package com.intellij.ide.starter.models
import com.intellij.ide.starter.ide.InstalledIde
import com.intellij.ide.starter.ide.command.MarshallableCommand
import com.intellij.ide.starter.path.IDEDataPaths
import com.intellij.ide.starter.system.SystemInfo
import com.intellij.ide.starter.utils.FileSystem.cleanPathFromSlashes
import com.intellij.ide.starter.utils.logOutput
import com.intellij.ide.starter.utils.writeJvmArgsFile
import java.io.File
import java.nio.file.Path
import kotlin.io.path.createDirectories
import kotlin.io.path.readLines
import kotlin.io.path.writeLines
import kotlin.io.path.writeText
/**
* allows to combine VMOptions mapping functions easily by calling this function as
* ```
* {}.andThen {} function
* ```
*/
fun (VMOptions.() -> VMOptions).andThen(right: VMOptions.() -> VMOptions): VMOptions.() -> VMOptions = {
val left = this@andThen
this.left().right()
}
data class VMOptions(
private val ide: InstalledIde,
private val data: List<String>,
val env: Map<String, String>
) {
companion object {
fun readIdeVMOptions(ide: InstalledIde, file: Path): VMOptions {
return VMOptions(
ide = ide,
data = file
.readLines()
.map { it.trim() }
.filter { it.isNotBlank() },
env = emptyMap()
)
}
}
override fun toString() = buildString {
appendLine("VMOptions{")
appendLine(" env=$env")
for (line in data) {
appendLine(" $line")
}
appendLine("} // VMOptions")
}
fun addSystemProperty(key: String, value: Boolean): VMOptions = addSystemProperty(key, value.toString())
fun addSystemProperty(key: String, value: Int): VMOptions = addSystemProperty(key, value.toString())
fun addSystemProperty(key: String, value: Long): VMOptions = addSystemProperty(key, value.toString())
fun addSystemProperty(key: String, value: Path): VMOptions = addSystemProperty(key, value.toAbsolutePath().toString())
fun addSystemProperty(key: String, value: String): VMOptions {
logOutput("Setting system property: [$key=$value]")
System.setProperty(key, value) // to synchronize behaviour in IDEA and on test runner side
return addLine(line = "-D$key=$value", filterPrefix = "-D$key=")
}
fun addLine(line: String, filterPrefix: String? = null): VMOptions {
if (data.contains(line)) return this
val copy = if (filterPrefix == null) data else data.filterNot { it.trim().startsWith(filterPrefix) }
return copy(data = copy + line)
}
private fun filterKeys(toRemove: (String) -> Boolean) = copy(data = data.filterNot(toRemove))
fun withEnv(key: String, value: String) = copy(env = env + (key to value))
fun writeIntelliJVmOptionFile(path: Path) {
path.writeLines(data)
logOutput("Write vmoptions patch to $path")
}
fun diffIntelliJVmOptionFile(theFile: Path): VMOptionsDiff {
val loadedOptions = readIdeVMOptions(this.ide, theFile).data
return VMOptionsDiff(originalLines = this.data, actualLines = loadedOptions)
}
fun writeJavaArgsFile(theFile: Path) {
writeJvmArgsFile(theFile, this.data)
}
fun overrideDirectories(paths: IDEDataPaths) = this
.addSystemProperty("idea.config.path", paths.configDir)
.addSystemProperty("idea.system.path", paths.systemDir)
.addSystemProperty("idea.plugins.path", paths.pluginsDir)
.addSystemProperty("idea.log.path", paths.logsDir)
fun enableStartupPerformanceLog(perf: IDEStartupReports): VMOptions {
return this
.addSystemProperty("idea.log.perf.stats.file", perf.statsJSON)
}
fun enableClassLoadingReport(filePath: Path): VMOptions {
return this
.addSystemProperty("idea.log.class.list.file", filePath)
.addSystemProperty("idea.record.classpath.info", "true")
}
fun enableVmtraceClassLoadingReport(filePath: Path): VMOptions {
if (!VMTrace.isSupported) return this
val vmTraceFile = VMTrace.vmTraceFile
return this
.addSystemProperty("idea.log.vmtrace.file", filePath)
.addLine("-agentpath:${vmTraceFile.toAbsolutePath()}=${filePath.toAbsolutePath()}")
}
fun configureLoggers(
debugLoggers: List<String> = emptyList(),
traceLoggers: List<String> = emptyList()
): VMOptions {
val withDebug = if (debugLoggers.isNotEmpty()) {
this.addSystemProperty("idea.log.debug.categories", debugLoggers.joinToString(separator = ",") { "#" + it.removePrefix("#") })
}
else {
this
}
return if (traceLoggers.isNotEmpty()) {
withDebug.addSystemProperty("idea.log.trace.categories", traceLoggers.joinToString(separator = ",") { "#" + it.removePrefix("#") })
}
else {
withDebug
}
}
fun debug(port: Int = 5005, suspend: Boolean = true): VMOptions {
val suspendKey = if (suspend) "y" else "n"
val configLine = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=${suspendKey},address=*:${port}"
return addLine(configLine, filterPrefix = "-agentlib:jdwp")
}
fun inHeadlessMode() = this
.addSystemProperty("java.awt.headless", true)
fun disableStartupDialogs() = this
.addSystemProperty("jb.consents.confirmation.enabled", false)
.addSystemProperty("jb.privacy.policy.text", "<!--999.999-->")
fun takeScreenshotIfFailure(logsDir: Path) = this
.addSystemProperty("ide.performance.screenshot.before.kill", logsDir.resolve("screenshot_beforeKill.jpg").toString())
fun installTestScript(testName: String,
paths: IDEDataPaths,
commands: Iterable<MarshallableCommand>): VMOptions {
val scriptText = commands.joinToString(separator = System.lineSeparator()) { it.storeToString() }
val scriptFileName = testName.cleanPathFromSlashes(replaceWith = "_") + ".text"
val scriptFile = paths.systemDir.resolve(scriptFileName).apply {
parent.createDirectories()
}
scriptFile.writeText(scriptText)
return this.addSystemProperty("testscript.filename", scriptFile)
// Use non-success status code 1 when running IDE as command line tool.
.addSystemProperty("testscript.must.exist.process.with.non.success.code.on.ide.error", "true")
// No need to report TeamCity test failure from within test script.
.addSystemProperty("testscript.must.report.teamcity.test.failure.on.error", "false")
}
/** @see com.intellij.startupTime.StartupTimeWithCDSonJDK13.runOnJDK13 **/
fun withCustomJRE(jre: Path): VMOptions {
if (SystemInfo.isLinux) {
val jrePath = jre.toAbsolutePath().toString()
val envKey = when (ide.productCode) {
"IU" -> "IDEA_JDK"
"WS" -> "WEBIDE_JDK"
else -> error("Not supported for product $ide")
}
return this.withEnv(envKey, jrePath)
}
if (SystemInfo.isMac) {
//Does not work -- https://intellij-support.jetbrains.com/hc/en-us/articles/206544879-Selecting-the-JDK-version-the-IDE-will-run-under
//see https://youtrack.jetbrains.com/issue/IDEA-223075
//see Launcher.m:226
val jrePath = jre.toAbsolutePath().toString()
val envKey = when (ide.productCode) {
"IU" -> "IDEA_JDK"
"WS" -> "WEBSTORM_JDK"
else -> error("Not supported for product $ide")
}
return this.withEnv(envKey, jrePath)
}
if (SystemInfo.isWindows) {
//see WinLauncher.rc and WinLauncher.cpp:294
//see https://youtrack.jetbrains.com/issue/IDEA-223348
val jrePath = jre.toRealPath().toString().replace("/", "\\")
val envKey = when (ide.productCode) {
"IU" -> "IDEA_JDK_64"
"WS" -> "WEBIDE_JDK_64"
else -> error("Not supported for product $ide")
}
return this.withEnv(envKey, jrePath)
}
error("Current OS is not supported")
}
fun usingStartupFramework() = this
.addSystemProperty("startup.performance.framework", true)
fun setFlagIntegrationTests() = this
.addSystemProperty("idea.is.integration.test", true)
fun setFatalErrorNotificationEnabled() = this
.addSystemProperty("idea.fatal.error.notification", true)
fun withJvmCrashLogDirectory(jvmCrashLogDirectory: Path) = this
.addLine("-XX:ErrorFile=${jvmCrashLogDirectory.toAbsolutePath()}${File.separator}java_error_in_idea_%p.log", "-XX:ErrorFile=")
fun withHeapDumpOnOutOfMemoryDirectory(directory: Path) = this
.addLine("-XX:HeapDumpPath=${directory.toAbsolutePath()}", "-XX:HeapDumpPath=")
fun withXmx(sizeMb: Int) = this
.addLine("-Xmx" + sizeMb + "m", "-Xmx")
fun withClassFileVerification() = this
.addLine("-XX:+UnlockDiagnosticVMOptions")
.addLine("-XX:+BytecodeVerificationLocal")
fun withG1GC() = this
.filterKeys { it == "-XX:+UseConcMarkSweepGC" }
.filterKeys { it == "-XX:+UseG1GC" }
.addLine("-XX:+UseG1GC")
/** see [JEP 318](https://openjdk.org/jeps/318) **/
fun withEpsilonGC() = this
.filterKeys { it == "-XX:+UseConcMarkSweepGC" }
.filterKeys { it == "-XX:+UseG1GC" }
.addLine("-XX:+UnlockExperimentalVMOptions")
.addLine("-XX:+UseEpsilonGC")
.addLine("-Xmx16g", "-Xmx")
// a dummy wrapper to simplify expressions
fun id() = this
}
| apache-2.0 | 7dee994d234a89ffbaf64d013753d005 | 35.223108 | 140 | 0.686538 | 4.014128 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/yesod/lucius/highlight/LuciusColors.kt | 1 | 1271 | package org.jetbrains.yesod.lucius.highlight
/**
* @author Leyla H
*/
import com.intellij.openapi.editor.colors.TextAttributesKey
interface LuciusColors {
companion object {
val COMMENT: TextAttributesKey = TextAttributesKey.createTextAttributesKey("LUCIUS_COMMENT")
val AT_RULE: TextAttributesKey = TextAttributesKey.createTextAttributesKey("LUCIUS_ATRULE")
val ATTRIBUTE: TextAttributesKey = TextAttributesKey.createTextAttributesKey("LUCIUS_ATTRIBUTE")
val DOT_IDENTIFIER: TextAttributesKey = TextAttributesKey.createTextAttributesKey("LUCIUS_DOTIDENTIFIER")
val SHARP_IDENTIFIER: TextAttributesKey = TextAttributesKey.createTextAttributesKey("LUCIUS_SHARPIDENTIFIER")
val COLON_IDENTIFIER: TextAttributesKey = TextAttributesKey.createTextAttributesKey("LUCIUS_COLONIDENTIFIER")
val CC_IDENTIFIER: TextAttributesKey = TextAttributesKey.createTextAttributesKey("LUCIUS_CCIDENTIFIER")
val INTERPOLATION: TextAttributesKey = TextAttributesKey.createTextAttributesKey("LUCIUS_INTERPOLATION")
val NUMBER: TextAttributesKey = TextAttributesKey.createTextAttributesKey("LUCIUS_NUMBER")
val STRING: TextAttributesKey = TextAttributesKey.createTextAttributesKey("LUCIUS_STRING")
}
} | apache-2.0 | 57c7d1ec64e7fe60da108677951e04c5 | 52 | 117 | 0.789929 | 5.408511 | false | false | false | false |
Leifzhang/AndroidRouter | kspCompiler/src/main/java/com/kronos/ksp/compiler/KspProcessor.kt | 1 | 2503 | package com.kronos.ksp.compiler
import com.google.auto.service.AutoService
import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSType
import com.google.devtools.ksp.symbol.Origin
import com.kronos.ksp.compiler.Const.KEY_MODULE_NAME
import com.kronos.router.BindRouter
class KspProcessor(
private val logger: KSPLogger,
private val codeGenerator: CodeGenerator,
private val moduleName: String
) : SymbolProcessor {
private lateinit var routerBindType: KSType
private var isload = false
private val ktGenerate by lazy {
KtGenerate(logger, moduleName, codeGenerator)
}
override fun process(resolver: Resolver): List<KSAnnotated> {
if (isload) {
return emptyList()
}
val symbols = resolver.getSymbolsWithAnnotation(BindRouter::class.java.name)
routerBindType = resolver.getClassDeclarationByName(
resolver.getKSNameFromString(BindRouter::class.java.name)
)?.asType() ?: kotlin.run {
logger.error("JsonClass type not found on the classpath.")
return emptyList()
}
symbols.asSequence().forEach {
add(it)
}
// logger.error("className:${moduleName}")
try {
ktGenerate.generateKt()
isload = true
} catch (e: Exception) {
logger.error(
"Error preparing :" + " ${e.stackTrace.joinToString("\n")}"
)
}
return symbols.toList()
}
private fun add(type: KSAnnotated) {
logger.check(type is KSClassDeclaration && type.origin == Origin.KOTLIN, type) {
"@JsonClass can't be applied to $type: must be a Kotlin class"
}
if (type !is KSClassDeclaration) return
ktGenerate.addStatement(type, routerBindType)
//class type
// val id: Array<String> = routerAnnotation.urls()
}
}
@AutoService(SymbolProcessorProvider::class)
class RouterProcessorProvider : SymbolProcessorProvider {
override fun create(
environment: SymbolProcessorEnvironment
): SymbolProcessor {
val moduleName = environment.options[KEY_MODULE_NAME] ?: Const.DEFAULT_APP_MODULE
val codeGenerator = environment.codeGenerator
val logger = environment.logger
return KspProcessor(logger, codeGenerator, moduleName)
}
} | mit | a38e71a2551fc844eeed78d56d99233c | 31.102564 | 89 | 0.663604 | 4.678505 | false | false | false | false |
apollographql/apollo-android | tests/integration-tests/src/commonTest/kotlin/test/StoreTest.kt | 1 | 5606 | package test
import IdCacheKeyGenerator
import IdCacheResolver
import assertEquals2
import com.apollographql.apollo3.ApolloClient
import com.apollographql.apollo3.annotations.ApolloExperimental
import com.apollographql.apollo3.cache.normalized.ApolloStore
import com.apollographql.apollo3.cache.normalized.FetchPolicy
import com.apollographql.apollo3.cache.normalized.api.CacheKey
import com.apollographql.apollo3.cache.normalized.api.MemoryCacheFactory
import com.apollographql.apollo3.cache.normalized.fetchPolicy
import com.apollographql.apollo3.cache.normalized.isFromCache
import com.apollographql.apollo3.cache.normalized.store
import com.apollographql.apollo3.exception.CacheMissException
import com.apollographql.apollo3.integration.normalizer.CharacterNameByIdQuery
import com.apollographql.apollo3.integration.normalizer.HeroAndFriendsNamesWithIDsQuery
import com.apollographql.apollo3.integration.normalizer.type.Episode
import com.apollographql.apollo3.mockserver.MockServer
import com.apollographql.apollo3.mockserver.enqueue
import com.apollographql.apollo3.testing.runTest
import testFixtureToUtf8
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.fail
/**
* Tests that write into the store programmatically.
*
* XXX: Do we need a client and mockServer for these tests?
*/
@OptIn(ApolloExperimental::class)
class StoreTest {
private lateinit var mockServer: MockServer
private lateinit var apolloClient: ApolloClient
private lateinit var store: ApolloStore
private suspend fun setUp() {
store = ApolloStore(MemoryCacheFactory(), cacheKeyGenerator = IdCacheKeyGenerator, cacheResolver = IdCacheResolver)
mockServer = MockServer()
apolloClient = ApolloClient.Builder().serverUrl(mockServer.url()).store(store).build()
}
private suspend fun tearDown() {
mockServer.stop()
}
@Test
fun removeFromStore() = runTest(before = { setUp() }, after = { tearDown() }) {
storeAllFriends()
assertFriendIsCached("1002", "Han Solo")
// remove the root query object
var removed = store.remove(CacheKey("2001"))
assertEquals(true, removed)
// Trying to get the full response should fail
assertRootNotCached()
// put everything in the cache
storeAllFriends()
assertFriendIsCached("1002", "Han Solo")
// remove a single object from the list
removed = store.remove(CacheKey("1002"))
assertEquals(true, removed)
// Trying to get the full response should fail
assertRootNotCached()
// Trying to get the object we just removed should fail
assertFriendIsNotCached("1002")
// Trying to get another object we did not remove should work
assertFriendIsCached("1003", "Leia Organa")
}
@Test
@Throws(Exception::class)
fun removeMultipleFromStore() = runTest(before = { setUp() }, after = { tearDown() }) {
storeAllFriends()
assertFriendIsCached("1000", "Luke Skywalker")
assertFriendIsCached("1002", "Han Solo")
assertFriendIsCached("1003", "Leia Organa")
// Now remove multiple keys
val removed = store.remove(listOf(CacheKey("1002"), CacheKey("1000")))
assertEquals(2, removed)
// Trying to get the objects we just removed should fail
assertFriendIsNotCached("1000")
assertFriendIsNotCached("1002")
assertFriendIsCached("1003", "Leia Organa")
}
@Test
@Throws(Exception::class)
fun cascadeRemove() = runTest(before = { setUp() }, after = { tearDown() }) {
// put everything in the cache
storeAllFriends()
assertFriendIsCached("1000", "Luke Skywalker")
assertFriendIsCached("1002", "Han Solo")
assertFriendIsCached("1003", "Leia Organa")
// test remove root query object
val removed = store.remove(CacheKey("2001"), true)
assertEquals(true, removed)
// Nothing should be cached anymore
assertRootNotCached()
assertFriendIsNotCached("1000")
assertFriendIsNotCached("1002")
assertFriendIsNotCached("1003")
}
@Test
@Throws(Exception::class)
fun directAccess() = runTest(before = { setUp() }, after = { tearDown() }) {
// put everything in the cache
storeAllFriends()
store.accessCache {
it.remove("10%")
}
assertFriendIsNotCached("1000")
assertFriendIsNotCached("1002")
assertFriendIsNotCached("1003")
}
private suspend fun storeAllFriends() {
mockServer.enqueue(testFixtureToUtf8("HeroAndFriendsNameWithIdsResponse.json"))
val response = apolloClient.query(HeroAndFriendsNamesWithIDsQuery(Episode.NEWHOPE))
.fetchPolicy(FetchPolicy.NetworkOnly).execute()
assertEquals(response.data?.hero?.name, "R2-D2")
assertEquals(response.data?.hero?.friends?.size, 3)
}
private suspend fun assertFriendIsCached(id: String, name: String) {
val characterResponse = apolloClient.query(CharacterNameByIdQuery(id))
.fetchPolicy(FetchPolicy.CacheOnly)
.execute()
assertEquals2(characterResponse.isFromCache, true)
assertEquals2(characterResponse.data?.character?.name, name)
}
private suspend fun assertFriendIsNotCached(id: String) {
try {
apolloClient.query(CharacterNameByIdQuery(id))
.fetchPolicy(FetchPolicy.CacheOnly)
.execute()
fail("A CacheMissException was expected")
} catch (e: CacheMissException) {
}
}
private suspend fun assertRootNotCached() {
try {
apolloClient.query(HeroAndFriendsNamesWithIDsQuery(Episode.NEWHOPE))
.fetchPolicy(FetchPolicy.CacheOnly)
.execute()
fail("A CacheMissException was expected")
} catch (e: CacheMissException) {
}
}
} | mit | 48da24418733b8e137a59ae266f471c2 | 31.789474 | 119 | 0.737246 | 4.400314 | false | true | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionTypeParameterToReceiverIntention.kt | 1 | 19716 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.CollectingNameValidator
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester
import org.jetbrains.kotlin.idea.base.psi.copied
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.refactoring.CallableRefactoring
import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.explicateReceiverOf
import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively
import org.jetbrains.kotlin.idea.refactoring.getAffectedCallables
import org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinIntroduceVariableHandler
import org.jetbrains.kotlin.idea.references.KtReference
import org.jetbrains.kotlin.idea.references.KtSimpleReference
import org.jetbrains.kotlin.idea.search.usagesSearch.searchReferencesOrMethodReferences
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch
import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType
import org.jetbrains.kotlin.resolve.calls.util.getArgumentByParameterIndex
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntention<KtTypeReference>(
KtTypeReference::class.java,
KotlinBundle.lazyMessage("convert.function.type.parameter.to.receiver")
) {
class FunctionDefinitionInfo(element: KtFunction) : AbstractProcessableUsageInfo<KtFunction, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val function = element ?: return
val functionParameter = function.valueParameters.getOrNull(data.functionParameterIndex) ?: return
val functionType = functionParameter.typeReference?.typeElement as? KtFunctionType ?: return
val functionTypeParameterList = functionType.parameterList ?: return
val parameterToMove = functionTypeParameterList.parameters.getOrNull(data.typeParameterIndex) ?: return
val typeReferenceToMove = parameterToMove.typeReference ?: return
runWriteAction {
functionType.setReceiverTypeReference(typeReferenceToMove)
functionTypeParameterList.removeParameter(parameterToMove)
}
}
}
class ParameterCallInfo(element: KtCallExpression) : AbstractProcessableUsageInfo<KtCallExpression, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val callExpression = element ?: return
val argumentList = callExpression.valueArgumentList ?: return
val expressionToMove = argumentList.arguments.getOrNull(data.typeParameterIndex)?.getArgumentExpression() ?: return
val callWithReceiver = KtPsiFactory(project)
.createExpressionByPattern("$0.$1", expressionToMove, callExpression) as KtQualifiedExpression
(callWithReceiver.selectorExpression as KtCallExpression).valueArgumentList!!.removeArgument(data.typeParameterIndex)
runWriteAction {
callExpression.replace(callWithReceiver)
}
}
}
class InternalReferencePassInfo(element: KtSimpleNameExpression) :
AbstractProcessableUsageInfo<KtSimpleNameExpression, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val expression = element ?: return
val lambdaType = data.lambdaType
val validator = CollectingNameValidator()
val parameterNames = lambdaType.arguments
.dropLast(1)
.map { Fe10KotlinNameSuggester.suggestNamesByType(it.type, validator, "p").first() }
val receiver = parameterNames.getOrNull(data.typeParameterIndex) ?: return
val arguments = parameterNames.filter { it != receiver }
val adapterLambda = KtPsiFactory(expression.project).createLambdaExpression(
parameterNames.joinToString(),
"$receiver.${expression.text}(${arguments.joinToString()})"
)
runWriteAction {
expression.replaced(adapterLambda).moveFunctionLiteralOutsideParenthesesIfPossible()
}
}
}
class LambdaInfo(element: KtExpression) : AbstractProcessableUsageInfo<KtExpression, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val expression = element ?: return
val context = expression.analyze(BodyResolveMode.PARTIAL)
val psiFactory = KtPsiFactory(expression.project)
if (expression is KtLambdaExpression || (expression !is KtSimpleNameExpression && expression !is KtCallableReferenceExpression)) {
expression.forEachDescendantOfType<KtThisExpression> {
if (it.getLabelName() != null) return@forEachDescendantOfType
val descriptor = context[BindingContext.REFERENCE_TARGET, it.instanceReference] ?: return@forEachDescendantOfType
runWriteAction {
it.replace(psiFactory.createExpression(explicateReceiverOf(descriptor)))
}
}
}
if (expression is KtLambdaExpression) {
expression.valueParameters.getOrNull(data.typeParameterIndex)?.let { parameterToConvert ->
val thisRefExpr = psiFactory.createThisExpression()
val search = ReferencesSearch.search(parameterToConvert, LocalSearchScope(expression)).toList()
runWriteAction {
for (ref in search) {
(ref.element as? KtSimpleNameExpression)?.replace(thisRefExpr)
}
val lambda = expression.functionLiteral
lambda.valueParameterList!!.removeParameter(parameterToConvert)
if (lambda.valueParameters.isEmpty()) {
lambda.arrow?.delete()
}
}
}
return
}
val originalLambdaTypes = data.lambdaType
val originalParameterTypes = originalLambdaTypes.arguments.dropLast(1).map { it.type }
val calleeText = when (expression) {
is KtSimpleNameExpression -> expression.text
is KtCallableReferenceExpression -> "(${expression.text})"
else -> generateVariable(expression)
}
val parameterNameValidator = CollectingNameValidator(
if (expression !is KtCallableReferenceExpression) listOf(calleeText) else emptyList()
)
val parameterNamesWithReceiver = originalParameterTypes.mapIndexed { i, type ->
if (i != data.typeParameterIndex) Fe10KotlinNameSuggester.suggestNamesByType(type, parameterNameValidator, "p")
.first() else "this"
}
val parameterNames = parameterNamesWithReceiver.filter { it != "this" }
val body = psiFactory.createExpression(parameterNamesWithReceiver.joinToString(prefix = "$calleeText(", postfix = ")"))
val replacingLambda = psiFactory.buildExpression {
appendFixedText("{ ")
appendFixedText(parameterNames.joinToString())
appendFixedText(" -> ")
appendExpression(body)
appendFixedText(" }")
} as KtLambdaExpression
runWriteAction {
expression.replaced(replacingLambda).moveFunctionLiteralOutsideParenthesesIfPossible()
}
}
private fun generateVariable(expression: KtExpression): String {
var baseCallee = ""
KotlinIntroduceVariableHandler.doRefactoring(project, null, expression, false, emptyList()) {
baseCallee = it.name!!
}
return baseCallee
}
}
private inner class Converter(
private val data: ConversionData,
editor: Editor?
) : CallableRefactoring<CallableDescriptor>(data.function.project, editor, data.functionDescriptor, text) {
override fun performRefactoring(descriptorsForChange: Collection<CallableDescriptor>) {
val callables = getAffectedCallables(project, descriptorsForChange)
val conflicts = MultiMap<PsiElement, String>()
val usages = ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>()
project.runSynchronouslyWithProgress(KotlinBundle.message("looking.for.usages.and.conflicts"), true) {
runReadAction {
val progressIndicator = ProgressManager.getInstance().progressIndicator
progressIndicator.isIndeterminate = false
val progressStep = 1.0 / callables.size
for ((i, callable) in callables.withIndex()) {
progressIndicator.fraction = (i + 1) * progressStep
if (callable !is PsiNamedElement) continue
if (!checkModifiable(callable)) {
val renderedCallable = RefactoringUIUtil.getDescription(callable, true).capitalize()
conflicts.putValue(callable, KotlinBundle.message("can.t.modify.0", renderedCallable))
}
usageLoop@ for (ref in callable.searchReferencesOrMethodReferences()) {
val refElement = ref.element
when (ref) {
is KtSimpleReference<*> -> processExternalUsage(conflicts, refElement, usages)
is KtReference -> continue@usageLoop
else -> {
if (data.isFirstParameter) continue@usageLoop
conflicts.putValue(
refElement,
KotlinBundle.message(
"can.t.replace.non.kotlin.reference.with.call.expression.0",
StringUtil.htmlEmphasize(refElement.text)
)
)
}
}
}
if (callable is KtFunction) {
usages += FunctionDefinitionInfo(callable)
processInternalUsages(callable, usages)
}
}
}
}
project.checkConflictsInteractively(conflicts) {
project.executeCommand(text) {
val elementsToShorten = ArrayList<KtElement>()
usages.sortedByDescending { it.element?.textOffset }.forEach { it.process(data, elementsToShorten) }
ShortenReferences.DEFAULT.process(elementsToShorten)
}
}
}
private fun processExternalUsage(
conflicts: MultiMap<PsiElement, String>,
refElement: PsiElement,
usages: ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>
) {
val callElement = refElement.getParentOfTypeAndBranch<KtCallElement> { calleeExpression }
if (callElement != null) {
val context = callElement.analyze(BodyResolveMode.PARTIAL)
val expressionToProcess = getArgumentExpressionToProcess(callElement, context) ?: return
if (!data.isFirstParameter
&& callElement is KtConstructorDelegationCall
&& expressionToProcess !is KtLambdaExpression
&& expressionToProcess !is KtSimpleNameExpression
&& expressionToProcess !is KtCallableReferenceExpression
) {
conflicts.putValue(
expressionToProcess,
KotlinBundle.message(
"following.expression.won.t.be.processed.since.refactoring.can.t.preserve.its.semantics.0",
expressionToProcess.text
)
)
return
}
if (!checkThisExpressionsAreExplicatable(conflicts, context, expressionToProcess)) return
if (data.isFirstParameter && expressionToProcess !is KtLambdaExpression) return
usages += LambdaInfo(expressionToProcess)
return
}
if (data.isFirstParameter) return
val callableReference = refElement.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference }
if (callableReference != null) {
conflicts.putValue(
refElement,
KotlinBundle.message(
"callable.reference.transformation.is.not.supported.0",
StringUtil.htmlEmphasize(callableReference.text)
)
)
return
}
}
private fun getArgumentExpressionToProcess(callElement: KtCallElement, context: BindingContext): KtExpression? {
return callElement
.getArgumentByParameterIndex(data.functionParameterIndex, context)
.singleOrNull()
?.getArgumentExpression()
?.let { KtPsiUtil.safeDeparenthesize(it) }
}
private fun checkThisExpressionsAreExplicatable(
conflicts: MultiMap<PsiElement, String>,
context: BindingContext,
expressionToProcess: KtExpression
): Boolean {
for (thisExpr in expressionToProcess.collectDescendantsOfType<KtThisExpression>()) {
if (thisExpr.getLabelName() != null) continue
val descriptor = context[BindingContext.REFERENCE_TARGET, thisExpr.instanceReference] ?: continue
if (explicateReceiverOf(descriptor) == "this") {
conflicts.putValue(
thisExpr,
KotlinBundle.message(
"following.expression.won.t.be.processed.since.refactoring.can.t.preserve.its.semantics.0",
thisExpr.text
)
)
return false
}
}
return true
}
private fun processInternalUsages(callable: KtFunction, usages: ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>) {
val body = when (callable) {
is KtConstructor<*> -> callable.containingClassOrObject?.body
else -> callable.bodyExpression
}
if (body != null) {
val functionParameter = callable.valueParameters.getOrNull(data.functionParameterIndex) ?: return
for (ref in ReferencesSearch.search(functionParameter, LocalSearchScope(body))) {
val element = ref.element as? KtSimpleNameExpression ?: continue
val callExpression = element.getParentOfTypeAndBranch<KtCallExpression> { calleeExpression }
if (callExpression != null) {
usages += ParameterCallInfo(callExpression)
} else if (!data.isFirstParameter) {
usages += InternalReferencePassInfo(element)
}
}
}
}
}
class ConversionData(
val typeParameterIndex: Int,
val functionParameterIndex: Int,
val lambdaType: KotlinType,
val function: KtFunction
) {
val isFirstParameter: Boolean get() = typeParameterIndex == 0
val functionDescriptor by lazy { function.unsafeResolveToDescriptor() as FunctionDescriptor }
}
private fun KtTypeReference.getConversionData(): ConversionData? {
val parameter = parent as? KtParameter ?: return null
val functionType = parameter.getParentOfTypeAndBranch<KtFunctionType> { parameterList } ?: return null
if (functionType.receiverTypeReference != null) return null
val lambdaType = functionType.getAbbreviatedTypeOrType(functionType.analyze(BodyResolveMode.PARTIAL)) ?: return null
val containingParameter = (functionType.parent as? KtTypeReference)?.parent as? KtParameter ?: return null
val ownerFunction = containingParameter.ownerFunction as? KtFunction ?: return null
val typeParameterIndex = functionType.parameters.indexOf(parameter)
val functionParameterIndex = ownerFunction.valueParameters.indexOf(containingParameter)
return ConversionData(typeParameterIndex, functionParameterIndex, lambdaType, ownerFunction)
}
override fun startInWriteAction(): Boolean = false
override fun applicabilityRange(element: KtTypeReference): TextRange? {
val data = element.getConversionData() ?: return null
val elementBefore = data.function.valueParameters[data.functionParameterIndex].typeReference!!.typeElement as KtFunctionType
val elementAfter = elementBefore.copied().apply {
setReceiverTypeReference(element)
parameterList!!.removeParameter(data.typeParameterIndex)
}
setTextGetter(KotlinBundle.lazyMessage("convert.0.to.1", elementBefore.text, elementAfter.text))
return element.textRange
}
override fun applyTo(element: KtTypeReference, editor: Editor?) {
element.getConversionData()?.let { Converter(it, editor).run() }
}
}
| apache-2.0 | a47c3637083c0cd252fe86c85fa7fb48 | 50.21039 | 158 | 0.643285 | 6.31114 | false | false | false | false |
youdonghai/intellij-community | plugins/settings-repository/src/readOnlySourcesEditor.kt | 2 | 5844 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.catchAndLog
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.options.ConfigurableUi
import com.intellij.openapi.progress.runModalTask
import com.intellij.openapi.ui.DialogBuilder
import com.intellij.openapi.ui.TextBrowseFolderListener
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.ui.DocumentAdapter
import com.intellij.util.Function
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.delete
import com.intellij.util.io.exists
import com.intellij.util.text.nullize
import com.intellij.util.text.trimMiddle
import com.intellij.util.ui.FormBuilder
import com.intellij.util.ui.table.TableModelEditor
import gnu.trove.THashSet
import org.jetbrains.settingsRepository.git.asProgressMonitor
import org.jetbrains.settingsRepository.git.cloneBare
import javax.swing.JTextField
import javax.swing.event.DocumentEvent
private val COLUMNS = arrayOf(object : TableModelEditor.EditableColumnInfo<ReadonlySource, Boolean>() {
override fun getColumnClass() = Boolean::class.java
override fun valueOf(item: ReadonlySource) = item.active
override fun setValue(item: ReadonlySource, value: Boolean) {
item.active = value
}
},
object : TableModelEditor.EditableColumnInfo<ReadonlySource, String>() {
override fun valueOf(item: ReadonlySource) = item.url
override fun setValue(item: ReadonlySource, value: String) {
item.url = value
}
})
internal fun createReadOnlySourcesEditor(): ConfigurableUi<IcsSettings> {
val itemEditor = object : TableModelEditor.DialogItemEditor<ReadonlySource> {
override fun clone(item: ReadonlySource, forInPlaceEditing: Boolean) = ReadonlySource(item.url, item.active)
override fun getItemClass() = ReadonlySource::class.java
override fun edit(item: ReadonlySource, mutator: Function<ReadonlySource, ReadonlySource>, isAdd: Boolean) {
val dialogBuilder = DialogBuilder()
val urlField = TextFieldWithBrowseButton(JTextField(20))
urlField.addBrowseFolderListener(TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFolderDescriptor()))
urlField.textField.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(event: DocumentEvent) {
dialogBuilder.setOkActionEnabled(checkUrl(urlField.text.nullize()))
}
})
dialogBuilder.title("Add read-only source").resizable(false).centerPanel(FormBuilder.createFormBuilder().addLabeledComponent("URL:", urlField).panel).setPreferredFocusComponent(urlField)
if (dialogBuilder.showAndGet()) {
mutator.`fun`(item).url = urlField.text
}
}
override fun applyEdited(oldItem: ReadonlySource, newItem: ReadonlySource) {
newItem.url = oldItem.url
}
override fun isUseDialogToAdd() = true
}
val editor = TableModelEditor(COLUMNS, itemEditor, "No sources configured")
editor.reset(if (ApplicationManager.getApplication().isUnitTestMode) emptyList() else icsManager.settings.readOnlySources)
return object : ConfigurableUi<IcsSettings> {
override fun isModified(settings: IcsSettings) = editor.isModified
override fun apply(settings: IcsSettings) {
val oldList = settings.readOnlySources
val toDelete = THashSet<String>(oldList.size)
for (oldSource in oldList) {
ContainerUtil.addIfNotNull(toDelete, oldSource.path)
}
val toCheckout = THashSet<ReadonlySource>()
val newList = editor.apply()
for (newSource in newList) {
val path = newSource.path
if (path != null && !toDelete.remove(path)) {
toCheckout.add(newSource)
}
}
if (toDelete.isEmpty && toCheckout.isEmpty) {
return
}
runModalTask(icsMessage("task.sync.title")) { indicator ->
indicator.isIndeterminate = true
val root = icsManager.readOnlySourcesManager.rootDir
if (toDelete.isNotEmpty()) {
indicator.text = "Deleting old repositories"
for (path in toDelete) {
indicator.checkCanceled()
LOG.catchAndLog {
indicator.text2 = path
root.resolve(path).delete()
}
}
}
if (toCheckout.isNotEmpty()) {
for (source in toCheckout) {
indicator.checkCanceled()
LOG.catchAndLog {
indicator.text = "Cloning ${source.url!!.trimMiddle(255)}"
val dir = root.resolve(source.path!!)
if (dir.exists()) {
dir.delete()
}
cloneBare(source.url!!, dir, icsManager.credentialsStore, indicator.asProgressMonitor()).close()
}
}
}
icsManager.readOnlySourcesManager.setSources(newList)
// blindly reload all
icsManager.schemeManagerFactory.value.process {
it.reload()
}
}
}
override fun reset(settings: IcsSettings) {
editor.reset(settings.readOnlySources)
}
override fun getComponent() = editor.createComponent()
}
}
| apache-2.0 | 6bb55f7eb44e12e2cf77945c7eaa6bee | 35.987342 | 192 | 0.710472 | 4.841756 | false | false | false | false |
JetBrains/intellij-community | python/pydevSrc/com/jetbrains/python/debugger/values/DataFrameDebugValueUtil.kt | 1 | 1010 | // 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.debugger.values
/**
*
* This function extracts children-columns of current sub-table.
* @param treeColumns - DataFrame columns in a tree structure
* @param columnsBefore - list of columns-nodes (path to the current node)
* @return set of children of an exact node
*
* Example: df.foo.bar.ba<caret>, columnsBefore = ["foo", "bar"]
*/
fun completePandasDataFrameColumns(treeColumns: DataFrameDebugValue.ColumnNode, columnsBefore: List<String?>): Set<String>? {
return if (columnsBefore.isNotEmpty()) {
var node: DataFrameDebugValue.ColumnNode? = treeColumns.children?.get(columnsBefore[0]) ?: return emptySet()
for (i in 1 until columnsBefore.size) {
node = node?.getChildIfExist(columnsBefore[i]!!)
if (node == null) {
return emptySet()
}
}
node?.childrenName
}
else {
treeColumns.childrenName
}
} | apache-2.0 | 37ded47ada2578b3eebec4501796d32c | 35.107143 | 125 | 0.708911 | 3.854962 | false | false | false | false |
spacecowboy/Feeder | app/src/main/java/com/nononsenseapps/feeder/ui/compose/feed/FeedItemIndicator.kt | 1 | 6095 | package com.nononsenseapps.feeder.ui.compose.feed
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bookmark
import androidx.compose.material.icons.filled.PushPin
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ProvideTextStyle
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.nononsenseapps.feeder.R
import com.nononsenseapps.feeder.archmodel.ThemeOptions
import com.nononsenseapps.feeder.ui.compose.theme.FeederTheme
@Composable
fun FeedItemIndicatorRow(
unread: Boolean,
bookmarked: Boolean,
pinned: Boolean,
modifier: Modifier = Modifier,
) {
Row(
modifier = modifier,
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
if (unread) {
FeedItemIndicator {
Text(stringResource(id = R.string.new_indicator))
}
}
if (bookmarked) {
FeedItemIndicator {
Icon(
Icons.Default.Bookmark,
contentDescription = stringResource(id = R.string.bookmark_article),
modifier = Modifier.size(16.dp),
)
}
}
if (pinned) {
FeedItemIndicator {
Icon(
Icons.Default.PushPin,
contentDescription = stringResource(id = R.string.pinned),
modifier = Modifier.size(16.dp),
)
}
}
}
}
@Composable
fun FeedItemIndicatorColumn(
unread: Boolean,
bookmarked: Boolean,
pinned: Boolean,
spacing: Dp = 8.dp,
iconSize: Dp = 16.dp,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier,
verticalArrangement = Arrangement.spacedBy(spacing),
horizontalAlignment = Alignment.End,
) {
if (unread) {
FeedItemIndicator {
Text(stringResource(id = R.string.new_indicator))
}
}
if (bookmarked) {
FeedItemIndicator {
Icon(
Icons.Default.Bookmark,
contentDescription = stringResource(id = R.string.bookmark_article),
modifier = Modifier.size(iconSize),
)
}
}
if (pinned) {
FeedItemIndicator {
Icon(
Icons.Default.PushPin,
contentDescription = stringResource(id = R.string.pinned),
modifier = Modifier.size(iconSize),
)
}
}
}
}
@Composable
fun FeedItemIndicator(
content: @Composable (() -> Unit),
) {
ProvideTextStyle(
value = MaterialTheme.typography.labelMedium
) {
Surface(
color = MaterialTheme.colorScheme.tertiaryContainer,
shape = MaterialTheme.shapes.medium,
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.defaultMinSize(
minHeight = 24.dp,
)
.padding(
start = 8.dp,
end = 8.dp,
),
) {
content()
}
}
}
}
@Preview("Light")
@Composable
fun PreviewLightFeedItemIndicatorRow() {
FeederTheme(currentTheme = ThemeOptions.DAY) {
Surface {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.padding(32.dp),
) {
FeedItemIndicatorRow(
unread = true,
bookmarked = true,
pinned = true,
)
}
}
}
}
@Preview("Dark")
@Composable
fun PreviewDarkFeedItemIndicatorRow() {
FeederTheme(currentTheme = ThemeOptions.NIGHT) {
Surface {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.padding(32.dp),
) {
FeedItemIndicatorRow(
unread = true,
bookmarked = true,
pinned = true,
)
}
}
}
}
@Preview("Light")
@Composable
fun PreviewLightFeedItemIndicatorColumn() {
FeederTheme(currentTheme = ThemeOptions.DAY) {
Surface {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.padding(32.dp),
) {
FeedItemIndicatorColumn(
unread = true,
bookmarked = true,
pinned = true,
)
}
}
}
}
@Preview("Dark")
@Composable
fun PreviewDarkFeedItemIndicatorColumn() {
FeederTheme(currentTheme = ThemeOptions.NIGHT) {
Surface {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.padding(32.dp),
) {
FeedItemIndicatorColumn(
unread = true,
bookmarked = true,
pinned = true,
)
}
}
}
}
| gpl-3.0 | e9becbcd8939e1b6b93d9d40f905e1b4 | 27.615023 | 88 | 0.541427 | 5.139123 | false | false | false | false |
allotria/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/EntityFamily.kt | 2 | 5808 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.workspaceModel.storage.WorkspaceEntity
import it.unimi.dsi.fastutil.ints.IntOpenHashSet
import it.unimi.dsi.fastutil.ints.IntSet
internal class ImmutableEntityFamily<E : WorkspaceEntity>(
override val entities: ArrayList<WorkspaceEntityData<E>?>,
private val emptySlotsSize: Int
) : EntityFamily<E>() {
fun toMutable() = MutableEntityFamily(entities, true)
override fun size(): Int = entities.size - emptySlotsSize
override fun familyCheck() {
val emptySlotsCounter = entities.count { it == null }
assert(emptySlotsCounter == emptySlotsSize) { "EntityFamily has unregistered gaps" }
}
}
internal class MutableEntityFamily<E : WorkspaceEntity>(
override var entities: ArrayList<WorkspaceEntityData<E>?>,
// if [freezed] is true, [entities] array MUST BE copied before modifying it.
private var freezed: Boolean
) : EntityFamily<E>() {
// This set contains empty slots at the moment of MutableEntityFamily creation
// New empty slots MUST NOT be added this this set, otherwise it would be impossible to distinguish (remove + add) and (replace) events
private val availableSlots: IntSet = IntOpenHashSet().also {
entities.mapIndexed { index, pEntityData -> if (pEntityData == null) it.add(index) }
}
// Current amount of nulls in entities
private var amountOfGapsInEntities = availableSlots.size
// Indexes of entity data that are copied for modification. These entities can be safely modified.
private val copiedToModify: IntSet = IntOpenHashSet()
fun remove(id: Int) {
if (availableSlots.contains(id)) {
thisLogger().error("id $id is already removed")
return
}
startWrite()
copiedToModify.remove(id)
entities[id] = null
amountOfGapsInEntities++
}
/**
* This method adds entityData and changes it's id to the actual one
*/
fun add(other: WorkspaceEntityData<E>) {
startWrite()
if (availableSlots.isEmpty()) {
other.id = entities.size
entities.add(other)
}
else {
val emptySlot = availableSlots.pop()
other.id = emptySlot
entities[emptySlot] = other
amountOfGapsInEntities--
}
copiedToModify.add(other.id)
}
fun book(): Int {
startWrite()
val bookedId = if (availableSlots.isEmpty()) {
entities.add(null)
amountOfGapsInEntities++
entities.lastIndex
}
else {
val emptySlot = availableSlots.pop()
entities[emptySlot] = null
emptySlot
}
copiedToModify.add(bookedId)
return bookedId
}
fun insertAtId(data: WorkspaceEntityData<E>) {
startWrite()
val prevValue = entities[data.id]
entities[data.id] = data
availableSlots.remove(data.id)
if (prevValue == null) amountOfGapsInEntities--
copiedToModify.add(data.id)
}
fun replaceById(entity: WorkspaceEntityData<E>) {
val id = entity.id
if (entities[id] == null) {
thisLogger().error("Nothing to replace. EntityData: $entity")
return
}
startWrite()
entities[id] = entity
copiedToModify.add(id)
}
/**
* Get entity data that can be modified in a save manne
*/
fun getEntityDataForModification(arrayId: Int): WorkspaceEntityData<E> {
val entity = entities.getOrNull(arrayId) ?: error("Nothing to modify")
if (arrayId in copiedToModify) return entity
startWrite()
val clonedEntity = entity.clone()
entities[arrayId] = clonedEntity
copiedToModify.add(arrayId)
return clonedEntity
}
fun set(position: Int, value: WorkspaceEntityData<E>) {
startWrite()
entities[position] = value
}
fun toImmutable(): ImmutableEntityFamily<E> {
freezed = true
copiedToModify.clear()
return ImmutableEntityFamily(entities, amountOfGapsInEntities)
}
override fun size(): Int = entities.size - amountOfGapsInEntities
override fun familyCheck() {}
internal fun isEmpty() = entities.size == amountOfGapsInEntities
/** This method should always be called before any modification */
private fun startWrite() {
if (!freezed) return
entities = ArrayList(entities)
freezed = false
}
private fun IntSet.pop(): Int {
val iterator = this.iterator()
if (!iterator.hasNext()) error("Set is empty")
val res = iterator.nextInt()
iterator.remove()
return res
}
companion object {
// Do not remove parameter. Kotlin fails with compilation without it
@Suppress("RemoveExplicitTypeArguments")
fun <T: WorkspaceEntity> createEmptyMutable() = MutableEntityFamily<T>(ArrayList(), false)
}
}
internal sealed class EntityFamily<E : WorkspaceEntity> {
internal abstract val entities: List<WorkspaceEntityData<E>?>
operator fun get(idx: Int) = entities.getOrNull(idx)
fun exists(id: Int) = get(id) != null
fun all() = entities.asSequence().filterNotNull()
abstract fun size(): Int
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is EntityFamily<*>) return false
if (entities != other.entities) return false
return true
}
override fun hashCode(): Int = entities.hashCode()
override fun toString(): String {
return "EntityFamily(entities=$entities)"
}
protected abstract fun familyCheck()
inline fun assertConsistency(entityAssertion: (WorkspaceEntityData<E>) -> Unit = {}) {
entities.forEachIndexed { idx, entity ->
if (entity != null) {
assert(idx == entity.id) { "Entity with id ${entity.id} is placed at index $idx" }
entityAssertion(entity)
}
}
familyCheck()
}
}
| apache-2.0 | 49dea49276633b460e4e74c1760cc196 | 27.470588 | 140 | 0.693698 | 4.484942 | false | false | false | false |
aporter/coursera-android | ExamplesKotlin/BcastRecCompOrdBcastWithResRec/app/src/main/java/course/examples/broadcastreceiver/resultreceiver/Receiver1.kt | 1 | 526 | package course.examples.broadcastreceiver.resultreceiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
class Receiver1 : BroadcastReceiver() {
companion object {
private const val TAG = "Receiver1"
}
override fun onReceive(context: Context, intent: Intent) {
Log.i(TAG, "INTENT RECEIVED by Receiver1")
val tmp = if (resultData == null) "" else resultData
resultData = "$tmp:Receiver 1:"
}
}
| mit | 1ddd1389b0739036bbfd66499b46c1cf | 22.909091 | 62 | 0.705323 | 4.383333 | false | false | false | false |
fluidsonic/fluid-json | coding/sources-jvm/JsonCodecProvider.kt | 1 | 2534 | package io.fluidsonic.json
import kotlin.reflect.*
public interface JsonCodecProvider<in Context : JsonCodingContext> {
public fun <ActualValue : Any> decoderCodecForType(decodableType: JsonCodingType<ActualValue>): JsonDecoderCodec<ActualValue, Context>?
public fun <ActualValue : Any> encoderCodecForClass(encodableClass: KClass<ActualValue>): JsonEncoderCodec<ActualValue, Context>?
public companion object {
@Deprecated(message = "replaced by JsonCodecProvider(…), but be careful because that one no longer adds base providers automatically")
@Suppress("DEPRECATION", "DeprecatedCallableAddReplaceWith")
public fun <Context : JsonCodingContext> of(
vararg providers: JsonCodecProvider<Context>,
base: JsonCodecProvider<JsonCodingContext>? = JsonCodecProvider.extended
): JsonCodecProvider<Context> =
of(providers.asIterable(), base = base)
@Deprecated(message = "replaced by JsonCodecProvider(…), but be careful because that one no longer adds base providers automatically")
@Suppress("DeprecatedCallableAddReplaceWith")
public fun <Context : JsonCodingContext> of(
providers: Iterable<JsonCodecProvider<Context>>,
base: JsonCodecProvider<JsonCodingContext>? = JsonCodecProvider.extended
): JsonCodecProvider<Context> =
FixedCodecProvider(providers = base?.let { providers + it } ?: providers)
}
}
private val basicProvider = JsonCodecProvider(DefaultJsonCodecs.basic + DefaultJsonCodecs.nonRecursive)
private val extendedProvider = JsonCodecProvider(DefaultJsonCodecs.extended + DefaultJsonCodecs.basic + DefaultJsonCodecs.nonRecursive)
public val JsonCodecProvider.Companion.basic: JsonCodecProvider<JsonCodingContext>
get() = basicProvider
public inline fun <reified ActualValue : Any, Context : JsonCodingContext> JsonCodecProvider<Context>.decoderCodecForType(): JsonDecoderCodec<ActualValue, Context>? =
decoderCodecForType(jsonCodingType())
public inline fun <reified ActualValue : Any, Context : JsonCodingContext> JsonCodecProvider<Context>.encoderCodecForClass(): JsonEncoderCodec<ActualValue, Context>? =
encoderCodecForClass(ActualValue::class)
public val JsonCodecProvider.Companion.extended: JsonCodecProvider<JsonCodingContext>
get() = extendedProvider
public fun <CodecProvider : JsonCodecProvider<*>> JsonCodecProvider.Companion.generated(interfaceClass: KClass<CodecProvider>): CodecProvider =
error("Cannot find annotation-based codec provider. Either $interfaceClass hasn't been annotated with @Json.CodecProvider or kapt hasn't been run.")
| apache-2.0 | 4ff9832b3bd3cc27a9a305a592a7012c | 44.178571 | 167 | 0.805138 | 4.800759 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-notifications/src/main/kotlin/slatekit/notifications/alerts/SlackAlerts.kt | 1 | 4049 | package slatekit.notifications.alerts
import okhttp3.Request
import org.json.simple.JSONArray
import org.json.simple.JSONObject
import slatekit.http.HttpRPC
import slatekit.common.Identity
import slatekit.results.Outcome
import slatekit.results.Success
import slatekit.results.builders.Outcomes
/**
* @param settings: The list of slack channels
*/
class SlackAlerts(
override val identity: Identity,
override val settings: AlertSettings,
override val client: HttpRPC = HttpRPC()
) : AlertService() {
private val baseUrl = "https://hooks.slack.com/services"
/**
* Whether or not sending is enabled
*/
override fun isEnabled(model: Alert): Boolean {
val target = this.settings.targets.firstOrNull { it.target == model.target }
return target?.enabled ?: false
}
/**
* Validates the model supplied
* @param model: The data model to send ( e.g. EmailMessage )
*/
override fun validate(model: Alert): Outcome<Alert> {
val target = this.settings.targets.firstOrNull { it.target == model.target }
return when {
model.target.isNullOrEmpty() -> Outcomes.invalid("target not provided")
model.name.isNullOrEmpty() -> Outcomes.invalid("name not provided")
target == null -> Outcomes.invalid("target invalid")
else -> Outcomes.success(model)
}
}
/**
* Builds the HttpRequest for the model
* @param model: The data model to send ( e.g. Alert )
*/
override fun build(model: Alert): Outcome<Request> {
// Parameters
val target = settings.targets.first { it.target == model.target }
val url = "$baseUrl/${target.account}/${target.channel}/${target.key}"
val json = build(model, target)
val jsonString = json.toString()
val request = HttpRPC().build(
url = url,
verb = HttpRPC.Method.Post,
meta = mapOf("Content-type" to "application/json"),
body = HttpRPC.Body.JsonContent(jsonString))
return Success(request)
}
fun build(alert: Alert, target: AlertTarget): JSONObject {
// Convert the code to a color
// 1. code 0 = pending = yellow
// 2. code 1 = success = green
// 3. code 2 = failure = red
val color = alert.code.color
// Convert all the fields supplied to a slack field definition
val json = JSONObject()
json.put("channel", "#${target.name}")
json.put("username", target.sender)
json.put("icon_emoji", ":slack:")
val attachment = JSONObject()
val fields = JSONArray()
attachment.put("fallback", alert.name)
attachment.put("pretext", alert.desc)
attachment.put("color", color)
attachment.put("title", alert.name)
attachment.put("fields", fields)
// 1 attachment only
val attachments = JSONArray()
json.put("attachments", attachments)
attachments.add(attachment)
// Fields
alert.fields?.forEach {
val field = JSONObject()
field.put("title", it.name)
field.put("value", it.value ?: "")
field.put("short", true)
fields.add(field)
}
return json
}
// /**
// *
// * curl -X POST --data-urlencode
// * channel : #service1-alerts
// * hook : https://hooks.slack.com/services/T00000000/B00000000/t00000000000000000000000
// * payload : { ... }
// */
// private fun send(target: AlertTarget, json: String):Notice<Boolean> {
// val url = "$baseUrl/${target.account}/${target.channel}/${target.key}"
// val result = HttpRPC().sendSync(
// method = HttpRPC.Method.Post,
// url = url,
// headers = mapOf("Content-type" to "application/json"),
// body = HttpRPC.Body.JsonContent(json)
// )
// return result.fold({ Success(true) }, { Failure(it.message ?: "") })
// }
}
| apache-2.0 | 38c0a1d8c87b489590ffd4593ca191e1 | 33.313559 | 96 | 0.594468 | 4.275607 | false | false | false | false |
io53/Android_RuuvitagScanner | app/src/main/java/com/ruuvi/station/tagdetails/ui/TagDetailsViewModel.kt | 1 | 2414 | package com.ruuvi.station.tagdetails.ui
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ruuvi.station.alarm.AlarmChecker
import com.ruuvi.station.app.preferences.Preferences
import com.ruuvi.station.database.tables.RuuviTagEntity
import com.ruuvi.station.tagdetails.domain.TagDetailsInteractor
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.util.Timer
import kotlin.concurrent.scheduleAtFixedRate
@ExperimentalCoroutinesApi
class TagDetailsViewModel(
private val tagDetailsInteractor: TagDetailsInteractor,
val preferences: Preferences
) : ViewModel() {
private val ioScope = CoroutineScope(Dispatchers.IO)
private var timer = Timer("timer", true)
private val isShowGraph = MutableStateFlow<Boolean>(false)
val isShowGraphFlow: StateFlow<Boolean> = isShowGraph
private val selectedTag = MutableStateFlow<RuuviTagEntity?>(null)
val selectedTagFlow: StateFlow<RuuviTagEntity?> = selectedTag
//FIXME change livedata to coroutines
val tags = MutableLiveData<List<RuuviTagEntity>>()
private val alarmStatus = MutableStateFlow<Int>(-1)
val alarmStatusFlow: StateFlow<Int> = alarmStatus
var dashboardEnabled = preferences.dashboardEnabled
var tag: RuuviTagEntity? = null
init {
ioScope.launch {
timer.scheduleAtFixedRate(0, 1000) {
checkForAlarm()
}
}
}
fun pageSelected(pageIndex: Int) {
viewModelScope.launch {
tags.value?.let {
selectedTag.value = it[pageIndex]
}
checkForAlarm()
}
}
fun switchShowGraphChannel() {
isShowGraph.value = !isShowGraph.value
}
fun refreshTags() {
tags.value = tagDetailsInteractor.getAllTags()
}
private fun checkForAlarm() {
ioScope.launch {
selectedTag.value?.id?.let { tagId ->
val tagEntry = tagDetailsInteractor.getTag(tagId)
tagEntry?.let {
withContext(Dispatchers.Main) {
alarmStatus.value = AlarmChecker.getStatus(it)
}
}
}
}
}
override fun onCleared() {
timer.cancel()
super.onCleared()
}
} | mit | 84ec56a00bcd0056c915dcf1e9f34b5e | 28.45122 | 70 | 0.669428 | 4.742633 | false | false | false | false |
leafclick/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/LabelIconCache.kt | 1 | 885 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.ui.render
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.containers.SLRUMap
import java.awt.Color
import javax.swing.JComponent
class LabelIconCache {
private val cache = SLRUMap<LabelIconId, LabelIcon>(40, 20)
fun getIcon(component: JComponent, height: Int, bgColor: Color, colors: List<Color>): LabelIcon {
val id = LabelIconId(JBUIScale.sysScale(component.graphicsConfiguration), height, bgColor, colors)
var icon = cache.get(id)
if (icon == null) {
icon = LabelIcon(component, height, bgColor, colors)
cache.put(id, icon)
}
return icon
}
private data class LabelIconId(val scale: Float, val height: Int, val bgColor: Color, val colors: List<Color>)
} | apache-2.0 | 54b347073a3a533dd0b0ffaa68f0b432 | 37.521739 | 140 | 0.737853 | 3.657025 | false | false | false | false |
Raizlabs/DBFlow | processor/src/main/kotlin/com/dbflow5/processor/definition/Methods.kt | 1 | 26009 | package com.dbflow5.processor.definition
import com.dbflow5.annotation.ConflictAction
import com.dbflow5.processor.ClassNames
import com.dbflow5.processor.ProcessorManager
import com.dbflow5.processor.definition.column.ColumnDefinition
import com.dbflow5.processor.definition.column.wrapperCommaIfBaseModel
import com.dbflow5.processor.utils.ModelUtils
import com.dbflow5.processor.utils.`override fun`
import com.dbflow5.processor.utils.codeBlock
import com.dbflow5.processor.utils.isNullOrEmpty
import com.dbflow5.quote
import com.grosner.kpoet.S
import com.grosner.kpoet.`=`
import com.grosner.kpoet.`for`
import com.grosner.kpoet.`private final field`
import com.grosner.kpoet.`return`
import com.grosner.kpoet.code
import com.grosner.kpoet.final
import com.grosner.kpoet.modifiers
import com.grosner.kpoet.param
import com.grosner.kpoet.public
import com.grosner.kpoet.statement
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.NameAllocator
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.TypeSpec
import com.squareup.javapoet.WildcardTypeName
import java.util.concurrent.atomic.AtomicInteger
import javax.lang.model.element.Modifier
/**
* Description:
*/
interface MethodDefinition {
val methodSpec: MethodSpec?
}
/**
* Description:
*
* @author Andrew Grosner (fuzz)
*/
/**
* Description: Writes the bind to content values method in the ModelDAO.
*/
class BindToContentValuesMethod(private val entityDefinition: EntityDefinition,
private val isInsert: Boolean,
private val implementsContentValuesListener: Boolean) : MethodDefinition {
override val methodSpec: MethodSpec?
get() {
val methodBuilder = MethodSpec.methodBuilder(if (isInsert) "bindToInsertValues" else "bindToContentValues")
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addParameter(ClassNames.CONTENT_VALUES, PARAM_CONTENT_VALUES)
.addParameter(entityDefinition.parameterClassName, ModelUtils.variable)
.returns(TypeName.VOID)
var retMethodBuilder: MethodSpec.Builder? = methodBuilder
if (isInsert) {
entityDefinition.columnDefinitions.forEach {
if (it.type !is ColumnDefinition.Type.PrimaryAutoIncrement
&& it.type !is ColumnDefinition.Type.RowId) {
methodBuilder.addCode(it.contentValuesStatement)
}
}
if (implementsContentValuesListener) {
methodBuilder.addStatement("\$L.onBindTo\$LValues(\$L)",
ModelUtils.variable, if (isInsert) "Insert" else "Content", PARAM_CONTENT_VALUES)
}
} else {
if (entityDefinition.primaryKeyColumnBehavior.hasAutoIncrement
|| entityDefinition.primaryKeyColumnBehavior.hasRowID) {
val autoIncrement = entityDefinition.primaryKeyColumnBehavior.associatedColumn
autoIncrement?.let {
methodBuilder.addCode(autoIncrement.contentValuesStatement)
}
} else if (!implementsContentValuesListener) {
retMethodBuilder = null
}
methodBuilder.addStatement("bindToInsertValues(\$L, \$L)", PARAM_CONTENT_VALUES, ModelUtils.variable)
if (implementsContentValuesListener) {
methodBuilder.addStatement("\$L.onBindTo\$LValues(\$L)",
ModelUtils.variable, if (isInsert) "Insert" else "Content", PARAM_CONTENT_VALUES)
}
}
return retMethodBuilder?.build()
}
companion object {
val PARAM_CONTENT_VALUES = "values"
}
}
/**
* Description:
*/
class BindToStatementMethod(private val tableDefinition: TableDefinition,
private val mode: Mode) : MethodDefinition {
enum class Mode {
INSERT {
override val methodName = "bindToInsertStatement"
override val sqlListenerName = "onBindToInsertStatement"
},
UPDATE {
override val methodName = "bindToUpdateStatement"
override val sqlListenerName = "onBindToUpdateStatement"
},
DELETE {
override val methodName = "bindToDeleteStatement"
override val sqlListenerName = "onBindToDeleteStatement"
};
abstract val methodName: String
abstract val sqlListenerName: String
}
override val methodSpec: MethodSpec?
get() {
val methodBuilder = MethodSpec.methodBuilder(mode.methodName)
.addAnnotation(Override::class.java)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addParameter(ClassNames.DATABASE_STATEMENT, PARAM_STATEMENT)
.addParameter(tableDefinition.parameterClassName,
ModelUtils.variable).returns(TypeName.VOID)
// attach non rowid first, then go onto the WHERE clause
when (mode) {
Mode.INSERT -> {
val start = AtomicInteger(1)
tableDefinition.sqlColumnDefinitions
.forEach {
methodBuilder.addCode(it.getSQLiteStatementMethod(start))
start.incrementAndGet()
}
}
Mode.UPDATE -> {
val realCount = AtomicInteger(1)
// attach non rowid first, then go onto the WHERE clause
tableDefinition.sqlColumnDefinitions
.forEach {
methodBuilder.addCode(it.getSQLiteStatementMethod(realCount))
realCount.incrementAndGet()
}
tableDefinition.primaryColumnDefinitions.forEach {
methodBuilder.addCode(it.getSQLiteStatementMethod(realCount,
defineProperty = false))
realCount.incrementAndGet()
}
}
Mode.DELETE -> {
val realCount = AtomicInteger(1)
tableDefinition.primaryColumnDefinitions.forEach {
methodBuilder.addCode(it.getSQLiteStatementMethod(realCount))
realCount.incrementAndGet()
}
}
}
if (tableDefinition.implementsSqlStatementListener) {
methodBuilder.addStatement("${ModelUtils.variable}.${mode.sqlListenerName}($PARAM_STATEMENT)")
}
return methodBuilder.build()
}
companion object {
val PARAM_STATEMENT = "statement"
}
}
/**
* Description:
*/
class CreationQueryMethod(private val tableDefinition: TableDefinition) : MethodDefinition {
override val methodSpec: MethodSpec
get() = `override fun`(String::class, "getCreationQuery") {
modifiers(public, final)
if (tableDefinition.type.isVirtual) {
addCode("return ${
codeBlock {
add("CREATE VIRTUAL TABLE IF NOT EXISTS ${tableDefinition.associationalBehavior.name.quote()} USING ")
when (tableDefinition.type) {
TableDefinition.Type.FTS4 -> add("FTS4")
TableDefinition.Type.FTS3 -> add("FTS3")
else -> {
ProcessorManager.manager.logError("Invalid table type found ${tableDefinition.type}")
}
}
add("(")
// FTS4 uses column names directly.
add(tableDefinition.columnDefinitions.joinToString { it.columnName.quote() })
tableDefinition.ftsBehavior?.addContentTableCode(tableDefinition.columnDefinitions.isNotEmpty(), this)
add(")")
}.S
};\n")
} else {
val foreignSize = tableDefinition.foreignKeyDefinitions.size
val creationBuilder = codeBlock {
add("CREATE ${if (tableDefinition.temporary) "TEMP " else ""}TABLE IF NOT EXISTS ${tableDefinition.associationalBehavior.name.quote()}(")
add(tableDefinition.columnDefinitions.joinToString { it.creationName.toString() })
tableDefinition.uniqueGroupsDefinitions.forEach {
if (it.columnDefinitionList.isNotEmpty()) add(it.creationName)
}
if (!tableDefinition.primaryKeyColumnBehavior.hasAutoIncrement) {
val primarySize = tableDefinition.primaryColumnDefinitions.size
if (primarySize > 0) {
add(", PRIMARY KEY(${tableDefinition.primaryColumnDefinitions.joinToString { it.primaryKeyName.toString() }})")
if (!tableDefinition.primaryKeyConflictActionName.isNullOrEmpty()) {
add(" ON CONFLICT ${tableDefinition.primaryKeyConflictActionName}")
}
}
}
if (foreignSize == 0) {
add(")")
}
this
}
val codeBuilder = CodeBlock.builder()
.add("return \"$creationBuilder")
tableDefinition.foreignKeyDefinitions.forEach { fk ->
val referencedTableDefinition = ProcessorManager.manager.getReferenceDefinition(tableDefinition.associationalBehavior.databaseTypeName, fk.referencedClassName)
if (referencedTableDefinition == null) {
fk.throwCannotFindReference()
} else {
codeBuilder.add(buildString {
append(", FOREIGN KEY(")
append(fk.referenceDefinitionList.joinToString { it.columnName.quote() })
append(") REFERENCES ")
append("${referencedTableDefinition.associationalBehavior.name} ")
append("(")
append(fk.referenceDefinitionList.joinToString { it.foreignColumnName.quote() })
append(") ON UPDATE ${fk.foreignKeyColumnBehavior!!.onUpdate.name.replace("_", " ")}")
append(" ON DELETE ${fk.foreignKeyColumnBehavior.onDelete.name.replace("_", " ")}")
if (fk.foreignKeyColumnBehavior.deferred) {
append(" DEFERRABLE INITIALLY DEFERRED")
}
})
}
}
if (foreignSize > 0) {
codeBuilder.add(")")
}
codeBuilder.add("\";\n")
addCode(codeBuilder.build())
}
}
}
/**
* Description: Writes out the custom type converter fields.
*/
class CustomTypeConverterPropertyMethod(private val entityDefinition: EntityDefinition)
: TypeAdder, CodeAdder {
override fun addToType(typeBuilder: TypeSpec.Builder) {
val customTypeConverters = entityDefinition.associatedTypeConverters.keys
customTypeConverters.forEach {
typeBuilder.`private final field`(it, "typeConverter${it.simpleName()}") { `=`("new \$T()", it) }
}
val globalTypeConverters = entityDefinition.globalTypeConverters.keys
globalTypeConverters.forEach {
typeBuilder.`private final field`(it, "global_typeConverter${it.simpleName()}")
}
}
override fun addCode(code: CodeBlock.Builder): CodeBlock.Builder {
// Constructor code
val globalTypeConverters = entityDefinition.globalTypeConverters.keys
globalTypeConverters.forEach {
val def = entityDefinition.globalTypeConverters[it]
val firstDef = def?.get(0)
firstDef?.typeConverterElementNames?.forEach { elementName ->
code.statement("global_typeConverter${it.simpleName()} " +
"= (\$T) holder.getTypeConverterForClass(\$T.class)", it, elementName)
}
}
return code
}
}
/**
* Description:
*/
class ExistenceMethod(private val tableDefinition: EntityDefinition) : MethodDefinition {
override val methodSpec: MethodSpec?
get() {
if (tableDefinition.primaryColumnDefinitions.isNotEmpty()) {
val primaryColumn = tableDefinition.primaryKeyColumnBehavior.associatedColumn
?: tableDefinition.primaryColumnDefinitions[0]
if (primaryColumn.shouldWriteExistence()) {
return `override fun`(TypeName.BOOLEAN, "exists",
param(tableDefinition.parameterClassName!!, ModelUtils.variable),
param(ClassNames.DATABASE_WRAPPER, "wrapper")) {
modifiers(public, final)
code {
primaryColumn.appendExistenceMethod(this)
this
}
}
}
}
return null
}
}
/**
* Description:
*/
class InsertStatementQueryMethod(private val tableDefinition: TableDefinition,
private val mode: Mode) : MethodDefinition {
enum class Mode {
INSERT,
SAVE
}
override val methodSpec: MethodSpec?
get() {
return `override fun`(String::class,
when (mode) {
Mode.INSERT -> "getInsertStatementQuery"
Mode.SAVE -> "getSaveStatementQuery"
}) {
modifiers(public, final)
`return`(codeBlock {
add("INSERT ")
if (mode != Mode.SAVE) {
if (!tableDefinition.insertConflictActionName.isEmpty()) {
add("OR ${tableDefinition.insertConflictActionName} ")
}
} else {
add("OR ${ConflictAction.REPLACE} ")
}
add("INTO ${tableDefinition.associationalBehavior.name.quote()}(")
tableDefinition.sqlColumnDefinitions
.forEachIndexed { index, columnDefinition ->
if (index > 0) add(",")
add(columnDefinition.insertStatementColumnName)
}
add(") VALUES (")
tableDefinition.sqlColumnDefinitions
.forEachIndexed { index, columnDefinition ->
if (index > 0) add(",")
add(columnDefinition.insertStatementValuesString)
}
add(")")
}.S)
}
}
}
class UpdateStatementQueryMethod(private val tableDefinition: TableDefinition) : MethodDefinition {
override val methodSpec: MethodSpec?
get() {
return `override fun`(String::class, "getUpdateStatementQuery") {
modifiers(public, final)
`return`(codeBlock {
add("UPDATE")
if (!tableDefinition.updateConflictActionName.isEmpty()) {
add(" OR ${tableDefinition.updateConflictActionName}")
}
add(" ${tableDefinition.associationalBehavior.name.quote()} SET ")
// can only change non primary key values.
tableDefinition.sqlColumnDefinitions
.forEachIndexed { index, columnDefinition ->
if (index > 0) add(",")
add(columnDefinition.updateStatementBlock)
}
add(" WHERE ")
// primary key values used as WHERE
tableDefinition.columnDefinitions
.filter { it.type.isPrimaryField || tableDefinition.type.isVirtual }
.forEachIndexed { index, columnDefinition ->
if (index > 0) add(" AND ")
add(columnDefinition.updateStatementBlock)
}
this
}.S)
}
}
}
class DeleteStatementQueryMethod(private val tableDefinition: TableDefinition) : MethodDefinition {
override val methodSpec: MethodSpec?
get() {
return `override fun`(String::class, "getDeleteStatementQuery") {
modifiers(public, final)
`return`(codeBlock {
add("DELETE FROM ${tableDefinition.associationalBehavior.name.quote()} WHERE ")
// primary key values used as WHERE
tableDefinition.columnDefinitions
.filter { it.type.isPrimaryField || tableDefinition.type.isVirtual }
.forEachIndexed { index, columnDefinition ->
if (index > 0) add(" AND ")
add(columnDefinition.updateStatementBlock)
}
this
}.S)
}
}
}
/**
* Description:
*/
class LoadFromCursorMethod(private val entityDefinition: EntityDefinition) : MethodDefinition {
override val methodSpec: MethodSpec
get() = `override fun`(entityDefinition.parameterClassName!!, "loadFromCursor",
param(ClassNames.FLOW_CURSOR, PARAM_CURSOR),
param(ClassNames.DATABASE_WRAPPER, ModelUtils.wrapper)) {
modifiers(public, final)
statement("\$1T ${ModelUtils.variable} = new \$1T()", entityDefinition.parameterClassName)
val index = AtomicInteger(0)
val nameAllocator = NameAllocator() // unique names
entityDefinition.columnDefinitions.forEach {
addCode(it.getLoadFromCursorMethod(true, index, nameAllocator))
index.incrementAndGet()
}
if (entityDefinition is TableDefinition) {
code {
entityDefinition.oneToManyDefinitions
.filter { it.isLoad }
.forEach { it.writeLoad(this) }
this
}
}
if (entityDefinition.implementsLoadFromCursorListener) {
statement("${ModelUtils.variable}.onLoadFromCursor($PARAM_CURSOR)")
}
`return`(ModelUtils.variable)
}
companion object {
val PARAM_CURSOR = "cursor"
}
}
/**
* Description:
*/
class OneToManyDeleteMethod(private val tableDefinition: TableDefinition,
private val isPlural: Boolean = false) : MethodDefinition {
private val variableName = if (isPlural) "models" else ModelUtils.variable
private val typeName: TypeName = if (!isPlural) tableDefinition.elementClassName!! else
ParameterizedTypeName.get(ClassName.get(Collection::class.java), WildcardTypeName.subtypeOf(tableDefinition.elementClassName!!))
private val methodName = "delete${if (isPlural) "All" else ""}"
override val methodSpec: MethodSpec?
get() {
val shouldWrite = tableDefinition.oneToManyDefinitions.any { it.isDelete }
if (shouldWrite || tableDefinition.cachingBehavior.cachingEnabled) {
val returnTypeName = if (isPlural) TypeName.LONG else TypeName.BOOLEAN
return `override fun`(returnTypeName, methodName,
param(typeName, variableName)) {
modifiers(public, final)
addParameter(ClassNames.DATABASE_WRAPPER, ModelUtils.wrapper)
if (tableDefinition.cachingBehavior.cachingEnabled) {
statement("cacheAdapter.removeModel${if (isPlural) "s" else ""}FromCache(${variableName})")
}
statement("\$T successful = super.${methodName}(${variableName}${wrapperCommaIfBaseModel(true)})", returnTypeName)
if (isPlural && tableDefinition.oneToManyDefinitions.isNotEmpty()) {
`for`("\$T model: models", tableDefinition.elementClassName!!) {
tableDefinition.oneToManyDefinitions.forEach { it.writeDelete(this) }
this
}
} else {
tableDefinition.oneToManyDefinitions.forEach { it.writeDelete(this) }
}
`return`("successful")
}
}
return null
}
}
/**
* Description: Overrides the save, update, and insert methods if the [com.dbflow5.annotation.OneToMany.Method.SAVE] is used.
*/
class OneToManySaveMethod(private val tableDefinition: TableDefinition,
private val methodName: String,
private val isPlural: Boolean = false) : MethodDefinition {
private val variableName = if (isPlural) "models" else ModelUtils.variable
private val typeName: TypeName = if (!isPlural) tableDefinition.elementClassName!! else
ParameterizedTypeName.get(ClassName.get(Collection::class.java), WildcardTypeName.subtypeOf(tableDefinition.elementClassName!!))
private val fullMethodName = "$methodName${if (isPlural) "All" else ""}"
override val methodSpec: MethodSpec?
get() {
if (!tableDefinition.oneToManyDefinitions.isEmpty() || tableDefinition.cachingBehavior.cachingEnabled) {
var retType = TypeName.BOOLEAN
var retStatement = "successful"
if (isPlural) {
retType = ClassName.LONG
retStatement = "count"
} else if (fullMethodName == METHOD_INSERT) {
retType = ClassName.LONG
retStatement = "rowId"
}
return `override fun`(
retType, fullMethodName,
param(typeName, variableName),
) {
modifiers(public, final)
addParameter(ClassNames.DATABASE_WRAPPER, ModelUtils.wrapper)
code {
if (isPlural) {
add("long count = ")
} else if (fullMethodName == METHOD_INSERT) {
add("long rowId = ")
} else if (fullMethodName == METHOD_UPDATE || fullMethodName == METHOD_SAVE) {
add("boolean successful = ")
}
statement("super.$fullMethodName(${variableName}${wrapperCommaIfBaseModel(true)})")
if (tableDefinition.cachingBehavior.cachingEnabled) {
statement("cacheAdapter.storeModel${if (isPlural) "s" else ""}InCache(${variableName})")
}
this
}
val filteredDefinitions = tableDefinition.oneToManyDefinitions.filter { it.isSave }
fun saveDefinitions() {
filteredDefinitions.forEach { oneToManyDefinition ->
when (methodName) {
METHOD_SAVE -> oneToManyDefinition.writeSave(this)
METHOD_UPDATE -> oneToManyDefinition.writeUpdate(this)
METHOD_INSERT -> oneToManyDefinition.writeInsert(this)
}
}
}
if (isPlural && filteredDefinitions.isNotEmpty()) {
`for`("\$T model: models", tableDefinition.elementClassName!!) {
saveDefinitions()
this
}
} else {
saveDefinitions()
}
`return`(retStatement)
}
} else {
return null
}
}
companion object {
val METHOD_SAVE = "save"
val METHOD_UPDATE = "update"
val METHOD_INSERT = "insert"
}
}
/**
* Description: Creates a method that builds a clause of ConditionGroup that represents its primary keys. Useful
* for updates or deletes.
*/
class PrimaryConditionMethod(private val tableDefinition: EntityDefinition) : MethodDefinition {
override val methodSpec: MethodSpec?
get() = `override fun`(ClassNames.OPERATOR_GROUP, "getPrimaryConditionClause",
param(tableDefinition.parameterClassName!!, ModelUtils.variable)) {
modifiers(public, final)
code {
statement("\$T clause = \$T.clause()", ClassNames.OPERATOR_GROUP, ClassNames.OPERATOR_GROUP)
tableDefinition.primaryColumnDefinitions.forEach {
val codeBuilder = CodeBlock.builder()
it.appendPropertyComparisonAccessStatement(codeBuilder)
add(codeBuilder.build())
}
this
}
`return`("clause")
}
}
| mit | f38636c3970e145150f645f70036b358 | 40.6144 | 179 | 0.551501 | 5.81987 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/refactoring/rename/impl/options.kt | 12 | 3260 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.rename.impl
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.refactoring.rename.api.RenameTarget
import com.intellij.refactoring.rename.api.ReplaceTextTargetContext
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
class RenameOptions(
val textOptions: TextOptions,
val searchScope: SearchScope,
)
/**
* @param commentStringOccurrences `null` means the option is not supported
* @param textOccurrences `null` means the option is not supported
*/
@ApiStatus.Internal
data class TextOptions(
val commentStringOccurrences: Boolean?,
val textOccurrences: Boolean?,
)
private val emptyTextOptions = TextOptions(null, null)
internal val TextOptions.isEmpty: Boolean get() = this == emptyTextOptions
internal fun renameOptions(project: Project, target: RenameTarget): RenameOptions {
return RenameOptions(
textOptions = getTextOptions(target),
searchScope = target.maximalSearchScope ?: GlobalSearchScope.allScope(project)
)
}
internal fun getTextOptions(target: RenameTarget): TextOptions {
val canRenameCommentAndStringOccurrences = !target.textTargets(ReplaceTextTargetContext.IN_COMMENTS_AND_STRINGS).isEmpty()
val canRenameTextOccurrences = !target.textTargets(ReplaceTextTargetContext.IN_PLAIN_TEXT).isEmpty()
if (!canRenameCommentAndStringOccurrences && !canRenameTextOccurrences) {
return emptyTextOptions
}
val textOptions = textOptionsService().options[target.javaClass.name]
return TextOptions(
commentStringOccurrences = if (!canRenameCommentAndStringOccurrences) null else textOptions?.commentStringOccurrences ?: true,
textOccurrences = if (!canRenameTextOccurrences) null else textOptions?.textOccurrences ?: true,
)
}
internal fun setTextOptions(target: RenameTarget, textOptions: TextOptions) {
val options = textOptionsService().options
if (textOptions.isEmpty) {
options.remove(target.javaClass.name)
}
else {
options[target.javaClass.name] = textOptions
}
}
private fun textOptionsService(): TextOptionsService = service()
@Service
@State(name = "TextOptionsService", storages = [Storage("renameTextOptions.xml")])
internal class TextOptionsService : PersistentStateComponent<TextOptionsService.State> {
class State(var entries: List<StateEntry> = ArrayList())
class StateEntry(
var fqn: String = "",
var commentsStringsOccurrences: Boolean? = null,
var textOccurrences: Boolean? = null,
)
val options: MutableMap<String, TextOptions> = HashMap() // key is RenameTarget class FQN
override fun getState(): State = State(
options.map { (fqn, textOptions) ->
StateEntry(fqn, textOptions.commentStringOccurrences, textOptions.textOccurrences)
}
)
override fun loadState(state: State) {
options.clear()
for (entry in state.entries) {
options[entry.fqn] = TextOptions(commentStringOccurrences = entry.commentsStringsOccurrences, textOccurrences = entry.textOccurrences)
}
}
}
| apache-2.0 | 7025256e7ab75f2fde73c8ef23c846ab | 35.222222 | 140 | 0.776994 | 4.521498 | false | false | false | false |
mglukhikh/intellij-community | uast/uast-common/src/org/jetbrains/uast/UastUtils.kt | 1 | 5827 | /*
* 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.
*/
@file:JvmMultifileClass
@file:JvmName("UastUtils")
package org.jetbrains.uast
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.util.PsiTreeUtil
import java.io.File
inline fun <reified T : UElement> UElement.getParentOfType(strict: Boolean = true): T? = getParentOfType(T::class.java, strict)
@JvmOverloads
fun <T : UElement> UElement.getParentOfType(parentClass: Class<out UElement>, strict: Boolean = true): T? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (parentClass.isInstance(element)) {
@Suppress("UNCHECKED_CAST")
return element as T
}
element = element.uastParent ?: return null
}
}
fun <T : UElement> UElement.getParentOfType(
parentClass: Class<out UElement>,
strict: Boolean = true,
vararg terminators: Class<out UElement>
): T? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (parentClass.isInstance(element)) {
@Suppress("UNCHECKED_CAST")
return element as T
}
if (terminators.any { it.isInstance(element) }) {
return null
}
element = element.uastParent ?: return null
}
}
fun <T : UElement> UElement.getParentOfType(
strict: Boolean = true,
firstParentClass: Class<out T>,
vararg parentClasses: Class<out T>
): T? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (firstParentClass.isInstance(element)) {
@Suppress("UNCHECKED_CAST")
return element as T
}
if (parentClasses.any { it.isInstance(element) }) {
@Suppress("UNCHECKED_CAST")
return element as T
}
element = element.uastParent ?: return null
}
}
fun UElement?.getUCallExpression(): UCallExpression? = this?.withContainingElements?.mapNotNull {
when (it) {
is UCallExpression -> it
is UQualifiedReferenceExpression -> it.selector as? UCallExpression
else -> null
}
}?.firstOrNull()
@Deprecated(message = "This function is deprecated, use getContainingUFile", replaceWith = ReplaceWith("getContainingUFile()"))
fun UElement.getContainingFile() = getContainingUFile()
fun UElement.getContainingUFile() = getParentOfType<UFile>(UFile::class.java)
fun UElement.getContainingUClass() = getParentOfType<UClass>(UClass::class.java)
fun UElement.getContainingUMethod() = getParentOfType<UMethod>(UMethod::class.java)
fun UElement.getContainingUVariable() = getParentOfType<UVariable>(UVariable::class.java)
fun UElement.getContainingMethod() = getContainingUMethod()?.psi
fun UElement.getContainingClass() = getContainingUClass()?.psi
fun UElement.getContainingVariable() = getContainingUVariable()?.psi
fun PsiElement?.getContainingClass() = this?.let { PsiTreeUtil.getParentOfType(it, PsiClass::class.java) }
fun UElement.isChildOf(probablyParent: UElement?, strict: Boolean = false): Boolean {
tailrec fun isChildOf(current: UElement?, probablyParent: UElement): Boolean {
return when (current) {
null -> false
probablyParent -> true
else -> isChildOf(current.uastParent, probablyParent)
}
}
if (probablyParent == null) return false
return isChildOf(if (strict) this else uastParent, probablyParent)
}
/**
* Resolves the receiver element if it implements [UResolvable].
*
* @return the resolved element, or null if the element was not resolved, or if the receiver element is not an [UResolvable].
*/
fun UElement.tryResolve(): PsiElement? = (this as? UResolvable)?.resolve()
fun UElement.tryResolveNamed(): PsiNamedElement? = (this as? UResolvable)?.resolve() as? PsiNamedElement
fun UElement.tryResolveUDeclaration(context: UastContext): UDeclaration? {
return (this as? UResolvable)?.resolve()?.let { context.convertElementWithParent(it, null) as? UDeclaration }
}
fun UReferenceExpression?.getQualifiedName() = (this?.resolve() as? PsiClass)?.qualifiedName
/**
* Returns the String expression value, or null if the value can't be calculated or if the calculated value is not a String.
*/
fun UExpression.evaluateString(): String? = evaluate() as? String
/**
* Get a physical [File] for this file, or null if there is no such file on disk.
*/
fun UFile.getIoFile(): File? = psi.virtualFile?.let { VfsUtilCore.virtualToIoFile(it) }
tailrec fun UElement.getUastContext(): UastContext {
val psi = this.psi
if (psi != null) {
return ServiceManager.getService(psi.project, UastContext::class.java) ?: error("UastContext not found")
}
return (uastParent ?: error("PsiElement should exist at least for UFile")).getUastContext()
}
tailrec fun UElement.getLanguagePlugin(): UastLanguagePlugin {
val psi = this.psi
if (psi != null) {
val uastContext = ServiceManager.getService(psi.project, UastContext::class.java) ?: error("UastContext not found")
return uastContext.findPlugin(psi) ?: error("Language plugin was not found for $this (${this.javaClass.name})")
}
return (uastParent ?: error("PsiElement should exist at least for UFile")).getLanguagePlugin()
}
fun Collection<UElement?>.toPsiElements() = mapNotNull { it?.psi }
| apache-2.0 | 33ed7fbb296aec1232a75f07de78b40c | 35.41875 | 127 | 0.730908 | 4.231663 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/delegatesTo/DefaultDelegatesToProvider.kt | 12 | 3140 | // 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 org.jetbrains.plugins.groovy.lang.resolve.delegatesTo
import com.intellij.psi.PsiMethod
import groovy.lang.Closure.*
import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.util.GdkMethodUtil
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_DELEGATES_TO
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_DELEGATES_TO_TARGET
import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument
class DefaultDelegatesToProvider : GrDelegatesToProvider {
override fun getDelegatesToInfo(expression: GrFunctionalExpression): DelegatesToInfo? {
val call = getContainingCall(expression) ?: return null
val result = call.advancedResolve()
val method = result.element as? PsiMethod ?: return null
if (GdkMethodUtil.isWithOrIdentity(method)) {
// this code cannot be deleted because https://issues.apache.org/jira/browse/GROOVY-6926
val qualifier = inferCallQualifier(call as GrMethodCall) ?: return null
return DelegatesToInfo(qualifier.type, DELEGATE_FIRST)
}
val argumentMapping = (result as? GroovyMethodResult)?.candidate?.argumentMapping ?: return null
val parameter = argumentMapping.targetParameter(ExpressionArgument(expression))?.psi ?: return null
parameter.getUserData(DELEGATES_TO_KEY)?.let {
return it
}
val delegateFqnData = parameter.getUserData(DELEGATES_TO_TYPE_KEY)
val strategyData = parameter.getUserData(DELEGATES_TO_STRATEGY_KEY)
if (delegateFqnData != null) {
return DelegatesToInfo(
TypesUtil.createType(delegateFqnData, expression),
strategyData ?: OWNER_FIRST
)
}
val modifierList = parameter.modifierList ?: return null
val delegatesTo = modifierList.findAnnotation(GROOVY_LANG_DELEGATES_TO) ?: return null
val strategyValue = getStrategyValue(delegatesTo.findAttributeValue("strategy"))
val delegateType = if (strategyValue == OWNER_ONLY || strategyValue == TO_SELF) {
null
}
else {
getFromValue(delegatesTo)?.takeUnless { it.equalsToText(GROOVY_LANG_DELEGATES_TO_TARGET) }
?: getFromTarget(method.parameterList, delegatesTo, argumentMapping)
?: getFromType(call, result, delegatesTo)
}
return DelegatesToInfo(delegateType, strategyValue)
}
private fun inferCallQualifier(call: GrMethodCall): GrExpression? {
val expression = call.invokedExpression
return if (expression !is GrReferenceExpression) null else expression.qualifier
}
}
| apache-2.0 | 646cf3654811b9cf34d4893e7da66719 | 45.865672 | 140 | 0.775478 | 4.537572 | false | true | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/activities/AccountActivity.kt | 1 | 7863 | package com.kickstarter.ui.activities
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.appcompat.app.AlertDialog
import com.kickstarter.R
import com.kickstarter.databinding.ActivityAccountBinding
import com.kickstarter.libs.BaseActivity
import com.kickstarter.libs.KSString
import com.kickstarter.libs.qualifiers.RequiresActivityViewModel
import com.kickstarter.libs.rx.transformers.Transformers.observeForUI
import com.kickstarter.libs.utils.ViewUtils
import com.kickstarter.libs.utils.extensions.getPaymentMethodsIntent
import com.kickstarter.ui.extensions.showSnackbar
import com.kickstarter.viewmodels.AccountViewModel
import rx.android.schedulers.AndroidSchedulers
import type.CurrencyCode
@RequiresActivityViewModel(AccountViewModel.ViewModel::class)
class AccountActivity : BaseActivity<AccountViewModel.ViewModel>() {
private var currentCurrencySelection: CurrencyCode? = null
private var newCurrencySelection: CurrencyCode? = null
private var showCurrencyChangeDialog: AlertDialog? = null
private lateinit var ksString: KSString
private lateinit var binding: ActivityAccountBinding
private val supportedCurrencies: List<CurrencyCode> by lazy {
arrayListOf(
CurrencyCode.AUD,
CurrencyCode.CAD,
CurrencyCode.CHF,
CurrencyCode.DKK,
CurrencyCode.EUR,
CurrencyCode.GBP,
CurrencyCode.HKD,
CurrencyCode.JPY,
CurrencyCode.MXN,
CurrencyCode.NOK,
CurrencyCode.PLN,
CurrencyCode.NZD,
CurrencyCode.SEK,
CurrencyCode.SGD,
CurrencyCode.USD
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAccountBinding.inflate(layoutInflater)
setContentView(binding.root)
this.ksString = requireNotNull(environment().ksString())
setUpSpinner()
this.viewModel.outputs.chosenCurrency()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { setSpinnerSelection(it) }
this.viewModel.outputs.email()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
binding.createPasswordTextView.text = this.ksString.format(getString(R.string.Youre_connected_via_Facebook_email_Create_a_password_for_this_account), "email", it)
}
this.viewModel.outputs.error()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { showSnackbar(binding.accountToolbar.accountToolbar, it) }
this.viewModel.outputs.progressBarIsVisible()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { ViewUtils.setGone(binding.progressBar, !it) }
this.viewModel.outputs.passwordRequiredContainerIsVisible()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe {
ViewUtils.setGone(binding.createPasswordContainer, it)
ViewUtils.setGone(binding.passwordRequiredContainer, !it)
}
this.viewModel.outputs.showEmailErrorIcon()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { ViewUtils.setGone(binding.emailErrorIcon, !it) }
this.viewModel.outputs.success()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { showSnackbar(binding.accountContainer, R.string.Got_it_your_changes_have_been_saved) }
binding.createPasswordRow.setOnClickListener { startActivity(Intent(this, CreatePasswordActivity::class.java)) }
binding.changeEmailRow.setOnClickListener { startActivity(Intent(this, ChangeEmailActivity::class.java)) }
binding.changePasswordRow.setOnClickListener { startActivity(Intent(this, ChangePasswordActivity::class.java)) }
binding.paymentMethodsRow.setOnClickListener { startActivity(Intent().getPaymentMethodsIntent(this, this.environment().optimizely())) }
binding.privacyRow.setOnClickListener { startActivity(Intent(this, PrivacyActivity::class.java)) }
}
private fun getListOfCurrencies(): List<String> {
val strings = arrayListOf<String>()
for (currency in supportedCurrencies) {
strings.add(getStringForCurrencyCode(currency))
}
return strings
}
private fun getStringForCurrencyCode(currency: CurrencyCode): String {
return when (currency) {
CurrencyCode.AUD -> getString(R.string.Currency_AUD)
CurrencyCode.CAD -> getString(R.string.Currency_CAD)
CurrencyCode.CHF -> getString(R.string.Currency_CHF)
CurrencyCode.DKK -> getString(R.string.Currency_DKK)
CurrencyCode.EUR -> getString(R.string.Currency_EUR)
CurrencyCode.GBP -> getString(R.string.Currency_GBP)
CurrencyCode.HKD -> getString(R.string.Currency_HKD)
CurrencyCode.JPY -> getString(R.string.Currency_JPY)
CurrencyCode.MXN -> getString(R.string.Currency_MXN)
CurrencyCode.NOK -> getString(R.string.Currency_NOK)
CurrencyCode.NZD -> getString(R.string.Currency_NZD)
CurrencyCode.PLN -> getString(R.string.Currency_PLN)
CurrencyCode.SEK -> getString(R.string.Currency_SEK)
CurrencyCode.SGD -> getString(R.string.Currency_SGD)
CurrencyCode.USD -> getString(R.string.Currency_USD)
else -> currency.rawValue()
}
}
private fun lazyFollowingOptOutConfirmationDialog(): AlertDialog {
if (this.showCurrencyChangeDialog == null) {
this.showCurrencyChangeDialog = AlertDialog.Builder(this, R.style.AlertDialog)
.setCancelable(false)
.setTitle(getString(R.string.Change_currency))
.setMessage(getString(R.string.Project_goal_and_pledge))
.setNegativeButton(R.string.Cancel) { _, _ ->
setSpinnerSelection(currentCurrencySelection!!.rawValue())
}
.setPositiveButton(R.string.Yes_change_currency) { _, _ ->
this.viewModel.inputs.onSelectedCurrency(newCurrencySelection!!)
setSpinnerSelection(newCurrencySelection!!.rawValue())
}
.create()
}
return this.showCurrencyChangeDialog!!
}
private fun setSpinnerSelection(currencyCode: String) {
val selectedCurrencyCode = CurrencyCode.safeValueOf(currencyCode)
currentCurrencySelection = selectedCurrencyCode
binding.currencySpinner.setSelection(supportedCurrencies.indexOf(selectedCurrencyCode))
}
private fun setUpSpinner() {
val arrayAdapter = ArrayAdapter<String>(this, R.layout.item_spinner, getListOfCurrencies())
arrayAdapter.setDropDownViewResource(R.layout.item_spinner_dropdown)
binding.currencySpinner.adapter = arrayAdapter
binding.currencySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, postion: Int, id: Long) {
currentCurrencySelection?.let {
if (supportedCurrencies.indexOf(it) != postion) {
newCurrencySelection = supportedCurrencies[postion]
lazyFollowingOptOutConfirmationDialog().show()
}
}
}
}
}
}
| apache-2.0 | 85911c2792abb755c2a05640e5ce9bbf | 42.441989 | 178 | 0.671245 | 4.967151 | false | false | false | false |
benjamin-bader/thrifty | thrifty-schema/src/main/kotlin/com/microsoft/thrifty/schema/render/ThriftSpec.kt | 1 | 2860 | /*
* Thrifty
*
* Copyright (c) Microsoft Corporation
*
* All rights reserved.
*
* 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
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE,
* FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/
package com.microsoft.thrifty.schema.render
import com.microsoft.thrifty.schema.NamespaceScope
import com.microsoft.thrifty.schema.Schema
import java.io.File
/**
* A representation of an individual thrift spec file.
*
* @property filePath the relative path of this file.
* @property namespaces the namespaces of this file.
* @property includes any includes this file declares.
* @property schema the [Schema] of elements contained within this file.
*/
data class ThriftSpec internal constructor(
val filePath: String,
val namespaces: Map<NamespaceScope, String>,
val includes: List<Include>,
val schema: Schema
) {
/**
* The simple name of this file.
*/
val name = File(filePath).nameWithoutExtension
/**
* @return a render of this file. This returns valid thrift that could be parsed back and yield
* an equivalent [Schema] to this spec's [schema].
*/
fun render(fileComment: String? = null) = renderTo(StringBuilder(), fileComment).toString()
/**
* Renders this file to a given [buffer]. This returns valid thrift that could be parsed back and
* yield an equivalent [Schema] to this spec's [schema].
*
* @return the [buffer] for convenience chaining.
*/
fun <A : Appendable> renderTo(buffer: A, fileComment: String? = null) = buffer.apply {
fileComment?.let {
append("// ", it)
appendLine()
appendLine()
}
if (namespaces.isNotEmpty()) {
namespaces.entries.joinEachTo(
buffer = buffer,
separator = NEWLINE,
postfix = DOUBLE_NEWLINE
) { _, (key, value) ->
buffer.append("namespace ", key.thriftName, " ", value)
}
}
if (includes.isNotEmpty()) {
includes
.sortedBy(Include::path)
.joinEachTo(buffer,
NEWLINE, postfix = DOUBLE_NEWLINE
) { _, include ->
buffer.append("include \"", include.path, "\"")
}
}
schema.renderTo(this)
}
}
| apache-2.0 | 21ad6b086e3c8f4509a054fe31abbbc5 | 32.647059 | 116 | 0.63007 | 4.440994 | false | false | false | false |
googlecodelabs/android-performance | benchmarking/app/src/main/java/com/example/macrobenchmark_codelab/ui/JetsnackAppState.kt | 1 | 6390 | /*
* 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.example.macrobenchmark_codelab.ui
import android.content.res.Resources
import androidx.compose.material.ScaffoldState
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.Lifecycle
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavDestination
import androidx.navigation.NavGraph
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.example.macrobenchmark_codelab.model.SnackbarManager
import com.example.macrobenchmark_codelab.ui.home.HomeSections
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
/**
* Destinations used in the [JetsnackMain].
*/
object MainDestinations {
const val HOME_ROUTE = "home"
const val SNACK_DETAIL_ROUTE = "snack"
const val SNACK_ID_KEY = "snackId"
}
/**
* Remembers and creates an instance of [JetsnackAppState]
*/
@Composable
fun rememberJetsnackAppState(
scaffoldState: ScaffoldState = rememberScaffoldState(),
navController: NavHostController = rememberNavController(),
snackbarManager: SnackbarManager = SnackbarManager,
resources: Resources = resources(),
coroutineScope: CoroutineScope = rememberCoroutineScope()
) =
remember(scaffoldState, navController, snackbarManager, resources, coroutineScope) {
JetsnackAppState(scaffoldState, navController, snackbarManager, resources, coroutineScope)
}
/**
* Responsible for holding state related to [JetsnackMain] and containing UI-related logic.
*/
@Stable
class JetsnackAppState(
val scaffoldState: ScaffoldState,
val navController: NavHostController,
private val snackbarManager: SnackbarManager,
private val resources: Resources,
coroutineScope: CoroutineScope
) {
// Process snackbars coming from SnackbarManager
init {
coroutineScope.launch {
snackbarManager.messages.collect { currentMessages ->
if (currentMessages.isNotEmpty()) {
val message = currentMessages[0]
val text = resources.getText(message.messageId)
// Display the snackbar on the screen. `showSnackbar` is a function
// that suspends until the snackbar disappears from the screen
scaffoldState.snackbarHostState.showSnackbar(text.toString())
// Once the snackbar is gone or dismissed, notify the SnackbarManager
snackbarManager.setMessageShown(message.id)
}
}
}
}
// ----------------------------------------------------------
// BottomBar state source of truth
// ----------------------------------------------------------
val bottomBarTabs = HomeSections.values()
private val bottomBarRoutes = bottomBarTabs.map { it.route }
// Reading this attribute will cause recompositions when the bottom bar needs shown, or not.
// Not all routes need to show the bottom bar.
val shouldShowBottomBar: Boolean
@Composable get() = navController
.currentBackStackEntryAsState().value?.destination?.route in bottomBarRoutes
// ----------------------------------------------------------
// Navigation state source of truth
// ----------------------------------------------------------
val currentRoute: String?
get() = navController.currentDestination?.route
fun upPress() {
navController.navigateUp()
}
fun navigateToBottomBarRoute(route: String) {
if (route != currentRoute) {
navController.navigate(route) {
launchSingleTop = true
restoreState = true
// Pop up backstack to the first destination and save state. This makes going back
// to the start destination when pressing back in any other bottom tab.
popUpTo(findStartDestination(navController.graph).id) {
saveState = true
}
}
}
}
fun navigateToSnackDetail(snackId: Long, from: NavBackStackEntry) {
// In order to discard duplicated navigation events, we check the Lifecycle
if (from.lifecycleIsResumed()) {
navController.navigate("${MainDestinations.SNACK_DETAIL_ROUTE}/$snackId")
}
}
}
/**
* If the lifecycle is not resumed it means this NavBackStackEntry already processed a nav event.
*
* This is used to de-duplicate navigation events.
*/
private fun NavBackStackEntry.lifecycleIsResumed() =
this.lifecycle.currentState == Lifecycle.State.RESUMED
private val NavGraph.startDestination: NavDestination?
get() = findNode(startDestinationId)
/**
* Copied from similar function in NavigationUI.kt
*
* https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:navigation/navigation-ui/src/main/java/androidx/navigation/ui/NavigationUI.kt
*/
private tailrec fun findStartDestination(graph: NavDestination): NavDestination {
return if (graph is NavGraph) findStartDestination(graph.startDestination!!) else graph
}
/**
* A composable function that returns the [Resources]. It will be recomposed when `Configuration`
* gets updated.
*/
@Composable
@ReadOnlyComposable
private fun resources(): Resources {
LocalConfiguration.current
return LocalContext.current.resources
}
| apache-2.0 | 171fae9cd001521f3f2df82f5e7ca8f3 | 36.810651 | 156 | 0.696401 | 5.220588 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/ui/base/activity/ActivityMixin.kt | 2 | 2299 | package eu.kanade.tachiyomi.ui.base.activity
import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.ActionBar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
interface ActivityMixin {
fun setupToolbar(toolbar: Toolbar, backNavigation: Boolean = true) {
setSupportActionBar(toolbar)
getSupportActionBar()?.setDisplayHomeAsUpEnabled(true)
if (backNavigation) {
toolbar.setNavigationOnClickListener { onBackPressed() }
}
}
fun setAppTheme() {
setTheme(when (Injekt.get<PreferencesHelper>().theme()) {
2 -> R.style.Theme_Tachiyomi_Dark
else -> R.style.Theme_Tachiyomi
})
}
fun setToolbarTitle(title: String) {
getSupportActionBar()?.title = title
}
fun setToolbarTitle(titleResource: Int) {
getSupportActionBar()?.title = getString(titleResource)
}
fun setToolbarSubtitle(title: String) {
getSupportActionBar()?.subtitle = title
}
fun setToolbarSubtitle(titleResource: Int) {
getSupportActionBar()?.subtitle = getString(titleResource)
}
/**
* Requests read and write permissions on Android M and higher.
*/
fun requestPermissionsOnMarshmallow() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE),
1)
}
}
}
fun getActivity(): AppCompatActivity
fun onBackPressed()
fun getSupportActionBar(): ActionBar?
fun setSupportActionBar(toolbar: Toolbar?)
fun setTheme(resource: Int)
fun getString(resource: Int): String
} | gpl-3.0 | 4b2671dabb923de3ef13554571338674 | 28.87013 | 119 | 0.685515 | 4.870763 | false | false | false | false |
jwren/intellij-community | plugins/devkit/intellij.devkit.i18n/src/IntelliJProjectResourceBundleManager.kt | 1 | 3190 | // 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.idea.devkit.i18n
import com.intellij.lang.properties.psi.I18nizedTextGenerator
import com.intellij.lang.properties.psi.PropertiesFile
import com.intellij.lang.properties.psi.ResourceBundleManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiShortNamesCache
import com.intellij.util.PathUtil
import org.jetbrains.idea.devkit.actions.generateDefaultBundleName
import org.jetbrains.idea.devkit.util.PsiUtil
class IntelliJProjectResourceBundleManager(project: Project) : ResourceBundleManager(project) {
override fun isActive(context: PsiFile): Boolean {
return PsiUtil.isIdeaProject(myProject)
}
override fun escapeValue(value: String): String {
return value.replace("&", "\\&")
}
override fun suggestPropertiesFiles(contextModules: MutableSet<Module>): MutableList<String> {
val preferredBundleNames = contextModules.mapTo(HashSet()) { generateDefaultBundleName(it) }
val files = super.suggestPropertiesFiles(contextModules)
val (preferredFiles, otherFiles) = files.partition {
FileUtil.getNameWithoutExtension(PathUtil.getFileName(it)) in preferredBundleNames
}
return (preferredFiles + otherFiles).toMutableList()
}
override fun getI18nizedTextGenerator(): I18nizedTextGenerator? {
return object : I18nizedTextGenerator() {
override fun getI18nizedText(propertyKey: String, propertiesFile: PropertiesFile?, context: PsiElement?): String {
return getI18nizedConcatenationText(propertyKey, "", propertiesFile, context)
}
override fun getI18nizedConcatenationText(propertyKey: String,
parametersString: String,
propertiesFile: PropertiesFile?,
context: PsiElement?): String {
val bundleClassName = suggestBundleClassName(propertiesFile, context)
val args = if (parametersString.isNotEmpty()) ", $parametersString" else ""
return "$bundleClassName.message(\"$propertyKey\"$args)"
}
private fun suggestBundleClassName(propertiesFile: PropertiesFile?, context: PsiElement?): String {
if (propertiesFile == null) return "UnknownBundle"
val bundleName = propertiesFile.virtualFile.nameWithoutExtension
val scope = context?.resolveScope ?: GlobalSearchScope.projectScope(myProject)
val classesByName = PsiShortNamesCache.getInstance(myProject).getClassesByName(bundleName, scope)
return classesByName.firstOrNull()?.qualifiedName ?: bundleName
}
}
}
override fun getResourceBundle(): PsiClass? = null
override fun getTemplateName(): String? = null
override fun getConcatenationTemplateName(): String? = null
override fun canShowJavaCodeInfo(): Boolean = false
} | apache-2.0 | 284341f46fd56af57eb22bce8c4a0fa8 | 47.348485 | 120 | 0.740125 | 4.915254 | false | false | false | false |
vovagrechka/fucking-everything | 1/global-menu/src/main/java/botinok-tests.kt | 1 | 4709 | package vgrechka.botinok
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Suite
import org.springframework.context.annotation.AnnotationConfigApplicationContext
import vgrechka.*
import vgrechka.db.*
import vgrechka.spew.*
@RunWith(Suite::class) @Suite.SuiteClasses(
BotinokTest1::class
)
class BotinokTests
class BotinokTest1 {
val log = TestLogger()
@Test fun test1() {
backPlatform.springctx = AnnotationConfigApplicationContext(BotinokTestAppConfig::class.java)
DBPile.executeBunchOfSQLStatementsAndCloseConnection(BotinokGeneratedDBPile.ddl.dropCreateAllScript)
backPlatform.tx {
botinokPlayRepo.save(newBotinokPlay(name = "Pizdaplay", pile = "{}")).also {play->
botinokArenaRepo.save(newBotinokArena(play = play, name = "Pizdarena", screenshot = byteArrayOf(), position = 0, pile = "{}")).also {arena->
botinokRegionRepo.save(newBotinokRegion(arena = arena, name = "Fucking region", x = 10, y = 20, w = 100, h = 200, position = 0, pile = "{}"))
botinokRegionRepo.save(newBotinokRegion(arena = arena, name = "Shitty region", x = 15, y = 23, w = 350, h = 60, position = 1, pile = "{}"))
}
botinokArenaRepo.save(newBotinokArena(play = play, name = "Mandarena", screenshot = byteArrayOf(), position = 1, pile = "{}")).also {arena->
botinokRegionRepo.save(newBotinokRegion(arena = arena, name = "Bitchy region", x = 43, y = 32, w = 784, h = 46, position = 0, pile = "{}"))
}
}
botinokPlayRepo.save(newBotinokPlay(name = "Hamlet", pile = "{}")).also {play->
botinokArenaRepo.save(newBotinokArena(play = play, name = "the fucking", screenshot = byteArrayOf(), position = 0, pile = "{}")).also {arena->
botinokRegionRepo.save(newBotinokRegion(arena = arena, name = "prince", x = 453, y = 858, w = 74, h = 500, position = 0, pile = "{}"))
botinokRegionRepo.save(newBotinokRegion(arena = arena, name = "of Denmark", x = 424, y = 483, w = 22, h = 33, position = 1, pile = "{}"))
}
}
}
backPlatform.tx {
log.forEach(botinokPlayRepo.findAll(), "5ac827cf-d160-439e-8bce-ef41e51ec69a") {play, itemLog ->
itemLog.println(play)
log.forEach(play.arenas, "6c363edb-8cd5-4b87-8bf0-f899024482f8") {arena, itemLog ->
itemLog.println(" $arena")
log.forEach(arena.regions, "84c184eb-91b9-41e4-8bd4-f42dfd5b268a") {region, itemLog ->
itemLog.println(" $region")
}
}
}
}
// Now that cascade and orphanRemoval are used, below is not relevant.
// TODO:vgrechka Provide an option to generate code without cascading delete -- for the sake of safety
//
// fun <T : GCommonEntityFields> checkForeignKeyPreventsDeletion(deleteFromRepo: GRepository<T>) {
// AssertPile.thrownExceptionOrOneOfItsCausesMessageContains("SQLITE_CONSTRAINT_FOREIGNKEY") {
// backPlatform.tx {
// val shit = deleteFromRepo.findAll().first()
// deleteFromRepo.delete(shit)
// }
// }
// }
//
// checkForeignKeyPreventsDeletion(deleteFromRepo = botinokPlayRepo)
// checkForeignKeyPreventsDeletion(deleteFromRepo = botinokArenaRepo)
log.assertEquals("""
BotinokPlay(name=Pizdaplay) 0--5ac827cf-d160-439e-8bce-ef41e51ec69a
BotinokArena(name=Pizdarena) 0-0--6c363edb-8cd5-4b87-8bf0-f899024482f8
BotinokRegion(name=Fucking region, x=10, y=20, w=100, h=200) 0-0-0--84c184eb-91b9-41e4-8bd4-f42dfd5b268a
BotinokRegion(name=Shitty region, x=15, y=23, w=350, h=60) 0-0-1--84c184eb-91b9-41e4-8bd4-f42dfd5b268a
BotinokArena(name=Mandarena) 0-1--6c363edb-8cd5-4b87-8bf0-f899024482f8
BotinokRegion(name=Bitchy region, x=43, y=32, w=784, h=46) 0-1-0--84c184eb-91b9-41e4-8bd4-f42dfd5b268a
BotinokPlay(name=Hamlet) 1--5ac827cf-d160-439e-8bce-ef41e51ec69a
BotinokArena(name=the fucking) 1-0--6c363edb-8cd5-4b87-8bf0-f899024482f8
BotinokRegion(name=prince, x=453, y=858, w=74, h=500) 1-0-0--84c184eb-91b9-41e4-8bd4-f42dfd5b268a
BotinokRegion(name=of Denmark, x=424, y=483, w=22, h=33) 1-0-1--84c184eb-91b9-41e4-8bd4-f42dfd5b268a
""")
}
}
| apache-2.0 | eaf64827a44c0f105f92188574fa9f84 | 51.322222 | 161 | 0.600127 | 3.194708 | false | true | false | false |
android/wear-os-samples | ComposeAdvanced/app/src/main/java/com/example/android/wearable/composeadvanced/presentation/MainActivity.kt | 1 | 2752 | /*
* 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.wearable.composeadvanced.presentation
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.LaunchedEffect
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.lifecycle.viewmodel.MutableCreationExtras
import androidx.navigation.NavHostController
import androidx.wear.compose.navigation.rememberSwipeDismissableNavController
import com.example.android.wearable.composeadvanced.data.WatchRepository
import com.example.android.wearable.composeadvanced.util.JankPrinter
/**
* Compose for Wear OS app that demonstrates how to use Wear specific Scaffold, Navigation,
* curved text, Chips, and many other composables.
*
* Displays different text at the bottom of the landing screen depending on shape of the device
* (round vs. square/rectangular).
*/
class MainActivity : ComponentActivity() {
private lateinit var jankPrinter: JankPrinter
internal lateinit var navController: NavHostController
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen()
super.onCreate(savedInstanceState)
jankPrinter = JankPrinter()
setTheme(android.R.style.Theme_DeviceDefault)
setContent {
navController = rememberSwipeDismissableNavController()
WearApp(
swipeDismissableNavController = navController
)
LaunchedEffect(Unit) {
navController.currentBackStackEntryFlow.collect {
jankPrinter.setRouteState(route = it.destination.route)
}
}
}
jankPrinter.installJankStats(activity = this)
}
override fun getDefaultViewModelCreationExtras(): CreationExtras {
return MutableCreationExtras(super.getDefaultViewModelCreationExtras()).apply {
set(
WatchRepository.WATCH_REPOSITORY_KEY,
(application as BaseApplication).watchRepository
)
}
}
}
| apache-2.0 | 3b8a7ac23eadb925c461876c3993ba86 | 35.693333 | 95 | 0.733648 | 5.134328 | false | false | false | false |
liz3/Liz3Web | src/main/java/de/liz3/liz3web/util/extension/Utils.kt | 1 | 5114 | package de.liz3.liz3web.util.extension
import com.eclipsesource.v8.V8
import com.eclipsesource.v8.V8Array
import com.eclipsesource.v8.V8Object
import com.eclipsesource.v8.V8Value
import com.teamdev.jxbrowser.chromium.Browser
import com.teamdev.jxbrowser.chromium.BrowserType
import com.teamdev.jxbrowser.chromium.JSObject
import com.teamdev.jxbrowser.chromium.JSValue
import java.util.*
/**
* Created by liz3 on 28.07.17.
*/
fun transportToV8Object(obj: JSValue, target: V8Object, runtime: V8) {
if(obj.isObject) {
for(key in obj.asObject().propertyNames) {
val value = obj.asObject().getProperty(key)
if(value.isObject) {
val newObject = V8Object(runtime)
transportToV8Object(value, newObject, runtime)
target.add(key, newObject)
continue
}
if(value.isArray) {
val newArray = V8Array(runtime)
transportToV8Object(value, newArray, runtime)
target.add(key, newArray)
continue
}
if(value.isNumber) {
target.add(key, value.asNumber().value)
continue
}
if(value.isBoolean) {
target.add(key, value.asBoolean().value)
continue
}
if(value.isBoolean) {
target.add(key, value.asBoolean().value)
continue
}
if(value.isString) {
target.add(key, value.asString().value)
continue
}
}
return
}
if(obj.isArray) {
val realTarget = target as V8Array
for(index in 0..obj.asArray().length()) {
val value = obj.asArray()[index]
if(value.isObject) {
val newObject = V8Object(runtime)
transportToV8Object(value, newObject, runtime)
realTarget.push(newObject)
continue
}
if(value.isArray) {
val newArray = V8Array(runtime)
transportToV8Object(value, newArray, runtime)
target.push(newArray)
continue
}
if(value.isNumber) {
target.push( value.asNumber().value)
continue
}
if(value.isBoolean) {
target.push( value.asBoolean().value)
continue
}
if(value.isBoolean) {
target.push( value.asBoolean().value)
continue
}
if(value.isString) {
target.push( value.asString().value)
continue
}
}
}
}
fun transportToJsObject(source:V8Value, target: JSValue, browser:Browser = Browser(BrowserType.LIGHTWEIGHT)) {
if(source is V8Object) {
for(key in source.keys) {
val value = source.get(key)
if(value is V8Object) {
val newObj = browser.executeJavaScriptAndReturnValue("{}")
transportToJsObject(value, newObj.asObject(), browser)
target.asObject().setProperty(key, newObj)
continue
}
if(value is V8Array) {
val newArr = browser.executeJavaScriptAndReturnValue("[]")
transportToJsObject(value, newArr, browser)
target.asObject().setProperty(key, newArr)
continue
}
target.asObject().setProperty(key, value)
}
}
if(source is V8Array) {
for(index in 0..source.length()){
val value = source.get(index)
if(value is V8Object) {
val newObj = browser.executeJavaScriptAndReturnValue("{}")
transportToJsObject(value, newObj.asObject(), browser)
target.asArray().set(target.asArray().length() + 1, newObj)
continue
}
if(value is V8Array) {
val newObj = browser.executeJavaScriptAndReturnValue("[]")
transportToJsObject(value, newObj.asArray(), browser)
target.asArray().set(target.asArray().length() + 1, newObj)
continue
}
target.asArray().set(target.asArray().length() + 1, value)
}
}
}
class ListenerList : Vector<Any>() {
private val addListener = Vector<Runnable>()
private val remListener = Vector<Runnable>()
var last: Any? = null
override fun add(element: Any?): Boolean {
last = element
for(listener in addListener) {
listener.run()
}
return super.add(element)
}
override fun remove(element: Any?): Boolean {
last = element
for(listener in remListener) {
listener.run()
}
return super.remove(element)
}
fun addPushListener(run:Runnable) {
addListener.addElement(run)
}
fun addRemoveListener(run:Runnable) {
remListener.addElement(run)
}
}
| apache-2.0 | 3798edba9157555705743fcc3855dbd7 | 28.732558 | 110 | 0.538131 | 4.537711 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/ExcludeUrlEntityImpl.kt | 2 | 6437 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ExcludeUrlEntityImpl(val dataSource: ExcludeUrlEntityData) : ExcludeUrlEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val url: VirtualFileUrl
get() = dataSource.url
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: ExcludeUrlEntityData?) : ModifiableWorkspaceEntityBase<ExcludeUrlEntity, ExcludeUrlEntityData>(
result), ExcludeUrlEntity.Builder {
constructor() : this(ExcludeUrlEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ExcludeUrlEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
index(this, "url", this.url)
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isUrlInitialized()) {
error("Field ExcludeUrlEntity#url should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ExcludeUrlEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.url != dataSource.url) this.url = dataSource.url
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var url: VirtualFileUrl
get() = getEntityData().url
set(value) {
checkModificationAllowed()
getEntityData(true).url = value
changedProperty.add("url")
val _diff = diff
if (_diff != null) index(this, "url", value)
}
override fun getEntityClass(): Class<ExcludeUrlEntity> = ExcludeUrlEntity::class.java
}
}
class ExcludeUrlEntityData : WorkspaceEntityData<ExcludeUrlEntity>() {
lateinit var url: VirtualFileUrl
fun isUrlInitialized(): Boolean = ::url.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ExcludeUrlEntity> {
val modifiable = ExcludeUrlEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ExcludeUrlEntity {
return getCached(snapshot) {
val entity = ExcludeUrlEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ExcludeUrlEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ExcludeUrlEntity(url, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ExcludeUrlEntityData
if (this.entitySource != other.entitySource) return false
if (this.url != other.url) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ExcludeUrlEntityData
if (this.url != other.url) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + url.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + url.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.url?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| apache-2.0 | eef474b6728f15b076ed6733bf146931 | 31.510101 | 120 | 0.725649 | 5.133174 | false | false | false | false |
GunoH/intellij-community | platform/testFramework/src/com/intellij/util/io/java/ClassFileBuilder.kt | 4 | 1643 | // 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.util.io.java
import com.intellij.util.io.DirectoryContentBuilder
import org.jetbrains.jps.model.java.LanguageLevel
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
import kotlin.reflect.KClass
/**
* Produces class-file with qualified name [name] in a place specified by [content]. If the class is not from the default package,
* the produced file will be placed in a sub-directory according to its package.
*/
inline fun DirectoryContentBuilder.classFile(name: String, content: ClassFileBuilder.() -> Unit) {
val builder = MethodHandles.lookup().findConstructor(
ClassFileBuilder::class.java.classLoader.loadClass("com.intellij.util.io.java.impl.ClassFileBuilderImpl"),
MethodType.methodType(Void.TYPE, String::class.java),
).invoke(name) as ClassFileBuilder
builder.content()
builder.generate(this)
}
abstract class ClassFileBuilder {
var javaVersion: LanguageLevel = LanguageLevel.JDK_1_8
var superclass: String = "java.lang.Object"
var interfaces: List<String> = emptyList()
var access: AccessModifier = AccessModifier.PUBLIC
abstract fun field(name: String, type: KClass<*>, access: AccessModifier = AccessModifier.PRIVATE)
/**
* Adds a field which type is a class with qualified name [type]
*/
abstract fun field(name: String, type: String, access: AccessModifier = AccessModifier.PRIVATE)
abstract fun generate(targetRoot: DirectoryContentBuilder)
}
enum class AccessModifier { PRIVATE, PUBLIC, PROTECTED, PACKAGE_LOCAL } | apache-2.0 | f234376078f1060e22e7621ba8ff0487 | 39.097561 | 130 | 0.772976 | 4.289817 | false | false | false | false |
GunoH/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/service/GradleFileModificationTracker.kt | 8 | 2310 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gradle.service
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileDocumentManagerListener
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.SingleAlarm
import org.gradle.tooling.ProjectConnection
import org.jetbrains.annotations.ApiStatus
import java.nio.file.Path
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicReference
/**
* Temporarily store latest virtual files written from documents.
*
* Used to report latest changes to Gradle Daemon.
* Will skip wrapper download progress events.
*/
@Service
@ApiStatus.Experimental
class GradleFileModificationTracker: Disposable {
private val myCacheRef = AtomicReference<MutableSet<Path>>(ConcurrentHashMap.newKeySet())
private val alarm = SingleAlarm.pooledThreadSingleAlarm(5000, this) {
myCacheRef.set(ConcurrentHashMap.newKeySet())
}
/**
* If called when wrapper is not yet available, wrapper download events will be lost!
* Make sure, wrapper is already downloaded in the call site
*/
fun notifyConnectionAboutChangedPaths(connection: ProjectConnection) {
val collection = myCacheRef.getAndSet(ConcurrentHashMap.newKeySet()).toList()
if (collection.isNotEmpty()) {
connection.notifyDaemonsAboutChangedPaths(collection)
}
}
fun beforeSaving(virtualFile: VirtualFile) {
val vfs = virtualFile.fileSystem
vfs.getNioPath(virtualFile)?.let {
myCacheRef.get().add(it)
}
alarm.cancelAndRequest()
}
override fun dispose() {
// nothing to do, just dispose the alarm
}
}
internal class GradleFileModificationListener: FileDocumentManagerListener {
override fun beforeDocumentSaving(document: Document) {
val modificationTracker = ApplicationManager.getApplication().getService(GradleFileModificationTracker::class.java)
FileDocumentManager.getInstance().getFile(document)?.let { modificationTracker.beforeSaving(it) }
}
} | apache-2.0 | 4421b4b6f222e38929c8e5f345a0d931 | 36.885246 | 120 | 0.792208 | 4.676113 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/ui/floating/FloatingToolbar.kt | 2 | 7797 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.ui.floating
import com.intellij.codeInsight.hint.HintManager
import com.intellij.codeInsight.hint.HintManagerImpl
import com.intellij.ide.ui.customization.CustomActionsSchema
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.event.EditorMouseEvent
import com.intellij.openapi.editor.event.EditorMouseListener
import com.intellij.openapi.editor.event.EditorMouseMotionListener
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiEditorUtil
import com.intellij.psi.util.PsiUtilCore
import com.intellij.psi.util.elementType
import com.intellij.psi.util.parents
import com.intellij.ui.LightweightHint
import com.intellij.util.ui.UIUtil
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile
import org.jetbrains.annotations.ApiStatus
import java.awt.BorderLayout
import java.awt.Point
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.JComponent
import javax.swing.JPanel
import kotlin.properties.Delegates
@ApiStatus.Internal
open class FloatingToolbar(val editor: Editor, private val actionGroupId: String) : Disposable {
private val mouseListener = MouseListener()
private val keyboardListener = KeyboardListener()
private val mouseMotionListener = MouseMotionListener()
private var hint: LightweightHint? = null
private var buttonSize: Int by Delegates.notNull()
private var lastSelection: String? = null
init {
registerListeners()
}
fun isShown() = hint != null
fun hideIfShown() {
hint?.hide()
}
fun showIfHidden() {
if (hint != null || !canBeShownAtCurrentSelection()) {
return
}
createActionToolbar(editor.contentComponent) { toolbar ->
val hint = hint ?: return@createActionToolbar
hint.component.add(toolbar.component, BorderLayout.CENTER)
showOrUpdateLocation(hint)
hint.addHintListener { [email protected] = null }
}
hint = LightweightHint(JPanel(BorderLayout())).apply {
setForceShowAsPopup(true)
}
}
fun updateLocationIfShown() {
showOrUpdateLocation(hint ?: return)
}
override fun dispose() {
unregisterListeners()
hideIfShown()
hint = null
}
private fun createActionToolbar(targetComponent: JComponent, onUpdated: (ActionToolbar) -> Unit) {
val group = CustomActionsSchema.getInstance().getCorrectedAction(actionGroupId) as? ActionGroup ?: return
val toolbar = createImmediatelyUpdatedToolbar(group, EDITOR_FLOATING_TOOLBAR, targetComponent, horizontal = true, onUpdated)
buttonSize = toolbar.maxButtonHeight
}
private fun showOrUpdateLocation(hint: LightweightHint) {
HintManagerImpl.getInstanceImpl().showEditorHint(
hint,
editor,
getHintPosition(hint),
HintManager.HIDE_BY_ESCAPE or HintManager.UPDATE_BY_SCROLLING,
0,
true
)
}
private fun registerListeners() {
editor.addEditorMouseListener(mouseListener)
editor.addEditorMouseMotionListener(mouseMotionListener)
editor.contentComponent.addKeyListener(keyboardListener)
}
private fun unregisterListeners() {
editor.removeEditorMouseListener(mouseListener)
editor.removeEditorMouseMotionListener(mouseMotionListener)
editor.contentComponent.removeKeyListener(keyboardListener)
}
private fun canBeShownAtCurrentSelection(): Boolean {
val file = PsiEditorUtil.getPsiFile(editor)
PsiDocumentManager.getInstance(file.project).commitDocument(editor.document)
val selectionModel = editor.selectionModel
val elementAtStart = PsiUtilCore.getElementAtOffset(file, selectionModel.selectionStart)
val elementAtEnd = PsiUtilCore.getElementAtOffset(file, selectionModel.selectionEnd)
return !(hasIgnoredParent(elementAtStart) || hasIgnoredParent(elementAtEnd))
}
protected open fun hasIgnoredParent(element: PsiElement): Boolean {
if (element.containingFile !is MarkdownFile) {
return true
}
return element.parents(withSelf = true).any { it.elementType in elementsToIgnore }
}
private fun getHintPosition(hint: LightweightHint): Point {
val hintPos = HintManagerImpl.getInstanceImpl().getHintPosition(hint, editor, HintManager.DEFAULT)
// because of `hint.setForceShowAsPopup(true)`, HintManager.ABOVE does not place the hint above
// the hint remains on the line, so we need to move it up ourselves
val dy = -(hint.component.preferredSize.height + verticalGap)
val dx = buttonSize * -2
hintPos.translate(dx, dy)
return hintPos
}
private fun updateOnProbablyChangedSelection(onSelectionChanged: (String) -> Unit) {
val newSelection = editor.selectionModel.selectedText
when (newSelection) {
null -> hideIfShown()
lastSelection -> Unit
else -> onSelectionChanged(newSelection)
}
lastSelection = newSelection
}
private inner class MouseListener : EditorMouseListener {
override fun mouseReleased(e: EditorMouseEvent) {
updateOnProbablyChangedSelection {
if (isShown()) {
updateLocationIfShown()
} else {
showIfHidden()
}
}
}
}
private inner class KeyboardListener : KeyAdapter() {
override fun keyReleased(e: KeyEvent) {
super.keyReleased(e)
if (e.source != editor.contentComponent) {
return
}
updateOnProbablyChangedSelection {
hideIfShown()
}
}
}
private inner class MouseMotionListener : EditorMouseMotionListener {
override fun mouseMoved(e: EditorMouseEvent) {
val visualPosition = e.visualPosition
val hoverSelected = editor.caretModel.allCarets.any {
val beforeSelectionEnd = it.selectionEndPosition.after(visualPosition)
val afterSelectionStart = visualPosition.after(it.selectionStartPosition)
beforeSelectionEnd && afterSelectionStart
}
if (hoverSelected) {
showIfHidden()
}
}
}
companion object {
internal const val EDITOR_FLOATING_TOOLBAR = "MarkdownEditorFloatingToolbar"
private const val verticalGap = 2
private val elementsToIgnore = listOf(
MarkdownElementTypes.CODE_FENCE,
MarkdownElementTypes.CODE_BLOCK,
MarkdownElementTypes.CODE_SPAN,
MarkdownElementTypes.HTML_BLOCK,
MarkdownElementTypes.LINK_DESTINATION
)
internal fun createImmediatelyUpdatedToolbar(
group: ActionGroup,
place: String,
targetComponent: JComponent,
horizontal: Boolean = true,
onUpdated: (ActionToolbar) -> Unit
): ActionToolbar {
val toolbar = object : ActionToolbarImpl(place, group, horizontal) {
override fun actionsUpdated(forced: Boolean, newVisibleActions: MutableList<out AnAction>) {
val firstTime = forced && !hasVisibleActions()
super.actionsUpdated(forced, newVisibleActions)
if (firstTime) {
UIUtil.markAsShowing(this, false)
onUpdated.invoke(this)
}
}
}
toolbar.targetComponent = targetComponent
toolbar.putClientProperty(ActionToolbarImpl.SUPPRESS_FAST_TRACK, true)
toolbar.setReservePlaceAutoPopupIcon(false)
UIUtil.markAsShowing(toolbar, true)
toolbar.updateActionsImmediately(true)
return toolbar
}
}
}
| apache-2.0 | dd451c06b2394bbe65252f6ea10e93b9 | 33.964126 | 158 | 0.74208 | 4.860973 | false | false | false | false |
kivensolo/UiUsingListView | module-Home/src/main/java/com/zeke/home/fragments/home/HomeLiveFragment.kt | 1 | 3577 | package com.zeke.home.fragments.home
import androidx.fragment.app.Fragment
import com.google.android.material.tabs.TabLayout
import com.kingz.module.common.BaseActivity
import com.kingz.module.home.R
import com.zeke.home.contract.LiveContract
import com.zeke.home.entity.Live
import com.zeke.home.entity.TemplatePageData
import com.zeke.home.entity.TimeTableData
import com.zeke.home.fragments.SimplePageContentFragment
import com.zeke.home.presenters.LivePresenter
import com.zeke.kangaroo.utils.ZLog
import java.util.*
/**
* date:2019/12/29
* description:首页 - 直播 Fragment
*/
class HomeLiveFragment : HomeBaseFragment<LivePresenter>(), LiveContract.View {
// 频道分组数据 <频道分组, 频道列表>
private var channleData: HashMap<String, ArrayList<Live>>
init {
mPresenter = LivePresenter(this)
channleData = HashMap()
}
override val isShown: Boolean
get() = activity != null && (activity as BaseActivity).isActivityShow && isVisible
// @Override
// public boolean isShown() {
// return getActivity() != null && ((BaseActivity) getActivity()).isActivityShow() && isVisible();
// }
override fun getLayoutId(): Int {
return R.layout.fragment_live_tab
}
override fun onViewCreated() {
super.onViewCreated() // 有公共控件可以复用 调用一次super
// 具体子页面对公共View组件的设置
tableLayout?.apply {
tabMode = TabLayout.MODE_SCROLLABLE
setSelectedTabIndicatorColor(resources.getColor(R.color.text_blue))
setTabTextColors(resources.getColor(android.R.color.white),
resources.getColor(R.color.text_blue))
}
fetchLiveInfo()
}
private fun fetchLiveInfo() {
mPresenter.getLiveInfo(activity!!)
}
override fun showLiveInfo(data: MutableList<Live>?) {
ZLog.d("showLiveInfo onResult. currentThread=" + Thread.currentThread().name)
val groupTempList:ArrayList<Live> = ArrayList()
val titleList:ArrayList<TemplatePageData> = ArrayList()
if (data != null) {
for (live in data) {
if (!live.isTitle) {
// 当前分类下的频道数据列表搜集
groupTempList.add(live)
} else {
if (groupTempList.size > 0) {
// 保存上次搜集的频道数据
channleData[titleList[titleList.size - 1].name] = groupTempList.clone() as ArrayList<Live>
}
groupTempList.clear()
// 直播频道分类数据
titleList.add(TemplatePageData(name = live.name))
}
}
}
if(groupTempList.size > 0){
channleData[titleList[titleList.size-1].name] = groupTempList.clone() as ArrayList<Live>
}
groupTempList.clear()
if(titleList.size > 0){
hideLoading()
}
viewPagerAdapter?.setData(titleList)
}
override fun createPageFragment(data: TemplatePageData, position: Int): Fragment {
val fragment = SimplePageContentFragment()
val pageTitle = viewPagerAdapter?.getPageTitle(position)
val channelList = channleData[pageTitle]
fragment.mRV.addAll(channelList)
fragment.mRV.notifyDataSetChanged()
return fragment
}
override fun showTimeTable(data: MutableList<TimeTableData>) {
}
override fun showVideo(url: String) {
}
}
| gpl-2.0 | b5045fb5796d91569441bb4741c8adf4 | 32.194175 | 114 | 0.630009 | 4.13422 | false | false | false | false |
jwren/intellij-community | plugins/settings-sync/tests/com/intellij/settingsSync/TestRemoteCommunicator.kt | 2 | 905 | package com.intellij.settingsSync
import java.util.concurrent.CountDownLatch
internal class TestRemoteCommunicator : SettingsSyncRemoteCommunicator {
var offline: Boolean = false
var updateResult: UpdateResult? = null
var pushed: SettingsSnapshot? = null
var startPushLatch: CountDownLatch? = null
lateinit var pushedLatch: CountDownLatch
override fun checkServerState(): ServerState {
return ServerState.UpdateNeeded
}
override fun receiveUpdates(): UpdateResult {
return updateResult ?: UpdateResult.Error("Unexpectedly null update result")
}
override fun push(snapshot: SettingsSnapshot): SettingsSyncPushResult {
startPushLatch?.countDown()
if (offline) return SettingsSyncPushResult.Error("Offline")
pushed = snapshot
if (::pushedLatch.isInitialized) pushedLatch.countDown()
return SettingsSyncPushResult.Success
}
override fun delete() {}
} | apache-2.0 | ff50bfcbff57004ee4dee4c3ddf16e72 | 29.2 | 80 | 0.771271 | 5.484848 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/commonUtils.kt | 4 | 7922 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions.loopToCallChain
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.readWriteAccess
import org.jetbrains.kotlin.idea.search.codeUsageScope
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
fun KtExpression.isConstant(): Boolean {
val bindingContext = analyze(BodyResolveMode.PARTIAL)
return ConstantExpressionEvaluator.getConstant(this, bindingContext) != null
}
fun KtExpression?.isTrueConstant() = this != null && node?.elementType == KtNodeTypes.BOOLEAN_CONSTANT && text == "true"
fun KtExpression?.isFalseConstant() = this != null && node?.elementType == KtNodeTypes.BOOLEAN_CONSTANT && text == "false"
private val ZERO_VALUES = setOf(0, 0L, 0f, 0.0)
fun KtExpression.isZeroConstant(): Boolean {
if (this !is KtConstantExpression) return false
val bindingContext = analyze(BodyResolveMode.PARTIAL)
val type = bindingContext.getType(this) ?: return false
val constant = ConstantExpressionEvaluator.getConstant(this, bindingContext) ?: return false
return constant.getValue(type) in ZERO_VALUES
}
fun KtExpression?.isVariableReference(variable: KtCallableDeclaration): Boolean {
return this is KtNameReferenceExpression && this.mainReference.isReferenceTo(variable)
}
fun KtExpression?.isSimpleName(name: Name): Boolean {
return this is KtNameReferenceExpression && this.getQualifiedExpressionForSelector() == null && this.getReferencedNameAsName() == name
}
fun KtCallableDeclaration.hasUsages(inElement: KtElement): Boolean {
assert(inElement.isPhysical)
return hasUsages(listOf(inElement))
}
fun KtCallableDeclaration.hasUsages(inElements: Collection<KtElement>): Boolean {
assert(this.isPhysical)
// TODO: it's a temporary workaround about strange dead-lock when running inspections
return inElements.any { ReferencesSearch.search(this, LocalSearchScope(it)).any() }
// return ReferencesSearch.search(this, LocalSearchScope(inElements.toTypedArray())).any()
}
fun KtVariableDeclaration.hasWriteUsages(): Boolean {
assert(this.isPhysical)
if (!isVar) return false
return ReferencesSearch.search(this, codeUsageScope()).any {
(it as? KtSimpleNameReference)?.element?.readWriteAccess(useResolveForReadWrite = true)?.isWrite == true
}
}
fun KtCallableDeclaration.countUsages(inElement: KtElement): Int {
assert(this.isPhysical)
return ReferencesSearch.search(this, LocalSearchScope(inElement)).count()
}
fun KtCallableDeclaration.countUsages(inElements: Collection<KtElement>): Int {
assert(this.isPhysical)
// TODO: it's a temporary workaround about strange dead-lock when running inspections
return inElements.sumOf { ReferencesSearch.search(this, LocalSearchScope(it)).count() }
}
fun KtCallableDeclaration.countUsages(): Int {
assert(this.isPhysical)
return ReferencesSearch.search(this, codeUsageScope()).count()
}
fun KtVariableDeclaration.countWriteUsages(): Int {
assert(this.isPhysical)
if (!isVar) return 0
return ReferencesSearch.search(this, codeUsageScope()).count {
(it as? KtSimpleNameReference)?.element?.readWriteAccess(useResolveForReadWrite = true)?.isWrite == true
}
}
fun KtVariableDeclaration.countWriteUsages(inElement: KtElement): Int {
assert(this.isPhysical)
if (!isVar) return 0
return ReferencesSearch.search(this, LocalSearchScope(inElement)).count {
(it as? KtSimpleNameReference)?.element?.readWriteAccess(useResolveForReadWrite = true)?.isWrite == true
}
}
fun KtVariableDeclaration.hasWriteUsages(inElement: KtElement): Boolean {
assert(this.isPhysical)
if (!isVar) return false
return ReferencesSearch.search(this, LocalSearchScope(inElement)).any {
(it as? KtSimpleNameReference)?.element?.readWriteAccess(useResolveForReadWrite = true)?.isWrite == true
}
}
fun KtCallableDeclaration.hasDifferentSetsOfUsages(elements1: Collection<KtElement>, elements2: Collection<KtElement>): Boolean {
val setOfElements1 = elements1.toSet()
val setOfElements2 = elements2.toSet()
return countUsages(setOfElements1 - setOfElements2) != countUsages(setOfElements2 - setOfElements1)
}
fun KtExpressionWithLabel.targetLoop(context: BindingContext? = null): KtLoopExpression? {
val label = getTargetLabel()
return if (label == null) {
parents.firstIsInstanceOrNull()
} else {
//TODO: does PARTIAL always work here?
(context ?: analyze(BodyResolveMode.PARTIAL))[BindingContext.LABEL_TARGET, label] as? KtLoopExpression
}
}
fun KtExpression.isPlusPlusOf(): KtExpression? {
if (this !is KtUnaryExpression) return null
if (operationToken != KtTokens.PLUSPLUS) return null
return baseExpression
}
fun KtExpression.previousStatement(): KtExpression? {
val statement = unwrapIfLabeled()
if (statement.parent !is KtBlockExpression) return null
return statement.siblings(forward = false, withItself = false).firstIsInstanceOrNull()
}
fun KtExpression.nextStatement(): KtExpression? {
val statement = unwrapIfLabeled()
if (statement.parent !is KtBlockExpression) return null
return statement.siblings(forward = true, withItself = false).firstIsInstanceOrNull()
}
fun KtExpression.unwrapIfLabeled(): KtExpression {
var statement = this
while (true) {
statement = statement.parent as? KtLabeledExpression ?: return statement
}
}
fun KtLoopExpression.deleteWithLabels() {
unwrapIfLabeled().delete()
}
fun PsiChildRange.withoutFirstStatement(): PsiChildRange {
val newFirst = first!!.siblings(forward = true, withItself = false).first { it !is PsiWhiteSpace }
return PsiChildRange(newFirst, last)
}
fun PsiChildRange.withoutLastStatement(): PsiChildRange {
val newLast = last!!.siblings(forward = false, withItself = false).first { it !is PsiWhiteSpace }
return PsiChildRange(first, newLast)
}
fun KtExpression?.extractStaticFunctionCallArguments(functionFqName: String): List<KtExpression?>? {
val callExpression = when (this) {
is KtDotQualifiedExpression -> selectorExpression as? KtCallExpression
is KtCallExpression -> this
else -> null
} ?: return null
val resolvedCall = callExpression.resolveToCall() ?: return null
val functionDescriptor = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return null
if (functionDescriptor.dispatchReceiverParameter != null || functionDescriptor.extensionReceiverParameter != null) return null
if (functionDescriptor.importableFqName?.asString() != functionFqName) return null
return resolvedCall.valueArgumentsByIndex?.map { it?.arguments?.singleOrNull()?.getArgumentExpression() }
}
| apache-2.0 | 43c5f39227494b137acfee9697326579 | 42.054348 | 158 | 0.77228 | 4.881084 | false | false | false | false |
alexames/flatbuffers | kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/Utf8.kt | 6 | 14906 | /*
* Copyright 2021 Google Inc. All rights reserved.
*
* 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.
*/
@file:Suppress("NOTHING_TO_INLINE")
package com.google.flatbuffers.kotlin
public object Utf8 {
/**
* Returns the number of bytes in the UTF-8-encoded form of `sequence`. For a string,
* this method is equivalent to `string.getBytes(UTF_8).length`, but is more efficient in
* both time and space.
*
* @throws IllegalArgumentException if `sequence` contains ill-formed UTF-16 (unpaired
* surrogates)
*/
private fun computeEncodedLength(sequence: CharSequence): Int {
// Warning to maintainers: this implementation is highly optimized.
val utf16Length = sequence.length
var utf8Length = utf16Length
var i = 0
// This loop optimizes for pure ASCII.
while (i < utf16Length && sequence[i].toInt() < 0x80) {
i++
}
// This loop optimizes for chars less than 0x800.
while (i < utf16Length) {
val c = sequence[i]
if (c.toInt() < 0x800) {
utf8Length += 0x7f - c.toInt() ushr 31 // branch free!
} else {
utf8Length += encodedLengthGeneral(sequence, i)
break
}
i++
}
if (utf8Length < utf16Length) {
// Necessary and sufficient condition for overflow because of maximum 3x expansion
error("UTF-8 length does not fit in int: ${(utf8Length + (1L shl 32))}")
}
return utf8Length
}
private fun encodedLengthGeneral(sequence: CharSequence, start: Int): Int {
val utf16Length = sequence.length
var utf8Length = 0
var i = start
while (i < utf16Length) {
val c = sequence[i]
if (c.toInt() < 0x800) {
utf8Length += 0x7f - c.toInt() ushr 31 // branch free!
} else {
utf8Length += 2
if (c.isSurrogate()) {
// Check that we have a well-formed surrogate pair.
val cp: Int = codePointAt(sequence, i)
if (cp < MIN_SUPPLEMENTARY_CODE_POINT) {
errorSurrogate(i, utf16Length)
}
i++
}
}
i++
}
return utf8Length
}
/**
* Returns the number of bytes in the UTF-8-encoded form of `sequence`. For a string,
* this method is equivalent to `string.getBytes(UTF_8).length`, but is more efficient in
* both time and space.
*
* @throws IllegalArgumentException if `sequence` contains ill-formed UTF-16 (unpaired
* surrogates)
*/
public fun encodedLength(sequence: CharSequence): Int = computeEncodedLength(sequence)
/**
* Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'.
*/
public inline fun isOneByte(b: Byte): Boolean = b >= 0
/**
* Returns whether this is a two-byte codepoint with the form 110xxxxx 0xC0..0xDF.
*/
public inline fun isTwoBytes(b: Byte): Boolean = b < 0xE0.toByte()
/**
* Returns whether this is a three-byte codepoint with the form 1110xxxx 0xE0..0xEF.
*/
public inline fun isThreeBytes(b: Byte): Boolean = b < 0xF0.toByte()
/**
* Returns whether this is a four-byte codepoint with the form 11110xxx 0xF0..0xF4.
*/
public inline fun isFourByte(b: Byte): Boolean = b < 0xF8.toByte()
public fun handleOneByte(byte1: Byte, resultArr: CharArray, resultPos: Int) {
resultArr[resultPos] = byte1.toChar()
}
public fun handleTwoBytes(
byte1: Byte,
byte2: Byte,
resultArr: CharArray,
resultPos: Int
) {
// Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and
// overlong 2-byte, '11000001'.
if (byte1 < 0xC2.toByte()) {
error("Invalid UTF-8: Illegal leading byte in 2 bytes utf")
}
if (isNotTrailingByte(byte2)) {
error("Invalid UTF-8: Illegal trailing byte in 2 bytes utf")
}
resultArr[resultPos] = (byte1.toInt() and 0x1F shl 6 or trailingByteValue(byte2)).toChar()
}
public fun handleThreeBytes(
byte1: Byte,
byte2: Byte,
byte3: Byte,
resultArr: CharArray,
resultPos: Int
) {
if (isNotTrailingByte(byte2) || // overlong? 5 most significant bits must not all be zero
byte1 == 0xE0.toByte() && byte2 < 0xA0.toByte() || // check for illegal surrogate codepoints
byte1 == 0xED.toByte() && byte2 >= 0xA0.toByte() ||
isNotTrailingByte(byte3)
) {
error("Invalid UTF-8")
}
resultArr[resultPos] =
(byte1.toInt() and 0x0F shl 12 or (trailingByteValue(byte2) shl 6) or trailingByteValue(byte3)).toChar()
}
public fun handleFourBytes(
byte1: Byte,
byte2: Byte,
byte3: Byte,
byte4: Byte,
resultArr: CharArray,
resultPos: Int
) {
if (isNotTrailingByte(byte2) || // Check that 1 <= plane <= 16. Tricky optimized form of:
// valid 4-byte leading byte?
// if (byte1 > (byte) 0xF4 ||
// overlong? 4 most significant bits must not all be zero
// byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 ||
// codepoint larger than the highest code point (U+10FFFF)?
// byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F)
(byte1.toInt() shl 28) + (byte2 - 0x90.toByte()) shr 30 != 0 || isNotTrailingByte(byte3) ||
isNotTrailingByte(byte4)
) {
error("Invalid UTF-8")
}
val codepoint: Int = (
byte1.toInt() and 0x07 shl 18
or (trailingByteValue(byte2) shl 12)
or (trailingByteValue(byte3) shl 6)
or trailingByteValue(byte4)
)
resultArr[resultPos] = highSurrogate(codepoint)
resultArr[resultPos + 1] = lowSurrogate(codepoint)
}
/**
* Returns whether the byte is not a valid continuation of the form '10XXXXXX'.
*/
private fun isNotTrailingByte(b: Byte): Boolean = b > 0xBF.toByte()
/**
* Returns the actual value of the trailing byte (removes the prefix '10') for composition.
*/
private fun trailingByteValue(b: Byte): Int = b.toInt() and 0x3F
private fun highSurrogate(codePoint: Int): Char =
(
Char.MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT ushr 10) +
(codePoint ushr 10)
)
private fun lowSurrogate(codePoint: Int): Char = (Char.MIN_LOW_SURROGATE + (codePoint and 0x3ff))
/**
* Encode a [CharSequence] UTF8 codepoint into a byte array.
* @param `in` CharSequence to be encoded
* @param start start position of the first char in the codepoint
* @param out byte array of 4 bytes to be filled
* @return return the amount of bytes occupied by the codepoint
*/
public fun encodeUtf8CodePoint(input: CharSequence, start: Int, out: ByteArray): Int {
// utf8 codepoint needs at least 4 bytes
val inLength = input.length
if (start >= inLength) {
return 0
}
val c = input[start]
return if (c.toInt() < 0x80) {
// One byte (0xxx xxxx)
out[0] = c.toByte()
1
} else if (c.toInt() < 0x800) {
// Two bytes (110x xxxx 10xx xxxx)
out[0] = (0xC0 or (c.toInt() ushr 6)).toByte()
out[1] = (0x80 or (0x3F and c.toInt())).toByte()
2
} else if (c < Char.MIN_SURROGATE || Char.MAX_SURROGATE < c) {
// Three bytes (1110 xxxx 10xx xxxx 10xx xxxx)
// Maximum single-char code point is 0xFFFF, 16 bits.
out[0] = (0xE0 or (c.toInt() ushr 12)).toByte()
out[1] = (0x80 or (0x3F and (c.toInt() ushr 6))).toByte()
out[2] = (0x80 or (0x3F and c.toInt())).toByte()
3
} else {
// Four bytes (1111 xxxx 10xx xxxx 10xx xxxx 10xx xxxx)
// Minimum code point represented by a surrogate pair is 0x10000, 17 bits, four UTF-8
// bytes
val low: Char = input[start + 1]
if (start + 1 == inLength || !(c.isHighSurrogate() and low.isLowSurrogate())) {
errorSurrogate(start, inLength)
}
val codePoint: Int = toCodePoint(c, low)
out[0] = (0xF shl 4 or (codePoint ushr 18)).toByte()
out[1] = (0x80 or (0x3F and (codePoint ushr 12))).toByte()
out[2] = (0x80 or (0x3F and (codePoint ushr 6))).toByte()
out[3] = (0x80 or (0x3F and codePoint)).toByte()
4
}
}
// Decodes a code point starting at index into out. Out parameter
// should have at least 2 chars.
public fun decodeUtf8CodePoint(bytes: ReadBuffer, index: Int, out: CharArray) {
// Bitwise OR combines the sign bits so any negative value fails the check.
val b1 = bytes[index]
when {
isOneByte(b1) -> handleOneByte(b1, out, 0)
isTwoBytes(b1) -> handleTwoBytes(b1, bytes[index + 1], out, 0)
isThreeBytes(b1) -> handleThreeBytes(b1, bytes[index + 1], bytes[index + 2], out, 0)
else -> handleFourBytes(b1, bytes[index + 1], bytes[index + 2], bytes[index + 3], out, 0)
}
}
public fun decodeUtf8Array(bytes: ByteArray, index: Int = 0, size: Int = bytes.size): String {
// Bitwise OR combines the sign bits so any negative value fails the check.
if (index or size or bytes.size - index - size < 0) {
error("buffer length=${bytes.size}, index=$index, size=$size")
}
var offset = index
val limit = offset + size
// The longest possible resulting String is the same as the number of input bytes, when it is
// all ASCII. For other cases, this over-allocates and we will truncate in the end.
val resultArr = CharArray(size)
var resultPos = 0
// Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this).
// This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII).
while (offset < limit) {
val b = bytes[offset]
if (!isOneByte(b)) {
break
}
offset++
handleOneByte(b, resultArr, resultPos++)
}
while (offset < limit) {
val byte1 = bytes[offset++]
if (isOneByte(byte1)) {
handleOneByte(byte1, resultArr, resultPos++)
// It's common for there to be multiple ASCII characters in a run mixed in, so add an
// extra optimized loop to take care of these runs.
while (offset < limit) {
val b = bytes[offset]
if (!isOneByte(b)) {
break
}
offset++
handleOneByte(b, resultArr, resultPos++)
}
} else if (isTwoBytes(byte1)) {
if (offset >= limit) {
error("Invalid UTF-8")
}
handleTwoBytes(
byte1, /* byte2 */
bytes[offset++], resultArr, resultPos++
)
} else if (isThreeBytes(byte1)) {
if (offset >= limit - 1) {
error("Invalid UTF-8")
}
handleThreeBytes(
byte1, /* byte2 */
bytes[offset++], /* byte3 */
bytes[offset++],
resultArr,
resultPos++
)
} else {
if (offset >= limit - 2) {
error("Invalid UTF-8")
}
handleFourBytes(
byte1, /* byte2 */
bytes[offset++], /* byte3 */
bytes[offset++], /* byte4 */
bytes[offset++],
resultArr,
resultPos++
)
// 4-byte case requires two chars.
resultPos++
}
}
return resultArr.concatToString(0, resultPos)
}
public fun encodeUtf8Array(input: CharSequence, out: ByteArray, offset: Int = 0, length: Int = out.size - offset): Int {
val utf16Length = input.length
var j = offset
var i = 0
val limit = offset + length
// Designed to take advantage of
// https://wikis.oracle.com/display/HotSpotInternals/RangeCheckElimination
if (utf16Length == 0)
return 0
var cc: Char = input[i]
while (i < utf16Length && i + j < limit && input[i].also { cc = it }.toInt() < 0x80) {
out[j + i] = cc.toByte()
i++
}
if (i == utf16Length) {
return j + utf16Length
}
j += i
var c: Char
while (i < utf16Length) {
c = input[i]
if (c.toInt() < 0x80 && j < limit) {
out[j++] = c.toByte()
} else if (c.toInt() < 0x800 && j <= limit - 2) { // 11 bits, two UTF-8 bytes
out[j++] = (0xF shl 6 or (c.toInt() ushr 6)).toByte()
out[j++] = (0x80 or (0x3F and c.toInt())).toByte()
} else if ((c < Char.MIN_SURROGATE || Char.MAX_SURROGATE < c) && j <= limit - 3) {
// Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes
out[j++] = (0xF shl 5 or (c.toInt() ushr 12)).toByte()
out[j++] = (0x80 or (0x3F and (c.toInt() ushr 6))).toByte()
out[j++] = (0x80 or (0x3F and c.toInt())).toByte()
} else if (j <= limit - 4) {
// Minimum code point represented by a surrogate pair is 0x10000, 17 bits,
// four UTF-8 bytes
var low: Char = Char.MIN_VALUE
if (i + 1 == input.length ||
!isSurrogatePair(c, input[++i].also { low = it })
) {
errorSurrogate(i - 1, utf16Length)
}
val codePoint: Int = toCodePoint(c, low)
out[j++] = (0xF shl 4 or (codePoint ushr 18)).toByte()
out[j++] = (0x80 or (0x3F and (codePoint ushr 12))).toByte()
out[j++] = (0x80 or (0x3F and (codePoint ushr 6))).toByte()
out[j++] = (0x80 or (0x3F and codePoint)).toByte()
} else {
// If we are surrogates and we're not a surrogate pair, always throw an
// UnpairedSurrogateException instead of an ArrayOutOfBoundsException.
if (Char.MIN_SURROGATE <= c && c <= Char.MAX_SURROGATE &&
(i + 1 == input.length || !isSurrogatePair(c, input[i + 1]))
) {
errorSurrogate(i, utf16Length)
}
error("Failed writing character ${c.toShort().toString(radix = 16)} at index $j")
}
i++
}
return j
}
public fun codePointAt(seq: CharSequence, position: Int): Int {
var index = position
val c1 = seq[index]
if (c1.isHighSurrogate() && ++index < seq.length) {
val c2 = seq[index]
if (c2.isLowSurrogate()) {
return toCodePoint(c1, c2)
}
}
return c1.toInt()
}
private fun isSurrogatePair(high: Char, low: Char) = high.isHighSurrogate() and low.isLowSurrogate()
private fun toCodePoint(high: Char, low: Char): Int = (high.toInt() shl 10) + low.toInt() +
(MIN_SUPPLEMENTARY_CODE_POINT - (Char.MIN_HIGH_SURROGATE.toInt() shl 10) - Char.MIN_LOW_SURROGATE.toInt())
private fun errorSurrogate(i: Int, utf16Length: Int): Unit =
error("Unpaired surrogate at index $i of $utf16Length length")
// The minimum value of Unicode supplementary code point, constant `U+10000`.
private const val MIN_SUPPLEMENTARY_CODE_POINT = 0x010000
}
| apache-2.0 | cebaba3b964416417f32dbcb93d7464d | 34.831731 | 122 | 0.607406 | 3.552431 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceWithEnumMapInspection.kt | 1 | 3341 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.project.platform
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.callExpressionVisitor
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.types.typeUtil.isEnum
private val hashMapCreationFqNames = setOf(
"java.util.HashMap.<init>",
"kotlin.collections.HashMap.<init>",
"kotlin.collections.hashMapOf"
)
class ReplaceWithEnumMapInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return callExpressionVisitor(fun(element: KtCallExpression) {
if (!element.platform.isJvm()) return
val context = element.safeAnalyzeNonSourceRootCode()
val fqName = element.getResolvedCall(context)?.resultingDescriptor?.fqNameUnsafe?.asString() ?: return
if (!hashMapCreationFqNames.contains(fqName)) return
if (element.valueArguments.isNotEmpty()) return
val expectedType = context[BindingContext.EXPECTED_EXPRESSION_TYPE, element] ?: return
val firstArgType = expectedType.arguments.firstOrNull()?.type ?: return
if (!firstArgType.isEnum()) return
val enumClassName = firstArgType.constructor.declarationDescriptor?.fqNameUnsafe?.asString() ?: return
holder.registerProblem(element, KotlinBundle.message("replaceable.with.enummap"), ReplaceWithEnumMapFix(enumClassName))
})
}
private class ReplaceWithEnumMapFix(
private val enumClassName: String
) : LocalQuickFix {
override fun getFamilyName() = name
override fun getName() = KotlinBundle.message("replace.with.enum.map.fix.text")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val call = descriptor.psiElement as? KtCallExpression ?: return
val factory = KtPsiFactory(call)
val file = call.containingKtFile
val enumMapDescriptor = file.resolveImportReference(FqName("java.util.EnumMap")).firstOrNull() ?: return
ImportInsertHelper.getInstance(project).importDescriptor(call.containingKtFile, enumMapDescriptor)
call.replace(factory.createExpressionByPattern("EnumMap($0::class.java)", enumClassName))
}
}
} | apache-2.0 | 55972c4cf32f90cd1d090f0517baff56 | 50.415385 | 158 | 0.763245 | 5.046828 | false | false | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/data/pullrequest/timeline/GHPRTimelineItem.kt | 10 | 4344 | // 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 org.jetbrains.plugins.github.api.data.pullrequest.timeline
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.intellij.collaboration.ui.codereview.timeline.TimelineItem
import org.jetbrains.plugins.github.api.data.GHIssueComment
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestCommitShort
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReview
import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineItem.Unknown
/*REQUIRED
IssueComment
PullRequestCommit (Commit in GHE)
PullRequestReview
RenamedTitleEvent
ClosedEvent | ReopenedEvent | MergedEvent
AssignedEvent | UnassignedEvent
LabeledEvent | UnlabeledEvent
ReviewRequestedEvent | ReviewRequestRemovedEvent
ReviewDismissedEvent
ReadyForReviewEvent
BaseRefChangedEvent | BaseRefForcePushedEvent
HeadRefDeletedEvent | HeadRefForcePushedEvent | HeadRefRestoredEvent
//comment reference
CrossReferencedEvent
//issue will be closed
ConnectedEvent | DisconnectedEvent
*/
/*MAYBE
LockedEvent | UnlockedEvent
MarkedAsDuplicateEvent | UnmarkedAsDuplicateEvent
ConvertToDraftEvent
???PullRequestCommitCommentThread
???PullRequestReviewThread
AddedToProjectEvent
ConvertedNoteToIssueEvent
RemovedFromProjectEvent
MovedColumnsInProjectEvent
TransferredEvent
UserBlockedEvent
PullRequestRevisionMarker
DeployedEvent
DeploymentEnvironmentChangedEvent
PullRequestReviewThread
PinnedEvent | UnpinnedEvent
SubscribedEvent | UnsubscribedEvent
MilestonedEvent | DemilestonedEvent
AutomaticBaseChangeSucceededEvent | AutomaticBaseChangeFailedEvent
*/
/*IGNORE
ReferencedEvent
MentionedEvent
CommentDeletedEvent
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "__typename", visible = true,
defaultImpl = Unknown::class)
@JsonSubTypes(
JsonSubTypes.Type(name = "IssueComment", value = GHIssueComment::class),
JsonSubTypes.Type(name = "PullRequestCommit", value = GHPullRequestCommitShort::class),
JsonSubTypes.Type(name = "PullRequestReview", value = GHPullRequestReview::class),
JsonSubTypes.Type(name = "ReviewDismissedEvent", value = GHPRReviewDismissedEvent::class),
JsonSubTypes.Type(name = "ReadyForReviewEvent", value = GHPRReadyForReviewEvent::class),
/*JsonSubTypes.Type(name = "ConvertToDraftEvent", value = GHPRConvertToDraftEvent::class),*/
JsonSubTypes.Type(name = "RenamedTitleEvent", value = GHPRRenamedTitleEvent::class),
JsonSubTypes.Type(name = "ClosedEvent", value = GHPRClosedEvent::class),
JsonSubTypes.Type(name = "ReopenedEvent", value = GHPRReopenedEvent::class),
JsonSubTypes.Type(name = "MergedEvent", value = GHPRMergedEvent::class),
JsonSubTypes.Type(name = "AssignedEvent", value = GHPRAssignedEvent::class),
JsonSubTypes.Type(name = "UnassignedEvent", value = GHPRUnassignedEvent::class),
JsonSubTypes.Type(name = "LabeledEvent", value = GHPRLabeledEvent::class),
JsonSubTypes.Type(name = "UnlabeledEvent", value = GHPRUnlabeledEvent::class),
JsonSubTypes.Type(name = "ReviewRequestedEvent", value = GHPRReviewRequestedEvent::class),
JsonSubTypes.Type(name = "ReviewRequestRemovedEvent", value = GHPRReviewUnrequestedEvent::class),
JsonSubTypes.Type(name = "BaseRefChangedEvent", value = GHPRBaseRefChangedEvent::class),
JsonSubTypes.Type(name = "BaseRefForcePushedEvent", value = GHPRBaseRefForcePushedEvent::class),
JsonSubTypes.Type(name = "HeadRefDeletedEvent", value = GHPRHeadRefDeletedEvent::class),
JsonSubTypes.Type(name = "HeadRefForcePushedEvent", value = GHPRHeadRefForcePushedEvent::class),
JsonSubTypes.Type(name = "HeadRefRestoredEvent", value = GHPRHeadRefRestoredEvent::class),
JsonSubTypes.Type(name = "CrossReferencedEvent", value = GHPRCrossReferencedEvent::class)/*,
JsonSubTypes.Type(name = "ConnectedEvent", value = GHPRConnectedEvent::class),
JsonSubTypes.Type(name = "DisconnectedEvent", value = GHPRDisconnectedEvent::class)*/
)
interface GHPRTimelineItem : TimelineItem {
class Unknown(val __typename: String) : GHPRTimelineItem
companion object {
val IGNORED_TYPES = setOf("ReferencedEvent", "MentionedEvent", "CommentDeletedEvent")
}
} | apache-2.0 | 141339a996c3a129e325ca5f339b7170 | 39.607477 | 140 | 0.812615 | 4.810631 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateLocalVariableActionFactory.kt | 1 | 4173 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createVariable
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil
import org.jetbrains.kotlin.idea.intentions.ConvertToBlockBodyIntention
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.CreateFromUsageFixBase
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.*
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getAssignmentByLHS
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElement
import org.jetbrains.kotlin.types.Variance
import java.util.*
object CreateLocalVariableActionFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val refExpr = QuickFixUtil.getParentElementOfType(diagnostic, KtNameReferenceExpression::class.java) ?: return null
if (refExpr.getQualifiedElement() != refExpr) return null
if (refExpr.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference } != null) return null
if (getContainer(refExpr) == null) return null
return CreateLocalFromUsageAction(refExpr)
}
private fun getContainer(refExpr: KtNameReferenceExpression): KtElement? {
var element: PsiElement = refExpr
while (true) {
when (val parent = element.parent) {
null, is KtAnnotationEntry -> return null
is KtBlockExpression -> return parent
is KtDeclarationWithBody -> {
if (parent.bodyExpression == element) return parent
element = parent
}
else -> element = parent
}
}
}
class CreateLocalFromUsageAction(refExpr: KtNameReferenceExpression, val propertyName: String = refExpr.getReferencedName())
: CreateFromUsageFixBase<KtNameReferenceExpression>(refExpr) {
override fun getText(): String = KotlinBundle.message("fix.create.from.usage.local.variable", propertyName)
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val refExpr = element ?: return
val container = getContainer(refExpr) ?: return
val assignment = refExpr.getAssignmentByLHS()
val varExpected = assignment != null
var originalElement: KtExpression = assignment ?: refExpr
val actualContainer = when (container) {
is KtBlockExpression -> container
else -> ConvertToBlockBodyIntention.convert(container as KtDeclarationWithBody, true).bodyExpression!!
} as KtBlockExpression
if (actualContainer != container) {
val bodyExpression = actualContainer.statements.first()!!
originalElement = (bodyExpression as? KtReturnExpression)?.returnedExpression ?: bodyExpression
}
val typeInfo = TypeInfo(
originalElement.getExpressionForTypeGuess(),
if (varExpected) Variance.INVARIANT else Variance.OUT_VARIANCE
)
val propertyInfo =
PropertyInfo(propertyName, TypeInfo.Empty, typeInfo, varExpected, Collections.singletonList(actualContainer))
with(CallableBuilderConfiguration(listOfNotNull(propertyInfo), originalElement, file, editor).createBuilder()) {
placement = CallablePlacement.NoReceiver(actualContainer)
project.executeCommand(text) { build() }
}
}
}
}
| apache-2.0 | e2baf49dd677774ede15c213ac0f2c24 | 49.277108 | 158 | 0.711479 | 5.608871 | false | false | false | false |
smmribeiro/intellij-community | platform/util/ui/src/com/intellij/util/ui/AvatarUtils.kt | 10 | 3839 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.ui
import com.intellij.openapi.util.Couple
import com.intellij.ui.JBColor
import com.intellij.ui.scale.ScaleContext
import com.intellij.util.ui.ImageUtil.applyQualityRenderingHints
import java.awt.Color
import java.awt.Font
import java.awt.GradientPaint
import java.awt.Rectangle
import java.awt.image.BufferedImage
import javax.swing.ImageIcon
import kotlin.math.abs
import kotlin.math.min
object AvatarUtils {
fun createRoundRectIcon(image: BufferedImage, targetSize: Int): ImageIcon {
val size: Int = min(image.width, image.height)
val baseArcSize = 6.0 * size / targetSize
val rounded = ImageUtil.createRoundedImage(image, baseArcSize)
val hiDpi = ImageUtil.ensureHiDPI(rounded, ScaleContext.create())
return JBImageIcon(ImageUtil.scaleImage(hiDpi, targetSize, targetSize))
}
fun generateColoredAvatar(gradientSeed: String, name: String, palette: ColorPalette = AvatarPalette): BufferedImage {
val (color1, color2) = palette.gradient(gradientSeed)
val shortName = Avatars.initials(name)
val size = 64
val image = ImageUtil.createImage(size, size, BufferedImage.TYPE_INT_ARGB)
val g2 = image.createGraphics()
applyQualityRenderingHints(g2)
g2.paint = GradientPaint(0.0f, 0.0f, color2,
size.toFloat(), size.toFloat(), color1)
g2.fillRect(0, 0, size, size)
g2.paint = JBColor.WHITE
g2.font = JBFont.create(Font("Segoe UI", Font.PLAIN, (size / 2.2).toInt()))
UIUtil.drawCenteredString(g2, Rectangle(0, 0, size, size), shortName)
g2.dispose()
return image
}
}
internal object Avatars {
// "John Smith" -> "JS"
fun initials(text: String): String {
val words = text
.filter { !it.isHighSurrogate() && !it.isLowSurrogate() }
.trim()
.split(' ', ',', '`', '\'', '\"').filter { it.isNotBlank() }
.let {
if (it.size > 2) listOf(it.first(), it.last()) else it
}
.take(2)
if (words.size == 1) {
return generateFromCamelCase(words.first())
}
return words.map { it.first() }
.joinToString("").toUpperCase()
}
private fun generateFromCamelCase(text: String) = text.filterIndexed { index, c -> index == 0 || c.isUpperCase() }.take(2).toUpperCase()
fun initials(firstName: String, lastName: String): String {
return listOf(firstName, lastName).joinToString("") { it.first().toString() }
}
}
abstract class ColorPalette {
abstract val gradients: Array<Pair<Color, Color>>
public fun gradient(seed: String? = null): Pair<Color, Color> {
val keyCode = if (seed != null) {
abs(seed.hashCode()) % gradients.size
}
else 0
return gradients[keyCode]
}
}
object AvatarPalette : ColorPalette() {
override val gradients: Array<Pair<Color, Color>>
get() = arrayOf(
Color(0x60A800) to Color(0xD5CA00),
Color(0x0A81F6) to Color(0x0A81F6),
Color(0xAB3AF2) to Color(0xE40568),
Color(0x21D370) to Color(0x03E9E1),
Color(0x765AF8) to Color(0x5A91F8),
Color(0x9F2AFF) to Color(0xE9A80B),
Color(0x3BA1FF) to Color(0x36E97D),
Color(0x9E54FF) to Color(0x0ACFF6),
Color(0xD50F6B) to Color(0xE73AE8),
Color(0x00C243) to Color(0x00FFFF),
Color(0xB345F1) to Color(0x669DFF),
Color(0xED5502) to Color(0xE73AE8),
Color(0x4BE098) to Color(0x627FFF),
Color(0x765AF8) to Color(0xC059EE),
Color(0xED358C) to Color(0xDBED18),
Color(0x168BFA) to Color(0x26F7C7),
Color(0x9039D0) to Color(0xC239D0),
Color(0xED358C) to Color(0xF9902E),
Color(0x9D4CFF) to Color(0x39D3C3),
Color(0x9F2AFF) to Color(0xFD56FD),
Color(0xFF7500) to Color(0xFFCA00)
)
} | apache-2.0 | 5c0bb3aadbdf7814409c9ea4f271ac68 | 33.594595 | 140 | 0.679865 | 3.212552 | false | false | false | false |
eggheadgames/android-in-app-payments | library/src/amazon/java/com/billing/AmazonBillingListener.kt | 1 | 5230 | package com.billing
import android.util.Log
import com.amazon.device.iap.PurchasingListener
import com.amazon.device.iap.PurchasingService
import com.amazon.device.iap.model.*
internal class AmazonBillingListener(private val amazonBillingService: BillingService) : PurchasingListener {
var mDebugLog = false
override fun onUserDataResponse(userDataResponse: UserDataResponse) {
logDebug("onUserDataResponse " + userDataResponse.requestStatus)
}
fun enableDebugLogging(enable: Boolean) {
mDebugLog = enable
}
override fun onProductDataResponse(response: ProductDataResponse) {
val status = response.requestStatus
logDebug("onProductDataResponse: RequestStatus ($status)")
when (status) {
ProductDataResponse.RequestStatus.SUCCESSFUL -> {
logDebug("onProductDataResponse: successful. The item data map in this response includes the valid SKUs")
val unavailableSkus = response.unavailableSkus
logDebug("onProductDataResponse: " + unavailableSkus.size + " unavailable skus")
val productData = response.productData
logDebug("onProductDataResponse productData : " + productData.size)
val iapkeyPrices = productData.map {
it.value.sku to it.value.price
}.toMap()
amazonBillingService.updatePrices(iapkeyPrices)
}
ProductDataResponse.RequestStatus.FAILED, ProductDataResponse.RequestStatus.NOT_SUPPORTED, null ->
logDebug("onProductDataResponse: failed, should retry request")
}
}
override fun onPurchaseResponse(response: PurchaseResponse) {
logDebug("onPurchaseResponse " + response.requestStatus)
val requestId = response.requestId.toString()
val userId = response.userData.userId
val status = response.requestStatus
val receipt: Receipt? = response.receipt
logDebug("onPurchaseResponse: requestId ($requestId) userId ($userId) purchaseRequestStatus ($status)")
when (status) {
PurchaseResponse.RequestStatus.SUCCESSFUL -> {
if (receipt != null) {
logDebug("onPurchaseResponse: receipt json:" + receipt.toJSON())
logDebug("onPurchaseResponse: getUserId:" + response.userData.userId)
logDebug("onPurchaseResponse: getMarketplace:" + response.userData.marketplace)
if (receipt.productType == ProductType.SUBSCRIPTION) {
amazonBillingService.subscriptionOwned(receipt.sku, false)
} else {
amazonBillingService.productOwned(receipt.sku, false)
}
PurchasingService.notifyFulfillment(receipt.receiptId, FulfillmentResult.FULFILLED)
}
}
PurchaseResponse.RequestStatus.ALREADY_PURCHASED -> {
logDebug("onPurchaseResponse: already purchased, you should verify the entitlement purchase on your side and make sure the purchase was granted to customer")
if (receipt != null && !receipt.isCanceled) {
if (receipt.productType == ProductType.SUBSCRIPTION) {
amazonBillingService.subscriptionOwned(receipt.sku, true)
} else {
amazonBillingService.productOwned(receipt.sku, true)
}
}
}
PurchaseResponse.RequestStatus.INVALID_SKU -> logDebug("onPurchaseResponse: invalid SKU! onProductDataResponse should have disabled buy button already.")
PurchaseResponse.RequestStatus.FAILED, PurchaseResponse.RequestStatus.NOT_SUPPORTED, null -> logDebug("onPurchaseResponse: failed so remove purchase request from local storage")
}
}
override fun onPurchaseUpdatesResponse(response: PurchaseUpdatesResponse?) {
logDebug("onPurchaseUpdatesResponse " + if (response == null) "null" else response.requestStatus)
if (response == null) return
if (response.requestStatus == PurchaseUpdatesResponse.RequestStatus.SUCCESSFUL) {
val receipts = response.receipts.toTypedArray()
for (receipt in receipts) {
if (receipt != null && !receipt.isCanceled) {
if (receipt.productType == ProductType.ENTITLED) {
amazonBillingService.productOwned(receipt.sku, true)
logDebug("onPurchaseUpdatesResponse productOwned: " + receipt.sku)
} else if (receipt.productType == ProductType.SUBSCRIPTION) {
amazonBillingService.subscriptionOwned(receipt.sku, true)
logDebug("onPurchaseUpdatesResponse subscriptionOwned: " + receipt.sku)
}
}
}
}
}
private fun logDebug(msg: String) {
if (mDebugLog) Log.d(TAG, msg)
}
companion object {
private val TAG = AmazonBillingListener::class.java.simpleName
}
init {
logDebug("IS_SANDBOX_MODE:" + PurchasingService.IS_SANDBOX_MODE)
}
} | mit | 7241b2560184f8cce9a7a79f3c7e7f48 | 48.349057 | 189 | 0.636329 | 5.293522 | false | false | false | false |
RADAR-CNS/RADAR-AndroidApplication | app/src/main/java/org/radarcns/detail/MainActivityBootStarter.kt | 1 | 2795 | /*
* Copyright 2017 The Hyve
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.radarcns.detail
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import android.widget.Toast
import androidx.core.app.NotificationCompat.CATEGORY_ALARM
import com.google.firebase.crashlytics.FirebaseCrashlytics
import org.radarbase.android.AbstractRadarApplication.Companion.radarApp
import org.radarbase.android.util.Boast
import org.radarbase.android.util.NotificationHandler.Companion.NOTIFICATION_CHANNEL_ALERT
/**
* Starts MainActivity on boot if configured to do so
*/
class MainActivityBootStarter : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if ((context.applicationContext as RadarApplicationImpl).isInForeground) {
return
}
when (intent.action) {
Intent.ACTION_MY_PACKAGE_REPLACED -> {
context.startApp()
Boast.makeText(context, R.string.appUpdated, Toast.LENGTH_LONG).show()
}
Intent.ACTION_BOOT_COMPLETED, "android.intent.action.QUICKBOOT_POWERON" -> {
context.startApp()
}
}
}
private fun Context.startApp() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
radarApp.notificationHandler.notify(
id = BOOT_START_NOTIFICATION_ID,
channel = NOTIFICATION_CHANNEL_ALERT,
includeStartIntent = true,
) {
setContentTitle(getString(R.string.bootstart_title))
setContentTitle(getString(R.string.bootstart_text))
setCategory(CATEGORY_ALARM)
setAutoCancel(true)
setOngoing(true)
}
} else {
packageManager.getLaunchIntentForPackage(packageName)?.also {
startActivity(it)
} ?: FirebaseCrashlytics.getInstance()
.recordException(IllegalStateException("Cannot start RADAR app $packageName without launch intent"))
}
}
companion object {
const val BOOT_START_NOTIFICATION_ID = 35002
}
}
| apache-2.0 | dbdf4da23ad0acd61bc93a7eaa97c8f3 | 36.77027 | 116 | 0.674776 | 4.635158 | false | false | false | false |
ifabijanovic/swtor-holonet | android/app/src/main/java/com/ifabijanovic/holonet/app/model/Settings.kt | 1 | 1634 | package com.ifabijanovic.holonet.app.model
/**
* Created by feb on 19/03/2017.
*/
interface Settings {
val appEmail: String
val categoryQueryParam: String
val threadQueryParam: String
val postQueryParam: String
val baseForumUrl: String
val devTrackerIconUrl: String
val devAvatarUrl: String
val stickyIconUrl: String
val dulfyNetUrl: String
val requestTimeout: Int
val localized: Map<String, LocalizedSettings>
}
data class LocalizedSettings(
val pathPrefix: String,
val rootCategoryId: Int,
val devTrackerId: Int
) {}
class AppSettings: Settings {
override val appEmail: String = "[email protected]"
override val categoryQueryParam: String = "f"
override val threadQueryParam: String = "t"
override val postQueryParam: String = "p"
override val baseForumUrl: String = "http://www.swtor.com"
override val devTrackerIconUrl: String = "http://cdn-www.swtor.com/sites/all/files/en/coruscant/main/forums/icons/devtracker_icon.png"
override val devAvatarUrl: String = "http://www.swtor.com/sites/all/files/avatars/BioWare.gif"
override val stickyIconUrl: String = "http://cdn-www.swtor.com/community/images/swtor/misc/sticky.gif"
override val dulfyNetUrl: String = "http://dulfy.net"
override val requestTimeout: Int = 10000
override val localized: Map<String, LocalizedSettings>
init {
val en = LocalizedSettings("", 3, 304)
val fr = LocalizedSettings("fr", 4, 305)
val de = LocalizedSettings("de", 5, 306)
this.localized = hashMapOf("en" to en, "fr" to fr, "de" to de)
}
}
| gpl-3.0 | 562a14b1a304370dfd4d9c68f7755e1c | 35.311111 | 138 | 0.698898 | 3.705215 | false | false | false | false |
erdo/asaf-project | example-kt-02coroutine/src/main/java/foo/bar/example/forecoroutine/ui/CounterActivity.kt | 1 | 2177 | package foo.bar.example.forecoroutine.ui
import android.os.Bundle
import android.view.View
import androidx.fragment.app.FragmentActivity
import co.early.fore.core.observer.Observer
import foo.bar.example.forecoroutine.OG
import foo.bar.example.forecoroutine.R
import foo.bar.example.forecoroutine.feature.counter.Counter
import foo.bar.example.forecoroutine.feature.counter.CounterWithProgress
import kotlinx.android.synthetic.main.activity_counter.*
/**
* Copyright © 2019 early.co. All rights reserved.
*/
class CounterActivity : FragmentActivity(R.layout.activity_counter) {
//models that we need to sync with
private val counterWithProgress: CounterWithProgress = OG[CounterWithProgress::class.java]
private val counter: Counter = OG[Counter::class.java]
//single observer reference
private var observer = Observer { syncView() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupButtonClickListeners()
}
private fun setupButtonClickListeners() {
counter_increase_btn.setOnClickListener { counter.increaseBy20() }
counterwprog_increase_btn.setOnClickListener { counterWithProgress.increaseBy20() }
}
//data binding stuff below
fun syncView() {
counterwprog_increase_btn.isEnabled = !counterWithProgress.isBusy
counterwprog_busy_progress.visibility = if (counterWithProgress.isBusy) View.VISIBLE else View.INVISIBLE
counterwprog_progress_txt.text = "${counterWithProgress.progress}"
counterwprog_current_txt.text = "${counterWithProgress.count}"
counter_increase_btn.isEnabled = !counter.isBusy
counter_busy_progress.visibility = if (counter.isBusy) View.VISIBLE else View.INVISIBLE
counter_current_txt.text = "${counter.count}"
}
override fun onStart() {
super.onStart()
counter.addObserver(observer)
counterWithProgress.addObserver(observer)
syncView() //<-- don't forget this
}
override fun onStop() {
super.onStop()
counter.removeObserver(observer)
counterWithProgress.removeObserver(observer)
}
}
| apache-2.0 | 8e0de4141ed02664e8b7a40ea0a1a3de | 31.477612 | 112 | 0.729779 | 4.431772 | false | false | false | false |
marverenic/Paper | app/src/main/java/com/marverenic/reader/data/FeedlyRssStore.kt | 1 | 6701 | package com.marverenic.reader.data
import com.marverenic.reader.data.database.RssDatabase
import com.marverenic.reader.data.service.ACTION_READ
import com.marverenic.reader.data.service.ArticleMarkerRequest
import com.marverenic.reader.data.service.FeedlyService
import com.marverenic.reader.model.Article
import com.marverenic.reader.model.Seconds
import com.marverenic.reader.model.Stream
import com.marverenic.reader.model.toDuration
import com.marverenic.reader.utils.orEpoch
import com.marverenic.reader.utils.replaceAll
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.functions.BiFunction
import io.reactivex.schedulers.Schedulers
import org.joda.time.DateTime
import retrofit2.Response
import java.io.IOException
private const val STREAM_LOAD_SIZE = 250
private const val MAX_STREAM_CACHE_AGE: Seconds = 24 * 60 * 60 // 1 day
private const val MAX_CATEGORY_CACHE_AGE: Seconds = 7 * 24 * 60 * 60 // 1 week
class FeedlyRssStore(private val authManager: AuthenticationManager,
private val service: FeedlyService,
private val prefStore: PreferenceStore,
private val rssDatabase: RssDatabase) : RssStore {
private val allArticlesStreamId: Single<String>
get() = authManager.getFeedlyUserId().map { "user/$it/category/global.all" }
private val categories = RxLoader(loadAsync { rssDatabase.getCategories() },
isCacheStale(MAX_CATEGORY_CACHE_AGE) { prefStore.lastCategoryRefreshTime }) {
authManager.getFeedlyAuthToken()
.flatMap { service.getCategories(it) }
.unwrapResponse()
.also {
it.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe { categories ->
rssDatabase.setCategories(categories)
}
}
}
private val streams = mutableMapOf<String, RxLoader<Stream>>()
private val unreadStreams = mutableMapOf<String, RxLoader<Stream>>()
override fun getAllArticles(unreadOnly: Boolean): Observable<Stream> {
return allArticlesStreamId.flatMapObservable { getStream(it, unreadOnly) }
}
override fun getAllCategories() = categories.getOrComputeValue()
private fun getStreamLoader(streamId: String, unreadOnly: Boolean): RxLoader<Stream> {
val streamsMap = if (unreadOnly) unreadStreams else streams
streamsMap[streamId]?.let { return it }
var cached = false
val cachedStream = loadAsync {
val stream = rssDatabase.getStream(streamId, unreadOnly)
cached = stream != null
return@loadAsync stream
}
val stale = isCacheStale(MAX_STREAM_CACHE_AGE) { rssDatabase.getStreamTimestamp(streamId, unreadOnly) }
return RxLoader(cachedStream, stale) {
authManager.getFeedlyAuthToken()
.flatMap { service.getStream(it, streamId, STREAM_LOAD_SIZE, unreadOnly) }
.unwrapResponse()
.map { it.copy(items = it.items.sortedByDescending(Article::timestamp)) }
}.also { loader ->
streamsMap[streamId] = loader
loader.getObservable()
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.skipWhile { cached.also { cached = false } }
.subscribe { stream -> rssDatabase.insertStream(stream, unreadOnly) }
}
}
override fun getStream(streamId: String, unreadOnly: Boolean): Observable<Stream> {
return getStreamLoader(streamId, unreadOnly).getOrComputeValue()
}
override fun refreshStream(streamId: String) {
getStreamLoader(streamId, true).computeValue()
getStreamLoader(streamId, false).computeValue()
}
override fun refreshAllArticles() {
allArticlesStreamId.subscribe { streamId -> refreshStream(streamId) }
}
override fun refreshCategories() {
categories.computeValue()
}
override fun isLoadingStream(streamId: String): Observable<Boolean> {
val loadingRead = getStreamLoader(streamId, false).isComputingValue()
val loadingUnread = getStreamLoader(streamId, true).isComputingValue()
return Observable.combineLatest(loadingRead, loadingUnread,
BiFunction { readLoading, unreadLoading -> readLoading || unreadLoading })
}
override fun loadMoreArticles(stream: Stream) {
if (stream.continuation == null) {
return
}
streams[stream.id]?.let { loader ->
authManager.getFeedlyAuthToken()
.flatMap { service.getStreamContinuation(it, stream.id, stream.continuation, STREAM_LOAD_SIZE) }
.unwrapResponse()
.subscribe { continuation ->
val combinedArticles = stream.items + continuation.items
val merged = continuation.copy(items = combinedArticles.sortedByDescending(Article::timestamp))
loader.setValue(merged)
}
}
}
override fun markAsRead(article: Article, read: Boolean) {
if (article.unread == !read) {
return
}
authManager.getFeedlyAuthToken()
.flatMap {
service.markArticles(it, ArticleMarkerRequest(
entryIds = listOf(article.id),
action = ACTION_READ))
}
.unwrapResponse()
.subscribe()
val readArticle = article.copy(unread = !read)
streams.forEach { (_, loader) ->
loader.getValue()?.let { stream ->
val newContents = stream.items.replaceAll(article, readArticle)
loader.setValue(stream.copy(items = newContents))
}
}
}
}
private fun <T: Any> Single<Response<T>>.unwrapResponse(): Single<T> =
map {
if (it.isSuccessful) it.body()
else throw IOException("${it.code()}: ${it.errorBody()?.string()}")
}
private inline fun <T: Any> loadAsync(crossinline load: () -> T?): Single<T> {
return Single.fromCallable { load() ?: throw NoSuchElementException("No value returned") }
.subscribeOn(Schedulers.io())
}
private inline fun isCacheStale(maxAge: Seconds, crossinline age: () -> DateTime?): Single<Boolean> {
return Single.fromCallable {
val expirationDate = age().orEpoch() + maxAge.toDuration()
return@fromCallable DateTime.now() > expirationDate
}
}
| apache-2.0 | d319a34f0290212f6544bef66affca81 | 39.125749 | 119 | 0.62916 | 4.859318 | false | false | false | false |
TachiWeb/TachiWeb-Server | AndroidCompat/src/main/java/xyz/nulldev/androidcompat/db/ScrollableResultSet.kt | 1 | 21540 | package xyz.nulldev.androidcompat.db
import java.io.InputStream
import java.io.Reader
import java.math.BigDecimal
import java.net.URL
import java.sql.*
import java.sql.Array
import java.sql.Date
import java.util.*
class ScrollableResultSet(val parent: ResultSet) : ResultSet by parent {
private val cachedContent = mutableListOf<ResultSetEntry>()
private val columnCache = mutableMapOf<String, Int>()
private var lastReturnWasNull = false
private var cursor = 0
var resultSetLength = 0
val parentMetadata = parent.metaData
val columnCount = parentMetadata.columnCount
val columnLabels = (1 .. columnCount).map {
parentMetadata.getColumnLabel(it)
}.toTypedArray()
init {
val columnCount = columnCount
// TODO
// Profiling reveals that this is a bottleneck (average ms for this call is: 48ms)
// How can we optimize this?
// We need to fill the cache as the set is loaded
//Fill cache
while(parent.next()) {
cachedContent += ResultSetEntry().apply {
for(i in 1 .. columnCount)
data += parent.getObject(i)
}
resultSetLength++
}
}
private fun notImplemented(): Nothing {
throw UnsupportedOperationException("This class currently does not support this operation!")
}
private fun cursorValid(): Boolean {
return isAfterLast || isBeforeFirst
}
private fun internalMove(row: Int) {
if(cursor < 0) cursor = 0
else if(cursor > resultSetLength + 1) cursor = resultSetLength + 1
else cursor = row
}
private fun obj(column: Int): Any? {
val obj = cachedContent[cursor - 1].data[column - 1]
lastReturnWasNull = obj == null
return obj
}
private fun obj(column: String?): Any? {
return obj(cachedFindColumn(column))
}
private fun cachedFindColumn(column: String?)
= columnCache.getOrPut(column!!, {
findColumn(column)
})
override fun getNClob(columnIndex: Int): NClob {
return obj(columnIndex) as NClob
}
override fun getNClob(columnLabel: String?): NClob {
return obj(columnLabel) as NClob
}
override fun updateNString(columnIndex: Int, nString: String?) {
notImplemented()
}
override fun updateNString(columnLabel: String?, nString: String?) {
notImplemented()
}
override fun updateBinaryStream(columnIndex: Int, x: InputStream?, length: Int) {
notImplemented()
}
override fun updateBinaryStream(columnLabel: String?, x: InputStream?, length: Int) {
notImplemented()
}
override fun updateBinaryStream(columnIndex: Int, x: InputStream?, length: Long) {
notImplemented()
}
override fun updateBinaryStream(columnLabel: String?, x: InputStream?, length: Long) {
notImplemented()
}
override fun updateBinaryStream(columnIndex: Int, x: InputStream?) {
notImplemented()
}
override fun updateBinaryStream(columnLabel: String?, x: InputStream?) {
notImplemented()
}
override fun updateTimestamp(columnIndex: Int, x: Timestamp?) {
notImplemented()
}
override fun updateTimestamp(columnLabel: String?, x: Timestamp?) {
notImplemented()
}
override fun updateNCharacterStream(columnIndex: Int, x: Reader?, length: Long) {
notImplemented()
}
override fun updateNCharacterStream(columnLabel: String?, reader: Reader?, length: Long) {
notImplemented()
}
override fun updateNCharacterStream(columnIndex: Int, x: Reader?) {
notImplemented()
}
override fun updateNCharacterStream(columnLabel: String?, reader: Reader?) {
notImplemented()
}
override fun updateInt(columnIndex: Int, x: Int) {
notImplemented()
}
override fun updateInt(columnLabel: String?, x: Int) {
notImplemented()
}
override fun moveToInsertRow() {
notImplemented()
}
override fun getDate(columnIndex: Int): Date {
//TODO Maybe?
notImplemented()
}
override fun getDate(columnLabel: String?): Date {
//TODO Maybe?
notImplemented()
}
override fun getDate(columnIndex: Int, cal: Calendar?): Date {
//TODO Maybe?
notImplemented()
}
override fun getDate(columnLabel: String?, cal: Calendar?): Date {
//TODO Maybe?
notImplemented()
}
override fun beforeFirst() {
//TODO Maybe?
notImplemented()
}
override fun updateFloat(columnIndex: Int, x: Float) {
notImplemented()
}
override fun updateFloat(columnLabel: String?, x: Float) {
notImplemented()
}
override fun getBoolean(columnIndex: Int): Boolean {
return obj(columnIndex) as Boolean
}
override fun getBoolean(columnLabel: String?): Boolean {
return obj(columnLabel) as Boolean
}
override fun isFirst(): Boolean {
return cursor - 1 < resultSetLength
}
override fun getBigDecimal(columnIndex: Int, scale: Int): BigDecimal {
//TODO Maybe?
notImplemented()
}
override fun getBigDecimal(columnLabel: String?, scale: Int): BigDecimal {
//TODO Maybe?
notImplemented()
}
override fun getBigDecimal(columnIndex: Int): BigDecimal {
return obj(columnIndex) as BigDecimal
}
override fun getBigDecimal(columnLabel: String?): BigDecimal {
return obj(columnLabel) as BigDecimal
}
override fun updateBytes(columnIndex: Int, x: ByteArray?) {
notImplemented()
}
override fun updateBytes(columnLabel: String?, x: ByteArray?) {
notImplemented()
}
override fun isLast(): Boolean {
return cursor == resultSetLength
}
override fun insertRow() {
notImplemented()
}
override fun getTime(columnIndex: Int): Time {
//TODO Maybe?
notImplemented()
}
override fun getTime(columnLabel: String?): Time {
//TODO Maybe?
notImplemented()
}
override fun getTime(columnIndex: Int, cal: Calendar?): Time {
//TODO Maybe?
notImplemented()
}
override fun getTime(columnLabel: String?, cal: Calendar?): Time {
//TODO Maybe?
notImplemented()
}
override fun rowDeleted() = false
override fun last(): Boolean {
internalMove(resultSetLength)
return cursorValid()
}
override fun isAfterLast(): Boolean {
return cursor > resultSetLength
}
override fun relative(rows: Int): Boolean {
internalMove(cursor + rows)
return cursorValid()
}
override fun absolute(row: Int): Boolean {
if(row > 0) {
internalMove(row)
} else {
last()
for(i in 1 .. row)
previous()
}
return cursorValid()
}
override fun getSQLXML(columnIndex: Int): SQLXML? {
//TODO Maybe?
notImplemented()
}
override fun getSQLXML(columnLabel: String?): SQLXML? {
//TODO Maybe?
notImplemented()
}
override fun <T : Any?> unwrap(iface: Class<T>?): T {
if(thisIsWrapperFor(iface))
return this as T
else
return parent.unwrap(iface)
}
override fun next(): Boolean {
internalMove(cursor + 1)
return cursorValid()
}
override fun getFloat(columnIndex: Int): Float {
return obj(columnIndex) as Float
}
override fun getFloat(columnLabel: String?): Float {
return obj(columnLabel) as Float
}
override fun wasNull() = lastReturnWasNull
override fun getRow(): Int {
return cursor
}
override fun first(): Boolean {
internalMove(1)
return cursorValid()
}
override fun updateAsciiStream(columnIndex: Int, x: InputStream?, length: Int) {
notImplemented()
}
override fun updateAsciiStream(columnLabel: String?, x: InputStream?, length: Int) {
notImplemented()
}
override fun updateAsciiStream(columnIndex: Int, x: InputStream?, length: Long) {
notImplemented()
}
override fun updateAsciiStream(columnLabel: String?, x: InputStream?, length: Long) {
notImplemented()
}
override fun updateAsciiStream(columnIndex: Int, x: InputStream?) {
notImplemented()
}
override fun updateAsciiStream(columnLabel: String?, x: InputStream?) {
notImplemented()
}
override fun getURL(columnIndex: Int): URL {
return obj(columnIndex) as URL
}
override fun getURL(columnLabel: String?): URL {
return obj(columnLabel) as URL
}
override fun updateShort(columnIndex: Int, x: Short) {
notImplemented()
}
override fun updateShort(columnLabel: String?, x: Short) {
notImplemented()
}
override fun getType() = ResultSet.TYPE_SCROLL_INSENSITIVE
override fun updateNClob(columnIndex: Int, nClob: NClob?) {
notImplemented()
}
override fun updateNClob(columnLabel: String?, nClob: NClob?) {
notImplemented()
}
override fun updateNClob(columnIndex: Int, reader: Reader?, length: Long) {
notImplemented()
}
override fun updateNClob(columnLabel: String?, reader: Reader?, length: Long) {
notImplemented()
}
override fun updateNClob(columnIndex: Int, reader: Reader?) {
notImplemented()
}
override fun updateNClob(columnLabel: String?, reader: Reader?) {
notImplemented()
}
override fun updateRef(columnIndex: Int, x: Ref?) {
notImplemented()
}
override fun updateRef(columnLabel: String?, x: Ref?) {
notImplemented()
}
override fun updateObject(columnIndex: Int, x: Any?, scaleOrLength: Int) {
notImplemented()
}
override fun updateObject(columnIndex: Int, x: Any?) {
notImplemented()
}
override fun updateObject(columnLabel: String?, x: Any?, scaleOrLength: Int) {
notImplemented()
}
override fun updateObject(columnLabel: String?, x: Any?) {
notImplemented()
}
override fun afterLast() {
internalMove(resultSetLength + 1)
}
override fun updateLong(columnIndex: Int, x: Long) {
notImplemented()
}
override fun updateLong(columnLabel: String?, x: Long) {
notImplemented()
}
override fun getBlob(columnIndex: Int): Blob {
//TODO Maybe?
notImplemented()
}
override fun getBlob(columnLabel: String?): Blob {
//TODO Maybe?
notImplemented()
}
override fun updateClob(columnIndex: Int, x: Clob?) {
notImplemented()
}
override fun updateClob(columnLabel: String?, x: Clob?) {
notImplemented()
}
override fun updateClob(columnIndex: Int, reader: Reader?, length: Long) {
notImplemented()
}
override fun updateClob(columnLabel: String?, reader: Reader?, length: Long) {
notImplemented()
}
override fun updateClob(columnIndex: Int, reader: Reader?) {
notImplemented()
}
override fun updateClob(columnLabel: String?, reader: Reader?) {
notImplemented()
}
override fun getByte(columnIndex: Int): Byte {
return obj(columnIndex) as Byte
}
override fun getByte(columnLabel: String?): Byte {
return obj(columnLabel) as Byte
}
override fun getString(columnIndex: Int): String? {
return obj(columnIndex) as String?
}
override fun getString(columnLabel: String?): String? {
return obj(columnLabel) as String?
}
override fun updateSQLXML(columnIndex: Int, xmlObject: SQLXML?) {
notImplemented()
}
override fun updateSQLXML(columnLabel: String?, xmlObject: SQLXML?) {
notImplemented()
}
override fun updateDate(columnIndex: Int, x: Date?) {
notImplemented()
}
override fun updateDate(columnLabel: String?, x: Date?) {
notImplemented()
}
override fun getObject(columnIndex: Int): Any? {
return obj(columnIndex)
}
override fun getObject(columnLabel: String?): Any? {
return obj(columnLabel)
}
override fun getObject(columnIndex: Int, map: MutableMap<String, Class<*>>?): Any {
//TODO Maybe?
notImplemented()
}
override fun getObject(columnLabel: String?, map: MutableMap<String, Class<*>>?): Any {
//TODO Maybe?
notImplemented()
}
override fun <T : Any?> getObject(columnIndex: Int, type: Class<T>?): T {
return obj(columnIndex) as T
}
override fun <T : Any?> getObject(columnLabel: String?, type: Class<T>?): T {
return obj(columnLabel) as T
}
override fun previous(): Boolean {
internalMove(cursor - 1)
return cursorValid()
}
override fun updateDouble(columnIndex: Int, x: Double) {
notImplemented()
}
override fun updateDouble(columnLabel: String?, x: Double) {
notImplemented()
}
private fun castToLong(obj: Any?): Long {
if(obj == null) return 0
else if(obj is Long) return obj
else if(obj is Number) return obj.toLong()
else throw IllegalStateException("Object is not a long!")
}
override fun getLong(columnIndex: Int): Long {
return castToLong(obj(columnIndex))
}
override fun getLong(columnLabel: String?): Long {
return castToLong(obj(columnLabel))
}
override fun getClob(columnIndex: Int): Clob {
//TODO Maybe?
notImplemented()
}
override fun getClob(columnLabel: String?): Clob {
//TODO Maybe?
notImplemented()
}
override fun updateBlob(columnIndex: Int, x: Blob?) {
notImplemented()
}
override fun updateBlob(columnLabel: String?, x: Blob?) {
notImplemented()
}
override fun updateBlob(columnIndex: Int, inputStream: InputStream?, length: Long) {
notImplemented()
}
override fun updateBlob(columnLabel: String?, inputStream: InputStream?, length: Long) {
notImplemented()
}
override fun updateBlob(columnIndex: Int, inputStream: InputStream?) {
notImplemented()
}
override fun updateBlob(columnLabel: String?, inputStream: InputStream?) {
notImplemented()
}
override fun updateByte(columnIndex: Int, x: Byte) {
notImplemented()
}
override fun updateByte(columnLabel: String?, x: Byte) {
notImplemented()
}
override fun updateRow() {
notImplemented()
}
override fun deleteRow() {
notImplemented()
}
override fun getNString(columnIndex: Int): String {
return obj(columnIndex) as String
}
override fun getNString(columnLabel: String?): String {
return obj(columnLabel) as String
}
override fun getArray(columnIndex: Int): Array {
//TODO Maybe?
notImplemented()
}
override fun getArray(columnLabel: String?): Array {
//TODO Maybe?
notImplemented()
}
override fun cancelRowUpdates() {
notImplemented()
}
override fun updateString(columnIndex: Int, x: String?) {
notImplemented()
}
override fun updateString(columnLabel: String?, x: String?) {
notImplemented()
}
override fun setFetchDirection(direction: Int) {
notImplemented()
}
override fun getCharacterStream(columnIndex: Int): Reader {
return getNCharacterStream(columnIndex)
}
override fun getCharacterStream(columnLabel: String?): Reader {
return getNCharacterStream(columnLabel)
}
override fun isBeforeFirst(): Boolean {
return cursor - 1 < resultSetLength
}
override fun updateBoolean(columnIndex: Int, x: Boolean) {
notImplemented()
}
override fun updateBoolean(columnLabel: String?, x: Boolean) {
notImplemented()
}
override fun refreshRow() {
notImplemented()
}
override fun rowUpdated() = false
override fun updateBigDecimal(columnIndex: Int, x: BigDecimal?) {
notImplemented()
}
override fun updateBigDecimal(columnLabel: String?, x: BigDecimal?) {
notImplemented()
}
override fun getShort(columnIndex: Int): Short {
return obj(columnIndex) as Short
}
override fun getShort(columnLabel: String?): Short {
return obj(columnLabel) as Short
}
override fun getAsciiStream(columnIndex: Int): InputStream {
return getBinaryStream(columnIndex)
}
override fun getAsciiStream(columnLabel: String?): InputStream {
return getBinaryStream(columnLabel)
}
override fun updateTime(columnIndex: Int, x: Time?) {
notImplemented()
}
override fun updateTime(columnLabel: String?, x: Time?) {
notImplemented()
}
override fun getTimestamp(columnIndex: Int): Timestamp {
//TODO Maybe?
notImplemented()
}
override fun getTimestamp(columnLabel: String?): Timestamp {
//TODO Maybe?
notImplemented()
}
override fun getTimestamp(columnIndex: Int, cal: Calendar?): Timestamp {
//TODO Maybe?
notImplemented()
}
override fun getTimestamp(columnLabel: String?, cal: Calendar?): Timestamp {
//TODO Maybe?
notImplemented()
}
override fun getRef(columnIndex: Int): Ref {
//TODO Maybe?
notImplemented()
}
override fun getRef(columnLabel: String?): Ref {
//TODO Maybe?
notImplemented()
}
override fun getConcurrency() = ResultSet.CONCUR_READ_ONLY
override fun updateRowId(columnIndex: Int, x: RowId?) {
notImplemented()
}
override fun updateRowId(columnLabel: String?, x: RowId?) {
notImplemented()
}
override fun getNCharacterStream(columnIndex: Int): Reader {
return getBinaryStream(columnIndex).reader()
}
override fun getNCharacterStream(columnLabel: String?): Reader {
return getBinaryStream(columnLabel).reader()
}
override fun updateArray(columnIndex: Int, x: Array?) {
notImplemented()
}
override fun updateArray(columnLabel: String?, x: Array?) {
notImplemented()
}
override fun getBytes(columnIndex: Int): ByteArray {
return obj(columnIndex) as ByteArray
}
override fun getBytes(columnLabel: String?): ByteArray {
return obj(columnLabel) as ByteArray
}
override fun getDouble(columnIndex: Int): Double {
return obj(columnIndex) as Double
}
override fun getDouble(columnLabel: String?): Double {
return obj(columnLabel) as Double
}
override fun getUnicodeStream(columnIndex: Int): InputStream {
return getBinaryStream(columnIndex)
}
override fun getUnicodeStream(columnLabel: String?): InputStream {
return getBinaryStream(columnLabel)
}
override fun rowInserted() = false
private fun thisIsWrapperFor(iface: Class<*>?) = this.javaClass.isInstance(iface)
override fun isWrapperFor(iface: Class<*>?): Boolean {
return thisIsWrapperFor(iface) || parent.isWrapperFor(iface)
}
override fun getInt(columnIndex: Int): Int {
return obj(columnIndex) as Int
}
override fun getInt(columnLabel: String?): Int {
return obj(columnLabel) as Int
}
override fun updateNull(columnIndex: Int) {
notImplemented()
}
override fun updateNull(columnLabel: String?) {
notImplemented()
}
override fun getRowId(columnIndex: Int): RowId {
//TODO Maybe?
notImplemented()
}
override fun getRowId(columnLabel: String?): RowId {
//TODO Maybe?
notImplemented()
}
override fun getMetaData(): ResultSetMetaData {
return object : ResultSetMetaData by parentMetadata {
override fun isReadOnly(column: Int) = true
override fun isWritable(column: Int) = false
override fun isDefinitelyWritable(column: Int) = false
override fun getColumnCount() = [email protected]
override fun getColumnLabel(column: Int): String {
return columnLabels[column - 1]
}
}
}
override fun getBinaryStream(columnIndex: Int): InputStream {
return (obj(columnIndex) as ByteArray).inputStream()
}
override fun getBinaryStream(columnLabel: String?): InputStream {
return (obj(columnLabel) as ByteArray).inputStream()
}
override fun updateCharacterStream(columnIndex: Int, x: Reader?, length: Int) {
notImplemented()
}
override fun updateCharacterStream(columnLabel: String?, reader: Reader?, length: Int) {
notImplemented()
}
override fun updateCharacterStream(columnIndex: Int, x: Reader?, length: Long) {
notImplemented()
}
override fun updateCharacterStream(columnLabel: String?, reader: Reader?, length: Long) {
notImplemented()
}
override fun updateCharacterStream(columnIndex: Int, x: Reader?) {
notImplemented()
}
override fun updateCharacterStream(columnLabel: String?, reader: Reader?) {
notImplemented()
}
class ResultSetEntry {
val data = mutableListOf<Any?>()
}
} | apache-2.0 | b8317a0d46c0a7b1901717d8c23d7c7a | 24.613555 | 100 | 0.627019 | 4.814484 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/SessionInfoStore.kt | 1 | 1040 | package ch.rmy.android.http_shortcuts.data
import android.content.Context
import ch.rmy.android.framework.utils.PreferencesStore
import ch.rmy.android.http_shortcuts.data.domains.categories.CategoryId
import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutId
import javax.inject.Inject
class SessionInfoStore
@Inject
constructor(
context: Context,
) : PreferencesStore(context, PREF_NAME) {
var editingShortcutId: ShortcutId?
get() = getString(KEY_EDITING_SHORTCUT_ID)
set(value) {
putString(KEY_EDITING_SHORTCUT_ID, value)
}
var editingShortcutCategoryId: CategoryId?
get() = getString(KEY_EDITING_SHORTCUT_CATEGORY_ID)
set(value) {
putString(KEY_EDITING_SHORTCUT_CATEGORY_ID, value)
}
companion object {
private const val PREF_NAME = "session-info"
private const val KEY_EDITING_SHORTCUT_ID = "editing_shortcut_id"
private const val KEY_EDITING_SHORTCUT_CATEGORY_ID = "editing_shortcut_category_id"
}
}
| mit | d360a52699ab1bd125968a96dde35b9b | 30.515152 | 91 | 0.7125 | 3.984674 | false | false | false | false |
TachiWeb/TachiWeb-Server | TachiServer/src/main/java/xyz/nulldev/ts/api/http/HttpAPI.kt | 1 | 16533 | /*
* Copyright 2016 Andy Bao
*
* 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 xyz.nulldev.ts.api.http
import mu.KotlinLogging
import okhttp3.*
import spark.Route
import spark.Spark
import xyz.nulldev.ts.api.http.auth.CheckSessionRoute
import xyz.nulldev.ts.api.http.auth.ClearSessionsRoute
import xyz.nulldev.ts.api.http.auth.TestAuthenticatedRoute
import xyz.nulldev.ts.api.http.catalogue.CatalogueRoute
import xyz.nulldev.ts.api.http.catalogue.GetFiltersRoute
import xyz.nulldev.ts.api.http.catalogue.ListSourcesRoute
import xyz.nulldev.ts.api.http.download.DownloadChapterRoute
import xyz.nulldev.ts.api.http.download.DownloadsOperationRoute
import xyz.nulldev.ts.api.http.download.GetDownloadStatusRoute
import xyz.nulldev.ts.api.http.image.CoverRoute
import xyz.nulldev.ts.api.http.image.ImageRoute
import xyz.nulldev.ts.api.http.library.*
import xyz.nulldev.ts.api.http.manga.*
import xyz.nulldev.ts.api.http.settings.ListLoginSourceRoute
import xyz.nulldev.ts.api.http.settings.PreferencesRoute
import xyz.nulldev.ts.api.http.settings.SetPreferenceRoute
import xyz.nulldev.ts.api.http.settings.SourceLoginRoute
import xyz.nulldev.ts.api.http.sync.SyncRoute
import xyz.nulldev.ts.api.http.task.TaskStatusRoute
import xyz.nulldev.ts.api.v2.http.HttpApplication
import xyz.nulldev.ts.api.v2.http.categories.CategoriesController
import xyz.nulldev.ts.api.v2.http.chapters.ChaptersController
import xyz.nulldev.ts.api.v2.http.extensions.ExtensionsController
import xyz.nulldev.ts.api.v2.http.jvcompat.JavalinShim
import xyz.nulldev.ts.api.v2.http.library.LibraryController
import xyz.nulldev.ts.api.v2.http.mangas.MangasController
import xyz.nulldev.ts.api.v3.WebAPI
import xyz.nulldev.ts.config.ConfigManager
import xyz.nulldev.ts.config.ServerConfig
import xyz.nulldev.ts.ext.kInstance
import java.util.concurrent.TimeUnit
/**
* Project: TachiServer
* Author: nulldev
* Creation Date: 30/09/16
*/
class HttpAPI {
private val serverConfig by lazy { kInstance<ConfigManager>().module<ServerConfig>() }
private val logger = KotlinLogging.logger { }
suspend fun start() {
//Get an image from a chapter
val imageRoute = ImageRoute()
getAPIRoute("/img/:mangaId/:chapterId/:page", imageRoute)
//Get the cover of a manga
val coverRoute = CoverRoute()
getAPIRoute("/cover/:mangaId", coverRoute)
//Get the library
val libraryRoute = LibraryRoute()
getAPIRoute("/library", libraryRoute)
//Get details about a manga
val mangaRoute = MangaRoute()
getAPIRoute("/manga_info/:mangaId", mangaRoute)
//Get the chapters of a manga
val chapterRoute = ChaptersRoute()
getAPIRoute("/chapters/:mangaId", chapterRoute)
//Get the page count of a chapter
val pageCountRoute = PageCountRoute()
getAPIRoute("/page_count/:mangaId/:chapterId", pageCountRoute)
//Backup the library
val createBackupRoute = CreateBackupRoute()
getAPIRoute("/backup", createBackupRoute)
//Restore the library
val restoreFromFileRoute = RestoreFromFileRoute()
postAPIRoute("/restore_file", restoreFromFileRoute)
//Favorite/unfavorite a manga
val faveRoute = FaveRoute()
getAPIRoute("/fave/:mangaId", faveRoute)
//Set the reading status of a chapter
val readingStatusRoute = ReadingStatusRoute()
getAPIRoute("/reading_status/:mangaId/:chapterId", readingStatusRoute)
//Update a manga/chapter
val updateRoute = UpdateRoute()
getAPIRoute("/update/:mangaId/:updateType", updateRoute)
//Source list
val listSourcesRoute = ListSourcesRoute()
getAPIRoute("/sources", listSourcesRoute)
//Catalogue
val catalogueRoute = CatalogueRoute()
postAPIRoute("/catalogue", catalogueRoute)
//Login source list
val listLoginSourceRoute = ListLoginSourceRoute()
getAPIRoute("/list_login_sources", listLoginSourceRoute)
//Login route
val sourceLoginRoute = SourceLoginRoute()
getAPIRoute("/source_login/:sourceId", sourceLoginRoute)
//Download
val downloadChapterRoute = DownloadChapterRoute()
getAPIRoute("/download/:mangaId/:chapterId", downloadChapterRoute)
//Downloads operation
val downloadsOperationRoute = DownloadsOperationRoute()
getAPIRoute("/downloads_op/:operation", downloadsOperationRoute)
//Get downloads
val getDownloadStatusRoute = GetDownloadStatusRoute()
getAPIRoute("/get_downloads", getDownloadStatusRoute)
//Set flags
val setFlagRoute = SetFlagRoute()
getAPIRoute("/set_flag/:mangaId/:flag/:state", setFlagRoute)
//Preferences route
val preferencesRoute = PreferencesRoute()
getAPIRoute("/prefs", preferencesRoute)
//Set preferences route
val setPreferenceRoute = SetPreferenceRoute()
getAPIRoute("/set_pref/:key/:type", setPreferenceRoute)
//Task status route
val taskStatusRoute = TaskStatusRoute()
getAPIRoute("/task/:taskId", taskStatusRoute)
//Check session
val checkSessionRoute = CheckSessionRoute()
getAPIRoute("/auth", checkSessionRoute)
//Clear sessions
val clearSessionsRoute = ClearSessionsRoute()
getAPIRoute("/clear_sessions", clearSessionsRoute)
//Test auth route
val testAuthRoute = TestAuthenticatedRoute()
getAPIRoute("/test_auth", testAuthRoute)
//Get categories
val getCategoriesRoute = GetCategoriesRoute()
getAPIRoute("/get_categories", getCategoriesRoute)
//Edit categories
val editCategoriesRoute = EditCategoriesRoute()
getAPIRoute("/edit_categories/:operation", editCategoriesRoute)
//Get filters
val getFiltersRoute = GetFiltersRoute()
getAPIRoute("/get_filters/:sourceId", getFiltersRoute)
// V2 APIs (TODO Move to Javalin once all routes are rewritten)
//TODO Change path params to use constants
HttpApplication() // Initialize Javalin API for now but do not start it
getAPIRoute("/v2/library/flags", JavalinShim(LibraryController::getLibraryFlags))
postAPIRoute("/v2/library/flags", JavalinShim(LibraryController::setLibraryFlags))
getAPIRoute("/v2/chapters/reading_status", JavalinShim(ChaptersController::getReadingStatus))
postAPIRoute("/v2/chapters/reading_status", JavalinShim(ChaptersController::setReadingStatus))
getAPIRoute("/v2/chapters/:chapters/reading_status", JavalinShim(ChaptersController::getReadingStatus))
postAPIRoute("/v2/chapters/:chapters/reading_status", JavalinShim(ChaptersController::setReadingStatus))
getAPIRoute("/v2/mangas/viewer", JavalinShim(MangasController::getViewer))
postAPIRoute("/v2/mangas/viewer", JavalinShim(MangasController::setViewer))
getAPIRoute("/v2/mangas/:mangas/viewer", JavalinShim(MangasController::getViewer))
postAPIRoute("/v2/mangas/:mangas/viewer", JavalinShim(MangasController::setViewer))
getAPIRoute("/v2/categories", JavalinShim(CategoriesController::getCategory))
postAPIRoute("/v2/categories", JavalinShim(CategoriesController::addCategory))
deleteAPIRoute("/v2/categories", JavalinShim(CategoriesController::deleteCategory))
getAPIRoute("/v2/categories/name", JavalinShim(CategoriesController::getName))
postAPIRoute("/v2/categories/name", JavalinShim(CategoriesController::setName))
getAPIRoute("/v2/categories/order", JavalinShim(CategoriesController::getOrder))
postAPIRoute("/v2/categories/order", JavalinShim(CategoriesController::setOrder))
getAPIRoute("/v2/categories/flags", JavalinShim(CategoriesController::getFlags))
postAPIRoute("/v2/categories/flags", JavalinShim(CategoriesController::setFlags))
getAPIRoute("/v2/categories/manga", JavalinShim(CategoriesController::getManga))
postAPIRoute("/v2/categories/manga", JavalinShim(CategoriesController::setManga))
getAPIRoute("/v2/categories/:categories", JavalinShim(CategoriesController::getCategory))
deleteAPIRoute("/v2/categories/:categories", JavalinShim(CategoriesController::deleteCategory))
getAPIRoute("/v2/categories/:categories/name", JavalinShim(CategoriesController::getName))
postAPIRoute("/v2/categories/:categories/name", JavalinShim(CategoriesController::setName))
getAPIRoute("/v2/categories/:categories/order", JavalinShim(CategoriesController::getOrder))
postAPIRoute("/v2/categories/:categories/order", JavalinShim(CategoriesController::setOrder))
getAPIRoute("/v2/categories/:categories/flags", JavalinShim(CategoriesController::getFlags))
postAPIRoute("/v2/categories/:categories/flags", JavalinShim(CategoriesController::setFlags))
getAPIRoute("/v2/categories/:categories/manga", JavalinShim(CategoriesController::getManga))
postAPIRoute("/v2/categories/:categories/manga", JavalinShim(CategoriesController::setManga))
postAPIRoute("/v2/extensions", JavalinShim(ExtensionsController::installExternal))
getAPIRoute("/v2/extensions", JavalinShim(ExtensionsController::getExtension))
deleteAPIRoute("/v2/extensions", JavalinShim(ExtensionsController::delete))
getAPIRoute("/v2/extensions/name", JavalinShim(ExtensionsController::getName))
getAPIRoute("/v2/extensions/status", JavalinShim(ExtensionsController::getStatus))
getAPIRoute("/v2/extensions/version_name", JavalinShim(ExtensionsController::getVersionName))
getAPIRoute("/v2/extensions/version_code", JavalinShim(ExtensionsController::getVersionCode))
getAPIRoute("/v2/extensions/signature_hash", JavalinShim(ExtensionsController::getSignatureHash))
getAPIRoute("/v2/extensions/lang", JavalinShim(ExtensionsController::getLang))
getAPIRoute("/v2/extensions/sources", JavalinShim(ExtensionsController::getSources))
getAPIRoute("/v2/extensions/has_update", JavalinShim(ExtensionsController::getHasUpdate))
getAPIRoute("/v2/extensions/icon", JavalinShim(ExtensionsController::getIcon))
postAPIRoute("/v2/extensions/install", JavalinShim(ExtensionsController::install))
postAPIRoute("/v2/extensions/reload-local", JavalinShim(ExtensionsController::reloadLocal))
postAPIRoute("/v2/extensions/reload-available", JavalinShim(ExtensionsController::reloadAvailable))
postAPIRoute("/v2/extensions/trust", JavalinShim(ExtensionsController::trust))
getAPIRoute("/v2/extensions/:extensions", JavalinShim(ExtensionsController::getExtension))
deleteAPIRoute("/v2/extensions/:extensions", JavalinShim(ExtensionsController::delete))
getAPIRoute("/v2/extensions/:extensions/name", JavalinShim(ExtensionsController::getName))
getAPIRoute("/v2/extensions/:extensions/status", JavalinShim(ExtensionsController::getStatus))
getAPIRoute("/v2/extensions/:extensions/version_name", JavalinShim(ExtensionsController::getVersionName))
getAPIRoute("/v2/extensions/:extensions/version_code", JavalinShim(ExtensionsController::getVersionCode))
getAPIRoute("/v2/extensions/:extensions/signature_hash", JavalinShim(ExtensionsController::getSignatureHash))
getAPIRoute("/v2/extensions/:extensions/lang", JavalinShim(ExtensionsController::getLang))
getAPIRoute("/v2/extensions/:extensions/sources", JavalinShim(ExtensionsController::getSources))
getAPIRoute("/v2/extensions/:extensions/has_update", JavalinShim(ExtensionsController::getHasUpdate))
getAPIRoute("/v2/extensions/:extensions/icon", JavalinShim(ExtensionsController::getIcon))
postAPIRoute("/v2/extensions/:extensions/install", JavalinShim(ExtensionsController::install))
//Sync route
val syncRoute = SyncRoute()
getAPIRoute("/sync", syncRoute)
postAPIRoute("/sync", syncRoute)
// Start v3 web API and proxy to it
val v3Api = WebAPI().start()
val proxyHttpClient = OkHttpClient.Builder()
.cache(null)
.followRedirects(true) // Our web client can't handle proxied redirects
.followSslRedirects(false) // v3 shouldn't be doing this
// Connection pool is causing issues so don't use it
.connectionPool(ConnectionPool(0, 1, TimeUnit.NANOSECONDS))
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build()
val v3Route = Route { incoming, outgoing ->
val targetUrl = "http://localhost:${v3Api.port}${incoming.contextPath() ?: ""}${incoming.servletPath()
?: ""}${incoming.pathInfo() ?: ""}?${incoming.queryString() ?: ""}"
logger.info {
val originalUrl = "${incoming.requestMethod()} ${incoming.contextPath() ?: ""}${incoming.servletPath()
?: ""}${incoming.pathInfo() ?: ""}?${incoming.queryString() ?: ""}"
"Proxying v3 API request: $originalUrl --> $targetUrl"
}
val request = Request.Builder()
.url(targetUrl)
.method(incoming.requestMethod(),
if (incoming.requestMethod() in listOf("POST", "PUT", "DELETE", "PATCH"))
RequestBody.create(null, incoming.bodyAsBytes())
else null
)
.headers(Headers.of(incoming.headers().associateWith { incoming.headers(it) }))
.build()
val result = proxyHttpClient.newCall(request).execute()
outgoing.status(result.code())
result.headers().toMultimap().forEach { name, values ->
values.forEach { value ->
outgoing.header(name, value)
}
}
result.body().byteStream().use { resultBody ->
resultBody.copyTo(outgoing.raw().outputStream)
}
""
}
fun proxyPath(path: String) {
Spark.get(buildAPIPath(path), v3Route)
Spark.post(buildAPIPath(path), v3Route)
Spark.put(buildAPIPath(path), v3Route)
Spark.patch(buildAPIPath(path), v3Route)
Spark.delete(buildAPIPath(path), v3Route)
Spark.head(buildAPIPath(path), v3Route)
Spark.trace(buildAPIPath(path), v3Route)
Spark.connect(buildAPIPath(path), v3Route)
Spark.options(buildAPIPath(path), v3Route)
}
proxyPath("/v3/*")
proxyPath("/v3")
}
private fun buildAPIPath(path: String): String {
return API_ROOT + path
}
private fun getAPIRoute(path: String, route: Route) {
if(!checkApi(path)) return
val builtPath = buildAPIPath(path)
Spark.get(builtPath, route)
Spark.get(builtPath + "/", route)
}
private fun postAPIRoute(path: String, route: Route) {
if(!checkApi(path)) return
val builtPath = buildAPIPath(path)
Spark.post(builtPath, route)
Spark.post(builtPath + "/", route)
}
private fun deleteAPIRoute(path: String, route: Route) {
if(!checkApi(path)) return
val builtPath = buildAPIPath(path)
Spark.delete(builtPath, route)
Spark.delete(builtPath + "/", route)
}
fun checkApi(path: String): Boolean {
val endpoint = path.split("/").filterNot(String::isBlank).first().trim().toLowerCase()
if(endpoint in serverConfig.disabledApiEndpoints) return false
if(serverConfig.enabledApiEndpoints.isNotEmpty()) {
if(endpoint !in serverConfig.enabledApiEndpoints) return false
}
return true
}
companion object {
val API_ROOT = "/api"
}
} | apache-2.0 | 12ad3cd5858c424e5fe2b647a875d01e | 49.873846 | 118 | 0.692433 | 4.418226 | false | false | false | false |
bugsnag/bugsnag-android-gradle-plugin | src/main/kotlin/com/bugsnag/android/gradle/BugsnagUploadProguardTask.kt | 1 | 3957 | package com.bugsnag.android.gradle
import com.bugsnag.android.gradle.internal.BugsnagHttpClientHelper
import com.bugsnag.android.gradle.internal.UploadRequestClient
import com.bugsnag.android.gradle.internal.md5HashCode
import com.bugsnag.android.gradle.internal.property
import com.bugsnag.android.gradle.internal.register
import okhttp3.RequestBody.Companion.asRequestBody
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.TaskProvider
import javax.inject.Inject
/**
* Task to upload ProGuard mapping files to Bugsnag.
*
* Reads meta-data tags from the project's AndroidManifest.xml to extract a
* build UUID (injected by BugsnagManifestTask) and a Bugsnag API Key:
*
* https://developer.android.com/guide/topics/manifest/manifest-intro.html
* https://developer.android.com/guide/topics/manifest/meta-data-element.html
*
* This task must be called after ProGuard mapping files are generated, so
* it is usually safe to have this be the absolute last task executed during
* a build.
*/
open class BugsnagUploadProguardTask @Inject constructor(
objects: ObjectFactory
) : DefaultTask(), AndroidManifestInfoReceiver, BugsnagFileUploadTask {
init {
group = BugsnagPlugin.GROUP_NAME
description = "Uploads the mapping file to Bugsnag"
}
@get:InputFile
override val manifestInfo: RegularFileProperty = objects.fileProperty()
@get:Internal
internal val uploadRequestClient: Property<UploadRequestClient> = objects.property()
@get:Internal
override val httpClientHelper: Property<BugsnagHttpClientHelper> = objects.property()
@get:InputFiles
val mappingFileProperty: RegularFileProperty = objects.fileProperty()
@get:OutputFile
val requestOutputFile: RegularFileProperty = objects.fileProperty()
@get:Input
override val failOnUploadError: Property<Boolean> = objects.property()
@get:Input
override val overwrite: Property<Boolean> = objects.property()
@get:Input
override val endpoint: Property<String> = objects.property()
@get:Input
override val retryCount: Property<Int> = objects.property()
@get:Input
override val timeoutMillis: Property<Long> = objects.property()
@TaskAction
fun upload() {
val mappingFile = mappingFileProperty.get().asFile
// Read the API key and Build ID etc..
// Construct a basic request
val manifestInfo = parseManifestInfo()
// Send the request
val request = BugsnagMultiPartUploadRequest.from(this)
val mappingFileHash = mappingFile.md5HashCode()
val response = uploadRequestClient.get().makeRequestIfNeeded(manifestInfo, mappingFileHash) {
request.uploadMultipartEntity(retryCount.get()) { builder ->
logger.lifecycle("Bugsnag: Uploading JVM mapping file from: $mappingFile")
builder.addAndroidManifestInfo(manifestInfo)
builder.addFormDataPart("proguard", mappingFile.name, mappingFile.asRequestBody())
}
}
requestOutputFile.asFile.get().writeText(response)
}
companion object {
/**
* Registers the appropriate subtype to this [project] with the given [name] and
* [configurationAction]
*/
internal fun register(
project: Project,
name: String,
configurationAction: BugsnagUploadProguardTask.() -> Unit
): TaskProvider<out BugsnagUploadProguardTask> {
return project.tasks.register(name, configurationAction)
}
}
}
| mit | 1aa4828fa642a76c8409a6306de3255c | 34.648649 | 101 | 0.728835 | 4.585168 | false | false | false | false |
sg26565/hott-transmitter-config | HoTT-Voice/src/main/kotlin/de/treichels/hott/voice/Buffer.kt | 1 | 1821 | package de.treichels.hott.voice
/**
* A rolling buffer with a fixed capacity.
*
* As new elements are added to the buffer, previous elements will be removed if the capacity is reached.
*
* @author Oliver Treichel <[email protected]>
*/
class Buffer(capacity: Int) {
/** all elements in this buffer */
private val elements: IntArray = IntArray(capacity)
/** the pointer to the next index where new values are inserted */
private var pointer = 0
/**
* Get the current capacity of the Buffer.
*
* @return The capacity
*/
val size: Int
get() = elements.size
/**
* Add a new element to the buffer. If the capacity is reached, older values will be automatically removed from the buffer.
*
* @param nextElement The new element.
*/
fun add(nextElement: Int) {
elements[pointer] = nextElement
pointer++
if (pointer == elements.size) pointer = 0
}
/**
* Get the element at the specified position. Where `get(0)` will return the oldest (first added) element and `get(capacity -1)` will
* return the newest (least added) element.
*
* @param index The position were `0 <= index < capacity`.
* @return The element at the specified position.
* @throws IndexOutOfBoundsException if index is negative or greater or equal to the capacity.
*/
operator fun get(index: Int): Int {
var i = index + pointer
if (i >= elements.size) i -= elements.size
return elements[i]
}
override fun toString(): String {
val b = StringBuilder()
b.append("Buffer[")
for (i in elements.indices) {
if (i > 0) b.append(", ")
b.append(get(i))
}
b.append("]")
return b.toString()
}
}
| lgpl-3.0 | dfc1a619d6644c5a5ba6a174d3c34fd1 | 27.453125 | 137 | 0.606809 | 4.264637 | false | false | false | false |
kirimin/mitsumine | app/src/main/java/me/kirimin/mitsumine/_common/database/entity/FeedTableEntity.kt | 1 | 1543 | package me.kirimin.mitsumine._common.database.entity;
import com.activeandroid.Model
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import me.kirimin.mitsumine._common.domain.model.Feed
/**
* フィードをDBに保存するためのテーブルモデル
*/
@Table(name = "feed")
class FeedTableEntity() : Model() {
constructor(feed: Feed): this() {
title = feed.title
thumbnailUrl = feed.thumbnailUrl
content = feed.content
linkUrl = feed.linkUrl
entryLinkUrl = feed.entryLinkUrl
bookmarkCountUrl = feed.bookmarkCountUrl
faviconUrl = feed.faviconUrl
type = feed.type
saveTime = feed.saveTime
}
@Column(name = "title")
var title: String = ""
@Column(name = "thumbnailUrl")
var thumbnailUrl: String = ""
@Column(name = "content")
var content: String = ""
@Column(name = "linkUrl", unique = true)
var linkUrl: String = ""
@Column(name = "entryLinkUrl")
var entryLinkUrl: String = ""
@Column(name = "bookmarkCountUrl")
var bookmarkCountUrl: String = ""
@Column(name = "faviconUrl")
var faviconUrl: String = ""
@Column(name = "type")
var type: String = ""
@Column(name = "saveTime")
var saveTime: Long = 0
fun toModel() = Feed(title = title, thumbnailUrl = thumbnailUrl, content = content, linkUrl = linkUrl, entryLinkUrl = entryLinkUrl, bookmarkCountUrl = bookmarkCountUrl, faviconUrl = faviconUrl, type = type, saveTime = saveTime)
}
| apache-2.0 | 4b919e51f143f1cf1e5b35f27992713e | 26.833333 | 231 | 0.659348 | 3.824427 | false | false | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/ui/disabled/DisabledController.kt | 1 | 5832 | /**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 3/25/20.
* Copyright (c) 2020 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.disabled
import android.os.Bundle
import android.view.View
import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.changehandler.FadeChangeHandler
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler
import com.breadwallet.R
import com.breadwallet.databinding.ControllerDisabledBinding
import com.breadwallet.logger.logDebug
import com.breadwallet.logger.logError
import com.breadwallet.tools.animation.SpringAnimator
import com.breadwallet.tools.security.BrdUserManager
import com.breadwallet.tools.security.BrdUserState
import com.breadwallet.tools.util.BRConstants
import com.breadwallet.tools.util.EventUtils
import com.breadwallet.ui.BaseController
import com.breadwallet.ui.changehandlers.BottomSheetChangeHandler
import com.breadwallet.ui.login.LoginController
import com.breadwallet.ui.navigation.NavigationTarget
import com.breadwallet.ui.navigation.asSupportUrl
import com.breadwallet.ui.recovery.RecoveryKey
import com.breadwallet.ui.recovery.RecoveryKeyController
import com.breadwallet.ui.web.WebController
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.kodein.di.erased.instance
import java.util.Locale
class DisabledController(args: Bundle? = null) : BaseController(args) {
private val userManager by instance<BrdUserManager>()
private val binding by viewBinding(ControllerDisabledBinding::inflate)
override fun onCreateView(view: View) {
super.onCreateView(view)
binding.faqButton.setOnClickListener {
val url = NavigationTarget.SupportPage(BRConstants.FAQ_WALLET_DISABLE).asSupportUrl()
router.pushController(
RouterTransaction.with(WebController(url))
.popChangeHandler(BottomSheetChangeHandler())
.pushChangeHandler(BottomSheetChangeHandler())
)
}
binding.resetButton.setOnClickListener {
val controller = RecoveryKeyController(RecoveryKey.Mode.RESET_PIN)
router.pushController(
RouterTransaction.with(controller)
.popChangeHandler(HorizontalChangeHandler())
.pushChangeHandler(HorizontalChangeHandler())
)
}
}
override fun onAttach(view: View) {
super.onAttach(view)
userManager.stateChanges(disabledUpdates = true)
.onEach { state ->
when (state) {
is BrdUserState.Disabled ->
walletDisabled(state.seconds)
else -> walletEnabled()
}
}
.flowOn(Main)
.launchIn(viewAttachScope)
}
override fun handleBack(): Boolean {
val isDisabled = userManager.getState() is BrdUserState.Disabled
if (isDisabled) {
SpringAnimator.failShakeAnimation(activity, binding.disabled)
}
return isDisabled
}
private fun walletDisabled(seconds: Int) {
binding.untilLabel.text = String.format(
Locale.ROOT,
"%02d:%02d:%02d",
seconds / 3600,
seconds % 3600 / 60,
seconds % 60
)
}
private fun walletEnabled() {
logError("Wallet enabled, going to Login.")
EventUtils.pushEvent(EventUtils.EVENT_LOGIN_UNLOCKED)
val returnStack = router.backstack
.takeWhile { it.controller !is DisabledController }
when {
returnStack.isEmpty() -> {
logDebug("Returning to Login for Home screen.")
router.setRoot(
RouterTransaction.with(LoginController(showHome = true))
.popChangeHandler(FadeChangeHandler())
.pushChangeHandler(FadeChangeHandler())
)
}
returnStack.last().controller !is LoginController -> {
logDebug("Returning to Login for previous backstack.")
val loginTransaction = RouterTransaction.with(LoginController(showHome = false))
.popChangeHandler(FadeChangeHandler())
.pushChangeHandler(FadeChangeHandler())
router.setBackstack(returnStack + loginTransaction, FadeChangeHandler())
}
else -> {
logDebug("Returning to Login with previous backstack.")
router.setBackstack(returnStack, FadeChangeHandler())
}
}
}
}
| mit | 9cb641de7ee175cfc1b0d191446118ce | 38.945205 | 97 | 0.683128 | 5.188612 | false | false | false | false |
wonderkiln/CameraKit-Android | camerakit/src/main/java/com/camerakit/api/camera1/Camera1.kt | 2 | 5253 | package com.camerakit.api.camera1
import android.graphics.SurfaceTexture
import android.hardware.Camera
import com.camerakit.api.CameraApi
import com.camerakit.api.CameraAttributes
import com.camerakit.api.CameraEvents
import com.camerakit.api.CameraHandler
import com.camerakit.api.camera1.ext.getFlashes
import com.camerakit.api.camera1.ext.getPhotoSizes
import com.camerakit.api.camera1.ext.getPreviewSizes
import com.camerakit.type.CameraFacing
import com.camerakit.type.CameraFlash
import com.camerakit.type.CameraSize
class Camera1(eventsDelegate: CameraEvents) :
CameraApi, CameraEvents by eventsDelegate {
override val cameraHandler: CameraHandler = CameraHandler.get()
private var camera: Camera? = null
private var cameraAttributes: CameraAttributes? = null
@Synchronized
override fun open(facing: CameraFacing) {
val cameraId = when (facing) {
CameraFacing.BACK -> Camera.CameraInfo.CAMERA_FACING_BACK
CameraFacing.FRONT -> Camera.CameraInfo.CAMERA_FACING_FRONT
}
val numberOfCameras = Camera.getNumberOfCameras()
val cameraInfo = Camera.CameraInfo()
for (i in 0 until numberOfCameras) {
Camera.getCameraInfo(i, cameraInfo)
if (cameraInfo.facing == cameraId) {
val camera = Camera.open(i)
val cameraParameters = camera.parameters
val cameraAttributes = Attributes(cameraInfo, cameraParameters, facing)
this.camera = camera
this.cameraAttributes = cameraAttributes
onCameraOpened(cameraAttributes)
}
}
}
@Synchronized
override fun release() {
camera?.release()
camera = null
cameraAttributes = null
onCameraClosed()
}
@Synchronized
override fun setPreviewOrientation(degrees: Int) {
val camera = camera
if (camera != null) {
camera.setDisplayOrientation(degrees)
}
}
@Synchronized
override fun setPreviewSize(size: CameraSize) {
val camera = camera
if (camera != null) {
val parameters = camera.parameters
parameters.setPreviewSize(size.width, size.height)
camera.parameters = parameters
}
}
@Synchronized
override fun startPreview(surfaceTexture: SurfaceTexture) {
val camera = camera
if (camera != null) {
val parameters = camera.parameters
if (parameters.supportedFocusModes != null && Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE in parameters.supportedFocusModes) {
parameters.focusMode = Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE
camera.parameters = parameters
}
camera.setPreviewTexture(surfaceTexture)
camera.setOneShotPreviewCallback { _, _ ->
onPreviewStarted()
}
camera.startPreview()
}
}
@Synchronized
override fun stopPreview() {
val camera = camera
if (camera != null) {
camera.stopPreview()
onPreviewStopped()
}
}
@Synchronized
override fun setFlash(flash: CameraFlash) {
val camera = camera
if (camera != null) {
val parameters = camera.parameters
parameters.flashMode = when(flash) {
CameraFlash.OFF -> Camera.Parameters.FLASH_MODE_OFF
CameraFlash.ON -> Camera.Parameters.FLASH_MODE_ON
CameraFlash.AUTO -> Camera.Parameters.FLASH_MODE_AUTO
CameraFlash.TORCH -> Camera.Parameters.FLASH_MODE_TORCH
}
try {
camera.parameters = parameters
} catch (e: Exception) {
// ignore failures for minor parameters like this for now
}
}
}
@Synchronized
override fun setPhotoSize(size: CameraSize) {
val camera = camera
if (camera != null) {
val parameters = camera.parameters
parameters.setPictureSize(size.width, size.height)
try {
camera.parameters = parameters
} catch (e: Exception) {
// ignore failures for minor parameters like this for now
}
}
}
@Synchronized
override fun capturePhoto(callback: (jpeg: ByteArray) -> Unit) {
val camera = camera
if (camera != null) {
camera.takePicture(null, null) { data, _ ->
callback(data)
camera.startPreview()
}
}
}
private class Attributes(cameraInfo: Camera.CameraInfo,
cameraParameters: Camera.Parameters,
cameraFacing: CameraFacing) : CameraAttributes {
override val facing: CameraFacing = cameraFacing
override val sensorOrientation: Int = cameraInfo.orientation
override val previewSizes: Array<CameraSize> = cameraParameters.getPreviewSizes()
override val photoSizes: Array<CameraSize> = cameraParameters.getPhotoSizes()
override val flashes: Array<CameraFlash> = cameraParameters.getFlashes()
}
} | mit | 3dac011a852b6a0eb2d642ce9c023c27 | 31.63354 | 142 | 0.617362 | 5.012405 | false | false | false | false |
EMResearch/EvoMaster | core/src/test/kotlin/org/evomaster/core/search/algorithms/MioAlgorithmOnOneMaxTest.kt | 1 | 1613 | package org.evomaster.core.search.algorithms
import com.google.inject.Injector
import com.google.inject.Key
import com.google.inject.Module
import com.google.inject.TypeLiteral
import com.netflix.governator.guice.LifecycleInjector
import org.evomaster.core.BaseModule
import org.evomaster.core.EMConfig
import org.evomaster.core.search.algorithms.onemax.OneMaxIndividual
import org.evomaster.core.search.algorithms.onemax.OneMaxModule
import org.evomaster.core.search.algorithms.onemax.OneMaxSampler
import org.evomaster.core.search.service.Randomness
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class MioAlgorithmOnOneMaxTest {
val injector: Injector = LifecycleInjector.builder()
.withModules(* arrayOf<Module>(OneMaxModule(), BaseModule()))
.build().createInjector()
@Test
fun testMIO(){
val mio = injector.getInstance(Key.get(
object : TypeLiteral<MioAlgorithm<OneMaxIndividual>>() {}))
val randomness = injector.getInstance(Randomness::class.java)
randomness.updateSeed(42)
val sampler = injector.getInstance(OneMaxSampler::class.java)
val config = injector.getInstance(EMConfig::class.java)
config.maxActionEvaluations = 30000
config.stoppingCriterion = EMConfig.StoppingCriterion.FITNESS_EVALUATIONS
val n = 20
sampler.n = n
val solution = mio.search()
Assertions.assertEquals(n.toDouble(), solution.overall.computeFitnessScore(), 0.001);
Assertions.assertEquals(1, solution.individuals.size)
}
} | lgpl-3.0 | b9fbdbb3cfefe30be5b4ba145438ca73 | 33.340426 | 93 | 0.734036 | 4.289894 | false | true | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/account/HomeAccountCreationFragment.kt | 1 | 4714 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Aline Bonnet <[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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package cx.ring.account
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.android.material.snackbar.Snackbar
import cx.ring.R
import cx.ring.databinding.FragAccHomeCreateBinding
import cx.ring.mvp.BaseSupportFragment
import cx.ring.utils.AndroidFileUtils.getCacheFile
import dagger.hilt.android.AndroidEntryPoint
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import net.jami.account.HomeAccountCreationPresenter
import net.jami.account.HomeAccountCreationView
import java.io.File
@AndroidEntryPoint
class HomeAccountCreationFragment :
BaseSupportFragment<HomeAccountCreationPresenter, HomeAccountCreationView>(),
HomeAccountCreationView {
private var binding: FragAccHomeCreateBinding? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
return FragAccHomeCreateBinding.inflate(inflater, container, false).apply {
ringAddAccount.setOnClickListener {presenter.clickOnLinkAccount() }
ringCreateBtn.setOnClickListener { presenter.clickOnCreateAccount() }
accountConnectServer.setOnClickListener { presenter.clickOnConnectAccount() }
ringImportAccount.setOnClickListener {performFileSearch() }
binding = this
}.root
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
override fun goToAccountCreation() {
val fragment: Fragment = JamiAccountCreationFragment()
replaceFragmentWithSlide(fragment, R.id.wizard_container)
}
override fun goToAccountLink() {
val fragment: Fragment = JamiLinkAccountFragment.newInstance(AccountCreationModelImpl().apply {
isLink = true
})
replaceFragmentWithSlide(fragment, R.id.wizard_container)
}
override fun goToAccountConnect() {
val fragment: Fragment = JamiAccountConnectFragment.newInstance(AccountCreationModelImpl().apply {
isLink = true
})
replaceFragmentWithSlide(fragment, R.id.wizard_container)
}
private fun performFileSearch() {
try {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
.addCategory(Intent.CATEGORY_OPENABLE)
.setType("*/*")
startActivityForResult(intent, ARCHIVE_REQUEST_CODE)
} catch (e: Exception) {
view?.let { v ->
Snackbar.make(v, "No file browser available on this device", Snackbar.LENGTH_SHORT).show() }
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
if (requestCode == ARCHIVE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
resultData?.data?.let { uri ->
getCacheFile(requireContext(), uri)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ file: File ->
val ringAccountViewModel = AccountCreationModelImpl()
ringAccountViewModel.isLink = true
ringAccountViewModel.archive = file
val fragment: Fragment = JamiLinkAccountFragment.newInstance(ringAccountViewModel)
replaceFragmentWithSlide(fragment, R.id.wizard_container)
}) { e: Throwable ->
view?.let { v ->
Snackbar.make(v, "Can't import archive: " + e.message, Snackbar.LENGTH_LONG).show() }
}
}
}
}
companion object {
private const val ARCHIVE_REQUEST_CODE = 42
val TAG = HomeAccountCreationFragment::class.simpleName!!
}
} | gpl-3.0 | 8d92c0dff76fbc1419ab8dd90463a332 | 40 | 115 | 0.679465 | 4.854789 | false | false | false | false |
tmarsteel/kotlin-prolog | async/src/test/kotlin/com/github/prologdb/async/LazySequenceBuilderTest.kt | 1 | 7924 | package com.github.prologdb.async
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.shouldBe
import java.util.concurrent.CompletableFuture
class LazySequenceBuilderTest : FreeSpec() { init {
"yield - single element" {
val seq = buildLazySequence<String>(RANDOM_PRINCIPAL) {
yield("foobar")
null
}
seq.tryAdvance() shouldBe "foobar"
seq.tryAdvance() shouldBe null
}
"yield - multiple elements" {
val seq = buildLazySequence<String>(RANDOM_PRINCIPAL) {
yield("foo")
yield("bar")
null
}
seq.tryAdvance() shouldBe "foo"
seq.tryAdvance() shouldBe "bar"
seq.tryAdvance() shouldBe null
}
"yieldAll - single element" {
val seq = buildLazySequence<String>(RANDOM_PRINCIPAL) {
yieldAll(buildLazySequence(principal) {
yield("foobar")
null
})
null
}
seq.tryAdvance() shouldBe "foobar"
seq.tryAdvance() shouldBe null
}
"yieldAll - multiple elements" {
val seq = buildLazySequence<String>(RANDOM_PRINCIPAL) {
yieldAll(buildLazySequence(principal) {
yield("foo")
yield("bar")
null
})
null
}
seq.tryAdvance() shouldBe "foo"
seq.tryAdvance() shouldBe "bar"
seq.tryAdvance() shouldBe null
}
"yield then yieldAll" {
val seq = buildLazySequence<String>(RANDOM_PRINCIPAL) {
yield("baz")
yieldAll(buildLazySequence(principal) {
yield("foo")
yield("bar")
null
})
null
}
seq.tryAdvance() shouldBe "baz"
seq.tryAdvance() shouldBe "foo"
seq.tryAdvance() shouldBe "bar"
seq.tryAdvance() shouldBe null
}
"yieldAll then yield" {
val seq = buildLazySequence<String>(RANDOM_PRINCIPAL) {
yieldAll(buildLazySequence(principal) {
yield("foo")
yield("bar")
null
})
yield("baz")
null
}
seq.tryAdvance() shouldBe "foo"
seq.tryAdvance() shouldBe "bar"
seq.tryAdvance() shouldBe "baz"
seq.tryAdvance() shouldBe null
}
"yield then yieldAll then yield" {
val seq = buildLazySequence<String>(RANDOM_PRINCIPAL) {
yield("beep")
yieldAll(buildLazySequence(principal) {
yield("foo")
yield("bar")
null
})
yield("baz")
null
}
seq.tryAdvance() shouldBe "beep"
seq.tryAdvance() shouldBe "foo"
seq.tryAdvance() shouldBe "bar"
seq.tryAdvance() shouldBe "baz"
seq.tryAdvance() shouldBe null
}
"failing await" {
val exceptionToThrow = RuntimeException("Some fancy exception")
val failingFuture = CompletableFuture<Unit>()
var exceptionCaughtInLS: Throwable? = null
val seq = buildLazySequence<Unit>(RANDOM_PRINCIPAL) {
try {
await(failingFuture)
}
catch (ex: Throwable) {
exceptionCaughtInLS = ex
}
null
}
seq.step() // now hangs on the future
failingFuture.completeExceptionally(exceptionToThrow)
seq.step() shouldBe LazySequence.State.DEPLETED // this should give the error to the catch code in the sequence
exceptionCaughtInLS shouldBe exceptionToThrow
seq.tryAdvance() shouldBe null
}
"failing nested" {
val ex = RuntimeException("Some fancy exception 1")
val seq = buildLazySequence<Unit>(RANDOM_PRINCIPAL) {
try {
yieldAll(buildLazySequence(this.principal) {
try {
buildLazySequence<Unit>(this.principal) {
throw ex
}.consumeAll()
} catch (ex: RuntimeException) {
throw RuntimeException(ex)
}
})
} catch (ex: RuntimeException) {
throw RuntimeException(ex)
}
}
val thrown = shouldThrow<RuntimeException> {
seq.consumeAll()
}
thrown.cause!!.cause shouldBe ex
}
"failing in nested yield all" {
val ex = RuntimeException("Some fancy exception")
val seq = buildLazySequence<Unit>(RANDOM_PRINCIPAL) {
try {
yieldAll(buildLazySequence(principal) {
throw ex
})
} catch (ex: RuntimeException) {
throw RuntimeException("Rethrow", ex)
}
}
val thrown = shouldThrow<RuntimeException> {
seq.consumeAll()
}
thrown.message shouldBe "Rethrow"
thrown.cause shouldBe ex
seq.state shouldBe LazySequence.State.FAILED
}
"recovering in yield all" {
val ex = RuntimeException("Some fancy exception")
val seq = buildLazySequence<Unit>(RANDOM_PRINCIPAL) {
try {
yieldAll(buildLazySequence(principal) {
throw ex
})
} catch (ex: RuntimeException) {
yield(Unit)
}
null
}
seq.tryAdvance() shouldBe Unit
seq.tryAdvance() shouldBe null
seq.state shouldBe LazySequence.State.DEPLETED
}
"failing in nested await" {
val ex = RuntimeException("Some fancy exception")
val seq = buildLazySequence<Unit>(RANDOM_PRINCIPAL) {
try {
await(launchWorkableFuture(principal) {
throw ex
})
} catch (ex: RuntimeException) {
throw RuntimeException("Rethrow", ex)
}
}
val thrown = shouldThrow<RuntimeException> {
seq.consumeAll()
}
thrown.message shouldBe "Rethrow"
thrown.cause shouldBe ex
}
"recovering in await" {
val ex = RuntimeException("Some fancy exception")
val seq = buildLazySequence<Unit>(RANDOM_PRINCIPAL) {
try {
await(launchWorkableFuture(principal) {
throw ex
})
} catch (ex: RuntimeException) {
yield(Unit)
}
null
}
seq.tryAdvance() shouldBe Unit
seq.tryAdvance() shouldBe null
seq.state shouldBe LazySequence.State.DEPLETED
}
"LazySequence of" {
val seq = LazySequence.of("foobar")
seq.tryAdvance() shouldBe "foobar"
seq.tryAdvance() shouldBe null
}
"final result" {
val withFinal = buildLazySequence<String>(RANDOM_PRINCIPAL) {
yield("a")
"b"
}
val withoutFinal = buildLazySequence<String>(RANDOM_PRINCIPAL) {
yield("a")
yield("b")
null
}
withFinal.tryAdvance() shouldBe "a"
withoutFinal.tryAdvance() shouldBe "a"
withFinal.state shouldBe LazySequence.State.PENDING
withoutFinal.state shouldBe LazySequence.State.PENDING
withFinal.step() shouldBe LazySequence.State.RESULTS_AVAILABLE
withoutFinal.step() shouldBe LazySequence.State.RESULTS_AVAILABLE
withFinal.tryAdvance() shouldBe "b"
withoutFinal.tryAdvance() shouldBe "b"
withFinal.state shouldBe LazySequence.State.DEPLETED
withoutFinal.state shouldBe LazySequence.State.PENDING
withoutFinal.step() shouldBe LazySequence.State.DEPLETED
}
}}
| mit | 08f482e19b3f7260a2d0e92a76f60aa4 | 27.099291 | 119 | 0.542024 | 5.060026 | false | false | false | false |
VerifAPS/verifaps-lib | symbex/src/main/kotlin/edu/kit/iti/formal/automation/st0/trans/CallEmbedding.kt | 1 | 9131 | package edu.kit.iti.formal.automation.st0.trans
import edu.kit.iti.formal.automation.datatypes.FunctionBlockDataType
import edu.kit.iti.formal.automation.scope.Scope
import edu.kit.iti.formal.automation.st.ast.*
import edu.kit.iti.formal.automation.st.util.AstMutableVisitor
import edu.kit.iti.formal.automation.st0.MultiCodeTransformation
import edu.kit.iti.formal.automation.st0.TransformationState
import java.util.*
val EMBEDDING_BODY_PIPELINE = MultiCodeTransformation(arrayListOf(
ActionEmbedder(),
FBEmbeddParameters(),
FBAssignments(),
FBEmbeddCode()
))
val EMBEDDING_PIPELINE = MultiCodeTransformation(arrayListOf(
ActionEmbedder(),
FBEmbeddVariables(),
EMBEDDING_BODY_PIPELINE,
FBRemoveInstance()
))
/**
* Seperator between identifier.
*/
var SCOPE_SEPARATOR = "$"
class CallEmbedding : CodeTransformation {
override fun transform(state: TransformationState): TransformationState = EMBEDDING_PIPELINE.transform(state)
}
class ActionEmbedder : CodeTransformation {
override fun transform(state: TransformationState): TransformationState {
state.stBody = state.stBody.accept(ActionEmbedderImpl()) as StatementList
return state
}
private class ActionEmbedderImpl : AstMutableVisitor() {
override fun visit(fbc: InvocationStatement): Statement {
try {
val ainvoke = fbc.invoked as Invoked.Action
val stmt = StatementList()
stmt += CommentStatement.single("Call of action: %s", fbc.callee.identifier)
stmt.addAll(ainvoke.action.stBody!!)
stmt += CommentStatement.single("End of action call: %s", fbc.callee.identifier)
return stmt
} catch (e: ClassCastException) {
}
return super.visit(fbc)
}
}
}
class FBEmbeddVariables : CodeTransformation {
fun transform(scope: Scope): ArrayList<VariableDeclaration> {
val variables = arrayListOf<VariableDeclaration>()
val mask = (VariableDeclaration.INPUT or VariableDeclaration.OUTPUT or VariableDeclaration.INOUT).inv()
for (vd in scope.variables) {
val type = vd.dataType
if (type is FunctionBlockDataType) {
val subScope = transform(type.functionBlock.scope)
subScope.forEach {
it.name = vd.name + SCOPE_SEPARATOR + it.name
it.type = it.type and mask or VariableDeclaration.LOCAL
}
variables.addAll(subScope)
}
variables.add(vd.clone())
}
return variables
}
override fun transform(state: TransformationState): TransformationState {
val vars = transform(state.scope)
state.scope.variables.clear()
state.scope.variables.addAll(vars)
return state
}
}
class FBEmbeddParameters : CodeTransformation {
override fun transform(state: TransformationState): TransformationState {
state.stBody = state.stBody.accept(FBEmbeddParamtersImpl(state)) as StatementList
return state
}
class FBEmbeddParamtersImpl(val state: TransformationState) : AstMutableVisitor() {
override fun visit(invocation: InvocationStatement): Statement {
val invoked = invocation.invoked
if (invoked != null && invoked is Invoked.FunctionBlock) {
val stmt = StatementList()
invocation.inputParameters.forEach { (name, _, expression) ->
if (name != null) {
val sr = invocation.callee.copy(sub = SymbolicReference(name))
stmt += AssignmentStatement(sr, expression)
} else {
throw IllegalStateException("Function block call without parameter name!")
}
}
//stmt += (CommentStatement.single("Call of %s", invocation.callee.identifier))
stmt += invocation
//rewrite output variables as trailing assignments.
invocation.outputParameters.forEach { (name, _, expression) ->
if (name != null) {
val out = invocation.callee.copy(sub = SymbolicReference(name))
stmt += AssignmentStatement(expression as SymbolicReference, out)
} else {
throw IllegalStateException("Output parameter in function block call w/o name.")
}
}
//stmt += CommentStatement.single("End of call")
//clear all parameters
invocation.parameters.clear()
return stmt
}
return invocation
}
}
}
class FBAssignments : CodeTransformation {
override fun transform(state: TransformationState): TransformationState {
state.stBody = state.stBody.accept(FBAssignmentsImpl(state.scope)) as StatementList
return state
}
class FBAssignmentsImpl(private val scope: Scope) : AstMutableVisitor() {
override fun visit(symbolicReference: SymbolicReference): Expression {
val s = scope.resolveVariable(symbolicReference)
val dt = s?.dataType
if (s != null && dt is FunctionBlockDataType && symbolicReference.hasSub()) {
return SymbolicReference(symbolicReference.toPath().joinToString(SCOPE_SEPARATOR))
}
return super.visit(symbolicReference)
}
}
}
class FBEmbeddCode : CodeTransformation, AstMutableVisitor() {
companion object {
private val bodyCache = hashMapOf<TransformationState, StatementList>()
var renaming: (state: TransformationState, statements: StatementList, prefix: (String) -> String) -> StatementList =
::defaultRenaming
fun defaultRenaming(state: TransformationState, statements: StatementList, prefix: (String) -> String)
= VariableRenamer(state.scope::isGlobalVariable, statements.clone(), prefix).rename()
}
override fun transform(state: TransformationState): TransformationState {
state.stBody = state.stBody.accept(this) as StatementList
return state
}
fun getBody(prefix: String, state: TransformationState): BlockStatement {
if (state !in bodyCache) {
val istate = TransformationState(
state.scope, state.stBody.clone(), SFCImplementation())
val s = EMBEDDING_BODY_PIPELINE.transform(istate)
bodyCache[state] = s.stBody
}
val statements = bodyCache[state]!!.clone()
val renameFn: (String) -> String = { prefix + SCOPE_SEPARATOR + it }
val renamed = renaming(state, statements, renameFn)
val block = BlockStatement(prefix)
block.input = rewrite(renameFn, state.scope) { it.isInput }
block.output = rewrite(renameFn, state.scope) { it.isOutput }
block.state = rewrite(renameFn, state.scope) { it.isLocal }
block.statements = renamed
return block
}
private fun rewrite(renameFn: (String) -> String,
scope: Scope,
filter: (VariableDeclaration) -> Boolean): MutableList<SymbolicReference> {
return scope.variables.filter(filter)
.map { SymbolicReference(renameFn(it.name)) }
.toMutableList()
}
override fun visit(invocation: InvocationStatement): Statement {
val invoked = invocation.invoked
?: throw IllegalStateException("Invocation was not resolved. Abort. $invocation")
if (invoked is Invoked.FunctionBlock) {
val state = TransformationState(invoked.fb)
val prefix = invocation.callee.toPath().joinToString(SCOPE_SEPARATOR)
return getBody(prefix, state).also { it.originalInvoked = invoked }
}
if (invoked is Invoked.Action && invocation.callee.hasSub()) {
val action = invocation.callee.toPath()
val fb = action.subList(0, action.lastIndex - 1)
val prefix = fb.joinToString(SCOPE_SEPARATOR)
val state = TransformationState(invoked.scope, invoked.action.stBody!!, SFCImplementation())
return getBody(prefix, state).also { it.originalInvoked = invoked }
}
if (invoked is Invoked.Function) {
val s = StatementList()
//s += CommentStatement.single("Removed function invocation to ${invoked.function.name}")
s += CommentStatement.single("TODO for feature: Embedd function body after substitution to cover global effects.")
s.addAll(invoked.function.stBody!!)
return s
}
return invocation
}
}
class FBRemoveInstance : CodeTransformation {
override fun transform(state: TransformationState): TransformationState {
val fbVars = state.scope.filter { it.dataType is FunctionBlockDataType }
state.scope.variables.removeAll(fbVars)
return state
}
}
| gpl-3.0 | d125839df7b7027e1dac4977e50f94fa | 39.402655 | 126 | 0.630928 | 4.82356 | false | false | false | false |
industrial-data-space/trusted-connector | ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/data/Account.kt | 1 | 913 | /*-
* ========================LICENSE_START=================================
* ids-webconsole
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.webconsole.api.data
class Account {
var username: String? = null
var password: String? = null
}
| apache-2.0 | 69eeee4d21b74afdcf836d712ffdecb4 | 35.52 | 75 | 0.625411 | 4.453659 | false | false | false | false |
zitmen/thunderstorm | src/main/java/cz/cuni/lf1/lge/ThunderSTORM/AboutPlugIn.kt | 1 | 2498 | package cz.cuni.lf1.lge.ThunderSTORM
import cz.cuni.lf1.lge.ThunderSTORM.UI.GUI
import cz.cuni.lf1.lge.ThunderSTORM.UI.Help
import cz.cuni.lf1.lge.ThunderSTORM.UI.HelpButton
import ij.IJ
import ij.plugin.BrowserLauncher
import ij.plugin.PlugIn
import java.awt.Cursor
import java.awt.Dialog
import java.awt.Dimension
import java.awt.Window
import javax.swing.BorderFactory
import javax.swing.JDialog
import javax.swing.JScrollPane
import javax.swing.event.HyperlinkEvent
private const val URL = "resources/help/about.html"
private const val WINDOW_WIDTH = 600
private const val WINDOW_HEIGHT = 600
class AboutPlugIn : PlugIn {
override fun run(arg: String) {
try {
GUI.setLookAndFeel()
val dialog = JDialog(IJ.getInstance(), "About ThunderSTORM (" + ThunderSTORM.VERSION + ")")
if(IJ.isJava17()) {
dialog.type = Window.Type.UTILITY
}
dialog.modalExclusionType = Dialog.ModalExclusionType.APPLICATION_EXCLUDE //for use within modal dialog
val htmlBrowser = HelpButton.createEditorUsingOurClassLoader()
htmlBrowser.border = BorderFactory.createEmptyBorder()
htmlBrowser.addHyperlinkListener({ e ->
if(e.eventType == HyperlinkEvent.EventType.ACTIVATED) {
try {
if("jar".equals(e.url.protocol)) {
htmlBrowser.page = e.url
} else {
BrowserLauncher.openURL(e.url.toString())
}
} catch(ex: Exception) {
IJ.handleException(ex)
}
} else if(e.eventType == HyperlinkEvent.EventType.ENTERED) {
htmlBrowser.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
} else if(e.eventType == HyperlinkEvent.EventType.EXITED) {
htmlBrowser.cursor = Cursor.getDefaultCursor()
}
})
val scrollPane = JScrollPane(htmlBrowser)
scrollPane.preferredSize = Dimension(WINDOW_WIDTH, WINDOW_HEIGHT)
dialog.contentPane.add(scrollPane)
htmlBrowser.page = Help.getUrl(URL)
dialog.pack()
dialog.setLocationRelativeTo(null)
dialog.isVisible = true
} catch(e: Exception) {
IJ.handleException(e)
}
}
}
| gpl-3.0 | e1b17772a87c261f6a3847bd9921693b | 38.650794 | 115 | 0.591673 | 4.625926 | false | false | false | false |
coil-kt/coil | coil-base/src/main/java/coil/util/FileSystems.kt | 1 | 1576 | /*
* Copyright (C) 2011 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.
*/
@file:JvmName("-FileSystems")
package coil.util
import okio.FileNotFoundException
import okio.FileSystem
import okio.IOException
import okio.Path
/** Create a new empty file if one doesn't already exist. */
internal fun FileSystem.createFile(file: Path) {
if (!exists(file)) sink(file).closeQuietly()
}
/** Tolerant delete, try to clear as many files as possible even after a failure. */
internal fun FileSystem.deleteContents(directory: Path) {
var exception: IOException? = null
val files = try {
list(directory)
} catch (_: FileNotFoundException) {
return
}
for (file in files) {
try {
if (metadata(file).isDirectory) {
deleteContents(file)
}
delete(file)
} catch (e: IOException) {
if (exception == null) {
exception = e
}
}
}
if (exception != null) {
throw exception
}
}
| apache-2.0 | d4cf6f3fe80392d52d3bb211d7b9622b | 28.735849 | 84 | 0.65165 | 4.32967 | false | false | false | false |
ujpv/intellij-rust | src/test/kotlin/org/rust/lang/core/resolve/RustMultiResolveTest.kt | 1 | 827 | package org.rust.lang.core.resolve
import org.rust.lang.core.psi.RustReferenceElement
class RustMultiResolveTest : RustResolveTestBase() {
fun testStructExpr() = doTest("""
struct S { foo: i32, foo: () }
fn main() {
let _ = S { foo: 1 };
//^
}
""")
fun testFieldExpr() = doTest("""
struct S { foo: i32, foo: () }
fn f(s: S) {
s.foo
//^
}
""")
fun testUseMultiReference() = doTest("""
use m::foo;
//^
mod m {
fn foo() {}
mod foo {}
}
""")
private fun doTest(code: String) {
InlineFile(code)
val ref = findElementInEditor<RustReferenceElement>().reference
check(ref.multiResolve().size == 2)
}
}
| mit | dd5769b4a357524a8b0d05a5f4ae93ce | 20.763158 | 71 | 0.469166 | 4.241026 | false | true | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/LavaCommand.kt | 1 | 3066 | package net.perfectdreams.loritta.morenitta.commands.vanilla.images
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.morenitta.utils.ImageUtils
import net.perfectdreams.loritta.morenitta.utils.enableFontAntiAliasing
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.common.commands.ArgumentType
import net.perfectdreams.loritta.common.commands.arguments
import net.perfectdreams.loritta.morenitta.utils.extensions.readImage
import java.awt.Color
import java.awt.Font
import java.awt.Rectangle
import java.awt.image.BufferedImage
import java.io.File
class LavaCommand(loritta: LorittaBot) : AbstractCommand(loritta, "lava", category = net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) {
override fun getDescriptionKey() = LocaleKeyData("commands.command.lava.description")
override fun getExamplesKey() = LocaleKeyData("commands.command.lava.examples")
override fun getUsage() = arguments {
argument(ArgumentType.IMAGE) {}
argument(ArgumentType.TEXT) {}
}
override fun needsToUploadFiles(): Boolean {
return true
}
override suspend fun run(context: CommandContext,locale: BaseLocale) {
if (context.args.isNotEmpty()) {
var contextImage = context.getImageAt(0) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; }
val template = readImage(File(LorittaBot.ASSETS + "lava.png")) // Template
context.rawArgs = context.rawArgs.sliceArray(1..context.rawArgs.size - 1)
if (context.rawArgs.isEmpty()) {
this.explain(context)
return
}
var joined = context.rawArgs.joinToString(separator = " ") // Vamos juntar tudo em uma string
var singular = true // E verificar se é singular ou não
if (context.rawArgs[0].endsWith("s", true)) { // Se termina com s...
singular = false // Então é plural!
}
var resized = contextImage.getScaledInstance(64, 64, BufferedImage.SCALE_SMOOTH)
var small = contextImage.getScaledInstance(32, 32, BufferedImage.SCALE_SMOOTH)
var templateGraphics = template.graphics
templateGraphics.drawImage(resized, 120, 0, null)
templateGraphics.drawImage(small, 487, 0, null)
var image = BufferedImage(700, 443, BufferedImage.TYPE_INT_ARGB)
var graphics = image.graphics.enableFontAntiAliasing()
graphics.color = Color.WHITE
graphics.fillRect(0, 0, 700, 443)
graphics.color = Color.BLACK
graphics.drawImage(template, 0, 100, null)
var font = Font.createFont(0, File(LorittaBot.ASSETS + "mavenpro-bold.ttf")).deriveFont(24F)
graphics.font = font
ImageUtils.drawCenteredString(graphics, "O chão " + (if (singular) "é" else "são") + " $joined", Rectangle(2, 2, 700, 100), font)
context.sendFile(image, "lava.png", context.getAsMention(true))
} else {
this.explain(context)
}
}
} | agpl-3.0 | ca902c98a439f1121b31d7fc55ab0580 | 42.714286 | 152 | 0.768552 | 3.82375 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/economy/CoinFlipBetCommand.kt | 1 | 13827 | package net.perfectdreams.loritta.morenitta.commands.vanilla.economy
import net.perfectdreams.loritta.morenitta.LorittaLauncher
import net.perfectdreams.loritta.morenitta.commands.vanilla.`fun`.CaraCoroaCommand
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.morenitta.utils.extensions.await
import net.perfectdreams.loritta.morenitta.utils.onReactionAdd
import net.perfectdreams.loritta.morenitta.utils.removeAllFunctions
import net.perfectdreams.loritta.morenitta.utils.stripCodeMarks
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import net.dv8tion.jda.api.entities.User
import net.perfectdreams.loritta.common.commands.ArgumentType
import net.perfectdreams.loritta.common.commands.arguments
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import net.perfectdreams.loritta.cinnamon.pudding.tables.CoinFlipBetMatchmakingResults
import net.perfectdreams.loritta.cinnamon.pudding.tables.SonhosTransactionsLog
import net.perfectdreams.loritta.cinnamon.pudding.tables.transactions.CoinFlipBetSonhosTransactionsLog
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase
import net.perfectdreams.loritta.morenitta.utils.AccountUtils
import net.perfectdreams.loritta.common.utils.Emotes
import net.perfectdreams.loritta.morenitta.utils.GACampaigns
import net.perfectdreams.loritta.morenitta.utils.GenericReplies
import net.perfectdreams.loritta.morenitta.utils.NumberUtils
import net.perfectdreams.loritta.morenitta.utils.PaymentUtils
import net.perfectdreams.loritta.morenitta.utils.SonhosPaymentReason
import net.perfectdreams.loritta.common.utils.UserPremiumPlans
import net.perfectdreams.loritta.morenitta.utils.extensions.addReaction
import net.perfectdreams.loritta.morenitta.utils.extensions.refreshInDeferredTransaction
import net.perfectdreams.loritta.morenitta.utils.extensions.toJDA
import net.perfectdreams.loritta.morenitta.utils.sendStyledReply
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.insertAndGetId
import java.time.Instant
class CoinFlipBetCommand(val m: LorittaBot) : DiscordAbstractCommandBase(
m,
listOf("coinflip", "flipcoin", "girarmoeda", "caracoroa")
.flatMap { listOf("$it bet", "$it apostar") },
net.perfectdreams.loritta.common.commands.CommandCategory.ECONOMY
) {
companion object {
// Used to avoid dupes
private val mutex = Mutex()
}
override fun command() = create {
localizedDescription("commands.command.flipcoinbet.description")
localizedExamples("commands.command.flipcoinbet.examples")
usage {
arguments {
argument(ArgumentType.USER) {}
argument(ArgumentType.NUMBER) {}
}
}
this.canUseInPrivateChannel = false
executesDiscord {
if (2 > args.size)
this.explainAndExit()
val _user = validate(user(0))
val invitedUser = _user.toJDA()
if (invitedUser == user)
fail(locale["commands.command.flipcoinbet.cantBetSelf"], Constants.ERROR)
val selfActiveDonations = loritta.getActiveMoneyFromDonationsAsync(discordMessage.author.idLong)
val otherActiveDonations = loritta.getActiveMoneyFromDonationsAsync(invitedUser.idLong)
val selfPlan = UserPremiumPlans.getPlanFromValue(selfActiveDonations)
val otherPlan = UserPremiumPlans.getPlanFromValue(otherActiveDonations)
val hasNoTax: Boolean
val whoHasTheNoTaxReward: User?
val plan: UserPremiumPlans?
val tax: Long?
val taxPercentage: Double?
val quantityAfterTax: Long
val money: Long
val number = NumberUtils.convertShortenedNumberToLong(args[1])
?: GenericReplies.invalidNumber(this, args[1].stripCodeMarks())
if (selfPlan.totalCoinFlipReward == 1.0) {
whoHasTheNoTaxReward = discordMessage.author
hasNoTax = true
plan = selfPlan
taxPercentage = 0.0
tax = null
money = number
} else if (otherPlan.totalCoinFlipReward == 1.0) {
whoHasTheNoTaxReward = invitedUser
hasNoTax = true
plan = otherPlan
taxPercentage = 0.0
tax = null
money = number
} else {
whoHasTheNoTaxReward = null
hasNoTax = false
plan = UserPremiumPlans.Essential
taxPercentage = (1.0.toBigDecimal() - selfPlan.totalCoinFlipReward.toBigDecimal()).toDouble() // Avoid rounding errors
tax = (number * taxPercentage).toLong()
money = number - tax
}
if (!hasNoTax && tax == 0L)
fail(locale["commands.command.flipcoinbet.youNeedToBetMore"], Constants.ERROR)
if (0 >= number)
fail(locale["commands.command.flipcoinbet.zeroMoney"], Constants.ERROR)
val selfUserProfile = lorittaUser.profile
if (number > selfUserProfile.money) {
sendStyledReply {
this.append {
message = locale["commands.command.flipcoinbet.notEnoughMoneySelf"]
prefix = Constants.ERROR
}
this.append {
message = GACampaigns.sonhosBundlesUpsellDiscordMessage(
"https://loritta.website/", // Hardcoded, woo
"bet-coinflip-legacy",
"bet-not-enough-sonhos"
)
prefix = Emotes.LORI_RICH.asMention
mentionUser = false
}
}
return@executesDiscord
}
val invitedUserProfile = loritta.getOrCreateLorittaProfile(invitedUser.id)
val bannedState = invitedUserProfile.getBannedState(loritta)
if (number > invitedUserProfile.money || bannedState != null)
fail(locale["commands.command.flipcoinbet.notEnoughMoneyInvited", invitedUser.asMention], Constants.ERROR)
// Self user check
run {
val epochMillis = user.timeCreated.toEpochSecond() * 1000
// Don't allow users to bet if they are recent accounts
if (epochMillis + (Constants.ONE_WEEK_IN_MILLISECONDS * 2) > System.currentTimeMillis()) // 14 dias
fail(
LorittaReply(
locale["commands.command.pay.selfAccountIsTooNew", 14] + " ${Emotes.LORI_CRYING}",
Constants.ERROR
)
)
}
// Invited user check
run {
val epochMillis = invitedUser.timeCreated.toEpochSecond() * 1000
// Don't allow users to bet if they are recent accounts
if (epochMillis + (Constants.ONE_WEEK_IN_MILLISECONDS * 2) > System.currentTimeMillis()) // 14 dias
fail(
LorittaReply(
locale["commands.command.pay.otherAccountIsTooNew", 14] + " ${Emotes.LORI_CRYING}",
Constants.ERROR
)
)
}
// Only allow users to participate in a coin flip bet if the user got their daily reward today
AccountUtils.getUserTodayDailyReward(loritta, lorittaUser.profile)
?: fail(locale["commands.youNeedToGetDailyRewardBeforeDoingThisAction", serverConfig.commandPrefix], Constants.ERROR)
val message = reply(
LorittaReply(
if (hasNoTax)
locale[
"commands.command.flipcoinbet.startBetNoTax",
invitedUser.asMention,
user.asMention,
locale["commands.command.flipcoin.heads"],
money,
locale["commands.command.flipcoin.tails"],
whoHasTheNoTaxReward?.asMention ?: "???"
]
else
locale[
"commands.command.flipcoinbet.startBet",
invitedUser.asMention,
user.asMention,
locale["commands.command.flipcoin.heads"],
money,
locale["commands.command.flipcoin.tails"],
number,
tax
],
Emotes.LORI_RICH,
mentionUser = false
),
LorittaReply(
locale[
"commands.command.flipcoinbet.clickToAcceptTheBet",
invitedUser.asMention,
"✅"
],
"🤝",
mentionUser = false
)
).toJDA()
message.onReactionAdd(this) {
if (it.emoji.name == "✅") {
mutex.withLock {
if (loritta.messageInteractionCache.containsKey(it.messageIdLong)) {
val usersThatReactedToTheMessage = it.reaction.retrieveUsers().await()
if (invitedUser in usersThatReactedToTheMessage && user in usersThatReactedToTheMessage) {
message.removeAllFunctions(loritta)
GlobalScope.launch(loritta.coroutineDispatcher) {
mutex.withLock {
listOf(
selfUserProfile.refreshInDeferredTransaction(loritta),
invitedUserProfile.refreshInDeferredTransaction(loritta)
).awaitAll()
if (number > selfUserProfile.money)
return@withLock
if (number > invitedUserProfile.money)
return@withLock
val isTails = LorittaBot.RANDOM.nextBoolean()
val prefix: String
val message: String
if (isTails) {
prefix = "<:coroa:412586257114464259>"
message = locale["${CaraCoroaCommand.LOCALE_PREFIX}.tails"]
} else {
prefix = "<:cara:412586256409559041>"
message = locale["${CaraCoroaCommand.LOCALE_PREFIX}.heads"]
}
val winner: User
val loser: User
val now = Instant.now()
if (isTails) {
winner = user
loser = invitedUser
loritta.newSuspendedTransaction {
selfUserProfile.addSonhosNested(money)
invitedUserProfile.takeSonhosNested(number)
PaymentUtils.addToTransactionLogNested(
number,
SonhosPaymentReason.COIN_FLIP_BET,
givenBy = invitedUserProfile.id.value,
receivedBy = selfUserProfile.id.value
)
// Cinnamon transaction system
val mmResult = CoinFlipBetMatchmakingResults.insertAndGetId {
it[CoinFlipBetMatchmakingResults.timestamp] = now
it[CoinFlipBetMatchmakingResults.winner] = selfUserProfile.id.value
it[CoinFlipBetMatchmakingResults.loser] = invitedUserProfile.id.value
it[CoinFlipBetMatchmakingResults.quantity] = number
it[CoinFlipBetMatchmakingResults.quantityAfterTax] = money
it[CoinFlipBetMatchmakingResults.tax] = tax
it[CoinFlipBetMatchmakingResults.taxPercentage] = taxPercentage
}
val winnerTransactionLogId = SonhosTransactionsLog.insertAndGetId {
it[SonhosTransactionsLog.user] = selfUserProfile.id.value
it[SonhosTransactionsLog.timestamp] = now
}
CoinFlipBetSonhosTransactionsLog.insert {
it[CoinFlipBetSonhosTransactionsLog.timestampLog] = winnerTransactionLogId
it[CoinFlipBetSonhosTransactionsLog.matchmakingResult] = mmResult
}
val loserTransactionLogId = SonhosTransactionsLog.insertAndGetId {
it[SonhosTransactionsLog.user] = invitedUserProfile.id.value
it[SonhosTransactionsLog.timestamp] = now
}
CoinFlipBetSonhosTransactionsLog.insert {
it[CoinFlipBetSonhosTransactionsLog.timestampLog] = loserTransactionLogId
it[CoinFlipBetSonhosTransactionsLog.matchmakingResult] = mmResult
}
}
} else {
winner = invitedUser
loser = user
loritta.newSuspendedTransaction {
invitedUserProfile.addSonhosNested(money)
selfUserProfile.takeSonhosNested(number)
PaymentUtils.addToTransactionLogNested(
number,
SonhosPaymentReason.COIN_FLIP_BET,
givenBy = selfUserProfile.id.value,
receivedBy = invitedUserProfile.id.value
)
// Cinnamon transaction system
val mmResult = CoinFlipBetMatchmakingResults.insertAndGetId {
it[CoinFlipBetMatchmakingResults.timestamp] = Instant.now()
it[CoinFlipBetMatchmakingResults.winner] = invitedUserProfile.id.value
it[CoinFlipBetMatchmakingResults.loser] = selfUserProfile.id.value
it[CoinFlipBetMatchmakingResults.quantity] = number
it[CoinFlipBetMatchmakingResults.quantityAfterTax] = money
it[CoinFlipBetMatchmakingResults.tax] = tax
it[CoinFlipBetMatchmakingResults.taxPercentage] = taxPercentage
}
val winnerTransactionLogId = SonhosTransactionsLog.insertAndGetId {
it[SonhosTransactionsLog.user] = invitedUserProfile.id.value
it[SonhosTransactionsLog.timestamp] = now
}
CoinFlipBetSonhosTransactionsLog.insert {
it[CoinFlipBetSonhosTransactionsLog.timestampLog] = winnerTransactionLogId
it[CoinFlipBetSonhosTransactionsLog.matchmakingResult] = mmResult
}
val loserTransactionLogId = SonhosTransactionsLog.insertAndGetId {
it[SonhosTransactionsLog.user] = selfUserProfile.id.value
it[SonhosTransactionsLog.timestamp] = now
}
CoinFlipBetSonhosTransactionsLog.insert {
it[CoinFlipBetSonhosTransactionsLog.timestampLog] = loserTransactionLogId
it[CoinFlipBetSonhosTransactionsLog.matchmakingResult] = mmResult
}
}
}
reply(
LorittaReply(
"**$message!**",
prefix,
mentionUser = false
),
LorittaReply(
locale["commands.command.flipcoinbet.congratulations", winner.asMention, money, loser.asMention],
Emotes.LORI_RICH,
mentionUser = false
),
LorittaReply(
"Psiu, cansado de procurar pessoas que querem apostar com você? Então experimente o `/bet coinflipglobal`, um novo comando que permite você apostar com outros usuários, inclusive de outros servidores, sem precisar sair do conforto da sua ~~casa~~ servidor!",
mentionUser = false
)
)
}
}
}
}
}
}
}
message.addReaction("✅").queue()
}
}
} | agpl-3.0 | a3cb994835447f9e38ed82d188843003 | 36.037534 | 270 | 0.693644 | 4.197508 | false | false | false | false |
VladRassokhin/intellij-hcl | src/kotlin/org/intellij/plugins/hcl/psi/impl/HCLStringLiteralMixin.kt | 1 | 3790 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.plugins.hcl.psi.impl
import com.intellij.lang.ASTNode
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.LiteralTextEscaper
import com.intellij.psi.PsiLanguageInjectionHost
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.impl.source.tree.LeafElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.util.IncorrectOperationException
import org.intellij.plugins.hcl.HCLElementTypes
import org.intellij.plugins.hcl.psi.HCLElementGenerator
import org.intellij.plugins.hcl.psi.HCLStringLiteral
import org.intellij.plugins.hcl.terraform.config.model.getTerraformSearchScope
abstract class HCLStringLiteralMixin(node: ASTNode) : HCLLiteralImpl(node), HCLStringLiteral, PsiLanguageInjectionHost, PsiNamedElement {
override fun isValidHost() = true
companion object {
val LOG = Logger.getInstance(HCLStringLiteralMixin::class.java)
}
override fun updateText(s: String): HCLStringLiteralMixin {
return updateText(s, true)
}
fun updateText(s: String, changeQuotes: Boolean): HCLStringLiteralMixin {
if (s.length < 2) {
val message = "New text '$s' too short: ${s.length}"
LOG.error(message)
throw IncorrectOperationException(message)
}
assert(s.length >= 2)
val quote = s[0]
if (quote != s[s.lastIndex]) {
val message = "First '$quote' and last '${s.last()}' quotes mismatch, text: $s"
LOG.error(message)
throw IncorrectOperationException(message)
}
if (!(quote == '\'' || quote == '"')) {
val message = "Quote symbol not ''' or '\"' : $quote"
LOG.error(message)
throw IncorrectOperationException(message)
}
val buffer = StringBuilder(s)
// TODO: Use HIL-aware string escaper (?)
// Fix quotes if needed
if (quote != quoteSymbol) {
if (changeQuotes) {
buffer[0] = quoteSymbol
buffer[buffer.lastIndex] = quoteSymbol
} else {
return replace(HCLElementGenerator(project).createStringLiteral(buffer.toString(), null)) as HCLStringLiteralMixin
}
}
(node.firstChildNode as LeafElement).replaceWithText(buffer.toString())
return this
}
override fun createLiteralTextEscaper(): LiteralTextEscaper<out PsiLanguageInjectionHost> {
return HCLStringLiteralTextEscaper(this)
}
override fun getName(): String? {
return this.value
}
override fun setName(s: String): HCLStringLiteralMixin {
val buffer = StringBuilder(s.length)
// TODO: Use HIL-aware string escaper (?)
if (node.elementType == HCLElementTypes.SINGLE_QUOTED_STRING) {
buffer.append('\'')
StringUtil.escapeStringCharacters(s.length, s, "\'", buffer)
buffer.append('\'')
} else {
buffer.append('\"')
StringUtil.escapeStringCharacters(s.length, s, "\"", buffer)
buffer.append('\"')
}
return updateText(buffer.toString())
}
override fun getUseScope(): SearchScope {
return this.getTerraformSearchScope()
}
override fun getResolveScope(): GlobalSearchScope {
return this.getTerraformSearchScope()
}
}
| apache-2.0 | 573a47a2686266bdd2cafa6c418d8b47 | 33.770642 | 137 | 0.71715 | 4.306818 | false | false | false | false |
AlmasB/GroupNet | src/test/kotlin/icurves/algorithm/DescriptionMatcherTest.kt | 1 | 4031 | package icurves.algorithm
import icurves.description.Description
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test
/**
*
*
* @author Almas Baimagambetov ([email protected])
*/
class DescriptionMatcherTest {
// @Test
// fun `Test permutations`() {
// var result = permute(setOf("a"))
// assertThat(result.size, `is`(1))
// assertThat(result, hasItem("a"))
//
// result = permute(setOf("a", "b"))
// assertThat(result.size, `is`(2))
// assertThat(result, hasItems("ab", "ba"))
//
// result = permute(setOf("a", "b", "c"))
// assertThat(result.size, `is`(6))
// assertThat(result, hasItems("abc", "acb", "bac", "bca", "cab", "cba"))
//
// result = permute(setOf("a", "b", "c", "d"))
// assertThat(result.size, `is`(24))
// assertThat(result, hasItems(
// "abcd", "abdc", "acbd", "acdb", "adbc", "adcb",
// "bacd", "badc", "bcad", "bcda", "bdac", "bdca",
// "cabd", "cadb", "cbad", "cbda", "cdab", "cdba",
// "dabc", "dacb", "dbca", "dbac", "dcab", "dcba"
// ))
//
// result = permute(setOf("a", "b", "c", "d", "e"))
// assertThat(result.size, `is`(120))
//
// result = permute(setOf("a", "b", "c", "d", "e", "f"))
// assertThat(result.size, `is`(720))
//
// result = permute(setOf("a", "b", "c", "d", "e", "f", "h"))
// assertThat(result.size, `is`(5040))
//
// result = permute(setOf("a", "b", "c", "d", "e", "f", "h", "i"))
// assertThat(result.size, `is`(40320))
//
// result = permute(setOf("a", "b", "c", "d", "e", "f", "h", "i", "j"))
// assertThat(result.size, `is`(362880))
//
// result = permute(setOf("a", "b", "c", "d", "e", "f", "h", "i", "j", "k"))
// assertThat(result.size, `is`(3628800))
// }
@Test
fun `Match descriptions`() {
var pattern = Description.from("a b c").getInformalDescription()
var result = DescriptionMatcher.match(pattern, "x y z")
assertThat(result.size, `is`(3))
assertThat(result["a"], `is`("x"))
assertThat(result["b"], `is`("y"))
assertThat(result["c"], `is`("z"))
pattern = Description.from("a ab b").getInformalDescription()
result = DescriptionMatcher.match(pattern, "xy x y")
assertThat(result.size, `is`(2))
assertThat(result["a"], `is`("x"))
assertThat(result["b"], `is`("y"))
pattern = Description.from("a b abc").getInformalDescription()
result = DescriptionMatcher.match(pattern, "x xyz z")
assertThat(result.size, `is`(3))
assertThat(result["a"], `is`("x"))
assertThat(result["b"], `is`("z"))
assertThat(result["c"], `is`("y"))
pattern = Description.from("a b c ab ac bc abc").getInformalDescription()
result = DescriptionMatcher.match(pattern, "x xyz y xy yz z xz")
assertThat(result.size, `is`(3))
assertThat(result["a"], `is`("x"))
assertThat(result["b"], `is`("y"))
assertThat(result["c"], `is`("z"))
pattern = Description.from("a b c ab ac bc abc abcd ae").getInformalDescription()
result = DescriptionMatcher.match(pattern, "x xyz y xy xzyv xu yz z xz")
assertThat(result.size, `is`(5))
assertThat(result["a"], `is`("x"))
assertThat(result["b"], `is`("y"))
assertThat(result["c"], `is`("z"))
assertThat(result["d"], `is`("v"))
assertThat(result["e"], `is`("u"))
pattern = Description.from("a b c ab ac bc abc abcd d ad bd cd abd acd bcd").getInformalDescription()
result = DescriptionMatcher.match(pattern, "x xyz y xy xzyv xv yv zv xyv xzv yzv v yz z xz")
assertThat(result.size, `is`(4))
assertThat(result["a"], `is`("x"))
assertThat(result["b"], `is`("y"))
assertThat(result["c"], `is`("z"))
assertThat(result["d"], `is`("v"))
}
} | apache-2.0 | 330c1b27c80004dc8436498fda732ed2 | 35.990826 | 109 | 0.53287 | 3.263968 | false | false | false | false |
tjeubaoit/netlog | app/src/main/kotlin/com/example/netlog/ui/TrackingBtsActivity.kt | 1 | 4127 | package com.example.netlog.ui
import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.*
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.ListView
import android.widget.TextView
import com.example.netlog.R
import com.example.netlog.common.Logger
import com.example.netlog.extensions.toast
import com.example.netlog.realm.TrackingBts
import com.example.netlog.realm.TrackingBtsDao
import io.realm.Realm
/**
* TODO: Class description here.
*
* @author <a href="https://github.com/tjeubaoit">tjeubaoit</a>
*/
class TrackingBtsActivity : AppCompatActivity() {
var list: ListView? = null
var editCid: EditText? = null
var editLac: EditText? = null
var adapter: TrackingBtsAdapter? = null
val items = arrayListOf<TrackingBts>()
var realm: Realm = Realm.getDefaultInstance()
var trackingBtsDao = TrackingBtsDao(realm)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tracking_bts)
val toolbar = findViewById(R.id.toolbar) as Toolbar?
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
editLac = findViewById(R.id.edit_lac) as EditText
editCid = findViewById(R.id.edit_cid) as EditText
findViewById(R.id.button_add).setOnClickListener { onAdd() }
adapter = TrackingBtsAdapter(this, items, itemDeletedCallback = { item, position ->
toast("Delete item at $position")
trackingBtsDao.delete(item)
})
adapter!!.setNotifyOnChange(true)
trackingBtsDao.findAll().forEach { adapter!!.add(it) }
list = findViewById(R.id.list_bts_tracking) as ListView
list!!.adapter = adapter
if (realm.isClosed) {
realm = Realm.getDefaultInstance()
trackingBtsDao = TrackingBtsDao(realm)
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_tracking_bts, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item!!.itemId) {
android.R.id.home, R.id.action_done -> {
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onDestroy() {
super.onDestroy()
realm.close()
}
private fun onAdd() {
val cid = editCid!!.text
val lac = editLac!!.text
if (cid.isEmpty() || lac.isEmpty()) {
toast(R.string.some_fields_invalid)
return
}
if (adapter!!.count >= 5) {
toast("Only support track max ${adapter!!.count} BTS")
return
}
val item = TrackingBts(lac.toString(), cid.toString())
item.id = item.toString()
trackingBtsDao.insert(item, onSuccess = {
adapter!!.add(item)
toast("Save to realm ${items.size} items")
}, onError = { t ->
toast("Save to realm failed, ${t.message}")
Logger.error(t)
})
}
class TrackingBtsAdapter(context: Context, items: List<TrackingBts>,
val itemDeletedCallback: ((TrackingBts, Int) -> Unit)?)
: ArrayAdapter<TrackingBts>(context, 0, items) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val item = getItem(position)
var v = convertView
if (v == null) {
v = LayoutInflater.from(context).inflate(R.layout.view_tracking_bts, parent, false)
}
val tvContent = v!!.findViewById(R.id.text) as TextView
tvContent.text = item.toString()
v.findViewById(R.id.button_delete).setOnClickListener { button ->
remove(item)
itemDeletedCallback?.invoke(item, position)
}
return v
}
}
}
| gpl-3.0 | 0773c86c559819f1892b147ecf4ae34b | 30.265152 | 99 | 0.621032 | 4.224156 | false | false | false | false |
ansman/kotshi | compiler/src/main/kotlin/se/ansman/kotshi/TypeSpecs.kt | 1 | 833 | package se.ansman.kotshi
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
internal val TypeSpec.typeName: TypeName
get() = tag<ClassName>()!!
.let {
if (typeVariables.isEmpty()) {
it
} else {
it.parameterizedBy(typeVariables)
}
}
internal fun TypeSpec.constructors(): Sequence<FunSpec> =
(primaryConstructor?.let { sequenceOf(it) } ?: emptySequence()) + funSpecs
.asSequence()
.filter { it.isConstructor }
internal data class KotshiConstructor(
val moshiParameterName: String? = null,
val typesParameterName: String? = null,
)
internal val KotshiConstructor.hasParameters: Boolean
get() = moshiParameterName != null || typesParameterName != null | apache-2.0 | a7812b5df3ca2338d32fcc763aa7d811 | 29.888889 | 78 | 0.663866 | 4.871345 | false | false | false | false |
FurhatRobotics/example-skills | Dog/src/main/kotlin/furhatos/app/dog/flow/showAllGestures.kt | 1 | 1467 | package furhatos.app.dog.flow
import furhatos.app.dog.gestures.*
import furhatos.flow.kotlin.State
import furhatos.flow.kotlin.furhat
import furhatos.flow.kotlin.state
val ShowAllGestures: State = state(Parent) {
onEntry {
furhat.gesture(panting1, async = false)
delay(500)
furhat.gesture(growlPositive2, async = false)
delay(500)
furhat.gesture(sniffing3, async = false)
delay(500)
furhat.gesture(growlPositive4, async = false)
delay(500)
furhat.gesture(sniffing3, async = false)
delay(500)
furhat.gesture(yawn1, async = false)
delay(500)
furhat.gesture(bark1, async = false)
delay(500)
furhat.gesture(whimpering3, async = false)
delay(500)
furhat.gesture(growl2, async = false)
delay(500)
furhat.gesture(whimpering2, async = false)
delay(500)
furhat.gesture(bark3, async = false)
delay(500)
furhat.gesture(shake1, async = false)
delay(500)
furhat.gesture(sniffing1, async = false)
delay(500)
furhat.gesture(whimpering5, async = false)
delay(500)
furhat.gesture(growl4, async = false)
delay(500)
furhat.gesture(meow, async = false)
delay(500)
furhat.gesture(bark2, async = false)
delay(500)
furhat.gesture(whimpering1, async = false)
delay(500)
goto(Main)
}
} | mit | a5d59742bab1d62dea9135ca7d23cafa | 28.959184 | 53 | 0.611452 | 3.658354 | false | false | false | false |
marvec/engine | lumeer-core/src/main/kotlin/io/lumeer/core/util/js/JvmListProxy.kt | 2 | 1887 | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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 io.lumeer.core.util.js
import org.graalvm.polyglot.Value
import org.graalvm.polyglot.proxy.ProxyArray
import java.util.*
class JvmListProxy(val values: MutableList<Any?>, val locale: Locale = Locale.getDefault()) : ProxyArray {
private val objects: Array<Any?> = Array(values.size) { null }
override fun get(index: Long): Any? {
checkIndex(index)
val i = index.toInt()
val o = objects[i]
if (o != null) {
return o
}
val v = values[i]
if (v != null) {
val enc = JvmObjectProxy.encodeObject(v, locale)
objects[i] = enc
return enc
}
return null
}
override fun set(index: Long, value: Value) = throw UnsupportedOperationException()
override fun remove(index: Long): Boolean = throw UnsupportedOperationException()
private fun checkIndex(index: Long) {
if (index > 2147483647L || index < 0L) {
throw ArrayIndexOutOfBoundsException("invalid index.")
}
}
override fun getSize(): Long = values.size.toLong()
}
| gpl-3.0 | 03c607b1f43eedf89fc42ffb06e62afd | 30.983051 | 106 | 0.664547 | 4.147253 | false | false | false | false |
k0shk0sh/FastHub | app/src/main/java/com/fastaccess/ui/widgets/markdown/MarkDownLayout.kt | 1 | 7500 | package com.fastaccess.ui.widgets.markdown
import android.annotation.SuppressLint
import android.content.Context
import com.google.android.material.snackbar.Snackbar
import androidx.transition.TransitionManager
import androidx.fragment.app.FragmentManager
import android.util.AttributeSet
import android.view.View
import android.widget.EditText
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.fastaccess.R
import com.fastaccess.helper.AppHelper
import com.fastaccess.helper.InputHelper
import com.fastaccess.helper.ViewHelper
import com.fastaccess.provider.emoji.Emoji
import com.fastaccess.provider.markdown.MarkDownProvider
import com.fastaccess.ui.modules.editor.emoji.EmojiBottomSheet
import com.fastaccess.ui.modules.editor.popup.EditorLinkImageDialogFragment
/**
* Created by kosh on 11/08/2017.
*/
class MarkDownLayout : LinearLayout {
private val sentFromFastHub: String by lazy {
"\n\n_" + resources.getString(R.string.sent_from_fasthub, AppHelper.getDeviceName(), "",
"[" + resources.getString(R.string.app_name) + "](https://play.google.com/store/apps/details?id=com.fastaccess.github)") + "_"
}
var markdownListener: MarkdownListener? = null
var selectionIndex = 0
@BindView(R.id.editorIconsHolder) lateinit var editorIconsHolder: HorizontalScrollView
@BindView(R.id.addEmoji) lateinit var addEmojiView: View
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()
orientation = HORIZONTAL
View.inflate(context, R.layout.markdown_buttons_layout, this)
if (isInEditMode) return
ButterKnife.bind(this)
}
override fun onDetachedFromWindow() {
markdownListener = null
super.onDetachedFromWindow()
}
@OnClick(R.id.view) fun onViewMarkDown() {
markdownListener?.let {
it.getEditText().let { editText ->
TransitionManager.beginDelayedTransition(this)
if (editText.isEnabled && !InputHelper.isEmpty(editText)) {
editText.isEnabled = false
selectionIndex = editText.selectionEnd
MarkDownProvider.setMdText(editText, InputHelper.toString(editText))
editorIconsHolder.visibility = View.INVISIBLE
addEmojiView.visibility = View.INVISIBLE
ViewHelper.hideKeyboard(editText)
} else {
editText.setText(it.getSavedText())
editText.setSelection(selectionIndex)
editText.isEnabled = true
editorIconsHolder.visibility = View.VISIBLE
addEmojiView.visibility = View.VISIBLE
ViewHelper.showKeyboard(editText)
}
}
}
}
@OnClick(R.id.headerOne, R.id.headerTwo, R.id.headerThree, R.id.bold, R.id.italic, R.id.strikethrough,
R.id.bullet, R.id.header, R.id.code, R.id.numbered, R.id.quote, R.id.link, R.id.image,
R.id.unCheckbox, R.id.checkbox, R.id.inlineCode, R.id.addEmoji,
R.id.signature)
fun onActions(v: View) {
markdownListener?.let {
it.getEditText().let { editText ->
if (!editText.isEnabled) {
Snackbar.make(this, R.string.error_highlighting_editor, Snackbar.LENGTH_SHORT).show()
} else {
when {
v.id == R.id.link -> EditorLinkImageDialogFragment.newInstance(true, getSelectedText())
.show(it.fragmentManager(), "EditorLinkImageDialogFragment")
v.id == R.id.image -> EditorLinkImageDialogFragment.newInstance(false, getSelectedText())
.show(it.fragmentManager(), "EditorLinkImageDialogFragment")
v.id == R.id.addEmoji -> {
ViewHelper.hideKeyboard(it.getEditText())
EmojiBottomSheet().show(it.fragmentManager(), "EmojiBottomSheet")
}
else -> onActionClicked(editText, v.id)
}
}
}
}
}
@SuppressLint("SetTextI18n")
private fun onActionClicked(editText: EditText, id: Int) {
if (editText.selectionEnd == -1 || editText.selectionStart == -1) {
return
}
when (id) {
R.id.headerOne -> MarkDownProvider.addHeader(editText, 1)
R.id.headerTwo -> MarkDownProvider.addHeader(editText, 2)
R.id.headerThree -> MarkDownProvider.addHeader(editText, 3)
R.id.bold -> MarkDownProvider.addBold(editText)
R.id.italic -> MarkDownProvider.addItalic(editText)
R.id.strikethrough -> MarkDownProvider.addStrikeThrough(editText)
R.id.numbered -> MarkDownProvider.addList(editText, "1.")
R.id.bullet -> MarkDownProvider.addList(editText, "-")
R.id.header -> MarkDownProvider.addDivider(editText)
R.id.code -> MarkDownProvider.addCode(editText)
R.id.quote -> MarkDownProvider.addQuote(editText)
R.id.checkbox -> MarkDownProvider.addList(editText, "- [x]")
R.id.unCheckbox -> MarkDownProvider.addList(editText, "- [ ]")
R.id.inlineCode -> MarkDownProvider.addInlinleCode(editText)
R.id.signature -> {
markdownListener?.getEditText()?.let {
if (!it.text.toString().contains(sentFromFastHub)) {
it.setText("${it.text}$sentFromFastHub")
} else {
it.setText(it.text.toString().replace(sentFromFastHub, ""))
}
editText.setSelection(it.text.length)
editText.requestFocus()
}
}
}
}
fun onEmojiAdded(emoji: Emoji?) {
markdownListener?.getEditText()?.let { editText ->
ViewHelper.showKeyboard(editText)
emoji?.let {
MarkDownProvider.insertAtCursor(editText, ":${it.aliases[0]}:")
}
}
}
interface MarkdownListener {
fun getEditText(): EditText
fun fragmentManager(): FragmentManager
fun getSavedText(): CharSequence?
}
fun onAppendLink(title: String?, link: String?, isLink: Boolean) {
markdownListener?.let {
if (isLink) {
MarkDownProvider.addLink(it.getEditText(), InputHelper.toString(title), InputHelper.toString(link))
} else {
MarkDownProvider.addPhoto(it.getEditText(), InputHelper.toString(title), InputHelper.toString(link))
}
}
}
private fun getSelectedText(): String? {
markdownListener?.getEditText()?.let {
if (!it.text.toString().isBlank()) {
val selectionStart = it.selectionStart
val selectionEnd = it.selectionEnd
return it.text.toString().substring(selectionStart, selectionEnd)
}
}
return null
}
} | gpl-3.0 | 69fcc6227dd5e166f6925241c086604c | 41.862857 | 142 | 0.611733 | 4.664179 | false | false | false | false |
7hens/KDroid | core/src/main/java/cn/thens/kdroid/core/web/BridgeImpl.kt | 1 | 1067 | package cn.thens.kdroid.core.web
internal class BridgeImpl(val foreignInterface: Interface) : Bridge {
private val handlerMap = HashMap<String, Bridge.Handler>()
private val callbackMap = HashMap<String, Bridge.Callback>()
val nativeInterface = object : Interface {
override fun func(name: String, arg: String) {
handlerMap[name]?.handle(arg) { data ->
foreignInterface.callback(name, data)
}
}
override fun callback(name: String, arg: String) {
callbackMap[name]?.invoke(arg)
}
}
override fun register(func: String, handler: Bridge.Handler) {
handlerMap[func] = handler
}
override fun unregister(func: String) {
handlerMap.remove(func)
}
override fun invoke(func: String, arg: String, callback: Bridge.Callback) {
callbackMap[func] = callback
foreignInterface.func(func, arg)
}
interface Interface {
fun func(name: String, arg: String)
fun callback(name: String, arg: String)
}
} | apache-2.0 | 586a3578b08eb35951fef808198ad973 | 28.666667 | 79 | 0.626992 | 4.319838 | false | false | false | false |
toastkidjp/Jitte | app/src/test/java/jp/toastkid/yobidashi/search/usecase/SearchFragmentFactoryUseCaseTest.kt | 1 | 2374 | /*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.search.usecase
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkConstructor
import io.mockk.mockkObject
import io.mockk.unmockkAll
import io.mockk.verify
import jp.toastkid.lib.Urls
import jp.toastkid.search.SearchQueryExtractor
import jp.toastkid.yobidashi.search.SearchFragment
import org.junit.After
import org.junit.Before
import org.junit.Test
class SearchFragmentFactoryUseCaseTest {
private lateinit var searchFragmentFactoryUseCase: SearchFragmentFactoryUseCase
@Before
fun setUp() {
searchFragmentFactoryUseCase = SearchFragmentFactoryUseCase()
mockkConstructor(SearchQueryExtractor::class)
every { anyConstructed<SearchQueryExtractor>().invoke(any<String>()) }.returns("test")
mockkObject(Urls)
every { Urls.isValidUrl(any()) }.returns(true)
mockkObject(SearchFragment)
every { SearchFragment.makeWith(any(), any()) }.returns(mockk())
every { SearchFragment.makeWithQuery(any(), any(), any()) }.returns(mockk())
}
@After
fun tearDown() {
unmockkAll()
}
@Test
fun testNormalCase() {
searchFragmentFactoryUseCase.invoke("title" to "https://www.yahoo.co.jp")
verify(exactly = 1) { anyConstructed<SearchQueryExtractor>().invoke(any<String>()) }
verify(exactly = 1) { SearchFragment.makeWith(any(), any()) }
verify(exactly = 0) { SearchFragment.makeWithQuery(any(), any(), any()) }
}
@Test
fun testCannotExtractedQueryAndNotUrlCase() {
every { anyConstructed<SearchQueryExtractor>().invoke(any<String>()) }.returns(null)
every { Urls.isValidUrl(any()) }.returns(false)
searchFragmentFactoryUseCase.invoke("title" to "https://www.yahoo.co.jp")
verify(exactly = 1) { anyConstructed<SearchQueryExtractor>().invoke(any<String>()) }
verify(exactly = 1) { SearchFragment.makeWith(any(), any()) }
verify(exactly = 0) { SearchFragment.makeWithQuery(any(), any(), any()) }
}
} | epl-1.0 | a1cca40c4eaeefe73e772976ce3f5c9d | 33.42029 | 94 | 0.692923 | 4.38817 | false | true | false | false |
sensefly-sa/dynamodb-to-s3 | src/test/kotlin/io/sensefly/dynamodbtos3/AbstractTestWithDynamoDB.kt | 1 | 1500 | package io.sensefly.dynamodbtos3
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput
import org.junit.Before
import javax.inject.Inject
// To run with IntelliJ add VM arguments:
// `-Djava.library.path=build/runtimeTestLibraries`
abstract class AbstractTestWithDynamoDB {
@Inject
lateinit var amazonDynamoDB: AmazonDynamoDB
@Before
fun createTables() {
val existingTables = amazonDynamoDB.listTables().tableNames
if (existingTables.contains(TABLE_TO_BACKUP)) {
amazonDynamoDB.deleteTable(TABLE_TO_BACKUP)
}
if (existingTables.contains(TABLE_TO_RESTORE)) {
amazonDynamoDB.deleteTable(TABLE_TO_RESTORE)
}
val request = CreateTableRequest()
.withTableName(TABLE_TO_BACKUP)
.withKeySchema(KeySchemaElement("id", "HASH"))
.withAttributeDefinitions(AttributeDefinition("id", "S"))
.withProvisionedThroughput(
ProvisionedThroughput().withReadCapacityUnits(10).withWriteCapacityUnits(10))
amazonDynamoDB.createTable(request)
request.tableName = TABLE_TO_RESTORE
amazonDynamoDB.createTable(request)
}
companion object {
const val TABLE_TO_BACKUP = "users-to-backup"
const val TABLE_TO_RESTORE = "users-to-restore"
}
} | bsd-3-clause | c1d0251c87625d3c756363ac059b4a21 | 32.355556 | 89 | 0.763333 | 4.189944 | false | false | false | false |
elpassion/android-commons | rxjava2-test/src/main/java/com/elpassion/android/commons/rxjava2/test/StubbingObservableExtension.kt | 1 | 1184 | package com.elpassion.android.commons.rxjava2.test
import com.nhaarman.mockito_kotlin.doReturn
import io.reactivex.Observable
import org.mockito.stubbing.OngoingStubbing
fun <T> OngoingStubbing<Observable<T>>.thenNever(): OngoingStubbing<Observable<T>> = thenReturn(Observable.never())
fun <T> OngoingStubbing<Observable<T>>.thenJust(value: T): OngoingStubbing<Observable<T>> = thenReturn(Observable.just(value))
fun <T> OngoingStubbing<Observable<List<T>>>.thenJust(vararg values: T): OngoingStubbing<Observable<List<T>>> = thenReturn(Observable.just(values.toList()))
fun <T> OngoingStubbing<Observable<T>>.thenError(exception: Exception = RuntimeException()): OngoingStubbing<Observable<T>> = thenReturn(Observable.error(exception))
fun <T> OngoingStubbing<Observable<T>>.doReturnJust(value: T) = doReturn(Observable.just(value))
fun <T> OngoingStubbing<Observable<List<T>>>.doReturnJust(vararg values: T) = doReturn(Observable.just(values.toList()))
fun <T> OngoingStubbing<Observable<T>>.doReturnNever() = doReturn(Observable.never())
fun <T> OngoingStubbing<Observable<T>>.doReturnError(exception: Exception = RuntimeException()) = doReturn(Observable.error(exception)) | apache-2.0 | 395d8b147b72e5e8423c5b53a2b7d91a | 55.428571 | 165 | 0.788851 | 4.054795 | false | false | false | false |
xfournet/intellij-community | platform/lang-impl/src/com/intellij/index/PrebuiltIndexAwareIdIndexer.kt | 4 | 2121 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.index
import com.intellij.openapi.diagnostic.Logger
import com.intellij.psi.impl.cache.impl.id.IdIndexEntry
import com.intellij.psi.impl.cache.impl.id.LexingIdIndexer
import com.intellij.util.indexing.FileContent
import com.intellij.util.io.DataExternalizer
import com.intellij.util.io.DataInputOutputUtil
import java.io.DataInput
import java.io.DataOutput
/**
* @author traff
*/
abstract class PrebuiltIndexAwareIdIndexer : PrebuiltIndexProviderBase<Map<IdIndexEntry, Int>>(), LexingIdIndexer {
companion object {
private val LOG = Logger.getInstance("#com.intellij.index.PrebuiltIndexAwareIdIndexer")
val ID_INDEX_FILE_NAME = "id-index"
}
override val indexName get() = ID_INDEX_FILE_NAME
override val indexExternalizer get() = IdIndexMapDataExternalizer()
override fun map(inputData: FileContent): Map<IdIndexEntry, Int> {
val map = get(inputData)
return if (map != null) {
if (DEBUG_PREBUILT_INDICES) {
if (map != idIndexMap(inputData)) {
LOG.error("Prebuilt id index differs from actual value for ${inputData.file.path}")
}
}
map
}
else {
idIndexMap(inputData)
}
}
abstract fun idIndexMap(inputData: FileContent): Map<IdIndexEntry, Int>
}
class IdIndexMapDataExternalizer : DataExternalizer<Map<IdIndexEntry, Int>> {
override fun save(out: DataOutput, value: Map<IdIndexEntry, Int>) {
DataInputOutputUtil.writeINT(out, value.size)
for (e in value.entries) {
DataInputOutputUtil.writeINT(out, e.key.wordHashCode)
DataInputOutputUtil.writeINT(out, e.value)
}
}
override fun read(`in`: DataInput): Map<IdIndexEntry, Int> {
val size = DataInputOutputUtil.readINT(`in`)
val map = HashMap<IdIndexEntry, Int>()
for (i in 0 until size) {
val wordHash = DataInputOutputUtil.readINT(`in`)
val value = DataInputOutputUtil.readINT(`in`)
map.put(IdIndexEntry(wordHash), value)
}
return map
}
}
| apache-2.0 | 898e368e367f7cf105ec696636758b11 | 32.140625 | 140 | 0.718058 | 4.055449 | false | false | false | false |
emufog/emufog | src/main/kotlin/emufog/fog/FogResult.kt | 1 | 2633 | /*
* MIT License
*
* Copyright (c) 2019 emufog contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package emufog.fog
/**
* This class represents the outcome of a fog node placement algorithm. If `true` the [placements] is returning the
* correct result. For `false` [placements] can be any intermediate result.
*
* @property status represents the success or failure of the placement
* @property placements the individual fog node placements.
*/
class FogResult internal constructor() {
var status: Boolean = false
private set
/**
* list of all fog node placements in the result set, exposed via [placements]
*/
private val results: MutableList<FogNodePlacement> = ArrayList()
val placements: List<FogNodePlacement>
get() = results
/**
* Adds a new fog node placement to the list of the result object.
*
* @param placement fog node placement to add
*/
internal fun addPlacement(placement: FogNodePlacement) {
results.add(placement)
}
/**
* Adds a collection of fog node placements to the list of the result object.
*
* @param placements collection of fog node placements to add
*/
internal fun addPlacements(placements: Collection<FogNodePlacement>) {
results.addAll(placements)
}
/**
* Sets the [.status] of the result object to `true`.
*/
internal fun setSuccess() {
status = true
}
/**
* Sets the [.status] of the result object to `false`.
*/
internal fun setFailure() {
status = false
}
}
| mit | a69b98b47766bca178f677a36f10b6b8 | 32.75641 | 115 | 0.697303 | 4.508562 | false | false | false | false |
google/ksp | common-util/src/main/kotlin/com/google/devtools/ksp/MemoizedSequence.kt | 1 | 1445 | /*
* Copyright 2022 Google LLC
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language 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.google.devtools.ksp
// TODO: garbage collect underlying sequence after exhaust.
class MemoizedSequence<T>(sequence: Sequence<T>) : Sequence<T> {
private val cache = arrayListOf<T>()
private val iter: Iterator<T> by lazy {
sequence.iterator()
}
private inner class CachedIterator() : Iterator<T> {
var idx = 0
override fun hasNext(): Boolean {
return idx < cache.size || iter.hasNext()
}
override fun next(): T {
if (idx == cache.size) {
cache.add(iter.next())
}
val value = cache[idx]
idx += 1
return value
}
}
override fun iterator(): Iterator<T> {
return CachedIterator()
}
}
| apache-2.0 | cf552fcb161bf8a816cd3ecc3429279d | 29.104167 | 85 | 0.642215 | 4.326347 | false | false | false | false |
alygin/intellij-rust | src/test/kotlin/org/rust/ide/inspections/RsMissingElseInspectionTest.kt | 4 | 2759 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
/**
* Tests for Missing Else inspection.
*/
class RsMissingElseInspectionTest : RsInspectionsTestBase(RsMissingElseInspection()) {
fun testSimple() = checkByText("""
fn main() {
if true {
}<warning descr="Suspicious if. Did you mean `else if`?"> if </warning>true {
}
}
""")
fun testNoSpaces() = checkByText("""
fn main() {
let a = 10;
if true {
}<warning descr="Suspicious if. Did you mean `else if`?">if</warning>(a > 10){
}
}
""")
fun testWideSpaces() = checkByText("""
fn main() {
let a = 10;
if true {
}<warning descr="Suspicious if. Did you mean `else if`?"> if </warning>(a > 10) {
}
}
""")
fun testComments() = checkByText("""
fn main() {
let a = 10;
if true {
}<warning descr="Suspicious if. Did you mean `else if`?"> /* commented */ /* else */ if </warning>a > 10 {
}
}
""")
fun testNotLastExpr() = checkByText("""
fn main() {
let a = 10;
if a > 5 {
}<warning descr="Suspicious if. Did you mean `else if`?"> if </warning>a > 10{
}
let b = 20;
}
""")
fun testHandlesBlocksWithNoSiblingsCorrectly() = checkByText("""
fn main() {if true {}}
""")
fun testNotAppliedWhenLineBreakExists() = checkByText("""
fn main() {
if true {}
if true {}
}
""")
fun testNotAppliedWhenTheresNoSecondIf() = checkByText("""
fn main() {
if {
92;
}
{}
}
""")
fun testFix() = checkFixByText("Change to `else if`", """
fn main() {
let a = 10;
if a > 7 {
}<warning descr="Suspicious if. Did you mean `else if`?"> i<caret>f </warning>a > 14 {
}
}
""", """
fn main() {
let a = 10;
if a > 7 {
} else if a > 14 {
}
}
""")
fun testFixPreservesComments() = checkFixByText("Change to `else if`", """
fn main() {
let a = 10;
if a > 7 {
}<warning descr="Suspicious if. Did you mean `else if`?"> /* comment */<caret> if /* ! */ </warning>a > 14 {
}
}
""", """
fn main() {
let a = 10;
if a > 7 {
} /* comment */ else if /* ! */ a > 14 {
}
}
""")
}
| mit | e946ce83485326d3d0980a0178f65997 | 24.311927 | 120 | 0.432765 | 4.393312 | false | true | false | false |
Fitbit/MvRx | todomvrx/src/main/java/com/airbnb/mvrx/todomvrx/TasksViewModel.kt | 1 | 3058 | package com.airbnb.mvrx.todomvrx
import com.airbnb.mvrx.Async
import com.airbnb.mvrx.MavericksState
import com.airbnb.mvrx.MavericksViewModelFactory
import com.airbnb.mvrx.Uninitialized
import com.airbnb.mvrx.ViewModelContext
import com.airbnb.mvrx.todomvrx.core.MvRxViewModel
import com.airbnb.mvrx.todomvrx.data.Task
import com.airbnb.mvrx.todomvrx.data.Tasks
import com.airbnb.mvrx.todomvrx.data.findTask
import com.airbnb.mvrx.todomvrx.data.source.TasksDataSource
import com.airbnb.mvrx.todomvrx.data.source.db.DatabaseDataSource
import com.airbnb.mvrx.todomvrx.data.source.db.ToDoDatabase
import com.airbnb.mvrx.todomvrx.util.copy
import com.airbnb.mvrx.todomvrx.util.delete
import com.airbnb.mvrx.todomvrx.util.upsert
import io.reactivex.Observable
data class TasksState(
val tasks: Tasks = emptyList(),
val taskRequest: Async<Tasks> = Uninitialized,
val isLoading: Boolean = false,
val lastEditedTask: String? = null
) : MavericksState
class TasksViewModel(initialState: TasksState, private val sources: List<TasksDataSource>) : MvRxViewModel<TasksState>(initialState) {
init {
logStateChanges()
refreshTasks()
}
fun refreshTasks() {
Observable.merge(sources.map { it.getTasks().toObservable() })
.doOnSubscribe { setState { copy(isLoading = true) } }
.doOnComplete { setState { copy(isLoading = false) } }
.execute { copy(taskRequest = it, tasks = it() ?: tasks, lastEditedTask = null) }
}
fun upsertTask(task: Task) {
setState { copy(tasks = tasks.upsert(task) { it.id == task.id }, lastEditedTask = task.id) }
sources.forEach { it.upsertTask(task) }
}
fun setComplete(id: String, complete: Boolean) {
setState {
val task = tasks.findTask(id) ?: return@setState this
if (task.complete == complete) return@setState this
copy(tasks = tasks.copy(tasks.indexOf(task), task.copy(complete = complete)), lastEditedTask = id)
}
sources.forEach { it.setComplete(id, complete) }
}
fun clearCompletedTasks() = setState {
sources.forEach { it.clearCompletedTasks() }
copy(tasks = tasks.filter { !it.complete }, lastEditedTask = null)
}
fun deleteTask(id: String) {
setState { copy(tasks = tasks.delete { it.id == id }, lastEditedTask = id) }
sources.forEach { it.deleteTask(id) }
}
companion object : MavericksViewModelFactory<TasksViewModel, TasksState> {
override fun create(viewModelContext: ViewModelContext, state: TasksState): TasksViewModel {
val database = ToDoDatabase.getInstance(viewModelContext.activity)
// Simulate data sources of different speeds.
// The slower one can be thought of as the network data source.
val dataSource1 = DatabaseDataSource(database.taskDao(), 2000)
val dataSource2 = DatabaseDataSource(database.taskDao(), 3500)
return TasksViewModel(state, listOf(dataSource1, dataSource2))
}
}
}
| apache-2.0 | d979244c473052006f40cf837b60669f | 39.236842 | 134 | 0.694572 | 4.082777 | false | false | false | false |
requery/requery | requery-android/src/main/java/io/requery/android/sqlcipher/SqlCipherStatement.kt | 1 | 3177 | /*
* Copyright 2018 requery.io
*
* 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 io.requery.android.sqlcipher
import android.annotation.SuppressLint
import io.requery.android.sqlite.BaseStatement
import io.requery.android.sqlite.CursorResultSet
import io.requery.android.sqlite.SingleResultSet
import net.sqlcipher.database.SQLiteException
import net.sqlcipher.database.SQLiteStatement
import java.sql.ResultSet
import java.sql.SQLException
import java.sql.Statement
/**
* [java.sql.Statement] implementation using Android's local SQLite database.
*
* @author Nikhil Purushe
*/
internal class SqlCipherStatement(protected val cipherConnection: SqlCipherConnection)
: BaseStatement(cipherConnection) {
@Throws(SQLException::class)
override fun execute(sql: String, autoGeneratedKeys: Int): Boolean {
var statement: SQLiteStatement? = null
try {
statement = cipherConnection.database.compileStatement(sql)
if (autoGeneratedKeys == Statement.RETURN_GENERATED_KEYS) {
val rowId = statement!!.executeInsert()
insertResult = SingleResultSet(this, rowId)
return true
} else {
statement!!.execute()
}
} catch (e: SQLiteException) {
SqlCipherConnection.throwSQLException(e)
} finally {
statement?.close()
}
return false
}
@Throws(SQLException::class)
override fun executeQuery(sql: String): ResultSet? {
try {
@SuppressLint("Recycle") // released with the queryResult
val cursor = cipherConnection.database.rawQuery(sql, null)
queryResult = CursorResultSet(this, cursor, true)
return queryResult
} catch (e: SQLiteException) {
SqlCipherConnection.throwSQLException(e)
}
return null
}
@Throws(SQLException::class)
override fun executeUpdate(sql: String, autoGeneratedKeys: Int): Int {
var statement: SQLiteStatement? = null
try {
statement = cipherConnection.database.compileStatement(sql)
if (autoGeneratedKeys == Statement.RETURN_GENERATED_KEYS) {
val rowId = statement!!.executeInsert()
insertResult = SingleResultSet(this, rowId)
return 1
} else {
updateCount = statement!!.executeUpdateDelete()
return updateCount
}
} catch (e: SQLiteException) {
SqlCipherConnection.throwSQLException(e)
} finally {
statement?.close()
}
return 0
}
}
| apache-2.0 | 91f75358b793d973524c92883d842d9f | 33.912088 | 86 | 0.65565 | 4.828267 | false | false | false | false |
RyotaMurohoshi/KotLinq | src/main/kotlin/com/muhron/kotlinq/defaultIfEmpty.kt | 1 | 1344 | package com.muhron.kotlinq
fun <TSource> Sequence<TSource>.defaultIfEmpty(defaultValue: TSource): Sequence<TSource> {
return Sequence {
if (any()) {
this.iterator()
} else {
sequenceOf(defaultValue).iterator()
}
}
}
fun <TSource> Array<TSource>.defaultIfEmpty(defaultValue: TSource): Sequence<TSource> =
asSequence().defaultIfEmpty(defaultValue)
fun <TSource> Iterable<TSource>.defaultIfEmpty(defaultValue: TSource): Sequence<TSource> =
asSequence().defaultIfEmpty(defaultValue)
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.defaultIfEmpty(defaultValue: Map.Entry<TSourceK, TSourceV>): Sequence<Map.Entry<TSourceK, TSourceV>> =
asSequence().defaultIfEmpty(defaultValue)
fun <TSource> Sequence<TSource?>.defaultIfEmpty(): Sequence<TSource?> {
return Sequence {
if (any()) {
this.iterator()
} else {
sequenceOf(null).iterator()
}
}
}
fun <TSource> Array<TSource?>.defaultIfEmpty(): Sequence<TSource?> =
asSequence().defaultIfEmpty()
fun <TSource> Iterable<TSource?>.defaultIfEmpty(): Sequence<TSource?> =
asSequence().defaultIfEmpty()
fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.defaultIfEmpty(): Sequence<Map.Entry<TSourceK, TSourceV>?> =
asSequence().defaultIfEmpty()
| mit | 77214e62ef214419958c92c0b77cc28b | 33.461538 | 151 | 0.672619 | 4.494983 | false | false | false | false |
Ingwersaft/James | src/main/kotlin/com/mkring/james/chatbackend/rocketchat/RocketchatApi.kt | 1 | 4045 | package com.mkring.james.chatbackend.rocketchat
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import com.google.gson.reflect.TypeToken
import java.util.*
// rocketchat -> james
private val gson = Gson()
internal data class RocketResponse(
val server_id: String? = null,
val msg: String? = null,
val session: String? = null,
val collection: String? = null,
val id: String? = null,
val fields: Fields? = null,
@SerializedName("result")
val resultObject: JsonElement? = null,
val methods: List<String>? = null,
val subs: List<String>? = null
) {
fun resultElement(): TokenResult? {
return if (resultObject?.isJsonObject == true) {
try {
gson.fromJson(resultObject, TokenResult::class.java)
} catch (e: Exception) {
null
}
} else {
null
}
}
fun resultArray(): List<ResultElement>? {
return if (resultObject?.isJsonArray == true) {
try {
gson.fromJson<List<ResultElement>>(resultObject, object : TypeToken<List<ResultElement>>() {}.type)
} catch (e: Exception) {
null
}
} else {
null
}
}
}
internal data class Fields(
val emails: List<Email>? = null,
val username: String? = null,
val eventName: String? = null,
val args: List<Arg>? = null
)
internal data class Arg(
val _id: String,
val rid: String,
val msg: String,
val ts: TokenExpires,
val u: U,
val mentions: List<Any?>,
val channels: List<Any?>,
val _updatedAt: TokenExpires
)
internal data class Email(
val address: String,
val verified: Boolean
)
internal data class ResultElement(
val t: String,
val ts: TokenExpires,
val ls: TokenExpires,
val name: String,
val fname: String,
val rid: String,
val u: U,
val open: Boolean,
val alert: Boolean,
val roles: List<String>,
val unread: Long,
val userMentions: Long,
val groupMentions: Long,
val _updatedAt: TokenExpires,
val _id: String
)
internal data class TokenExpires(
val `$date`: Long
)
internal data class U(
val _id: String,
val username: String,
val name: Any? = null
)
internal data class TokenResult(
val id: String,
val token: String,
val tokenExpires: TokenExpires,
val type: String
)
// james -> rocketchat
private val rand = Random()
internal data class Connect(
private val msg: String = "connect",
private val version: String = "1",
private val support: List<String> = listOf("1")
)
internal data class Pong(
private val msg: String = "pong"
)
internal data class LoginRequest(
val params: List<Param>
) : GenericRequest("method", "login")
internal class GetSubscriptionRequest : GenericRequest("method", "subscriptions/get")
internal data class Param(
val user: User,
val password: String
)
internal data class User(
val username: String
)
internal open class GenericRequest(
private val msg: String,
val method: String,
val id: String = rand.nextInt(10_000).toString()
)
internal data class SubscribeRequest(
private val msg: String = "sub",
private val name: String = "stream-room-messages",
private val id: String = rand.nextInt(10_000).toString(),
@Expose(serialize = false)
val roomId: String,
private val params: List<Any> = listOf(roomId, false)
)
internal data class SendMessageRequest(
@Expose(serialize = false)
private val rid: String,
@Expose(serialize = false)
private val emoji: String,
@Expose(serialize = false)
private val messageText: String,
private val params: List<Map<String, String>> = listOf(
mapOf(
"rid" to rid,
"msg" to messageText,
"emoji" to emoji
)
)
) : GenericRequest("method", "sendMessage") | gpl-3.0 | fce075333284b4183535c69f0a75fe9b | 21.988636 | 115 | 0.631397 | 3.90444 | false | false | false | false |
Yubyf/QuoteLock | app/src/main/java/com/crossbowffs/quotelock/utils/WorkUtils.kt | 1 | 5790 | package com.crossbowffs.quotelock.utils
import android.content.Context
import android.net.ConnectivityManager
import androidx.preference.PreferenceDataStore
import androidx.work.*
import com.crossbowffs.quotelock.app.QuoteWorker
import com.crossbowffs.quotelock.consts.*
import com.crossbowffs.quotelock.data.commonDataStore
import com.crossbowffs.quotelock.data.quotesDataStore
import java.util.concurrent.TimeUnit
object WorkUtils {
private val TAG = className<WorkUtils>()
fun shouldRefreshQuote(context: Context): Boolean {
// If our provider doesn't require internet access, we should always be
// refreshing the quote.
if (!commonDataStore.getBoolean(PREF_COMMON_REQUIRES_INTERNET, true)) {
Xlog.d(TAG, "WorkUtils#shouldRefreshQuote: YES (provider doesn't require internet)")
return true
}
// If we're not connected to the internet, we shouldn't refresh the quote.
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
val netInfo = manager?.activeNetworkInfo
if (netInfo == null || !netInfo.isConnected) {
Xlog.d(TAG, "WorkUtils#shouldRefreshQuote: NO (not connected to internet)")
return false
}
// Check if we're on a metered connection and act according to the
// user's preference.
val unmeteredOnly =
commonDataStore.getBoolean(PREF_COMMON_UNMETERED_ONLY,
PREF_COMMON_UNMETERED_ONLY_DEFAULT)
if (unmeteredOnly && manager.isActiveNetworkMetered) {
Xlog.d(TAG,
"WorkUtils#shouldRefreshQuote: NO (can only update on unmetered connections)")
return false
}
Xlog.d(TAG, "WorkUtils#shouldRefreshQuote: YES")
return true
}
fun createQuoteDownloadWork(context: Context, recreate: Boolean) {
Xlog.d(TAG, "WorkUtils#createQuoteDownloadWork called, recreate == %s", recreate)
// Instead of canceling the work whenever we disconnect from the
// internet, we wait until the work executes. Upon execution, we re-check
// the condition -- if network connectivity has been restored, we just
// proceed as normal, otherwise, we do not reschedule the task until
// we receive a network connectivity event.
if (!shouldRefreshQuote(context)) {
Xlog.d(TAG, "Should not create work under current conditions, ignoring")
return
}
val workManager = WorkManager.getInstance(context)
// If we're not forcing a work refresh (e.g. when a setting changes),
// keep the request if the work already exists
val existingWorkPolicy =
if (recreate) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP
Xlog.d(TAG, "ExistingWorkPolicy - $existingWorkPolicy")
val delay = getUpdateDelay()
val networkType = getNetworkType()
val constraints = Constraints.Builder()
.setRequiredNetworkType(networkType)
.build()
val oneTimeWorkRequest = OneTimeWorkRequestBuilder<QuoteWorker>()
.setInitialDelay(delay.toLong(), TimeUnit.SECONDS)
.setBackoffCriteria(
BackoffPolicy.LINEAR, (
2 * 1000).toLong(),
TimeUnit.MILLISECONDS)
.setConstraints(constraints)
.build()
workManager.enqueueUniqueWork(
QuoteWorker.TAG,
existingWorkPolicy,
oneTimeWorkRequest)
Xlog.d(TAG, "Scheduled quote download work with delay: %d", delay)
}
private fun getUpdateDelay(): Int {
// This compensates for the time since the last update in order
// to ensure that the quote will be updated in a reasonable time
// window. If the quote was updated >= refreshInterval time ago,
// the update will be scheduled with zero delay.
val refreshInterval = getRefreshInterval(commonDataStore)
val currentTime = System.currentTimeMillis()
val lastUpdateTime = quotesDataStore.getLong(PREF_QUOTES_LAST_UPDATED, currentTime)
Xlog.d(TAG, "Current time: %d", currentTime)
Xlog.d(TAG, "Last update time: %d", lastUpdateTime)
var deltaSecs = ((currentTime - lastUpdateTime) / 1000).toInt()
if (deltaSecs < 0) {
// In case the user has a time machine or
// changes the system clock back in time
deltaSecs = 0
}
var delay = refreshInterval - deltaSecs
if (delay < 0) {
// This occurs if the user has been offline for
// longer than the refresh interval
delay = 0
}
return delay
}
private fun getRefreshInterval(commonPrefs: PreferenceDataStore): Int {
var refreshInterval = commonPrefs.getInt(PREF_COMMON_REFRESH_RATE_OVERRIDE, 0)
if (refreshInterval == 0) {
val refreshIntervalStr =
commonPrefs.getString(PREF_COMMON_REFRESH_RATE, PREF_COMMON_REFRESH_RATE_DEFAULT)!!
refreshInterval = refreshIntervalStr.toInt()
}
if (refreshInterval < 60) {
Xlog.w(TAG, "Refresh period too short, clamping to 60 seconds")
refreshInterval = 60
}
return refreshInterval
}
private fun getNetworkType(): NetworkType {
if (!commonDataStore.getBoolean(PREF_COMMON_REQUIRES_INTERNET, true)) {
return NetworkType.NOT_REQUIRED
}
val unmeteredOnly =
commonDataStore.getBoolean(PREF_COMMON_UNMETERED_ONLY,
PREF_COMMON_UNMETERED_ONLY_DEFAULT)
return if (unmeteredOnly) NetworkType.UNMETERED else NetworkType.CONNECTED
}
} | mit | 26c114ce0609a078b4aa59c7c7f8814a | 42.541353 | 100 | 0.650259 | 4.861461 | false | false | false | false |
vhromada/Catalog-Swing | src/main/kotlin/cz/vhromada/catalog/gui/season/SeasonDataPanel.kt | 1 | 6235 | package cz.vhromada.catalog.gui.season
import cz.vhromada.catalog.entity.Season
import cz.vhromada.catalog.facade.EpisodeFacade
import cz.vhromada.catalog.gui.common.AbstractDataPanel
import cz.vhromada.common.entity.Time
import cz.vhromada.common.result.Status
import javax.swing.GroupLayout
import javax.swing.JLabel
/**
* A class represents panel with season's data.
*
* @author Vladimir Hromada
*/
class SeasonDataPanel(
season: Season,
private val episodeFacade: EpisodeFacade) : AbstractDataPanel<Season>() {
/**
* Label for number
*/
private val numberLabel = JLabel("Number of season")
/**
* Label with number
*/
private val numberData = JLabel()
/**
* Label for year
*/
private val yearLabel = JLabel("Year")
/**
* Label with year
*/
private val yearData = JLabel()
/**
* Label for language
*/
private val languageLabel = JLabel("Language")
/**
* Label with language
*/
private val languageData = JLabel()
/**
* Label for subtitles
*/
private val subtitlesLabel = JLabel("Subtitles")
/**
* Label with subtitles
*/
private val subtitlesData = JLabel()
/**
* Label for count of episodes
*/
private val episodesCountLabel = JLabel("Count of episodes")
/**
* Label with count of episodes
*/
private val episodesCountData = JLabel()
/**
* Label for total length
*/
private val totalLengthLabel = JLabel("Total length")
/**
* Label with total length
*/
private val totalLengthData = JLabel()
/**
* Label for note
*/
private val noteLabel = JLabel("Note")
/**
* Label with note
*/
private val noteData = JLabel()
init {
updateData(season)
initData(numberLabel, numberData)
initData(yearLabel, yearData)
initData(languageLabel, languageData)
initData(subtitlesLabel, subtitlesData)
initData(episodesCountLabel, episodesCountData)
initData(totalLengthLabel, totalLengthData)
initData(noteLabel, noteData)
createLayout()
}
override fun updateComponentData(data: Season) {
numberData.text = data.number?.toString()
yearData.text = getYear(data)
languageData.text = data.language?.toString()
subtitlesData.text = getSubtitles(data.subtitles)
episodesCountData.text = getEpisodesCount(data)
totalLengthData.text = getSeasonLength(data)
noteData.text = data.note
}
override fun getCzWikiUrl(): String {
error { "Getting URL to czech Wikipedia page is not allowed for seasons." }
}
override fun getEnWikiUrl(): String {
error { "Getting URL to english Wikipedia page is not allowed for seasons." }
}
override fun getCsfdUrl(): String {
error { "Getting URL to ČSFD page is not allowed for seasons." }
}
override fun getImdbUrl(): Int {
error { "Getting URL to IMDB page is not allowed for seasons." }
}
override fun getHorizontalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group {
return group
.addGroup(createHorizontalDataComponents(layout, numberLabel, numberData))
.addGroup(createHorizontalDataComponents(layout, yearLabel, yearData))
.addGroup(createHorizontalDataComponents(layout, languageLabel, languageData))
.addGroup(createHorizontalDataComponents(layout, subtitlesLabel, subtitlesData))
.addGroup(createHorizontalDataComponents(layout, episodesCountLabel, episodesCountData))
.addGroup(createHorizontalDataComponents(layout, totalLengthLabel, totalLengthData))
.addGroup(createHorizontalDataComponents(layout, noteLabel, noteData))
}
@Suppress("DuplicatedCode")
override fun getVerticalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group {
return group
.addGroup(createVerticalComponents(layout, numberLabel, numberData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, yearLabel, yearData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, languageLabel, languageData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, subtitlesLabel, subtitlesData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, episodesCountLabel, episodesCountData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, totalLengthLabel, totalLengthData))
.addGap(VERTICAL_GAP_SIZE)
.addGroup(createVerticalComponents(layout, noteLabel, noteData))
.addGap(VERTICAL_GAP_SIZE)
}
/**
* Returns count of season's episodes.
*
* @param season season
* @return count of season's episodes
*/
private fun getEpisodesCount(season: Season): String {
val result = episodeFacade.find(season)
if (Status.OK == result.status) {
return result.data!!.size.toString()
}
throw IllegalArgumentException("Can't get data. $result")
}
/**
* Returns total length of all season's episodes.
*
* @param season season
* @return total length of all season's episodes
*/
private fun getSeasonLength(season: Season): String {
val result = episodeFacade.find(season)
if (Status.OK == result.status) {
return Time(result.data!!.sumBy { it.length!! }).toString()
}
throw IllegalArgumentException("Can't get data. $result")
}
/**
* Returns season's year.
*
* @param season season
* @return season's year
*/
private fun getYear(season: Season): String {
val startYear = season.startYear!!
val endYear = season.endYear!!
return if (startYear == endYear) startYear.toString() else "$startYear - $endYear"
}
}
| mit | 22442445a1fabaaf104054767e5ba9c5 | 29.70936 | 118 | 0.64068 | 4.825077 | false | false | false | false |
vilnius/tvarkau-vilniu | app/src/main/java/lt/vilnius/tvarkau/dagger/module/RestAdapterModule.kt | 1 | 3782 | package lt.vilnius.tvarkau.dagger.module
import ca.mimic.oauth2library.OAuth2Client
import com.google.gson.Gson
import dagger.Module
import dagger.Provides
import io.reactivex.Scheduler
import lt.vilnius.tvarkau.R
import lt.vilnius.tvarkau.TvarkauApplication
import lt.vilnius.tvarkau.api.ApiEndpoint
import lt.vilnius.tvarkau.api.AppRxAdapterFactory
import lt.vilnius.tvarkau.dagger.Api
import lt.vilnius.tvarkau.dagger.IoScheduler
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Named
import javax.inject.Qualifier
import javax.inject.Singleton
@Module
class RestAdapterModule {
@Provides
@Named(HOST)
fun provideHost(): String {
return "https://api.tvarkaumiesta.lt"
}
@Provides
@Named(VIISP_AUTH_URI)
fun provideViispAuthUri(
@Named(HOST) host: String
): String {
return "$host/auth/viisp/new"
}
@Provides
@ApiOAuth
fun provideOAuthEndpoint(
application: TvarkauApplication,
@Named(HOST) host: String
): ApiEndpoint {
return ApiEndpoint(application.getString(R.string.api_root_oauth).format(host))
}
@Provides
@Api
fun provideApiV2Endpoint(
@Named(HOST) host: String
): ApiEndpoint {
return ApiEndpoint(host.plus("/"))
}
@Provides
@GuestToken
fun provideGuestTokenOAuthBuilder(
@ApiOAuth endpoint: ApiEndpoint,
@RawOkHttpClient client: OkHttpClient
): OAuth2Client.Builder {
return OAuth2Client.Builder(
OAUTH_CLIENT_ID,
"",
endpoint.url + OAUTH_TOKEN_ENDPOINT
)
.grantType("client_credentials")
.scope("user")
.okHttpClient(client)
}
@Provides
@ThirdPartyToken
fun provideSocialSignInOAuthBuilder(
@ApiOAuth endpoint: ApiEndpoint,
@RawOkHttpClient client: OkHttpClient
): OAuth2Client.Builder {
return OAuth2Client.Builder(
OAUTH_CLIENT_ID,
"",
endpoint.url + OAUTH_TOKEN_ENDPOINT
)
.grantType("assertion")
.scope("user")
.okHttpClient(client)
}
@Provides
@RefreshToken
fun provideRefreshTokenOAuthBuilder(
@ApiOAuth endpoint: ApiEndpoint,
@RawOkHttpClient client: OkHttpClient
): OAuth2Client.Builder {
return OAuth2Client.Builder(
OAUTH_CLIENT_ID,
"",
endpoint.url + OAUTH_TOKEN_ENDPOINT
)
.grantType("refresh_token")
.okHttpClient(client)
}
@Provides
@Api
@Singleton
fun provideApi2Retrofit(
@Api endpoint: ApiEndpoint,
@IoScheduler ioScheduler: Scheduler,
@Api client: OkHttpClient,
gson: Gson
): Retrofit {
val factory = RxJava2CallAdapterFactory.createWithScheduler(ioScheduler)
return Retrofit.Builder()
.client(client)
.baseUrl(endpoint.url)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(AppRxAdapterFactory(factory))
.build()
}
companion object {
const val HOST = "host"
const val VIISP_AUTH_URI = "viisp"
const val OAUTH_CLIENT_ID = "android"
const val OAUTH_TOKEN_ENDPOINT = "token"
}
}
@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ApiOAuth
@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class GuestToken
@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class RefreshToken
@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ThirdPartyToken
| mit | c10af7b8b52e87caa76684656dd2e7fe | 25.447552 | 87 | 0.66605 | 4.392567 | false | false | false | false |
nosix/vue-kotlin | single-file/greeting-component/main/GreetingComponent.kt | 1 | 997 | import azadev.kotlin.css.dimens.em
import azadev.kotlin.css.fontSize
import azadev.kotlin.css.textAlign
import org.musyozoku.vuekt.Data
import org.musyozoku.vuekt.Vue
import org.musyozoku.vuekt.js2vue.ComponentOptionsBuilder
import org.musyozoku.vuekt.js2vue.ComponentVue
import org.musyozoku.vuekt.js2vue.StyleBuilder
import org.musyozoku.vuekt.js2vue.translate
import org.musyozoku.vuekt.json
external class GreetingComponent : Vue {
var greeting: String
}
class GreetingComponentVue : ComponentVue<GreetingComponent> {
override val template: String = """<p>{{ greeting }} World!</p>"""
override val style: StyleBuilder = {
p {
fontSize = 2.em
textAlign = center
}
}
override val script: ComponentOptionsBuilder<GreetingComponent> = {
data = Data {
json<GreetingComponent> {
greeting = "Hello"
}
}
}
}
@Suppress("unused")
val options = translate(GreetingComponentVue()) | apache-2.0 | 90bbcbd46632dbf23577956049a385d5 | 25.972973 | 71 | 0.693079 | 3.720149 | false | false | false | false |
rock3r/detekt | detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/Context.kt | 1 | 3239 | package io.gitlab.arturbosch.detekt.api
import io.gitlab.arturbosch.detekt.api.internal.isSuppressedBy
import org.jetbrains.kotlin.psi.KtFile
/**
* A context describes the storing and reporting mechanism of [Finding]'s inside a [Rule].
* Additionally it handles suppression and aliases management.
*
* The detekt engine retrieves the findings after each KtFile visit and resets the context
* before the next KtFile.
*/
interface Context {
val findings: List<Finding>
/**
* Reports a single new violation.
*/
@Deprecated("Overloaded version with extra ruleSetId parameter should be used.")
fun report(finding: Finding, aliases: Set<String> = emptySet())
/**
* Reports a single new violation.
* By contract the implementation can check if
* this finding is already suppressed and should not get reported.
* An alias set can be given to additionally check if an alias was used when suppressing.
* Additionally suppression by rule set id is supported.
*/
fun report(finding: Finding, aliases: Set<String> = emptySet(), ruleSetId: RuleSetId? = null) {
report(finding, aliases, null)
}
/**
* Same as [report] but reports a list of findings.
*/
@Deprecated("Overloaded version with extra ruleSetId parameter should be used.")
fun report(findings: List<Finding>, aliases: Set<String> = emptySet())
/**
* Same as [report] but reports a list of findings.
*/
fun report(findings: List<Finding>, aliases: Set<String> = emptySet(), ruleSetId: RuleSetId? = null) {
report(findings, aliases, null)
}
/**
* Clears previous findings.
* Normally this is done on every new [KtFile] analyzed and should be called by clients.
*/
fun clearFindings()
}
/**
* Default [Context] implementation.
*/
open class DefaultContext : Context {
/**
* Returns a copy of violations for this rule.
*/
override val findings: List<Finding>
get() = _findings.toList()
private var _findings: MutableList<Finding> = mutableListOf()
/**
* Reports a single code smell finding.
*
* Before adding a finding, it is checked if it is not suppressed
* by @Suppress or @SuppressWarnings annotations.
*/
override fun report(finding: Finding, aliases: Set<String>, ruleSetId: RuleSetId?) {
val ktElement = finding.entity.ktElement
if (ktElement == null || !ktElement.isSuppressedBy(finding.id, aliases, ruleSetId)) {
_findings.add(finding)
}
}
/**
* Reports a list of code smell findings.
*
* Before adding a finding, it is checked if it is not suppressed
* by @Suppress or @SuppressWarnings annotations.
*/
override fun report(findings: List<Finding>, aliases: Set<String>, ruleSetId: RuleSetId?) {
findings.forEach { report(it, aliases, ruleSetId) }
}
final override fun clearFindings() {
_findings = mutableListOf()
}
override fun report(finding: Finding, aliases: Set<String>) {
report(finding, aliases, null)
}
override fun report(findings: List<Finding>, aliases: Set<String>) {
report(findings, aliases, null)
}
}
| apache-2.0 | 8551faacb3e30a6bf691a258466771b0 | 31.069307 | 106 | 0.663476 | 4.436986 | false | false | false | false |
cemrich/zapp | app/src/main/java/de/christinecoenen/code/zapp/models/channels/SimpleChannelList.kt | 1 | 601 | package de.christinecoenen.code.zapp.models.channels
/**
* Simple IChannelList wrapper around a List of ChannelModels.
*/
class SimpleChannelList(private val channels: List<ChannelModel>) : IChannelList {
override val list
get() = channels
override fun get(index: Int) = channels[index]
override fun get(id: String): ChannelModel? {
val index = indexOf(id)
return if (index == -1) null else get(index)
}
override fun size() = channels.size
override fun indexOf(channelId: String) = channels.indexOfFirst { it.id == channelId }
override fun iterator() = channels.listIterator()
}
| mit | afcee25b94e815fa2f9d54c12f7f5611 | 25.130435 | 87 | 0.730449 | 3.732919 | false | false | false | false |
alyphen/guildford-game-jam-2016 | core/src/main/kotlin/com/seventh_root/guildfordgamejam/component/ComponentMappers.kt | 1 | 1556 | package com.seventh_root.guildfordgamejam.component
import com.badlogic.ashley.core.ComponentMapper
val position: ComponentMapper<PositionComponent> = ComponentMapper.getFor(PositionComponent::class.java)
val velocity: ComponentMapper<VelocityComponent> = ComponentMapper.getFor(VelocityComponent::class.java)
val friction: ComponentMapper<FrictionComponent> = ComponentMapper.getFor(FrictionComponent::class.java)
val gravity: ComponentMapper<GravityComponent> = ComponentMapper.getFor(GravityComponent::class.java)
val player: ComponentMapper<PlayerComponent> = ComponentMapper.getFor(PlayerComponent::class.java)
//val grapple: ComponentMapper<GrappleComponent> = ComponentMapper.getFor(GrappleComponent::class.java)
val color: ComponentMapper<ColorComponent> = ComponentMapper.getFor(ColorComponent::class.java)
val radius: ComponentMapper<RadiusComponent> = ComponentMapper.getFor(RadiusComponent::class.java)
val texture: ComponentMapper<TextureComponent> = ComponentMapper.getFor(TextureComponent::class.java)
val level: ComponentMapper<LevelComponent> = ComponentMapper.getFor(LevelComponent::class.java)
val collectedColors: ComponentMapper<CollectedColorsComponent> = ComponentMapper.getFor(CollectedColorsComponent::class.java)
val radiusScaling: ComponentMapper<RadiusScalingComponent> = ComponentMapper.getFor(RadiusScalingComponent::class.java)
val finish: ComponentMapper<FinishComponent> = ComponentMapper.getFor(FinishComponent::class.java)
val timer: ComponentMapper<TimerComponent> = ComponentMapper.getFor(TimerComponent::class.java)
| apache-2.0 | eed6410db646921d5fe5992856bc9660 | 85.444444 | 125 | 0.854756 | 4.847352 | false | false | false | false |
rarnu/deprecated_project | src/main/kotlin/com/rarnu/tophighlight/util/UIUtils.kt | 1 | 1882 | package com.rarnu.tophighlight.util
import android.content.Context
import android.graphics.Color
import android.util.DisplayMetrics
import android.view.WindowManager
import com.flask.colorpicker.ColorPickerView
import com.flask.colorpicker.builder.ColorPickerClickListener
import com.flask.colorpicker.builder.ColorPickerDialogBuilder
import com.rarnu.tophighlight.R
/**
* Created by rarnu on 3/23/16.
*/
object UIUtils {
//private var context: Context? = null
var dm: DisplayMetrics? = null
fun initDisplayMetrics(ctx: Context, wm: WindowManager) {
//context = ctx
dm = DisplayMetrics()
wm.defaultDisplay.getMetrics(dm)
}
fun dip2px(dip: Int): Int {
if (dm == null) {
return -1
}
return (dip * dm!!.density + 0.5f).toInt()
}
fun getDarkerColor(color: Int, factor: Float): Int {
val hsv = FloatArray(3)
Color.colorToHSV(color, hsv)
hsv[2] = hsv[2] * factor
return Color.HSVToColor(hsv)
}
fun isSimilarToWhite(color: Int): Boolean {
val gray = (Color.red(color) * 0.2126f + Color.green(color) * 0.7152f + Color.blue(color) * 0.0722f).toInt()
return gray > 0xcc
}
fun showDialog(context: Context, pickerClickListener: ColorPickerClickListener, longClick: Boolean = false) =
ColorPickerDialogBuilder
.with(context)
.setTitle(if (!longClick) R.string.view_select_background_color else R.string.view_select_press_color)
.initialColor(Color.WHITE)
.wheelType(ColorPickerView.WHEEL_TYPE.FLOWER)
.density(12)
.setPositiveButton(R.string.alert_ok, pickerClickListener)
.setNegativeButton(R.string.alert_cancel, null)
.build()
.show()
} | gpl-3.0 | 821517a9646a3305e8baf9bd5666b636 | 31.465517 | 122 | 0.627524 | 4.047312 | false | false | false | false |
debop/debop4k | debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/timeranges/HalfyearRange.kt | 1 | 1825 | /*
* 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.timeperiod.timeranges
import debop4k.core.kodatimes.today
import debop4k.timeperiod.DefaultTimeCalendar
import debop4k.timeperiod.ITimeCalendar
import debop4k.timeperiod.models.Halfyear
import debop4k.timeperiod.utils.addHalfyear
import debop4k.timeperiod.utils.startTimeOfHalfyear
import org.joda.time.DateTime
/**
* Created by debop
*/
open class HalfyearRange @JvmOverloads constructor(moment: DateTime = today(),
calendar: ITimeCalendar = DefaultTimeCalendar)
: HalfyearTimeRange(moment, 1, calendar) {
@JvmOverloads
constructor(year: Int, halfyear: Halfyear, calendar: ITimeCalendar = DefaultTimeCalendar)
: this(startTimeOfHalfyear(year, halfyear), calendar)
@JvmOverloads
constructor(year: Int, monthOfYear: Int, calendar: ITimeCalendar = DefaultTimeCalendar)
: this(startTimeOfHalfyear(year, monthOfYear), calendar)
fun nextHalfyear(): HalfyearRange = addHalfyears(1)
fun prevHalfyear(): HalfyearRange = addHalfyears(-1)
fun addHalfyears(count: Int): HalfyearRange {
val yhy = addHalfyear(startYear, halfyearOfStart, count)
return HalfyearRange(yhy.year, yhy.halfyear, calendar)
}
} | apache-2.0 | 428b7c2bf34e930a04969d7887696633 | 35.52 | 97 | 0.751233 | 4.138322 | false | false | false | false |
PaulWoitaschek/Voice | bookOverview/src/main/kotlin/voice/bookOverview/views/MigrateHint.kt | 1 | 1174 | package voice.bookOverview.views
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import voice.bookOverview.R
@Composable
internal fun MigrateHint(onClick: () -> Unit) {
ExplanationTooltip {
Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
Text(stringResource(R.string.migration_hint_title), style = MaterialTheme.typography.headlineSmall)
Spacer(modifier = Modifier.size(8.dp))
Text(stringResource(R.string.migration_hint_content))
Spacer(modifier = Modifier.size(16.dp))
Button(
modifier = Modifier.align(Alignment.End),
onClick = onClick,
) {
Text(stringResource(R.string.migration_hint_confirm))
}
}
}
}
| gpl-3.0 | 44afd5de1bdc1e93dac5f695f0f519cc | 34.575758 | 105 | 0.76661 | 4.048276 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.