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
java-opengl-labs/learn-OpenGL
src/main/kotlin/learnOpenGL/b_lighting/3.1 materials.kt
1
5563
package learnOpenGL.b_lighting /** * Created by GBarbieri on 28.04.2017. */ import glm_.func.rad import glm_.glm import glm_.glm.sin import glm_.mat4x4.Mat4 import glm_.vec3.Vec3 import gln.buffer.glBindBuffer import gln.draw.glDrawArrays import gln.get import gln.glClearColor import gln.glf.glf import gln.uniform.glUniform import gln.uniform.glUniform3 import gln.vertexArray.glEnableVertexAttribArray import gln.vertexArray.glVertexAttribPointer import learnOpenGL.a_gettingStarted.end import learnOpenGL.a_gettingStarted.swapAndPoll import org.lwjgl.opengl.GL11.* import org.lwjgl.opengl.GL15.* import org.lwjgl.opengl.GL20.glGetUniformLocation import org.lwjgl.opengl.GL30.* import uno.buffer.destroyBuf import uno.buffer.intBufferBig import uno.glfw.glfw import uno.glsl.Program import uno.glsl.glDeletePrograms import uno.glsl.glUseProgram fun main(args: Array<String>) { with(Materials()) { run() end() } } private class Materials { val window = initWindow0("Materials") val lighting = Lighting() val lamp = Lamp() val vbo = intBufferBig(1) enum class VA { Cube, Light } val vao = intBufferBig<VA>() val lightPos = Vec3(1.2f, 1f, 2f) inner class Lighting : Lamp("shaders/b/_3_1", "materials") { val viewPos = glGetUniformLocation(name, "viewPos") val lgt = Light() val mtl = Material() inner class Light { val pos = glGetUniformLocation(name, "light.position") val ambient = glGetUniformLocation(name, "light.ambient") val diffuse = glGetUniformLocation(name, "light.diffuse") val specular = glGetUniformLocation(name, "light.specular") } inner class Material { val ambient = glGetUniformLocation(name, "material.ambient") val diffuse = glGetUniformLocation(name, "material.diffuse") val specular = glGetUniformLocation(name, "material.specular") val shininess = glGetUniformLocation(name, "material.shininess") } } inner open class Lamp(root: String = "shaders/b/_1", shader: String = "lamp") : Program(root, "$shader.vert", "$shader.frag") { val model = glGetUniformLocation(name, "model") val view = glGetUniformLocation(name, "view") val proj = glGetUniformLocation(name, "projection") } init { glEnable(GL_DEPTH_TEST) glGenVertexArrays(vao) // first, configure the cube's VAO (and VBO) glGenBuffers(vbo) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, verticesCube0, GL_STATIC_DRAW) glBindVertexArray(vao[VA.Cube]) glVertexAttribPointer(glf.pos3_nor3) glEnableVertexAttribArray(glf.pos3_nor3) // second, configure the light's VAO (VBO stays the same; the vertices are the same for the light object which is also a 3D cube) glBindVertexArray(vao[VA.Light]) glBindBuffer(GL_ARRAY_BUFFER, vbo) // note that we update the lamp's position attribute's stride to reflect the updated buffer data glVertexAttribPointer(glf.pos3_nor3[0]) glEnableVertexAttribArray(glf.pos3_nor3[0]) } fun run() { while (window.open) { window.processFrame() // render glClearColor(clearColor0) glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT) // be sure to activate shader when setting uniforms/drawing objects glUseProgram(lighting) glUniform(lighting.lgt.pos, lightPos) glUniform(lighting.viewPos, camera.position) // light properties val lightColor = Vec3( x = sin(glfw.time * 2f), y = sin(glfw.time * 0.7f), z = sin(glfw.time * 1.3f)) val diffuseColor = lightColor * 0.5f // decrease the influence val ambientColor = diffuseColor * 0.2f // low influence glUniform(lighting.lgt.ambient, ambientColor) glUniform(lighting.lgt.diffuse, diffuseColor) glUniform3(lighting.lgt.specular, 1f) // material properties glUniform(lighting.mtl.ambient, 1f, 0.5f, 0.31f) glUniform(lighting.mtl.diffuse, 1f, 0.5f, 0.31f) glUniform3(lighting.mtl.specular, 0.5f) glUniform(lighting.mtl.shininess, 32f) // view/projection transformations val projection = glm.perspective(camera.zoom.rad, window.aspect, 0.1f, 100f) val view = camera.viewMatrix glUniform(lighting.proj, projection) glUniform(lighting.view, view) // world transformation var model = Mat4() glUniform(lighting.model, model) // render the cube glBindVertexArray(vao[VA.Cube]) glDrawArrays(GL_TRIANGLES, 36) // also draw the lamp object glUseProgram(lamp) glUniform(lamp.proj, projection) glUniform(lamp.view, view) model = model .translate(lightPos) .scale(0.2f) // a smaller cube glUniform(lamp.model, model) glBindVertexArray(vao[VA.Light]) glDrawArrays(GL_TRIANGLES, 36) window.swapAndPoll() } } fun end() { glDeletePrograms(lighting, lamp) glDeleteVertexArrays(vao) glDeleteBuffers(vbo) destroyBuf(vao, vbo) window.end() } }
mit
bdafede8a9e361e74934599a6b72cdb5
28.13089
137
0.627
4.176426
false
false
false
false
anlun/haskell-idea-plugin
generator/src/org/jetbrains/generator/GrammarParser.kt
1
3612
package org.jetbrains.generator import org.jetbrains.generator.grammar.Grammar import org.jetbrains.generator.grammar.TokenDescription import java.util.ArrayList import org.jetbrains.generator.grammar.Rule import org.jetbrains.generator.TokenType.* import org.jetbrains.generator.grammar.Variant import org.jetbrains.generator.grammar.RuleRef import org.jetbrains.generator.grammar.NonFinalVariant import org.jetbrains.generator.grammar.FinalVariant /** * Created by atsky on 11/7/14. */ class GrammarParser(val tokens : List<Token>) { var current : Int = -1; fun parseGrammar( ) : Grammar? { match("token") match(OBRACE) val tokens = parseTokens() match(CBRACE) val rules = parseRules() return Grammar(tokens, rules); } fun text(): String { return tokens[current].text; } fun parseTokens( ) : List<TokenDescription> { val list = ArrayList<TokenDescription>() while (true) { if (tryMatch(TokenType.STRING)) { val tokenText = text() list.add(TokenDescription(tokenText.substring(1, tokenText.length() - 1), getNext()!!.text, true)) } else if (tryMatch(TokenType.ID)) { val tokenText = text() list.add(TokenDescription(tokenText, getNext()!!.text, false)) } else { break } } return list; } fun match(text: String) { getNext() if (text() == text) { throw RuntimeException() } } fun match(expected: TokenType) : Token { val next = getNext() if (next == null || next.type != expected) { throw ParserException(next, "${expected} expected, but ${next?.type}"); } return next; } fun tryMatch(type: TokenType): Boolean { if (getNext()!!.type != type) { current--; return false } return true; } fun getNext(): Token? { if (current < tokens.size()) { current++ return if (current < tokens.size()) tokens[current] else null; } else { return null; } } fun parseRules() : List<Rule> { val list = ArrayList<Rule>() while (!eof()) { list.add(parseRule()) } return list; } fun parseRule() : Rule { val name = match(ID).text match(COLON) val variants = ArrayList<Variant>() while (true) { variants.add(parseVariant()) if (!tryMatch(VBAR)) { break; } } match(SEMICOLON) return Rule(name, variants) } fun eof(): Boolean { return current >= tokens.size() - 1; } fun parseVariant() : Variant { val list = ArrayList<RuleRef>() while (true) { if (tryMatch(TokenType.STRING)) { val t = text() list.add(RuleRef(t.substring(1, t.length() - 1), false)) } else if (tryMatch(TokenType.ID)) { list.add(RuleRef(text(), true)) } else { break } } val name = if (tryMatch(OBRACE)) { match(TokenType.ID) val text = text() match(CBRACE) text } else { null } var variant : Variant = FinalVariant(name); for (ref in list.reverse()) { variant = NonFinalVariant(ref, listOf(variant)) } return variant; } }
apache-2.0
a5e5ed5737392f9ef4e72f83504ec336
23.917241
114
0.527132
4.437346
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/leadForms/dto/LeadFormsForm.kt
1
3130
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.leadForms.dto import com.google.gson.annotations.SerializedName import com.vk.dto.common.id.UserId import com.vk.sdk.api.base.dto.BaseBoolInt import kotlin.Int import kotlin.String import kotlin.collections.List /** * @param formId * @param groupId * @param leadsCount * @param url * @param photo * @param name * @param title * @param description * @param confirmation * @param siteLinkUrl * @param policyLinkUrl * @param questions * @param active * @param pixelCode * @param oncePerUser * @param notifyAdmins * @param notifyEmails */ data class LeadFormsForm( @SerializedName("form_id") val formId: Int, @SerializedName("group_id") val groupId: UserId, @SerializedName("leads_count") val leadsCount: Int, @SerializedName("url") val url: String, @SerializedName("photo") val photo: String? = null, @SerializedName("name") val name: String? = null, @SerializedName("title") val title: String? = null, @SerializedName("description") val description: String? = null, @SerializedName("confirmation") val confirmation: String? = null, @SerializedName("site_link_url") val siteLinkUrl: String? = null, @SerializedName("policy_link_url") val policyLinkUrl: String? = null, @SerializedName("questions") val questions: List<LeadFormsQuestionItem>? = null, @SerializedName("active") val active: BaseBoolInt? = null, @SerializedName("pixel_code") val pixelCode: String? = null, @SerializedName("once_per_user") val oncePerUser: Int? = null, @SerializedName("notify_admins") val notifyAdmins: String? = null, @SerializedName("notify_emails") val notifyEmails: String? = null )
mit
2fb793d3d09808e4e65629622e0bb43a
33.395604
81
0.682109
4.201342
false
false
false
false
czyzby/ktx
style/src/main/kotlin/ktx/style/style.kt
2
20293
package ktx.style import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.TextureAtlas import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle import com.badlogic.gdx.scenes.scene2d.ui.CheckBox.CheckBoxStyle import com.badlogic.gdx.scenes.scene2d.ui.ImageButton.ImageButtonStyle import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton.ImageTextButtonStyle import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle import com.badlogic.gdx.scenes.scene2d.ui.List.ListStyle import com.badlogic.gdx.scenes.scene2d.ui.ProgressBar.ProgressBarStyle import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.ScrollPaneStyle import com.badlogic.gdx.scenes.scene2d.ui.SelectBox.SelectBoxStyle import com.badlogic.gdx.scenes.scene2d.ui.Skin import com.badlogic.gdx.scenes.scene2d.ui.Slider.SliderStyle import com.badlogic.gdx.scenes.scene2d.ui.SplitPane.SplitPaneStyle import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle import com.badlogic.gdx.scenes.scene2d.ui.TextTooltip.TextTooltipStyle import com.badlogic.gdx.scenes.scene2d.ui.Touchpad.TouchpadStyle import com.badlogic.gdx.scenes.scene2d.ui.Tree.TreeStyle import com.badlogic.gdx.scenes.scene2d.ui.Window.WindowStyle import com.badlogic.gdx.utils.GdxRuntimeException import com.badlogic.gdx.utils.ObjectMap import kotlin.annotation.AnnotationTarget.CLASS import kotlin.annotation.AnnotationTarget.FUNCTION import kotlin.annotation.AnnotationTarget.TYPE import kotlin.annotation.AnnotationTarget.TYPEALIAS import kotlin.annotation.AnnotationTarget.TYPE_PARAMETER import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind import kotlin.contracts.contract /** Should annotate builder methods of Scene2D [Skin]. */ @DslMarker @Target(CLASS, TYPE_PARAMETER, FUNCTION, TYPE, TYPEALIAS) annotation class SkinDsl /** * Name of default resources in [Skin]. Often used as default Scene2D actor style names. */ const val defaultStyle = "default" /** * @param init will be applied to the [Skin] instance. Inlined. * @return a new instance of [Skin]. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun skin(init: (@SkinDsl Skin).(Skin) -> Unit = {}): Skin { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } val skin = Skin() skin.init(skin) return skin } /** * @param atlas will be disposed along with the [Skin]. * @param init will be applied to the [Skin] instance. Inlined. * @return a new instance of [Skin]. */ @OptIn(ExperimentalContracts::class) inline fun skin(atlas: TextureAtlas, init: (@SkinDsl Skin).(Skin) -> Unit = {}): Skin { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } val skin = Skin(atlas) skin.init(skin) return skin } /** * Allows to create new UI component styles with the KTX DSL. This method is very similar * to the [apply] extension method from the standard library, but supports the DSL annotation. * @param styles will be applied to this [Skin] instance. Inlined. */ @OptIn(ExperimentalContracts::class) inline fun Skin.register(styles: (@SkinDsl Skin).(Skin) -> Unit) { contract { callsInPlace(styles, InvocationKind.EXACTLY_ONCE) } styles(this) } /** * Utility function that makes it easier to access [Skin] assets. * @param name name of the requested resource. Defaults to [defaultStyle]. * @return resource of the specified type with the selected name. * @throws GdxRuntimeException if unable to find the resource. */ inline operator fun <reified Resource : Any> Skin.get(name: String = defaultStyle): Resource = this[name, Resource::class.java] /** * Utility function that makes it easier to access [Skin] assets. * @param name name of the requested resource. * @return resource of the specified type with the selected name. * @throws GdxRuntimeException if unable to find the resource. */ inline operator fun <reified Resource : Any, E : Enum<E>> Skin.get(name: E): Resource = this[name.toString()] /** * Utility function that makes it easier to access [Skin] assets or return null if they don't exist. * @param name name of the requested resource. Defaults to [defaultStyle]. * @return resource of the specified type with the selected name, or `null` if it doesn't exist. */ inline fun <reified Resource : Any> Skin.optional(name: String = defaultStyle): Resource? = this.optional(name, Resource::class.java) /** * Utility function that makes it easier to add [Skin] assets. * @param name name of the passed resource. * @param resource will be added to the skin and mapped to the selected name. */ inline operator fun <reified Resource : Any> Skin.set(name: String, resource: Resource) = this.add(name, resource, Resource::class.java) /** * Utility function that makes it easier to add [Skin] assets. * @param name name of the passed resource. * @param resource will be added to the skin and mapped to the selected name. */ inline operator fun <reified Resource : Any, E : Enum<E>> Skin.set(name: E, resource: Resource) = this.set(name.toString(), resource) /** * Utility function that makes it easier to add [Skin] assets. * @param name name of the passed resource. Defaults to [defaultStyle]. * @param resource will be added to the skin and mapped to the selected name. */ inline fun <reified Resource : Any> Skin.add(resource: Resource, name: String = defaultStyle) = this.add(name, resource, Resource::class.java) /** * Utility function that makes it easier to add [Skin] assets under the [defaultStyle] name. * @param resource will be added to the skin and mapped to the selected name. */ inline operator fun <reified Resource : Any> Skin.plusAssign(resource: Resource) = this.add(resource) /** * Utility function that makes it easier to remove [Skin] assets. * @param name name of the passed resource. Defaults to [defaultStyle]. * @throws NullPointerException if unable to find the resource. */ inline fun <reified Resource : Any> Skin.remove(name: String = defaultStyle) = this.remove(name, Resource::class.java) /** * Utility function that makes it easier to check if [Skin] contains assets. * @param name name of the resource to look for. Defaults to [defaultStyle]. */ inline fun <reified Resource : Any> Skin.has(name: String = defaultStyle): Boolean = this.has(name, Resource::class.java) /** * Utility function that makes it easier to access all [Skin] assets of a certain type. * @return map of the resources for the [Resource] type, or `null` if no resources of that type is in the skin. */ inline fun <reified Resource : Any> Skin.getAll(): ObjectMap<String, Resource>? = this.getAll(Resource::class.java) /** * Utility function for adding existing styles to the skin. Mostly for internal use. * @param name name of the style as it will appear in the [Skin] instance. * @param style non-null existing style instance. * @param init will be applied to the style instance. Inlined. * @return passed style instance (for chaining). */ @OptIn(ExperimentalContracts::class) inline fun <Style> Skin.addStyle(name: String, style: Style, init: Style.() -> Unit = {}): Style { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } style.init() this.add(name, style) return style } /** * Adds a new [Color] instance to the skin. * @param name name of the color. * @param red red color component in range of [0, 1]. * @param green green color component in range of [0, 1]. * @param blue blue color component in range of [0, 1]. * @param alpha alpha (transparency) color component in range of [0, 1]. Defaults to 1f. * @return a new instance of [Color]. */ fun Skin.color( name: String, red: Float, green: Float, blue: Float, alpha: Float = 1f ): Color { val color = Color(red, green, blue, alpha) this.add(name, color) return color } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [ButtonStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.button( name: String = defaultStyle, extend: String? = null, init: (@SkinDsl ButtonStyle).() -> Unit = {} ): ButtonStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) ButtonStyle() else ButtonStyle(get(extend)), init) } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [CheckBoxStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.checkBox( name: String = defaultStyle, extend: String? = null, init: (@SkinDsl CheckBoxStyle).() -> Unit = {} ): CheckBoxStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) CheckBoxStyle() else CheckBoxStyle(get(extend)), init) } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [ImageButtonStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.imageButton( name: String = defaultStyle, extend: String? = null, init: (@SkinDsl ImageButtonStyle).() -> Unit = {} ): ImageButtonStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) ImageButtonStyle() else ImageButtonStyle(get(extend)), init) } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [ImageTextButtonStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.imageTextButton( name: String = defaultStyle, extend: String? = null, init: (@SkinDsl ImageTextButtonStyle).() -> Unit = {} ): ImageTextButtonStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) ImageTextButtonStyle() else ImageTextButtonStyle(get(extend)), init) } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [LabelStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.label( name: String = defaultStyle, extend: String? = null, init: (@SkinDsl LabelStyle).() -> Unit = {} ): LabelStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) LabelStyle() else LabelStyle(get(extend)), init) } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [ListStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.list( name: String = defaultStyle, extend: String? = null, init: (@SkinDsl ListStyle).() -> Unit = {} ): ListStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) ListStyle() else ListStyle(get(extend)), init) } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [ProgressBarStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.progressBar( name: String = defaultStyle, extend: String? = null, init: (@SkinDsl ProgressBarStyle).() -> Unit = {} ): ProgressBarStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) ProgressBarStyle() else ProgressBarStyle(get(extend)), init) } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [ScrollPaneStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.scrollPane( name: String = defaultStyle, extend: String? = null, init: (@SkinDsl ScrollPaneStyle).() -> Unit = {} ): ScrollPaneStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) ScrollPaneStyle() else ScrollPaneStyle(get(extend)), init) } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [SelectBoxStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.selectBox( name: String = defaultStyle, extend: String? = null, init: (@SkinDsl SelectBoxStyle).() -> Unit = {} ): SelectBoxStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) SelectBoxStyle() else SelectBoxStyle(get(extend)), init) } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [SliderStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.slider( name: String = defaultStyle, extend: String? = null, init: (@SkinDsl SliderStyle).() -> Unit = {} ): SliderStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) SliderStyle() else SliderStyle(get(extend)), init) } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [SplitPaneStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.splitPane( name: String = defaultStyle, extend: String? = null, init: (@SkinDsl SplitPaneStyle).() -> Unit = {} ): SplitPaneStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) SplitPaneStyle() else SplitPaneStyle(get<SplitPaneStyle>(extend)), init) } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [ButtonStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.textButton( name: String = defaultStyle, extend: String? = null, init: (@SkinDsl TextButtonStyle).() -> Unit = {} ): TextButtonStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) TextButtonStyle() else TextButtonStyle(get(extend)), init) } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [TextFieldStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.textField( name: String = defaultStyle, extend: String? = null, init: (@SkinDsl TextFieldStyle).() -> Unit = {} ): TextFieldStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) TextFieldStyle() else TextFieldStyle(get(extend)), init) } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [TextFieldStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.textTooltip( name: String = defaultStyle, extend: String? = null, init: (@SkinDsl TextTooltipStyle).() -> Unit = {} ): TextTooltipStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) TextTooltipStyle() else TextTooltipStyle(get(extend)), init) } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [TouchpadStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.touchpad( name: String = defaultStyle, extend: String? = null, init: (@SkinDsl TouchpadStyle).() -> Unit = {} ): TouchpadStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) TouchpadStyle() else TouchpadStyle(get(extend)), init) } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [TreeStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.tree( name: String = defaultStyle, extend: String? = null, init: TreeStyle.() -> Unit = {} ): TreeStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) TreeStyle() else TreeStyle(get(extend)), init) } /** * @param name name of the style as it will appear in the [Skin] instance. * @param extend optional name of an _existing_ style of the same type. Its values will be copied and used as base for * this style. * @param init will be applied to the style instance. Inlined. * @return a new instance of [WindowStyle] added to the [Skin] with the selected name. */ @SkinDsl @OptIn(ExperimentalContracts::class) inline fun Skin.window( name: String = defaultStyle, extend: String? = null, init: (@SkinDsl WindowStyle).() -> Unit = {} ): WindowStyle { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return addStyle(name, if (extend == null) WindowStyle() else WindowStyle(get(extend)), init) }
cc0-1.0
8669f61526662c3f2e597e74da3488b0
39.667335
118
0.732371
3.843371
false
false
false
false
heinika/MyGankio
app/src/main/java/lijin/heinika/cn/mygankio/ganhuodataview/GanHuoAdapter.kt
1
2278
package lijin.heinika.cn.mygankio.ganhuodataview import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.net.Uri import android.support.v7.widget.CardView import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import lijin.heinika.cn.mygankio.R import lijin.heinika.cn.mygankio.entiy.GanHuoBean /** * Created by heinika on 17-1-3. * Android 适配器 */ class GanHuoAdapter internal constructor(private val mContext: Context) : RecyclerView.Adapter<GanHuoAdapter.ViewHolder>() { private var ganHuoBeanList: List<GanHuoBean>? = null internal fun setGanHuoBeanList(ganHuoBeanList: List<GanHuoBean>) { this.ganHuoBeanList = ganHuoBeanList notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_ganhuo_view, parent, false)) } @SuppressLint("SimpleDateFormat") override fun onBindViewHolder(holder: ViewHolder, position: Int) { val data = ganHuoBeanList!![position] holder.textViewTitle.text = data.desc if (data.images != null) { holder.imageViewGirl.visibility = View.VISIBLE Glide.with(mContext).load(data.images[0]).into(holder.imageViewGirl) } else { holder.imageViewGirl.visibility = View.GONE } holder.cardView.setOnClickListener { val intent = Intent() intent.action = Intent.ACTION_VIEW intent.data = Uri.parse(data.url) mContext.startActivity(intent) } } override fun getItemCount(): Int { return if (ganHuoBeanList == null) 0 else ganHuoBeanList!!.size } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var textViewTitle: TextView = itemView.findViewById(R.id.title_android) var imageViewGirl: ImageView = itemView.findViewById(R.id.imageView_android_image) var cardView: CardView = itemView.findViewById(R.id.cardView_android) } }
apache-2.0
4e0ddcfa217b9357df947d6c1a4f53b2
35.063492
124
0.71875
4.262664
false
false
false
false
googlecodelabs/android-people
app-start/src/main/java/com/example/android/people/data/NotificationHelper.kt
1
6122
/* * Copyright (C) 2020 The Android Open Source Project * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.people.data import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Person import android.app.RemoteInput import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.LocusId import android.content.pm.ShortcutInfo import android.content.pm.ShortcutManager import android.graphics.BitmapFactory import android.graphics.drawable.Icon import android.net.Uri import androidx.annotation.WorkerThread import androidx.core.content.getSystemService import androidx.core.net.toUri import com.example.android.people.BubbleActivity import com.example.android.people.MainActivity import com.example.android.people.R import com.example.android.people.ReplyReceiver /** * Handles all operations related to [Notification]. */ class NotificationHelper(private val context: Context) { companion object { /** * The notification channel for messages. This is used for showing Bubbles. */ private const val CHANNEL_NEW_MESSAGES = "new_messages" private const val REQUEST_CONTENT = 1 private const val REQUEST_BUBBLE = 2 } private val notificationManager: NotificationManager = context.getSystemService() ?: throw IllegalStateException() private val shortcutManager: ShortcutManager = context.getSystemService() ?: throw IllegalStateException() fun setUpNotificationChannels() { if (notificationManager.getNotificationChannel(CHANNEL_NEW_MESSAGES) == null) { notificationManager.createNotificationChannel( NotificationChannel( CHANNEL_NEW_MESSAGES, context.getString(R.string.channel_new_messages), // The importance must be IMPORTANCE_HIGH to show Bubbles. NotificationManager.IMPORTANCE_HIGH ).apply { description = context.getString(R.string.channel_new_messages_description) } ) } updateShortcuts(null) } @WorkerThread fun updateShortcuts(importantContact: Contact?) { // TODO 2: Create dynamic shortcuts. } @WorkerThread fun showNotification(chat: Chat, fromUser: Boolean) { updateShortcuts(chat.contact) val icon = Icon.createWithAdaptiveBitmapContentUri(chat.contact.iconUri) val user = Person.Builder().setName(context.getString(R.string.sender_you)).build() val person = Person.Builder().setName(chat.contact.name).setIcon(icon).build() val contentUri = "https://android.example.com/chat/${chat.contact.id}".toUri() val builder = Notification.Builder(context, CHANNEL_NEW_MESSAGES) // TODO 5: Set up a BubbleMetadata. // The user can turn off the bubble in system settings. In that case, this notification // is shown as a normal notification instead of a bubble. Make sure that this // notification works as a normal notification as well. .setContentTitle(chat.contact.name) .setSmallIcon(R.drawable.ic_message) // TODO 4: Associate the notification with a shortcut. .addPerson(person) .setShowWhen(true) // The content Intent is used when the user clicks on the "Open Content" icon button on // the expanded bubble, as well as when the fall-back notification is clicked. .setContentIntent( PendingIntent.getActivity( context, REQUEST_CONTENT, Intent(context, MainActivity::class.java) .setAction(Intent.ACTION_VIEW) .setData(contentUri), PendingIntent.FLAG_UPDATE_CURRENT ) ) // Direct Reply .addAction( Notification.Action .Builder( Icon.createWithResource(context, R.drawable.ic_send), context.getString(R.string.label_reply), PendingIntent.getBroadcast( context, REQUEST_CONTENT, Intent(context, ReplyReceiver::class.java).setData(contentUri), PendingIntent.FLAG_UPDATE_CURRENT ) ) .addRemoteInput( RemoteInput.Builder(ReplyReceiver.KEY_TEXT_REPLY) .setLabel(context.getString(R.string.hint_input)) .build() ) .setAllowGeneratedReplies(true) .build() ) // TODO 1: Use MessagingStyle. .setContentText(chat.messages.last().text) .setWhen(chat.messages.last().timestamp) notificationManager.notify(chat.contact.id.toInt(), builder.build()) } fun dismissNotification(id: Long) { notificationManager.cancel(id.toInt()) } fun canBubble(contact: Contact): Boolean { val channel = notificationManager.getNotificationChannel( CHANNEL_NEW_MESSAGES, contact.shortcutId ) return notificationManager.areBubblesAllowed() || channel?.canBubble() == true } }
apache-2.0
55606a70203203180bdb840b40dad16e
39.276316
99
0.63378
5.188136
false
false
false
false
kronenpj/iqtimesheet
IQTimeSheet/src/main/com/github/kronenpj/iqtimesheet/IQTimeSheet/MyArrayAdapter.kt
1
4336
package com.github.kronenpj.iqtimesheet.IQTimeSheet import android.content.Context import android.graphics.Color import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.TextView internal class MyArrayAdapter<T> : ArrayAdapter<T> { /** * The resource indicating what views to inflate to display the content of * this array adapter. */ private var mResource: Int = 0 /** * If the inflated resource is not a TextView, #mFieldId is used to * find a TextView inside the inflated views hierarchy. This field must * contain the identifier that matches the one defined in the resource file. */ private var mFieldId = 0 private var mInflater: LayoutInflater? = null /** * {@inheritDoc} */ constructor(context: Context, resource: Int, textViewResourceId: Int) : super(context, resource, textViewResourceId) { init(context, resource, textViewResourceId) } /** * {@inheritDoc} */ constructor(context: Context, textViewResourceId: Int) : super(context, textViewResourceId) { init(context, textViewResourceId, 0) } /** * {@inheritDoc} */ constructor(context: Context, textViewResourceId: Int, objects: Array<T>) : super(context, textViewResourceId, objects) { init(context, textViewResourceId, 0) } /** * {@inheritDoc} */ constructor(context: Context, resource: Int, textViewResourceId: Int, objects: Array<T>) : super(context, resource, textViewResourceId, listOf(*objects)) { init(context, resource, textViewResourceId) } /** * {@inheritDoc} */ constructor(context: Context, textViewResourceId: Int, objects: List<T>) : super(context, textViewResourceId, objects) { init(context, textViewResourceId, 0) } /** * {@inheritDoc} */ constructor(context: Context, resource: Int, textViewResourceId: Int, objects: List<T>) : super(context, resource, textViewResourceId, objects) { init(context, resource, textViewResourceId) } private fun init(context: Context, resource: Int, textViewResourceId: Int) { mResource = resource mFieldId = textViewResourceId mInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater } /** * {@inheritDoc} */ override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { return createViewFromResource(position, convertView, parent, mResource) } /** * {@inheritDoc} */ private fun createViewFromResource(position: Int, convertView: View?, parent: ViewGroup, resource: Int): View { mResource = resource val view = super.getView(position, convertView, parent) as View val text = view as TextView var red = 255 var green = 255 var blue = 255 // FIXME: Horrible hack to get the list visible in a dark theme. // I've invested hours trying to figure out the proper way to fix this. // FIXME: Need to figure out how to obtain the TimeSheetDbAdapter.getTaskUsageTuple // information without bogging the app down horribly. Because this is horrible. try { val dbA = TimeSheetDbAdapter(context) val myTaskID = dbA.getTaskIDByName(text.text.toString()) val usageTuple = dbA.getTaskUsageTuple(myTaskID) val parentTask = dbA.getSplitTaskParent(myTaskID) if (parentTask > 0) { // TODO: Make this a property/setting. // Yellow red = 255 green = 250 blue = 0 } if (usageTuple!!.usage < 0) { // Gray-ify the current color. red = (red * .75).toInt() green = (green * .75).toInt() blue = (blue * .75).toInt() } } catch (e: Exception) { Log.i("MyArrayAdapter", "Retrieval of usageTuple failed for: " + text.text.toString()) } text.setTextColor(Color.rgb(red, green, blue)) return text } }
apache-2.0
e05791fc93c2d47c0bf20f7048c95ef7
33.141732
126
0.618312
4.617678
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/AbstractBreakpointApplicabilityTest.kt
2
2730
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.test import com.intellij.psi.PsiFile import com.intellij.testFramework.LightProjectDescriptor import org.jetbrains.kotlin.idea.core.util.getLineCount import org.jetbrains.kotlin.idea.core.util.getLineEndOffset import org.jetbrains.kotlin.idea.core.util.getLineStartOffset import org.jetbrains.kotlin.idea.debugger.breakpoints.BreakpointChecker import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinTestUtils import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.psi.KtFile abstract class AbstractBreakpointApplicabilityTest : KotlinLightCodeInsightFixtureTestCase() { private companion object { private const val COMMENT = "///" } override fun getProjectDescriptor(): LightProjectDescriptor { return KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE } protected fun doTest(unused: String) { val ktFile = myFixture.configureByFile(fileName()) as KtFile val actualContents = checkBreakpoints(ktFile, BreakpointChecker()) KotlinTestUtils.assertEqualsToFile(dataFile(), actualContents) } private fun checkBreakpoints(file: KtFile, checker: BreakpointChecker): String { val lineCount = file.getLineCount() return (0 until lineCount).joinToString("\n") { line -> checkLine(file, line, checker) } } private fun checkLine(file: KtFile, line: Int, checker: BreakpointChecker): String { val lineText = file.getLine(line) val expectedBreakpointTypes = lineText.substringAfterLast(COMMENT).trim().split(",").map { it.trim() }.toSortedSet() val actualBreakpointTypes = checker.check(file, line).map { it.prefix }.distinct().toSortedSet() return if (expectedBreakpointTypes != actualBreakpointTypes) { val lineWithoutComments = lineText.substringBeforeLast(COMMENT).trimEnd() if (actualBreakpointTypes.isNotEmpty()) { "$lineWithoutComments $COMMENT " + actualBreakpointTypes.joinToString() } else { lineWithoutComments } } else { lineText } } private fun PsiFile.getLine(line: Int): String { val start = getLineStartOffset(line, skipWhitespace = false) ?: error("Cannot find start for line $line") val end = getLineEndOffset(line) ?: error("Cannot find end for line $line") if (start >= end) { return "" } return text.substring(start, end) } }
apache-2.0
f9bcc3d93ff25db785b500d8defc90d9
42.333333
124
0.716117
4.936709
false
true
false
false
digitalfondue/lavagna
src/main/java/io/lavagna/model/CardLabelValue.kt
1
5347
/** * This file is part of lavagna. * lavagna 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. * lavagna 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 lavagna. If not, see //www.gnu.org/licenses/>. */ package io.lavagna.model import ch.digitalfondue.npjt.ConstructorAnnotationRowMapper.Column import io.lavagna.model.CardLabel.LabelType import org.apache.commons.lang3.builder.EqualsBuilder import org.apache.commons.lang3.builder.HashCodeBuilder import java.util.* open class CardLabelValue(@Column("CARD_LABEL_VALUE_ID") val cardLabelValueId: Int, @Column("CARD_ID_FK") val cardId: Int, @Column("CARD_LABEL_ID_FK") val labelId: Int, @Column("CARD_LABEL_VALUE_USE_UNIQUE_INDEX") val useUniqueIndex: Boolean?, @Column("CARD_LABEL_VALUE_TYPE") val labelValueType: LabelType, @Column("CARD_LABEL_VALUE_STRING") valueString: String?, @Column("CARD_LABEL_VALUE_TIMESTAMP") valueDate: Date?, @Column("CARD_LABEL_VALUE_INT") valueInt: Int?, @Column("CARD_LABEL_VALUE_CARD_FK") valueCard: Int?, @Column("CARD_LABEL_VALUE_USER_FK") valueUser: Int?, @Column("CARD_LABEL_VALUE_LIST_VALUE_FK") valueList: Int?) { val value: LabelValue init { this.value = LabelValue(valueString, valueDate, valueInt, valueCard, valueUser, valueList) } fun newValue(value: String): CardLabelValue { return CardLabelValue(cardLabelValueId, cardId, labelId, useUniqueIndex, LabelType.STRING, value, null, null, null, null, null) } fun newValue(date: Date): CardLabelValue { return CardLabelValue(cardLabelValueId, cardId, labelId, useUniqueIndex, LabelType.TIMESTAMP, null, date, null, null, null, null) } fun newValue(integer: Int?): CardLabelValue { return CardLabelValue(cardLabelValueId, cardId, labelId, useUniqueIndex, LabelType.INT, null, null, integer, null, null, null) } fun newCardValue(cardId: Int?): CardLabelValue { return CardLabelValue(cardLabelValueId, cardId!!, labelId, useUniqueIndex, LabelType.CARD, null, null, null, cardId, null, null) } fun newUserValue(userId: Int?): CardLabelValue { return CardLabelValue(cardLabelValueId, cardId, labelId, useUniqueIndex, LabelType.USER, null, null, null, null, userId, null) } fun newListValue(listId: Int?): CardLabelValue { return CardLabelValue(cardLabelValueId, cardId, labelId, useUniqueIndex, LabelType.CARD, null, null, null, null, null, listId) } fun newNullValue(): CardLabelValue { return CardLabelValue(cardLabelValueId, cardId, labelId, useUniqueIndex, LabelType.NULL, null, null, null, null, null, null) } fun newValue(type: LabelType, value: LabelValue): CardLabelValue { return CardLabelValue(cardLabelValueId, cardId, labelId, useUniqueIndex, type, value.valueString, value.valueTimestamp, value.valueInt, value.valueCard, value.valueUser, value.valueList) } class LabelValue @JvmOverloads constructor(@Column("CARD_LABEL_VALUE_STRING") val valueString: String? = null, @Column("CARD_LABEL_VALUE_TIMESTAMP") val valueTimestamp: Date? = null, @Column("CARD_LABEL_VALUE_INT") val valueInt: Int? = null, @Column("CARD_LABEL_VALUE_CARD_FK") val valueCard: Int? = null, @Column("CARD_LABEL_VALUE_USER_FK") val valueUser: Int? = null, @Column("CARD_LABEL_VALUE_LIST_VALUE_FK") val valueList: Int? = null) { constructor(valueTimestamp: Date) : this(null, valueTimestamp, null, null, null, null) { } constructor(valueUser: Int?) : this(null, null, null, null, valueUser, null) { } override fun equals(obj: Any?): Boolean { if (obj == null || obj !is LabelValue) { return false } return EqualsBuilder().append(valueString, obj.valueString).append(if (valueTimestamp == null) null else valueTimestamp.time / 1000, if (obj.valueTimestamp == null) null else obj.valueTimestamp.time / 1000)//go down to second... .append(valueInt, obj.valueInt).append(valueCard, obj.valueCard).append(valueUser, obj.valueUser).append(valueList, obj.valueList).isEquals } override fun hashCode(): Int { return HashCodeBuilder().append(valueString).append(valueTimestamp).append(valueInt).append(valueCard).append(valueUser).append(valueList).toHashCode() } } }
gpl-3.0
db10e70c4d0b7527dff12fb8edcd0ae8
48.971963
240
0.638302
4.226877
false
false
false
false
AcornUI/Acorn
acornui-core/src/main/kotlin/com/acornui/observe/ModTag.kt
1
2725
/* * Copyright 2019 Poly Forest, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.acornui.observe import com.acornui.recycle.Clearable interface Mutable { /** * A value that changes every time this object changes. * No two objects within this application can will have the same check value. */ val checkValue: Long /** * Updates [checkValue] to indicate that this object has changed. */ fun updateCheckValue() } /** * A modification tag allows for quick checking if an object has changed. * This is usually paired with [Watch]. */ class ModTag : Mutable { private val id: Long = (++counter).toLong() private var modCount = 0 /** * The first 32 bits represents a unique ID. The last 32 bits represents a modification count. */ override val checkValue: Long get() = id shl 32 or modCount.toLong() /** * Marks the modification tag as having been changed. */ override fun updateCheckValue() { modCount++ } companion object { private var counter = 0 } } fun modTag(): ModTag = ModTag() /** * A watch checks if a list of objects has changed between calls. * Watch supports two types of objects. Objects where the hash code is unique to the data (such as data objects), and * [Mutable] objects where the [Mutable.checkValue] is unique to the object and its data. */ class Watch : Clearable { private var crc = -1L /** * Invokes the given callback if any of the targets have changed since the last call to [check]. * The values checked will be either [Mutable.checkValue] if the object implements [Mutable], or * [hashCode] otherwise. * * @return Returns true if there was a change, false if modification tag is current. */ fun check(vararg targets: Any, callback: () -> Unit = {}): Boolean { Crc32.CRC.reset() for (i in 0..targets.lastIndex) { val target = targets[i] if (target is Mutable) Crc32.CRC.update(target.checkValue) else Crc32.CRC.update(target.hashCode()) } val newCrc = Crc32.CRC.getValue() if (crc == newCrc) return false crc = newCrc callback() return true } /** * Resets the watch so that the next set will always return true. */ override fun clear() { crc = -1L } }
apache-2.0
9f00ec5533ca2c97ffba92bc73b4b6a9
25.201923
117
0.69945
3.732877
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/insights/usecases/PublicizeUseCase.kt
1
5939
package org.wordpress.android.ui.stats.refresh.lists.sections.insights.usecases import android.view.View import kotlinx.coroutines.CoroutineDispatcher import org.wordpress.android.R import org.wordpress.android.analytics.AnalyticsTracker import org.wordpress.android.fluxc.model.stats.LimitMode import org.wordpress.android.fluxc.model.stats.PublicizeModel import org.wordpress.android.fluxc.store.StatsStore.InsightType.PUBLICIZE import org.wordpress.android.fluxc.store.stats.insights.PublicizeStore import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.ui.stats.refresh.NavigationTarget.ViewPublicizeStats import org.wordpress.android.ui.stats.refresh.lists.BLOCK_ITEM_COUNT import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase.StatelessUseCase import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase.UseCaseMode.BLOCK import org.wordpress.android.ui.stats.refresh.lists.sections.BaseStatsUseCase.UseCaseMode.VIEW_ALL import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Empty import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Header import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Link import org.wordpress.android.ui.utils.ListItemInteraction import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Title import org.wordpress.android.ui.stats.refresh.lists.sections.insights.InsightUseCaseFactory import org.wordpress.android.ui.stats.refresh.utils.ItemPopupMenuHandler import org.wordpress.android.ui.stats.refresh.utils.ServiceMapper import org.wordpress.android.ui.stats.refresh.utils.StatsSiteProvider import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper import javax.inject.Inject import javax.inject.Named private const val VIEW_ALL_ITEM_COUNT = 100 class PublicizeUseCase @Inject constructor( @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher, private val publicizeStore: PublicizeStore, private val statsSiteProvider: StatsSiteProvider, private val mapper: ServiceMapper, private val analyticsTracker: AnalyticsTrackerWrapper, private val popupMenuHandler: ItemPopupMenuHandler, private val useCaseMode: UseCaseMode ) : StatelessUseCase<PublicizeModel>(PUBLICIZE, mainDispatcher, backgroundDispatcher) { private val itemsToLoad = if (useCaseMode == VIEW_ALL) VIEW_ALL_ITEM_COUNT else BLOCK_ITEM_COUNT override suspend fun loadCachedData(): PublicizeModel? { return publicizeStore.getPublicizeData( statsSiteProvider.siteModel, LimitMode.Top(itemsToLoad) ) } override suspend fun fetchRemoteData(forced: Boolean): State<PublicizeModel> { val response = publicizeStore.fetchPublicizeData( statsSiteProvider.siteModel, LimitMode.Top(itemsToLoad), forced ) val model = response.model val error = response.error return when { error != null -> State.Error( error.message ?: error.type.name ) model != null && model.services.isNotEmpty() -> State.Data(model) else -> State.Empty() } } override fun buildLoadingItem(): List<BlockListItem> = listOf(Title(R.string.stats_view_publicize)) override fun buildEmptyItem(): List<BlockListItem> { return listOf(buildTitle(), Empty()) } override fun buildUiModel(domainModel: PublicizeModel): List<BlockListItem> { val items = mutableListOf<BlockListItem>() if (useCaseMode == BLOCK) { items.add(buildTitle()) } if (domainModel.services.isEmpty()) { items.add(Empty()) } else { val header = Header(R.string.stats_publicize_service_label, R.string.stats_publicize_followers_label) items.add(header) items.addAll(domainModel.services.let { mapper.map(it, header) }) if (useCaseMode == BLOCK && domainModel.hasMore) { items.add( Link( text = R.string.stats_insights_view_more, navigateAction = ListItemInteraction.create(this::onLinkClick) ) ) } } return items } private fun buildTitle() = Title(R.string.stats_view_publicize, menuAction = this::onMenuClick) private fun onLinkClick() { analyticsTracker.track(AnalyticsTracker.Stat.STATS_PUBLICIZE_VIEW_MORE_TAPPED) return navigateTo(ViewPublicizeStats) } private fun onMenuClick(view: View) { popupMenuHandler.onMenuClick(view, type) } class PublicizeUseCaseFactory @Inject constructor( @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) private val backgroundDispatcher: CoroutineDispatcher, private val publicizeStore: PublicizeStore, private val statsSiteProvider: StatsSiteProvider, private val mapper: ServiceMapper, private val analyticsTracker: AnalyticsTrackerWrapper, private val popupMenuHandler: ItemPopupMenuHandler ) : InsightUseCaseFactory { override fun build(useCaseMode: UseCaseMode) = PublicizeUseCase( mainDispatcher, backgroundDispatcher, publicizeStore, statsSiteProvider, mapper, analyticsTracker, popupMenuHandler, useCaseMode ) } }
gpl-2.0
b7b81d233ad921cffc397743cde95777
42.036232
113
0.696414
4.687451
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/ui/activities/imageviewer/ImageViewerActivity.kt
1
5909
package forpdateam.ru.forpda.ui.activities.imageviewer import android.app.Activity import android.content.Context import android.content.Intent import android.content.Intent.FLAG_ACTIVITY_NEW_TASK import android.graphics.Color import android.graphics.PorterDuff import android.os.Build import android.os.Bundle import androidx.core.content.ContextCompat import androidx.viewpager.widget.ViewPager import androidx.appcompat.app.AppCompatActivity import android.view.View import android.view.WindowManager import com.github.chrisbanes.photoview.OnPhotoTapListener import forpdateam.ru.forpda.R import forpdateam.ru.forpda.common.LocaleHelper import forpdateam.ru.forpda.common.Utils import kotlinx.android.synthetic.main.activity_img_viewer.* import java.util.* /** * Created by radiationx on 24.05.17. */ class ImageViewerActivity : AppCompatActivity() { private val currentImages = mutableListOf<String>() private val names = mutableListOf<String>() private var currentIndex = 0 private val adapter: ImageViewerAdapter = ImageViewerAdapter() override fun attachBaseContext(base: Context) { super.attachBaseContext(LocaleHelper.onAttach(base)) } public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setTheme(R.style.ImageViewTheme) setContentView(R.layout.activity_img_viewer) window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_IMMERSIVE window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) image_viewer_pullBack.setCallback(pullBackCallback) setSupportActionBar(toolbar) toolbar.setNavigationOnClickListener { finish() } toolbar.navigationIcon = ContextCompat.getDrawable(toolbar.context, R.drawable.ic_arrow_back_white_24dp)?.apply { setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP) } val extUrls = mutableListOf<String>() if (intent != null && intent.extras != null && intent.extras!!.containsKey(IMAGE_URLS_KEY)) { extUrls.addAll(intent.extras!!.getStringArrayList(IMAGE_URLS_KEY)!!) } else if (savedInstanceState != null && savedInstanceState.containsKey(IMAGE_URLS_KEY)) { extUrls.addAll(savedInstanceState.getStringArrayList(IMAGE_URLS_KEY)!!) } currentImages.addAll(extUrls) names.addAll(currentImages.map { Utils.getFileNameFromUrl(it) }) if (savedInstanceState != null && savedInstanceState.containsKey(SELECTED_INDEX_KEY)) { currentIndex = savedInstanceState.getInt(SELECTED_INDEX_KEY, 0) } else if (intent != null && intent.extras != null && intent.extras!!.containsKey(SELECTED_INDEX_KEY)) { currentIndex = intent.extras!!.getInt(SELECTED_INDEX_KEY, 0) } if (currentIndex < 0) { currentIndex = 0 } img_viewer_pager.addOnPageChangeListener(object : androidx.viewpager.widget.ViewPager.SimpleOnPageChangeListener() { override fun onPageSelected(position: Int) { updateTitle(position) } }) adapter.setTapListener(OnPhotoTapListener { view, x, y -> toggle() }) adapter.bindItem(currentImages) img_viewer_pager.adapter = adapter img_viewer_pager.currentItem = currentIndex img_viewer_pager.clipChildren = false toolbar.post { updateTitle(currentIndex) } } private fun updateTitle(selectedPageIndex: Int) { currentIndex = selectedPageIndex toolbar.title = names[selectedPageIndex] toolbar.subtitle = String.format(getString(R.string.image_viewer_subtitle_Cur_All), selectedPageIndex + 1, currentImages.size) } private fun toggle() { if (supportActionBar?.isShowing == true) { hide() } else { show() } } private fun hide() { supportActionBar?.hide() setShowNavigationBar(false) } private fun show() { supportActionBar?.show() setShowNavigationBar(true) } private fun setShowNavigationBar(value: Boolean) { val view = window.decorView var flags = view.systemUiVisibility flags = if (value) { flags and View.SYSTEM_UI_FLAG_HIDE_NAVIGATION.inv() } else { flags or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION } view.systemUiVisibility = flags } private val pullBackCallback = object : PullBackLayout.Callback { override fun onPullStart() {} override fun onPull(@PullBackLayout.Direction direction: Int, progress: Float) {} override fun onPullCancel(@PullBackLayout.Direction direction: Int) {} override fun onPullComplete(@PullBackLayout.Direction direction: Int) { finish() } } companion object { const val IMAGE_URLS_KEY = "IMAGE_URLS_KEY" const val SELECTED_INDEX_KEY = "SELECTED_INDEX_KEY" @JvmStatic fun startActivity(context: Context, imageUrl: String) { val intent = Intent(context, ImageViewerActivity::class.java) val urls = ArrayList<String>() urls.add(imageUrl) intent.putExtra(IMAGE_URLS_KEY, urls) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP intent.addFlags(FLAG_ACTIVITY_NEW_TASK) context.startActivity(intent) } @JvmStatic fun startActivity(context: Context, imageUrls: ArrayList<String>, selectedIndex: Int) { val intent = Intent(context, ImageViewerActivity::class.java) intent.putExtra(IMAGE_URLS_KEY, imageUrls) intent.putExtra(SELECTED_INDEX_KEY, selectedIndex) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP intent.addFlags(FLAG_ACTIVITY_NEW_TASK) context.startActivity(intent) } } }
gpl-3.0
1548c9e8e8f70d346c85bae245baa67c
37.122581
134
0.677949
4.627251
false
false
false
false
Yusuzhan/kotlin-koans
src/iii_conventions/_31_Invoke_.kt
1
734
package iii_conventions import util.TODO class Invokable { var count = 0 fun getNumberOfInvocations(): Int = count operator fun invoke(): Invokable{ count++ return this } } class Foo2{ operator fun invoke() { println("invoke") } } fun main(args: Array<String>) { val f: Foo2 = Foo2() f() } fun todoTask31(): Nothing = TODO( """ Task 31. Change class Invokable to count the number of invocations (round brackets). Uncomment the commented code - it should return 4. """, references = { invokable: Invokable -> }) fun task31(invokable: Invokable): Int { //todoTask31() return invokable()()()().getNumberOfInvocations() }
mit
0ee749c33d3b632d64001db02c598661
15.681818
83
0.603542
4.123596
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/sitecreation/theme/HomePagePickerViewModel.kt
1
5469
package org.wordpress.android.ui.sitecreation.theme import androidx.lifecycle.LiveData import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import org.wordpress.android.R import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.ui.sitecreation.misc.SiteCreationErrorType.INTERNET_UNAVAILABLE_ERROR import org.wordpress.android.ui.sitecreation.misc.SiteCreationErrorType.UNKNOWN import org.wordpress.android.ui.sitecreation.misc.SiteCreationTracker import org.wordpress.android.ui.layoutpicker.LayoutPickerUiState.Content import org.wordpress.android.ui.layoutpicker.LayoutPickerUiState.Loading import org.wordpress.android.ui.layoutpicker.LayoutPickerUiState.Error import org.wordpress.android.ui.layoutpicker.LayoutPickerViewModel import org.wordpress.android.ui.sitecreation.usecases.FetchHomePageLayoutsUseCase import org.wordpress.android.util.NetworkUtilsWrapper import org.wordpress.android.viewmodel.SingleLiveEvent import javax.inject.Inject import javax.inject.Named const val defaultTemplateSlug = "default" private const val ERROR_CONTEXT = "design" @HiltViewModel class HomePagePickerViewModel @Inject constructor( override val networkUtils: NetworkUtilsWrapper, private val dispatcher: Dispatcher, private val fetchHomePageLayoutsUseCase: FetchHomePageLayoutsUseCase, private val analyticsTracker: SiteCreationTracker, @Named(BG_THREAD) override val bgDispatcher: CoroutineDispatcher, @Named(UI_THREAD) override val mainDispatcher: CoroutineDispatcher, private val recommendationProvider: SiteDesignRecommendationProvider ) : LayoutPickerViewModel(mainDispatcher, bgDispatcher, networkUtils, analyticsTracker) { private val _onDesignActionPressed = SingleLiveEvent<DesignSelectionAction>() val onDesignActionPressed: LiveData<DesignSelectionAction> = _onDesignActionPressed private val _onBackButtonPressed = SingleLiveEvent<Unit>() val onBackButtonPressed: LiveData<Unit> = _onBackButtonPressed private var vertical: String = "" override val useCachedData: Boolean = false override val shouldUseMobileThumbnail = true override val thumbnailTapOpensPreview = true sealed class DesignSelectionAction(val template: String) { object Skip : DesignSelectionAction(defaultTemplateSlug) class Choose(template: String) : DesignSelectionAction(template) } init { dispatcher.register(fetchHomePageLayoutsUseCase) } override fun onCleared() { super.onCleared() dispatcher.unregister(fetchHomePageLayoutsUseCase) } fun start(intent: String? = null, isTablet: Boolean = false) { val verticalChanged = vertical != intent if (verticalChanged) { vertical = intent ?: "" } initializePreviewMode(isTablet) if (uiState.value !is Content || verticalChanged) { analyticsTracker.trackSiteDesignViewed(selectedPreviewMode().key) fetchLayouts() } } override fun fetchLayouts(preferCache: Boolean) { if (!networkUtils.isNetworkAvailable()) { analyticsTracker.trackErrorShown(ERROR_CONTEXT, INTERNET_UNAVAILABLE_ERROR, "Retry error") updateUiState(Error(toast = R.string.hpp_retry_error)) return } if (isLoading) return updateUiState(Loading) launch { val event = fetchHomePageLayoutsUseCase.fetchStarterDesigns() withContext(mainDispatcher) { if (event.isError) { analyticsTracker.trackErrorShown(ERROR_CONTEXT, UNKNOWN, "Error fetching designs") updateUiState(Error()) } else { recommendationProvider.handleResponse( vertical, event.designs, event.categories, this@HomePagePickerViewModel::handleResponse ) } } } } override fun onLayoutTapped(layoutSlug: String, isRecommended: Boolean) { (uiState.value as? Content)?.let { if (it.loadedThumbnailSlugs.contains(layoutSlug)) { updateUiState(it.copy(selectedLayoutSlug = layoutSlug, isSelectedLayoutRecommended = isRecommended)) onPreviewTapped() loadLayouts() } } } override fun onPreviewChooseTapped() { onChooseTapped() } fun onChooseTapped() { selectedLayout?.let { layout -> super.onPreviewChooseTapped() val template = layout.slug val isRecommended = (uiState.value as? Content)?.isSelectedLayoutRecommended == true analyticsTracker.trackSiteDesignSelected(template, isRecommended) _onDesignActionPressed.value = DesignSelectionAction.Choose(template) return } analyticsTracker.trackErrorShown(ERROR_CONTEXT, UNKNOWN, "Error choosing design") updateUiState(Error(toast = R.string.hpp_choose_error)) } fun onSkippedTapped() { analyticsTracker.trackSiteDesignSkipped() _onDesignActionPressed.value = DesignSelectionAction.Skip } fun onBackPressed() = _onBackButtonPressed.call() }
gpl-2.0
317f1b62fd2655d84be066f1b9b98985
39.511111
116
0.706528
5.045203
false
false
false
false
mdaniel/intellij-community
platform/platform-impl/src/com/intellij/toolWindow/ToolWindowEntry.kt
2
1855
// 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.toolWindow import com.intellij.openapi.Disposable import com.intellij.openapi.ui.FrameWrapper import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.wm.WindowInfo import com.intellij.openapi.wm.impl.FloatingDecorator import com.intellij.openapi.wm.impl.ToolWindowImpl import javax.swing.Icon import javax.swing.JComponent internal interface StripeButtonManager { val id: String val toolWindow: ToolWindowImpl val windowDescriptor: WindowInfo fun updateState(toolWindow: ToolWindowImpl) fun updatePresentation() fun updateIcon(icon: Icon?) fun remove() fun getComponent(): JComponent } internal class ToolWindowEntry(stripeButton: StripeButtonManager?, @JvmField val toolWindow: ToolWindowImpl, @JvmField val disposable: Disposable) { var stripeButton: StripeButtonManager? = stripeButton set(value) { if (value == null) { assert(field != null) } else { assert(field == null) } field = value } @JvmField var floatingDecorator: FloatingDecorator? = null @JvmField var windowedDecorator: FrameWrapper? = null @JvmField var balloon: Balloon? = null val id: String get() = toolWindow.id val readOnlyWindowInfo: WindowInfo get() = toolWindow.windowInfo fun removeStripeButton() { val stripeButton = stripeButton ?: return this.stripeButton = null stripeButton.remove() } fun applyWindowInfo(newInfo: WindowInfo) { toolWindow.applyWindowInfo(newInfo) // must be applied _after_ updating tool window layout info val stripeButton = stripeButton ?: return stripeButton.updateState(toolWindow) } }
apache-2.0
c0b6d1ca1069ddbc6ddff593d4d3b821
25.514286
120
0.715903
4.75641
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/substring/ReplaceSubstringInspection.kt
3
3207
// 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.inspections.substring import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection import org.jetbrains.kotlin.idea.intentions.branchedTransformations.evaluatesTo import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isStableSimpleExpression import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.intentions.toResolvedCall import org.jetbrains.kotlin.idea.util.calleeTextRangeInThis import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode abstract class ReplaceSubstringInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>( KtDotQualifiedExpression::class.java ) { protected abstract fun isApplicableInner(element: KtDotQualifiedExpression): Boolean protected open val isAlwaysStable: Boolean = false final override fun isApplicable(element: KtDotQualifiedExpression): Boolean = if ((isAlwaysStable || element.receiverExpression.isStableSimpleExpression()) && element.isMethodCall("kotlin.text.substring")) { isApplicableInner(element) } else false override fun inspectionHighlightRangeInElement(element: KtDotQualifiedExpression) = element.calleeTextRangeInThis() protected fun isIndexOfCall(expression: KtExpression?, expectedReceiver: KtExpression): Boolean { return expression is KtDotQualifiedExpression && expression.isMethodCall("kotlin.text.indexOf") && expression.receiverExpression.evaluatesTo(expectedReceiver) && expression.callExpression!!.valueArguments.size == 1 } private fun KtDotQualifiedExpression.isMethodCall(fqMethodName: String): Boolean { val resolvedCall = toResolvedCall(BodyResolveMode.PARTIAL) ?: return false return resolvedCall.resultingDescriptor.fqNameUnsafe.asString() == fqMethodName } protected fun KtDotQualifiedExpression.isFirstArgumentZero(): Boolean { val bindingContext = analyze() val resolvedCall = callExpression.getResolvedCall(bindingContext) ?: return false val expression = resolvedCall.call.valueArguments[0].getArgumentExpression() as? KtConstantExpression ?: return false val constant = ConstantExpressionEvaluator.getConstant(expression, bindingContext) ?: return false val constantType = bindingContext.getType(expression) ?: return false return constant.getValue(constantType) == 0 } protected fun KtDotQualifiedExpression.replaceWith(pattern: String, argument: KtExpression) { val psiFactory = KtPsiFactory(this) replace(psiFactory.createExpressionByPattern(pattern, receiverExpression, argument)) } }
apache-2.0
3a43a045a49fa8dd1c4ae7b7098eb7f2
54.310345
158
0.787028
5.656085
false
false
false
false
GunoH/intellij-community
plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/contributors/FirSuperMemberCompletionContributor.kt
4
10720
// 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.completion.contributors import com.intellij.psi.util.parentsOfType import com.intellij.refactoring.suggested.createSmartPointer import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionLikeSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtSyntheticJavaPropertySymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithModality import org.jetbrains.kotlin.analysis.api.types.KtIntersectionType import org.jetbrains.kotlin.analysis.api.types.KtType import org.jetbrains.kotlin.analysis.api.types.KtUsualClassType import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.idea.completion.ItemPriority import org.jetbrains.kotlin.idea.completion.checkers.CompletionVisibilityChecker import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext import org.jetbrains.kotlin.idea.completion.context.FirSuperReceiverNameReferencePositionContext import org.jetbrains.kotlin.idea.completion.contributors.helpers.collectNonExtensions import org.jetbrains.kotlin.idea.completion.lookups.CallableInsertionOptions import org.jetbrains.kotlin.idea.completion.lookups.CallableInsertionStrategy import org.jetbrains.kotlin.idea.completion.weighers.WeighingContext import org.jetbrains.kotlin.idea.completion.weighers.WeighingContext.Companion.createWeighingContext import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.StandardClassIds import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtSuperExpression import org.jetbrains.kotlin.utils.addIfNotNull internal class FirSuperMemberCompletionContributor( basicContext: FirBasicCompletionContext, priority: Int ) : FirCompletionContributorBase<FirSuperReceiverNameReferencePositionContext>(basicContext, priority) { override fun KtAnalysisSession.complete(positionContext: FirSuperReceiverNameReferencePositionContext) = with(positionContext) { val superReceiver = positionContext.superExpression val expectedType = nameExpression.getExpectedType() val visibilityChecker = CompletionVisibilityChecker.create(basicContext, positionContext) val superType = superReceiver.getKtType() ?: return val weighingContext = createWeighingContext( superReceiver, expectedType, emptyList(), // Implicit receivers do not match for this completion contributor. fakeKtFile ) val (nonExtensionMembers: Iterable<Pair<KtType, KtCallableSymbol>>, namesNeedDisambiguation: Set<Name>) = if (superType !is KtIntersectionType) { val scope = superType.getTypeScope()?.getDeclarationScope() ?: return collectNonExtensions(scope, visibilityChecker, scopeNameFilter).map { superType to it }.asIterable() to emptySet() } else { getSymbolsAndNamesNeedDisambiguation(superType.conjuncts, visibilityChecker) } collectCallToSuperMember(superReceiver, nonExtensionMembers, weighingContext, namesNeedDisambiguation) collectDelegateCallToSuperMember(weighingContext, superReceiver, nonExtensionMembers, namesNeedDisambiguation) } private fun KtAnalysisSession.getSymbolsAndNamesNeedDisambiguation( superTypes: List<KtType>, visibilityChecker: CompletionVisibilityChecker ): Pair<List<Pair<KtType, KtCallableSymbol>>, Set<Name>> { val allSymbols = mutableListOf<Pair<KtType, KtCallableSymbol>>() val symbolsInAny = mutableSetOf<KtCallableSymbol>() val symbolCountsByName = mutableMapOf<Name, Int>() for (superType in superTypes) { for (symbol in getNonExtensionsMemberSymbols(superType, visibilityChecker)) { // Abstract symbol does not participate completion. if (symbol !is KtSymbolWithModality || symbol.modality == Modality.ABSTRACT) continue // Unlike typical diamond cases, calls to method of `Any` always do not need extra qualification. if (symbol.callableIdIfNonLocal?.classId == StandardClassIds.Any) { if (symbol in symbolsInAny) continue symbolsInAny.add(symbol) } allSymbols.add(superType to symbol) val name = symbol.callableIdIfNonLocal?.callableName ?: continue symbolCountsByName[name] = (symbolCountsByName[name] ?: 0) + 1 } } val nameNeedDisambiguation = mutableSetOf<Name>() for ((name, count) in symbolCountsByName) { if (count > 1) { nameNeedDisambiguation.add(name) } } return Pair(allSymbols, nameNeedDisambiguation) } private fun KtAnalysisSession.getNonExtensionsMemberSymbols( receiverType: KtType, visibilityChecker: CompletionVisibilityChecker ): Sequence<KtCallableSymbol> { val possibleReceiverScope = receiverType.getTypeScope()?.getDeclarationScope() ?: return emptySequence() return collectNonExtensions(possibleReceiverScope, visibilityChecker, scopeNameFilter) } private fun KtAnalysisSession.collectCallToSuperMember( superReceiver: KtSuperExpression, nonExtensionMembers: Iterable<Pair<KtType, KtCallableSymbol>>, context: WeighingContext, namesNeedDisambiguation: Set<Name> ) { val syntheticPropertyOrigins = mutableSetOf<KtFunctionSymbol>() nonExtensionMembers .onEach { if (it is KtSyntheticJavaPropertySymbol) { syntheticPropertyOrigins.add(it.javaGetterSymbol) syntheticPropertyOrigins.addIfNotNull(it.javaSetterSymbol) } } .forEach { (superType, callableSymbol) -> if (callableSymbol !in syntheticPropertyOrigins) { // For basic completion, FE1.0 skips Java functions that are mapped to Kotlin properties. addCallableSymbolToCompletion( context, callableSymbol, CallableInsertionOptions( importStrategyDetector.detectImportStrategy(callableSymbol), wrapWithDisambiguationIfNeeded( getInsertionStrategy(callableSymbol), superType, callableSymbol, namesNeedDisambiguation, superReceiver ) ) ) } } } private fun KtAnalysisSession.getInsertionStrategy(symbol: KtCallableSymbol): CallableInsertionStrategy = when (symbol) { is KtFunctionLikeSymbol -> CallableInsertionStrategy.AsCall else -> CallableInsertionStrategy.AsIdentifier } private fun KtAnalysisSession.collectDelegateCallToSuperMember( context: WeighingContext, superReceiver: KtSuperExpression, nonExtensionMembers: Iterable<Pair<KtType, KtCallableSymbol>>, namesNeedDisambiguation: Set<Name> ) { // A map that contains all containing functions as values, each of which is indexed by symbols it overrides. For example, consider // the following code // ``` // class A : Runnable { // override fun run() { // val o = object: Callable<String> { // override fun call(): String { // super.<caret> // } // } // } // } // ``` // The map would contain // // * Runnable.run -> A.run // * Callable.call -> <anonymous object>.call val superFunctionToContainingFunction = superReceiver .parentsOfType<KtNamedFunction>(withSelf = false) .flatMap { containingFunction -> containingFunction .getFunctionLikeSymbol() .getAllOverriddenSymbols() .map { superFunctionSymbol -> superFunctionSymbol to containingFunction } }.toMap() if (superFunctionToContainingFunction.isEmpty()) return for ((superType, callableSymbol) in nonExtensionMembers) { val matchedContainingFunction = superFunctionToContainingFunction[callableSymbol] ?: continue if (callableSymbol !is KtFunctionSymbol) continue if (callableSymbol.valueParameters.isEmpty()) continue val args = matchedContainingFunction.valueParameters.mapNotNull { val name = it.name ?: return@mapNotNull null if (it.isVarArg) { "*$name" } else { name } } if (args.size < matchedContainingFunction.valueParameters.size) continue addCallableSymbolToCompletion( context, callableSymbol, CallableInsertionOptions( importStrategyDetector.detectImportStrategy(callableSymbol), wrapWithDisambiguationIfNeeded( CallableInsertionStrategy.WithCallArgs(args), superType, callableSymbol, namesNeedDisambiguation, superReceiver ) ), priority = ItemPriority.SUPER_METHOD_WITH_ARGUMENTS ) } } private fun KtAnalysisSession.wrapWithDisambiguationIfNeeded( insertionStrategy: CallableInsertionStrategy, superType: KtType, callableSymbol: KtCallableSymbol, namesNeedDisambiguation: Set<Name>, superReceiver: KtSuperExpression ): CallableInsertionStrategy { val superClassId = (superType as? KtUsualClassType)?.classId val needDisambiguation = callableSymbol.callableIdIfNonLocal?.callableName in namesNeedDisambiguation return if (needDisambiguation && superClassId != null) { CallableInsertionStrategy.WithSuperDisambiguation(superReceiver.createSmartPointer(), superClassId, insertionStrategy) } else { insertionStrategy } } }
apache-2.0
60074895c3c7785a30a70bb5472dbb70
47.292793
158
0.665485
5.609628
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/InvertIfConditionIntention.kt
3
11902
// 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.editor.Editor import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.core.unblockDocument import org.jetbrains.kotlin.idea.inspections.ReplaceNegatedIsEmptyWithIsNotEmptyInspection.Companion.invertSelectorFunction import org.jetbrains.kotlin.idea.refactoring.getLineNumber import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.idea.util.psi.patternMatching.matches import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance import org.jetbrains.kotlin.utils.addToStdlib.lastIsInstanceOrNull class InvertIfConditionIntention : SelfTargetingIntention<KtIfExpression>( KtIfExpression::class.java, KotlinBundle.lazyMessage("invert.if.condition") ) { override fun isApplicableTo(element: KtIfExpression, caretOffset: Int): Boolean { if (!element.ifKeyword.textRange.containsOffset(caretOffset)) return false return element.condition != null && element.then != null } override fun applyTo(element: KtIfExpression, editor: Editor?) { val rBrace = parentBlockRBrace(element) val commentSavingRange = if (rBrace != null) PsiChildRange(element, rBrace) else PsiChildRange.singleElement(element) val commentSaver = CommentSaver(commentSavingRange) if (rBrace != null) element.nextEolCommentOnSameLine()?.delete() val condition = element.condition!! val newCondition = (condition as? KtQualifiedExpression)?.invertSelectorFunction() ?: condition.negate() val newIf = handleSpecialCases(element, newCondition) ?: handleStandardCase(element, newCondition) val commentRestoreRange = if (rBrace != null) PsiChildRange(newIf, rBrace) else PsiChildRange(newIf, parentBlockRBrace(newIf) ?: newIf) commentSaver.restore(commentRestoreRange) val newIfCondition = newIf.condition (newIfCondition as? KtPrefixExpression)?.let { //use De Morgan's law only for negated condition to not make it more complex if (it.operationReference.getReferencedNameElementType() == KtTokens.EXCL) { val binaryExpr = (it.baseExpression as? KtParenthesizedExpression)?.expression as? KtBinaryExpression if (binaryExpr != null) { ConvertBinaryExpressionWithDemorgansLawIntention.convertIfPossible(binaryExpr) } } } editor?.apply { unblockDocument() moveCaret(newIf.textOffset) } } private fun handleStandardCase(ifExpression: KtIfExpression, newCondition: KtExpression): KtIfExpression { val psiFactory = KtPsiFactory(ifExpression) val thenBranch = ifExpression.then!! val elseBranch = ifExpression.`else` ?: psiFactory.createEmptyBody() val newThen = if (elseBranch is KtIfExpression) psiFactory.createSingleStatementBlock(elseBranch) else elseBranch val newElse = if (thenBranch is KtBlockExpression && thenBranch.statements.isEmpty()) null else thenBranch val conditionLineNumber = ifExpression.condition?.getLineNumber(false) val thenBranchLineNumber = thenBranch.getLineNumber(false) val elseKeywordLineNumber = ifExpression.elseKeyword?.getLineNumber() val afterCondition = if (newThen !is KtBlockExpression && elseKeywordLineNumber != elseBranch.getLineNumber(false)) "\n" else "" val beforeElse = if (newThen !is KtBlockExpression && conditionLineNumber != elseKeywordLineNumber) "\n" else " " val afterElse = if (newElse !is KtBlockExpression && conditionLineNumber != thenBranchLineNumber) "\n" else " " val newIf = if (newElse == null) { psiFactory.createExpressionByPattern("if ($0)$afterCondition$1", newCondition, newThen) } else { psiFactory.createExpressionByPattern("if ($0)$afterCondition$1${beforeElse}else$afterElse$2", newCondition, newThen, newElse) } as KtIfExpression return ifExpression.replaced(newIf) } private fun handleSpecialCases(ifExpression: KtIfExpression, newCondition: KtExpression): KtIfExpression? { val elseBranch = ifExpression.`else` if (elseBranch != null) return null val factory = KtPsiFactory(ifExpression) val thenBranch = ifExpression.then!! val lastThenStatement = thenBranch.lastBlockStatementOrThis() if (lastThenStatement.isExitStatement()) { val block = ifExpression.parent as? KtBlockExpression if (block != null) { val rBrace = block.rBrace val afterIfInBlock = ifExpression.siblings(withItself = false).takeWhile { it != rBrace }.toList() val lastStatementInBlock = afterIfInBlock.lastIsInstanceOrNull<KtExpression>() if (lastStatementInBlock != null) { val exitStatementAfterIf = if (lastStatementInBlock.isExitStatement()) lastStatementInBlock else exitStatementExecutedAfter(lastStatementInBlock) if (exitStatementAfterIf != null) { val first = afterIfInBlock.first() val last = afterIfInBlock.last() // build new then branch from statements after if (we will add exit statement if necessary later) //TODO: no block if single? val newThenRange = if (isEmptyReturn(lastThenStatement) && isEmptyReturn(lastStatementInBlock)) { PsiChildRange(first, lastStatementInBlock.prevSibling).trimWhiteSpaces() } else { PsiChildRange(first, last).trimWhiteSpaces() } val newIf = factory.createExpressionByPattern("if ($0) { $1 }", newCondition, newThenRange) as KtIfExpression // remove statements after if as they are moving under if block.deleteChildRange(first, last) if (isEmptyReturn(lastThenStatement)) { if (block.parent is KtDeclarationWithBody && block.parent !is KtFunctionLiteral) { lastThenStatement.delete() } } val updatedIf = copyThenBranchAfter(ifExpression) // check if we need to add exit statement to then branch if (exitStatementAfterIf != lastStatementInBlock) { // don't insert the exit statement, if the new if statement placement has the same exit statement executed after it val exitAfterNewIf = exitStatementExecutedAfter(updatedIf) if (exitAfterNewIf == null || !exitAfterNewIf.matches(exitStatementAfterIf)) { val newThen = newIf.then as KtBlockExpression newThen.addBefore(exitStatementAfterIf, newThen.rBrace) } } return updatedIf.replace(newIf) as KtIfExpression } } } } val exitStatement = exitStatementExecutedAfter(ifExpression) ?: return null val updatedIf = copyThenBranchAfter(ifExpression) val newIf = factory.createExpressionByPattern("if ($0) $1", newCondition, exitStatement) return updatedIf.replace(newIf) as KtIfExpression } private fun isEmptyReturn(statement: KtExpression) = statement is KtReturnExpression && statement.returnedExpression == null && statement.labeledExpression == null private fun copyThenBranchAfter(ifExpression: KtIfExpression): KtIfExpression { val factory = KtPsiFactory(ifExpression) val thenBranch = ifExpression.then ?: return ifExpression val parent = ifExpression.parent if (parent !is KtBlockExpression) { assert(parent is KtContainerNode) val block = factory.createEmptyBody() block.addAfter(ifExpression, block.lBrace) val newBlock = ifExpression.replaced(block) val newIf = newBlock.statements.single() as KtIfExpression return copyThenBranchAfter(newIf) } if (thenBranch is KtBlockExpression) { (thenBranch.statements.lastOrNull() as? KtContinueExpression)?.delete() val range = thenBranch.contentRange() if (!range.isEmpty) { parent.addRangeAfter(range.first, range.last, ifExpression) parent.addAfter(factory.createNewLine(), ifExpression) } } else if (thenBranch !is KtContinueExpression) { parent.addAfter(thenBranch, ifExpression) parent.addAfter(factory.createNewLine(), ifExpression) } return ifExpression } private fun exitStatementExecutedAfter(expression: KtExpression): KtExpression? { val parent = expression.parent if (parent is KtBlockExpression) { val lastStatement = parent.statements.last() return if (expression == lastStatement) { exitStatementExecutedAfter(parent) } else if (lastStatement.isExitStatement() && expression.siblings(withItself = false).firstIsInstance<KtExpression>() == lastStatement ) { lastStatement } else { null } } when (parent) { is KtNamedFunction -> { if (parent.bodyExpression == expression) { if (!parent.hasBlockBody()) return null val returnType = parent.resolveToDescriptorIfAny()?.returnType if (returnType == null || !returnType.isUnit()) return null return KtPsiFactory(expression).createExpression("return") } } is KtContainerNode -> when (val pparent = parent.parent) { is KtLoopExpression -> { if (expression == pparent.body) { return KtPsiFactory(expression).createExpression("continue") } } is KtIfExpression -> { if (expression == pparent.then || expression == pparent.`else`) { return exitStatementExecutedAfter(pparent) } } } } return null } private fun parentBlockRBrace(element: KtIfExpression): PsiElement? = (element.parent as? KtBlockExpression)?.rBrace private fun KtIfExpression.nextEolCommentOnSameLine(): PsiElement? = getLineNumber(false).let { lastLineNumber -> siblings(withItself = false) .takeWhile { it.getLineNumber() == lastLineNumber } .firstOrNull { it is PsiComment && it.node.elementType == KtTokens.EOL_COMMENT } } }
apache-2.0
facbea71a373163140079d6a1d75e37b
46.608
158
0.636364
5.572097
false
false
false
false
himikof/intellij-rust
src/main/kotlin/org/rust/ide/intentions/SetMutableIntention.kt
1
1605
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RsBaseType import org.rust.lang.core.psi.RsRefLikeType import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.psi.ext.isMut import org.rust.lang.core.psi.ext.isRef import org.rust.lang.core.psi.ext.parentOfType import org.rust.lang.core.psi.ext.typeElement /** * Set reference mutable * * ``` * &type * ``` * * to this: * * ``` * &mut type * ``` */ open class SetMutableIntention : RsElementBaseIntentionAction<SetMutableIntention.Context>() { override fun getText() = "Set reference mutable" override fun getFamilyName() = text open val mutable = true data class Context( val refType: RsRefLikeType, val baseType: RsBaseType ) override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? { val refType = element.parentOfType<RsRefLikeType>() ?: return null if (!refType.isRef) return null val baseType = refType.typeReference.typeElement as? RsBaseType ?: return null if (refType.isMut == mutable) return null return Context(refType, baseType) } override fun invoke(project: Project, editor: Editor, ctx: Context) { val newType = RsPsiFactory(project).createReferenceType(ctx.baseType.text, mutable) ctx.refType.replace(newType) } }
mit
c646ec7ed0093c654a3836abc5f820c4
27.660714
105
0.711526
3.98263
false
false
false
false
jk1/intellij-community
python/src/com/jetbrains/python/codeInsight/stdlib/PyDataclassTypeProvider.kt
3
8188
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.jetbrains.python.codeInsight.stdlib import com.intellij.openapi.util.Ref import com.intellij.psi.util.PsiTreeUtil import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyCallExpressionNavigator import com.jetbrains.python.psi.impl.stubs.PyDataclassFieldStubImpl import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.stubs.PyDataclassFieldStub import com.jetbrains.python.psi.types.* class PyDataclassTypeProvider : PyTypeProviderBase() { override fun getReferenceExpressionType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyType? { return getDataclassTypeForCallee(referenceExpression, context) ?: getDataclassesReplaceType(referenceExpression, context) } override fun getParameterType(param: PyNamedParameter, func: PyFunction, context: TypeEvalContext): Ref<PyType>? { if (!param.isPositionalContainer && !param.isKeywordContainer && param.annotationValue == null && func.name == DUNDER_POST_INIT) { val cls = func.containingClass val name = param.name if (cls != null && name != null && parseStdDataclassParameters(cls, context)?.init == true) { cls .findClassAttribute(name, false, context) ?.let { return Ref.create(getTypeForParameter(cls, it, PyDataclassParameters.Type.STD, context)) } } } return null } private fun getDataclassTypeForCallee(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyCallableType? { if (PyCallExpressionNavigator.getPyCallExpressionByCallee(referenceExpression) == null) return null val resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context) val resolveResults = referenceExpression.getReference(resolveContext).multiResolve(false) return PyUtil.filterTopPriorityResults(resolveResults) .asSequence() .map { when { it is PyClass -> getDataclassTypeForClass(it, context) it is PyParameter && it.isSelf -> { PsiTreeUtil.getParentOfType(it, PyFunction::class.java) ?.takeIf { it.modifier == PyFunction.Modifier.CLASSMETHOD } ?.let { it.containingClass?.let { getDataclassTypeForClass(it, context) } } } else -> null } } .firstOrNull { it != null } } private fun getDataclassesReplaceType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyCallableType? { val call = PyCallExpressionNavigator.getPyCallExpressionByCallee(referenceExpression) ?: return null val callee = call.callee as? PyReferenceExpression ?: return null val resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context) val resolvedCallee = PyUtil.multiResolveTopPriority(callee.getReference(resolveContext)).singleOrNull() if (resolvedCallee is PyCallable) { val instanceName = when (resolvedCallee.qualifiedName) { "dataclasses.replace" -> "obj" "attr.__init__.assoc", "attr.__init__.evolve" -> "inst" else -> return null } val obj = call.getArgument(0, instanceName, PyTypedElement::class.java) ?: return null val objType = context.getType(obj) as? PyClassType ?: return null if (objType.isDefinition) return null val dataclassType = getDataclassTypeForClass(objType.pyClass, context) ?: return null val dataclassParameters = dataclassType.getParameters(context) ?: return null val parameters = mutableListOf<PyCallableParameter>() val elementGenerator = PyElementGenerator.getInstance(referenceExpression.project) parameters.add(PyCallableParameterImpl.nonPsi(instanceName, objType)) parameters.add(PyCallableParameterImpl.psi(elementGenerator.createSingleStarParameter())) val ellipsis = elementGenerator.createEllipsis() dataclassParameters.mapTo(parameters, { PyCallableParameterImpl.nonPsi(it.name, it.getType(context), it.defaultValue ?: ellipsis) }) return PyCallableTypeImpl(parameters, dataclassType.getReturnType(context)) } return null } private fun getDataclassTypeForClass(cls: PyClass, context: TypeEvalContext): PyCallableType? { val dataclassParameters = parseDataclassParameters(cls, context) if (dataclassParameters == null || !dataclassParameters.init) { return null } val ellipsis = PyElementGenerator.getInstance(cls.project).createEllipsis() val parameters = cls .classAttributes .asSequence() .filterNot { PyTypingTypeProvider.isClassVar(it, context) } .mapNotNull { fieldToParameter(cls, it, dataclassParameters.type, ellipsis, context) } .toList() return PyCallableTypeImpl(parameters, context.getType(cls)?.let { if (it is PyInstantiableType<*>) it.toInstance() else it }) } private fun fieldToParameter(cls: PyClass, field: PyTargetExpression, dataclassType: PyDataclassParameters.Type, ellipsis: PyNoneLiteralExpression, context: TypeEvalContext): PyCallableParameter? { val stub = field.stub val fieldStub = if (stub == null) PyDataclassFieldStubImpl.create(field) else stub.getCustomStub(PyDataclassFieldStub::class.java) if (fieldStub?.initValue() == false) return null val name = field.name?.let { if (dataclassType == PyDataclassParameters.Type.ATTRS && PyUtil.getInitialUnderscores(it) == 1) it.substring(1) else it } return PyCallableParameterImpl.nonPsi(name, getTypeForParameter(cls, field, dataclassType, context), getDefaultValueForParameter(cls, field, fieldStub, dataclassType, ellipsis, context)) } private fun getTypeForParameter(cls: PyClass, field: PyTargetExpression, dataclassType: PyDataclassParameters.Type, context: TypeEvalContext): PyType? { if (dataclassType == PyDataclassParameters.Type.ATTRS && context.maySwitchToAST(field)) { (field.findAssignedValue() as? PyCallExpression) ?.getKeywordArgument("type") ?.let { PyTypingTypeProvider.getType(it, context) } ?.apply { return get() } } val type = context.getType(field) if (type is PyCollectionType && type.classQName == DATACLASSES_INITVAR_TYPE) { return type.elementTypes.firstOrNull() } if (type == null && dataclassType == PyDataclassParameters.Type.ATTRS) { methodDecoratedAsAttributeDefault(cls, field.name) ?.let { context.getReturnType(it) } ?.let { return PyUnionType.createWeakType(it) } } return type } private fun getDefaultValueForParameter(cls: PyClass, field: PyTargetExpression, fieldStub: PyDataclassFieldStub?, dataclassType: PyDataclassParameters.Type, ellipsis: PyNoneLiteralExpression, context: TypeEvalContext): PyExpression? { return if (fieldStub == null) { when { context.maySwitchToAST(field) -> field.findAssignedValue() field.hasAssignedValue() -> ellipsis else -> null } } else if (fieldStub.hasDefault() || fieldStub.hasDefaultFactory() || dataclassType == PyDataclassParameters.Type.ATTRS && methodDecoratedAsAttributeDefault(cls, field.name) != null) { ellipsis } else null } private fun methodDecoratedAsAttributeDefault(cls: PyClass, attributeName: String?): PyFunction? { if (attributeName == null) return null return cls.methods.firstOrNull { it.decoratorList?.findDecorator("$attributeName.default") != null } } }
apache-2.0
40f323becdcb3c3f16d44c46bd96baa9
43.748634
140
0.681729
5.348138
false
false
false
false
helloworld1/FreeOTPPlus
app/src/main/java/org/fedorahosted/freeotp/ui/AboutActivity.kt
1
2434
/* * FreeOTP * * Authors: Nathaniel McCallum <[email protected]> * * Copyright (C) 2013 Nathaniel McCallum, Red Hat * * 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.fedorahosted.freeotp.ui import android.os.Bundle import android.text.method.LinkMovementMethod import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.core.content.pm.PackageInfoCompat import androidx.core.text.HtmlCompat import dagger.hilt.android.AndroidEntryPoint import org.fedorahosted.freeotp.R import org.fedorahosted.freeotp.databinding.AboutBinding @AndroidEntryPoint class AboutActivity : AppCompatActivity() { private lateinit var binding: AboutBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = AboutBinding.inflate(layoutInflater) setContentView(binding.root) } public override fun onStart() { super.onStart() setSupportActionBar(findViewById(R.id.toolbar)) val res = resources val aboutVersion: TextView = findViewById(R.id.about_version) val pm = packageManager val info = pm.getPackageInfo(packageName, 0) val version = res.getString(R.string.about_version, info.versionName, PackageInfoCompat.getLongVersionCode(info)) aboutVersion.text = version val apache2 = res.getString(R.string.link_apache2) val license = res.getString(R.string.about_license, apache2) binding.aboutLicense.movementMethod = LinkMovementMethod.getInstance() binding.aboutLicense.text = HtmlCompat.fromHtml(license, HtmlCompat.FROM_HTML_MODE_COMPACT) binding.aboutTokenImage.movementMethod = LinkMovementMethod.getInstance() binding.aboutTokenImage.text = HtmlCompat.fromHtml(getString(R.string.about_token_image), HtmlCompat.FROM_HTML_MODE_COMPACT) } }
apache-2.0
75dbc91842e4b4b34e0a2ff9e716f5cd
35.878788
99
0.739523
4.354204
false
false
false
false
roylanceMichael/yaclib
core/src/main/java/org/roylance/yaclib/core/services/cpp/server/jni/CPPJNIBridgeBuilder.kt
1
2045
package org.roylance.yaclib.core.services.cpp.server.jni import org.roylance.common.service.IBuilder import org.roylance.yaclib.YaclibModel import org.roylance.yaclib.core.enums.CommonTokens import org.roylance.yaclib.core.utilities.JavaUtilities import org.roylance.yaclib.core.utilities.StringUtilities class CPPJNIBridgeBuilder(private val controller: YaclibModel.Controller, private val dependency: YaclibModel.Dependency) : IBuilder<YaclibModel.File> { private val className = JavaUtilities.buildJavaBridgeName(controller) private val initialTemplate = """${CommonTokens.DoNotAlterMessage} package ${dependency.group}.${CommonTokens.ServicesName}; public class $className { """ override fun build(): YaclibModel.File { val workspace = StringBuilder(initialTemplate) controller.actionsList.forEach { action -> val colonSeparatedInputs = action.inputsList.map { input -> "byte[] ${input.argumentName}" }.joinToString() val actionTemplate = "\tprivate native byte[] ${action.name}JNI($colonSeparatedInputs);\n" workspace.append(actionTemplate) } controller.actionsList.forEach { action -> val commaSeparatedInputs = action.inputsList.map { input -> "byte[] ${input.argumentName}" }.joinToString() val commaSeparatedNames = action.inputsList.map { it.argumentName }.joinToString() val actionTemplate = "\tpublic byte[] ${action.name}($commaSeparatedInputs) {\n" workspace.append(actionTemplate) workspace.appendln("\t\treturn ${action.name}JNI($commaSeparatedNames);") workspace.appendln("\t}"); } workspace.appendln("}") val returnFile = YaclibModel.File.newBuilder() .setFileName(className) .setFileExtension(YaclibModel.FileExtension.JAVA_EXT) .setFileToWrite(workspace.toString()) .setFullDirectoryLocation(StringUtilities.convertPackageToJavaFolderStructureServices( dependency.group, CommonTokens.ServicesName)) return returnFile.build() } }
mit
0e1512c21887f591a35aee2938cdd0bf
34.275862
96
0.73154
4.626697
false
false
false
false
abertschi/ad-free
app/src/main/java/ch/abertschi/adfree/detector/AccuradioDetector.kt
1
3208
package ch.abertschi.adfree.detector import android.annotation.SuppressLint import android.widget.RemoteViews import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.info import org.jetbrains.anko.warn import kotlin.reflect.jvm.internal.impl.load.kotlin.JvmType class AccuradioDetector : AdDetectable, AnkoLogger, AbstractNotificationDetector() { override fun getPackageName(): String { return "com.slipstream.accuradio" } override fun getMeta(): AdDetectorMeta = AdDetectorMeta( "Accuradio", "notification text based detector for accuradio", true, category = "Accuradio", debugOnly = false ) private fun extractObject(target: JvmType.Object, declaredField: String): Any? { try { val f = target.javaClass.getDeclaredField(declaredField) //NoSuchFieldException f.isAccessible = true return f.get(target) } catch (e: Exception) { warn("Can not access $declaredField with reflection, $e") } return null } @SuppressLint("DiscouragedPrivateApi") private fun getActions(views: RemoteViews): List<*>? { try { val f = views.javaClass.getDeclaredField("mActions") //NoSuchFieldException f.isAccessible = true return f.get(views) as List<*> } catch (e: Exception) { warn("Can not access mactions with reflection, $e") } return null } private fun extractObject(target: Any, declaredField: String): Any? { return try { val f = target.javaClass.getDeclaredField(declaredField) //NoSuchFieldException f.isAccessible = true return f.get(target) } catch (e: Exception) { warn("Can not access $declaredField with reflection, $e") null } } override fun flagAsAdvertisement(payload: AdPayload): Boolean { try { val contentView = payload.statusbarNotification?.notification?.contentView info(payload) if (contentView != null) { val actions = extractObject(contentView, "mActions") as List<*>? if (actions != null) { for (a in actions) { if (a == null) { continue } val methodName: Any = extractObject(a, "methodName") ?: continue if (methodName !is CharSequence) { continue } if (methodName != "setText") { continue } val value: Any = extractObject(a, "value") ?: continue if (value !is CharSequence) { continue } if (value.toString().trim().toLowerCase().contains("music will resume shortly")) { return true } } } } } catch (e: Exception) { warn(e) } return false } }
apache-2.0
c38f9478dac700bc3e0c70edab60d9cf
34.263736
106
0.533978
5.199352
false
false
false
false
airbnb/lottie-android
sample-compose/src/main/java/com/airbnb/lottie/sample/compose/ui/Theme.kt
1
533
package com.airbnb.lottie.sample.compose.ui import androidx.compose.material.MaterialTheme import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val ColorPalette = lightColors( primary = Teal, primaryVariant = TealDark, secondary = purple200 ) @Composable fun LottieTheme(content: @Composable () -> Unit) { MaterialTheme( colors = ColorPalette, typography = typography, shapes = shapes, content = content ) }
apache-2.0
4f1492dd1c984c1f22dc9d0d08b3b535
24.428571
50
0.681051
4.758929
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/i18n/reference/I18nReferencesSearcher.kt
1
2604
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.i18n.reference import com.demonwav.mcdev.i18n.lang.gen.psi.I18nEntry import com.intellij.find.FindModel import com.intellij.find.impl.FindInProjectUtil import com.intellij.psi.PsiReference import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.usages.FindUsagesProcessPresentation import com.intellij.usages.UsageViewPresentation import com.intellij.util.Processor import com.intellij.util.QueryExecutor class I18nReferencesSearcher : QueryExecutor<PsiReference, ReferencesSearch.SearchParameters> { override fun execute(parameters: ReferencesSearch.SearchParameters, consumer: Processor<in PsiReference>): Boolean { val entry = parameters.elementToSearch if (entry is I18nEntry) { fun <A> power(start: List<A>): Set<List<A>> { tailrec fun pwr(s: List<A>, acc: Set<List<A>>): Set<List<A>> = if (s.isEmpty()) { acc } else { pwr(s.takeLast(s.size - 1), acc + acc.map { it + s.first() }) } return pwr(start, setOf(emptyList())) } val model = FindModel() model.customScope = parameters.effectiveSearchScope model.isCaseSensitive = true model.searchContext = FindModel.SearchContext.IN_STRING_LITERALS model.isRegularExpressions = true // Enables custom translations functions (for auto-prefixing calls, for instance) model.stringToFind = power(entry.key.split('.')) .map { it.joinToString(".") } .filter { it.isNotEmpty() } .joinToString("|") { "(${Regex.escape(it)})" } FindInProjectUtil.findUsages( model, parameters.project, { if (it.file != null && it.element != null && it.rangeInElement != null) { val highlighted = it.file?.findElementAt(it.rangeInElement!!.startOffset) val ref = highlighted?.parent?.references?.find { it is I18nReference } as I18nReference? if (ref?.key == entry.key) { consumer.process(ref) } } true }, FindUsagesProcessPresentation(UsageViewPresentation()) ) } return true } }
mit
3f49f177a2e675f27ee35fba1dcc61f9
39.061538
120
0.578341
4.717391
false
false
false
false
drakelord/wire
wire-compiler/src/test/java/com/squareup/wire/StringWireLogger.kt
1
1703
/* * Copyright 2015 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire import com.google.common.collect.Iterables import com.squareup.javapoet.JavaFile import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.TypeSpec import com.squareup.wire.schema.ProtoType import java.nio.file.Path internal class StringWireLogger : WireLogger { private var quiet: Boolean = false private val buffer = StringBuilder() val log: String get() = buffer.toString() override fun setQuiet(quiet: Boolean) { this.quiet = quiet } @Synchronized override fun artifact(outputPath: Path, javaFile: JavaFile) { buffer.append("$outputPath ${javaFile.packageName}.${javaFile.typeSpec.name}\n") } @Synchronized override fun artifact(outputPath: Path, kotlinFile: FileSpec) { val typeSpec = Iterables.getOnlyElement(kotlinFile.members) as TypeSpec buffer.append("$outputPath ${kotlinFile.packageName}.${typeSpec.name}\n") } override fun artifactSkipped(type: ProtoType) { buffer.append("skipped $type\n") } @Synchronized override fun info(message: String) { if (!quiet) { buffer.append("$message\n") } } }
apache-2.0
eeff3d968f20a67f351595dc0aa9c35e
31.132075
84
0.739284
4.163814
false
false
false
false
sys1yagi/DroiDon
app/src/main/java/com/sys1yagi/mastodon/android/view/FooterAdapter.kt
1
1763
package com.sys1yagi.mastodon.android.view import android.support.v7.widget.RecyclerView import android.view.ViewGroup import com.sys1yagi.mastodon.android.databinding.ListItemFooterBinding import com.sys1yagi.mastodon.android.extensions.gone import com.sys1yagi.mastodon.android.extensions.layoutInflator import com.sys1yagi.mastodon.android.extensions.visible typealias OnRetryClick = () -> Unit class FooterAdapter : RecyclerView.Adapter<FooterAdapter.Holder>() { enum class State { PROGRESS, FAILED, COMPLETED } var state: State = State.PROGRESS set(value) { field = value notifyDataSetChanged() } var onRetryClick: OnRetryClick = {} class Holder(val binding: ListItemFooterBinding) : RecyclerView.ViewHolder(binding.root) override fun onBindViewHolder(holder: FooterAdapter.Holder, position: Int) { when (state) { State.PROGRESS -> { holder.binding.apply { root.visible() errorText.gone() progressBar.visible() } } State.FAILED -> { holder.binding.apply { root.visible() errorText.visible() errorText.setOnClickListener { onRetryClick() } progressBar.gone() } } State.COMPLETED -> { holder.binding.root.gone() } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = Holder(ListItemFooterBinding.inflate(parent.layoutInflator(), parent, false)) override fun getItemCount() = 1 }
mit
d0db1bb8d18111ae831d2f3e0366cb9e
29.396552
149
0.587635
5.008523
false
false
false
false
StPatrck/edac
app/src/main/java/com/phapps/elitedangerous/companion/data/doa/ShipDao.kt
1
1731
package com.phapps.elitedangerous.companion.data.doa import android.arch.lifecycle.LiveData import android.arch.persistence.room.Dao import android.arch.persistence.room.Insert import android.arch.persistence.room.OnConflictStrategy import android.arch.persistence.room.Query import com.phapps.elitedangerous.companion.data.entities.Module import com.phapps.elitedangerous.companion.data.entities.ModuleSlot import com.phapps.elitedangerous.companion.data.entities.Ship import com.phapps.elitedangerous.companion.data.entities.ShipModuleSlot @Dao interface ShipDao { @Query("SELECT * FROM ships") fun getAll(): LiveData<List<Ship>> @Query("SELECT * FROM ships WHERE ships.id = :id") fun getById(id: Long): LiveData<Ship> @Query("SELECT * FROM ships WHERE name = :name") fun getByName(name: String): LiveData<Ship> @Query("DELETE FROM ships WHERE id = :id") fun delete(id: Long) @Query("SELECT module_slots.* FROM module_slots WHERE name IN (SELECT ship_module_slots.module_slot_name FROM ship_module_slots WHERE ship_module_slots.ship_id = :shipId)") fun getModuleSlots(shipId: Long): LiveData<List<ModuleSlot>> @Query("SELECT * FROM modules WHERE id = :id") fun getModule(id: Long): LiveData<Module> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(vararg ships: Ship) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(ship: Ship) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(vararg modules: Module) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(vararg moduleSlots: ModuleSlot) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(vararg shipModuleSlot: ShipModuleSlot) }
gpl-3.0
8362682d00528e5cf759a6272ab89251
35.0625
176
0.756788
3.97931
false
false
false
false
martijn-heil/wac-core
src/main/kotlin/tk/martijn_heil/wac_core/craft/vessel/SimpleRudder.kt
1
4751
/* * wac-core * Copyright (C) 2016 Martijn Heil * * 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 tk.martijn_heil.wac_core.craft.vessel import org.bukkit.Bukkit import org.bukkit.Location import org.bukkit.block.Sign import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority import org.bukkit.event.EventPriority.HIGHEST import org.bukkit.event.EventPriority.MONITOR import org.bukkit.event.HandlerList import org.bukkit.event.Listener import org.bukkit.event.block.Action import org.bukkit.event.block.BlockBreakEvent import org.bukkit.event.block.BlockPhysicsEvent import org.bukkit.event.entity.EntityExplodeEvent import org.bukkit.event.player.PlayerInteractEvent import tk.martijn_heil.wac_core.WacCore import tk.martijn_heil.wac_core.craft.Rotation import tk.martijn_heil.wac_core.craft.util.getRotatedLocation /* [Rudder] 0 */ class SimpleRudder(private var sign: Sign) : AutoCloseable { private var world = sign.world private val listener = object : Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) fun onEntityExplode(e: EntityExplodeEvent) { e.blockList().remove(sign.block) e.blockList().remove(sign.block.getRelative((sign.data as org.bukkit.material.Sign).attachedFace)) } @EventHandler(ignoreCancelled = true, priority = HIGHEST) fun onBlockPhysics(e: BlockPhysicsEvent) { if(e.block == sign.block) e.isCancelled = true } @EventHandler(ignoreCancelled = true, priority = MONITOR) fun onPlayerInteract(e: PlayerInteractEvent) { try { if (e.clickedBlock == sign.block) { if (e.action == Action.LEFT_CLICK_BLOCK) { var newCourse = course - 10 if (newCourse < 0) newCourse += 360 course = newCourse } else if (e.action == Action.RIGHT_CLICK_BLOCK) { var newCourse = course + 10 if (newCourse >= 360) newCourse = 0 + (newCourse - 360) course = newCourse } } } catch(t: Throwable) { t.printStackTrace() } } @EventHandler(ignoreCancelled = true) fun onBlockBreak(e: BlockBreakEvent) { val signData = (sign.data as org.bukkit.material.Sign) if (e.block == sign.block || e.block == sign.block.getRelative(signData.attachedFace)) { e.isCancelled = true } } } var onChangeCourseCallback: (heading: Int) -> Boolean = { true } var course: Int = 0 set(value) { val previous = field field = value if(!onChangeCourseCallback(value)) { field = previous; return } sign.setLine(1, course.toString()) sign.update(true, false) } init { this.sign = sign Bukkit.getPluginManager().registerEvents(listener, WacCore.plugin) if(sign.lines.size >= 2) { try { course = sign.lines[1].toInt() } catch(e: NumberFormatException) { sign.setLine(1, course.toString()) sign.update(true, false) } } else { sign.setLine(1, course.toString()) sign.update(true, false) } } fun updateLocation(relativeX: Int, relativeZ: Int) { val newLoc = Location(world, (sign.block.x + relativeX).toDouble(), (sign.block.y).toDouble(), (sign.block.z + relativeZ).toDouble()) sign = newLoc.block.state as Sign } fun updateLocationRotated(rotationPoint: Location, rotation: Rotation) { sign = world.getBlockAt(getRotatedLocation(rotationPoint, rotation, sign.location)).state as Sign } override fun close() { HandlerList.unregisterAll(listener) } }
gpl-3.0
5ac6df0d28a590ed74647de4708ca3d2
35.425197
141
0.604083
4.342779
false
false
false
false
michaelbull/kotlin-result
kotlin-result/src/commonMain/kotlin/com/github/michaelbull/result/Result.kt
1
2236
package com.github.michaelbull.result /** * [Result] is a type that represents either success ([Ok]) or failure ([Err]). * * - Elm: [Result](http://package.elm-lang.org/packages/elm-lang/core/5.1.1/Result) * - Haskell: [Data.Either](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html) * - Rust: [Result](https://doc.rust-lang.org/std/result/enum.Result.html) */ public sealed class Result<out V, out E> { public abstract operator fun component1(): V? public abstract operator fun component2(): E? public companion object { /** * Invokes a [function] and wraps it in a [Result], returning an [Err] * if an [Exception] was thrown, otherwise [Ok]. */ @Deprecated("Use top-level runCatching instead", ReplaceWith("runCatching(function)")) public inline fun <V> of(function: () -> V): Result<V, Exception> { return try { Ok(function.invoke()) } catch (ex: Exception) { Err(ex) } } } } /** * Represents a successful [Result], containing a [value]. */ public class Ok<out V>(public val value: V) : Result<V, Nothing>() { override fun component1(): V = value override fun component2(): Nothing? = null override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false other as Ok<*> if (value != other.value) return false return true } override fun hashCode(): Int = value.hashCode() override fun toString(): String = "Ok($value)" } /** * Represents a failed [Result], containing an [error]. */ public class Err<out E>(public val error: E) : Result<Nothing, E>() { override fun component1(): Nothing? = null override fun component2(): E = error override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false other as Err<*> if (error != other.error) return false return true } override fun hashCode(): Int = error.hashCode() override fun toString(): String = "Err($error)" }
isc
d21222b25d1a39543e7c6fe666b246e7
28.421053
100
0.601968
3.93662
false
false
false
false
dahlstrom-g/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/repositories/RepositoryTree.kt
2
6846
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.repositories import com.intellij.ide.CopyProvider import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.application.EDT import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.ui.TreeUIHelper import com.intellij.ui.treeStructure.Tree import com.intellij.util.ui.tree.TreeUtil import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories import com.jetbrains.packagesearch.intellij.plugin.ui.util.Displayable import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.DefaultTreeModel import javax.swing.tree.TreePath import javax.swing.tree.TreeSelectionModel internal class RepositoryTree( private val project: Project ) : Tree(), DataProvider, CopyProvider, Displayable<KnownRepositories.All> { private val rootNode: DefaultMutableTreeNode get() = (model as DefaultTreeModel).root as DefaultMutableTreeNode init { setCellRenderer(RepositoryTreeItemRenderer()) selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION rootVisible = false isRootVisible = false showsRootHandles = true @Suppress("MagicNumber") // Swing dimension constants border = emptyBorder(left = 8) emptyText.text = PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.repositories.no.repositories.configured") addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent?) { if (e != null && e.clickCount >= 1) { val treePath = getPathForLocation(e.x, e.y) ?: return val item = getRepositoryItemFrom(treePath) if (item != null && item is RepositoryTreeItem.Module) { openFile(item) } } } }) addTreeSelectionListener { val item = getRepositoryItemFrom(it.newLeadSelectionPath) if (item != null && item is RepositoryTreeItem.Module) { openFile(item) } } addKeyListener(object : KeyAdapter() { override fun keyPressed(e: KeyEvent?) { if (e?.keyCode == KeyEvent.VK_ENTER) { val item = getRepositoryItemFrom(selectionPath) if (item != null && item is RepositoryTreeItem.Module) { openFile(item) } } } }) TreeUIHelper.getInstance().installTreeSpeedSearch(this) TreeUtil.installActions(this) } private fun openFile(repositoryModuleItem: RepositoryTreeItem.Module, focusEditor: Boolean = false) { if (!PackageSearchGeneralConfiguration.getInstance(project).autoScrollToSource) return val file = repositoryModuleItem.usageInfo.projectModule.buildFile FileEditorManager.getInstance(project).openFile(file, focusEditor, true) } override suspend fun display(viewModel: KnownRepositories.All) = withContext(Dispatchers.EDT) { val previouslySelectedItem = getSelectedRepositoryItem() clearSelection() rootNode.removeAllChildren() val sortedRepositories = viewModel.sortedBy { it.displayName } for (repository in sortedRepositories) { if (repository.usageInfo.isEmpty()) continue val repoItem = RepositoryTreeItem.Repository(repository) val repoNode = DefaultMutableTreeNode(repoItem) for (usageInfo in repository.usageInfo) { val moduleItem = RepositoryTreeItem.Module(usageInfo) val treeNode = DefaultMutableTreeNode(moduleItem) repoNode.add(treeNode) if (previouslySelectedItem == moduleItem) { selectionModel.selectionPath = TreePath(treeNode) } } rootNode.add(repoNode) if (previouslySelectedItem == repoItem) { selectionModel.selectionPath = TreePath(repoNode) } } TreeUtil.expandAll(this@RepositoryTree) updateUI() } override fun getData(dataId: String) = when (val selectedItem = getSelectedRepositoryItem()) { is DataProvider -> selectedItem.getData(dataId) else -> null } override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT override fun performCopy(dataContext: DataContext) { val selectedItem = getSelectedRepositoryItem() if (selectedItem is CopyProvider) selectedItem.performCopy(dataContext) } override fun isCopyEnabled(dataContext: DataContext): Boolean { val selectedItem = getSelectedRepositoryItem() return selectedItem is CopyProvider && selectedItem.isCopyEnabled(dataContext) } override fun isCopyVisible(dataContext: DataContext): Boolean { val selectedItem = getSelectedRepositoryItem() return selectedItem is CopyProvider && selectedItem.isCopyVisible(dataContext) } private fun getSelectedRepositoryItem() = getRepositoryItemFrom(this.selectionPath) private fun getRepositoryItemFrom(treePath: TreePath?): RepositoryTreeItem? { val item = treePath?.lastPathComponent as? DefaultMutableTreeNode? return item?.userObject as? RepositoryTreeItem } }
apache-2.0
1ce6dca1255d3340281247f08732344d
39.508876
127
0.681566
5.390551
false
false
false
false
android/privacy-codelab
PhotoLog_start/src/main/java/com/example/photolog_start/ui/theme/Type.kt
1
1616
/* * Copyright (C) 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.photolog_start.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
apache-2.0
5682b40ad06fd18cab3062c1aa773942
31.34
75
0.693069
4.263852
false
false
false
false
Jay-Y/yframework
yframework-android/framework/src/main/java/org/yframework/android/hardware/HardwareInformation.kt
1
1229
package org.yframework.android.hardware import android.os.Build import java.io.Serializable /** * Description: HardwareInformation<br> * Comments Name: HardwareInformation<br> * Date: 2019-09-20 17:31<br> * Author: ysj<br> * EditorDate: 2019-09-20 17:31<br> * Editor: ysj */ class HardwareInformation( val bid: String = Build.ID, // 系统当前开发版本 val display: String = Build.DISPLAY, // 设备显示版本 val serial: String = Build.SERIAL, // 串口序列号 val fingerprint: String = Build.FINGERPRINT, // 设备指纹 val host: String = Build.HOST, // 主机地址 val productBrand: String = Build.BRAND, // 产品出厂商品牌 val productName: String = Build.PRODUCT, // 产品名称 val productBoardName: String = Build.BOARD, // 产品主板名字 val productDeviceName: String = Build.DEVICE, // 产品驱动名 val productManufacturer: String = Build.MANUFACTURER, // 产品制造商 val sdkVersion: Int = Build.VERSION.SDK_INT, // 当前手机SDK版本号 val systemVersion: String = Build.VERSION.RELEASE, // 手机系统版本号 val systemBootloaderVersion: String = Build.BOOTLOADER // 系统引导程序版本号 ) : Serializable
apache-2.0
566f20ec993b2434e162dcd1dfbb4244
25.9
71
0.702326
3.267477
false
false
false
false
paplorinc/intellij-community
plugins/stats-collector/src/com/intellij/stats/network/service/SimpleRequestService.kt
1
3626
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.stats.network.service import com.google.common.net.HttpHeaders import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.text.StringUtil import com.intellij.util.io.HttpRequests import org.apache.commons.codec.binary.Base64OutputStream import java.io.ByteArrayOutputStream import java.io.File import java.io.IOException import java.net.HttpURLConnection import java.net.URLConnection import java.util.zip.GZIPOutputStream class SimpleRequestService: RequestService() { private companion object { val LOG = logger<SimpleRequestService>() } override fun postZipped(url: String, file: File): ResponseData? { return try { val zippedArray = getZippedContent(file) return HttpRequests.post(url, null).tuner { it.setRequestProperty(HttpHeaders.CONTENT_ENCODING, "gzip") }.connect { request -> request.write(zippedArray) return@connect request.connection.asResponseData(zippedArray.size) } } catch (e: HttpRequests.HttpStatusException) { ResponseData(e.statusCode, StringUtil.notNullize(e.message)) } catch (e: IOException) { LOG.debug(e) null } } private fun getZippedContent(file: File): ByteArray { val fileText = file.readText() return GzipBase64Compressor.compress(fileText) } override fun get(url: String): ResponseData? { return try { val requestBuilder = HttpRequests.request(url) return requestBuilder.connect { request -> val responseCode = request.getResponseCode() val responseText = request.readString() ResponseData(responseCode, responseText) } } catch (e: IOException) { LOG.debug(e) null } } private fun URLConnection.asResponseData(sentDataSize: Int?): ResponseData? { if (this is HttpURLConnection) { return ResponseData(this.responseCode, StringUtil.notNullize(this.responseMessage, ""), sentDataSize) } LOG.error("Could not get code and message from http response") return null } private fun HttpRequests.Request.getResponseCode(): Int { val connection = this.connection if (connection is HttpURLConnection) { return connection.responseCode } LOG.error("Could not get code from http response") return -1 } } data class ResponseData(val code: Int, val text: String = "", val sentDataSize: Int? = null) { fun isOK(): Boolean = code in 200..299 } object GzipBase64Compressor { fun compress(text: String): ByteArray { val outputStream = ByteArrayOutputStream() val base64Stream = GZIPOutputStream(Base64OutputStream(outputStream)) base64Stream.write(text.toByteArray()) base64Stream.close() return outputStream.toByteArray() } }
apache-2.0
708fe3991f963de9c698ef5167eeb93b
32.583333
113
0.668781
4.696891
false
false
false
false
dzharkov/intellij-markdown
src/org/intellij/markdown/parser/sequentialparsers/impl/AutolinkParser.kt
1
1717
package org.intellij.markdown.parser.sequentialparsers.impl import org.intellij.markdown.IElementType import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.parser.sequentialparsers.SequentialParser import org.intellij.markdown.parser.sequentialparsers.SequentialParserUtil import org.intellij.markdown.parser.sequentialparsers.TokensCache import java.util.ArrayList public class AutolinkParser(private val typesAfterLT: List<IElementType>) : SequentialParser { override fun parse(tokens: TokensCache, rangesToGlue: Collection<Range<Int>>): SequentialParser.ParsingResult { val result = SequentialParser.ParsingResult() val delegateIndices = ArrayList<Int>() val indices = SequentialParserUtil.textRangesToIndices(rangesToGlue) var i = 0 while (i < indices.size()) { var iterator: TokensCache.Iterator = tokens.ListIterator(indices, i) if (iterator.type == MarkdownTokenTypes.LT && iterator.rawLookup(1) in typesAfterLT) { val start = i while (iterator.type != MarkdownTokenTypes.GT && iterator.type != null) { iterator = iterator.advance() i++ } if (iterator.type == null) { i-- } result.withNode(SequentialParser.Node(indices.get(start)..indices.get(i) + 1, MarkdownElementTypes.AUTOLINK)) } else { delegateIndices.add(indices.get(i)) } ++i } return result.withFurtherProcessing(SequentialParserUtil.indicesToTextRanges(delegateIndices)) } }
apache-2.0
2e578eeddbbf77b1692c752f3c2b198e
43.025641
125
0.670355
5.05
false
false
false
false
square/okio
okio/src/jvmMain/kotlin/okio/-JvmPlatform.kt
1
1379
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okio internal actual fun ByteArray.toUtf8String(): String = String(this, Charsets.UTF_8) internal actual fun String.asUtf8ToByteArray(): ByteArray = toByteArray(Charsets.UTF_8) // TODO remove if https://youtrack.jetbrains.com/issue/KT-20641 provides a better solution actual typealias ArrayIndexOutOfBoundsException = java.lang.ArrayIndexOutOfBoundsException internal actual inline fun <R> synchronized(lock: Any, block: () -> R): R { return kotlin.synchronized(lock, block) } actual typealias IOException = java.io.IOException actual typealias ProtocolException = java.net.ProtocolException actual typealias EOFException = java.io.EOFException actual typealias FileNotFoundException = java.io.FileNotFoundException actual typealias Closeable = java.io.Closeable
apache-2.0
32c957270f224ad869c48d9392f4cfa4
35.289474
90
0.777375
4.336478
false
false
false
false
fluidsonic/fluid-json
coding/tests-jvm/utility/Sequence.kt
1
589
package tests.coding internal fun <T> emptyEquatableSequence(): Sequence<T> = EquatableSequence(emptySequence()) internal fun <T> equatableSequenceOf(vararg elements: T): Sequence<T> = EquatableSequence(elements.asSequence()) @Suppress("EqualsOrHashCode") internal class EquatableSequence<out Element>(val source: Sequence<Element>) : Sequence<Element> by source { // careful, this isn't reflexive override fun equals(other: Any?): Boolean { if (other === this) { return true } if (other !is Sequence<*>) { return false } return toList() == other.toList() } }
apache-2.0
39bebf028a3b3c04ae1062b6c00d45bf
21.653846
108
0.713073
3.569697
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/test/flow/terminal/LaunchFlow.kt
1
3394
/* * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.flow import kotlinx.coroutines.* import kotlin.jvm.* import kotlin.reflect.* public typealias Handler<T> = suspend CoroutineScope.(T) -> Unit /* * Design of this builder is not yet stable, so leaving it as is. */ public class LaunchFlowBuilder<T> { /* * NB: this implementation is a temporary ad-hoc (and slightly incorrect) * solution until coroutine-builders are ready * * NB 2: this internal stuff is required to workaround KT-30795 */ @PublishedApi internal var onEach: Handler<T>? = null @PublishedApi internal var finally: Handler<Throwable?>? = null @PublishedApi internal var exceptionHandlers = LinkedHashMap<KClass<*>, Handler<Throwable>>() public fun onEach(action: suspend CoroutineScope.(value: T) -> Unit) { check(onEach == null) { "onEach block is already registered" } check(exceptionHandlers.isEmpty()) { "onEach block should be registered before exceptionHandlers block" } check(finally == null) { "onEach block should be registered before finally block" } onEach = action } public inline fun <reified T : Throwable> catch(noinline action: suspend CoroutineScope.(T) -> Unit) { check(onEach != null) { "onEach block should be registered first" } check(finally == null) { "exceptionHandlers block should be registered before finally block" } @Suppress("UNCHECKED_CAST") exceptionHandlers[T::class] = action as Handler<Throwable> } public fun finally(action: suspend CoroutineScope.(cause: Throwable?) -> Unit) { check(finally == null) { "Finally block is already registered" } check(onEach != null) { "onEach block should be registered before finally block" } if (finally == null) finally = action } internal fun build(): Handlers<T> = Handlers(onEach ?: error("onEach is not registered"), exceptionHandlers, finally) } internal class Handlers<T>( @JvmField internal var onEach: Handler<T>, @JvmField internal var exceptionHandlers: Map<KClass<*>, Handler<Throwable>>, @JvmField internal var finally: Handler<Throwable?>? ) private fun <T> CoroutineScope.launchFlow( flow: Flow<T>, builder: LaunchFlowBuilder<T>.() -> Unit ): Job { val handlers = LaunchFlowBuilder<T>().apply(builder).build() return launch { var caught: Throwable? = null try { coroutineScope { flow.collect { value -> handlers.onEach(this, value) } } } catch (e: Throwable) { handlers.exceptionHandlers.forEach { (key, value) -> if (key.isInstance(e)) { caught = e value.invoke(this, e) return@forEach } } if (caught == null) { caught = e throw e } } finally { cancel() // TODO discuss handlers.finally?.invoke(CoroutineScope(coroutineContext + NonCancellable), caught) } } } public fun <T> Flow<T>.launchIn( scope: CoroutineScope, builder: LaunchFlowBuilder<T>.() -> Unit ): Job = scope.launchFlow(this, builder)
apache-2.0
bc910aa36a0e8903ffc67e929dea9c11
33.632653
113
0.620801
4.574124
false
false
false
false
bitsydarel/DBWeather
dbweatherlives/src/main/java/com/dbeginc/dbweatherlives/iptvplaylistdetail/IpTvPlaylistDetailViewModel.kt
1
2970
/* * Copyright (C) 2017 Darel Bitsy * 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.dbeginc.dbweatherlives.iptvplaylistdetail import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import com.dbeginc.dbweathercommon.BaseViewModel import com.dbeginc.dbweathercommon.utils.RequestState import com.dbeginc.dbweathercommon.utils.addTo import com.dbeginc.dbweatherdomain.Logger import com.dbeginc.dbweatherdomain.ThreadProvider import com.dbeginc.dbweatherdomain.entities.requests.lives.IpTvLiveRequest import com.dbeginc.dbweatherdomain.repositories.LivesRepository import com.dbeginc.dbweatherlives.viewmodels.IpTvLiveModel import com.dbeginc.dbweatherlives.viewmodels.toUi import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject class IpTvPlaylistDetailViewModel @Inject constructor(private val model: LivesRepository, private val threads: ThreadProvider, private val logger: Logger) : BaseViewModel() { override val subscriptions: CompositeDisposable = CompositeDisposable() override val requestState: MutableLiveData<RequestState> = MutableLiveData() private val _channels: MutableLiveData<List<IpTvLiveModel>> = MutableLiveData() fun getIpTvLives(): LiveData<List<IpTvLiveModel>> = _channels fun loadIpTvLives(playlistId: String) { model.getIpTvLives(IpTvLiveRequest(playlist = playlistId, arg = Unit)) .doOnSubscribe { requestState.postValue(RequestState.LOADING) } .doAfterNext { requestState.postValue(RequestState.COMPLETED) } .doOnError { requestState.postValue(RequestState.ERROR) } .map { iptvLives -> iptvLives.map { it.toUi() } } .observeOn(threads.UI) .subscribe(_channels::postValue, logger::logError) .addTo(subscriptions) } fun findIpTvLive(playlistId: String, possibleLiveName: String) { model.findIpTvLive(playlistId = playlistId, name = possibleLiveName) .doOnSubscribe { requestState.postValue(RequestState.LOADING) } .doAfterSuccess { requestState.postValue(RequestState.COMPLETED) } .doOnError { requestState.postValue(RequestState.ERROR) } .map { iptvLives -> iptvLives.map { it.toUi() } } .observeOn(threads.UI) .subscribe(_channels::postValue, logger::logError) .addTo(subscriptions) } }
gpl-3.0
12594f3f8b2d8bbf43be53b01aa1d6b5
48.516667
174
0.73266
4.493192
false
false
false
false
leafclick/intellij-community
platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/autoimport/AutoImportTestCase.kt
1
12462
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.autoimport import com.intellij.core.CoreBundle import com.intellij.ide.file.BatchFileChangeListener import com.intellij.openapi.Disposable import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.editor.Document import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.externalSystem.test.ExternalSystemTestCase import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.util.Computable import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.use import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsBundle import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.replaceService import java.io.File import java.io.IOException abstract class AutoImportTestCase : ExternalSystemTestCase() { override fun getTestsTempDir() = "tmp${System.currentTimeMillis()}" override fun getExternalSystemConfigFileName() = throw UnsupportedOperationException() private lateinit var testDisposable: Disposable private val notificationAware get() = ProjectNotificationAware.getInstance(myProject) private val projectTracker get() = AutoImportProjectTracker.getInstance(myProject).also { it.enableAutoImportInTests() } private fun ensureExistsParentDirectory(relativePath: String): VirtualFile { return relativePath.split("/").dropLast(1) .fold(myProjectRoot!!) { file, name -> file.findOrCreateChildDirectory(name) } } private fun VirtualFile.findOrCreateChildDirectory(name: String): VirtualFile { val file = findChild(name) ?: createChildDirectory(null, name) if (!file.isDirectory) throw IOException(VfsBundle.message("new.directory.failed.error", name)) return file } private fun VirtualFile.findOrCreateChildFile(name: String): VirtualFile { val file = findChild(name) ?: createChildData(null, name) if (file.isDirectory) throw IOException(VfsBundle.message("new.file.failed.error", name)) return file } protected fun createVirtualFile(relativePath: String) = runWriteAction { val directory = ensureExistsParentDirectory(relativePath) directory.createChildData(null, relativePath.split("/").last()) } protected fun findOrCreateVirtualFile(relativePath: String) = runWriteAction { val directory = ensureExistsParentDirectory(relativePath) directory.findOrCreateChildFile(relativePath.split("/").last()) } protected fun createIoFile(relativePath: String): VirtualFile { val file = File(projectPath, relativePath) FileUtil.ensureExists(file.parentFile) FileUtil.ensureCanCreateFile(file) if (!file.createNewFile()) { throw IOException(CoreBundle.message("file.create.already.exists.error", parentPath, relativePath)) } return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file)!! } protected fun findOrCreateDirectory(relativePath: String) = createProjectSubDir(relativePath)!! private fun <R> runWriteAction(update: () -> R): R = WriteCommandAction.runWriteCommandAction(myProject, Computable { update() }) private fun getPath(relativePath: String) = "$projectPath/$relativePath" private fun getFile(relativePath: String) = File(projectPath, relativePath) private fun VirtualFile.updateIoFile(action: File.() -> Unit) { File(path).apply(action) refreshIoFiles(path) } private fun refreshIoFiles(vararg paths: String) { val localFileSystem = LocalFileSystem.getInstance() localFileSystem.refreshIoFiles(paths.map { File(it) }, false, true, null) } protected fun VirtualFile.replaceContentInIoFile(content: String) = updateIoFile { writeText(content) } protected fun VirtualFile.replaceStringInIoFile(old: String, new: String) = updateIoFile { writeText(readText().replace(old, new)) } protected fun VirtualFile.deleteIoFile() = updateIoFile { delete() } protected fun VirtualFile.rename(name: String) = runWriteAction { rename(null, name) } protected fun VirtualFile.copy(relativePath: String) = runWriteAction { val newFile = getFile(relativePath) val parent = VfsUtil.findFileByIoFile(newFile.parentFile, true)!! copy(null, parent, newFile.name) } protected fun VirtualFile.move(parent: VirtualFile) = runWriteAction { move(null, parent) } protected fun VirtualFile.removeContent() = runWriteAction { VfsUtil.saveText(this, "") } protected fun VirtualFile.replaceContent(content: String) = runWriteAction { VfsUtil.saveText(this, content) } protected fun VirtualFile.insertString(offset: Int, string: String) = runWriteAction { val text = VfsUtil.loadText(this) val before = text.substring(0, offset) val after = text.substring(offset, text.length) VfsUtil.saveText(this, before + string + after) } protected fun VirtualFile.insertStringAfter(prefix: String, string: String) = runWriteAction { val text = VfsUtil.loadText(this) val offset = text.indexOf(prefix) val before = text.substring(0, offset) val after = text.substring(offset + prefix.length, text.length) VfsUtil.saveText(this, before + prefix + string + after) } protected fun VirtualFile.appendString(string: String) = runWriteAction { VfsUtil.saveText(this, VfsUtil.loadText(this) + string) } protected fun VirtualFile.replaceString(old: String, new: String) = runWriteAction { VfsUtil.saveText(this, VfsUtil.loadText(this).replace(old, new)) } protected fun VirtualFile.delete() = runWriteAction { delete(null) } protected fun VirtualFile.asDocument(): Document { val fileDocumentManager = FileDocumentManager.getInstance() return fileDocumentManager.getDocument(this)!! } protected fun Document.save() = runWriteAction { FileDocumentManager.getInstance().saveDocument(this) } protected fun Document.replaceContent(content: String) = runWriteAction { replaceString(0, text.length, content) } protected fun Document.replaceString(old: String, new: String) = runWriteAction { val startOffset = text.indexOf(old) val endOffset = startOffset + old.length replaceString(startOffset, endOffset, new) } protected fun register(projectAware: ExternalSystemProjectAware) = projectTracker.register(projectAware) protected fun remove(projectId: ExternalSystemProjectId) = projectTracker.remove(projectId) protected fun refreshProject() = projectTracker.scheduleProjectRefresh() protected fun forceRefreshProject(projectId: ExternalSystemProjectId) { projectTracker.markDirty(projectId) projectTracker.scheduleProjectRefresh() } private fun loadState(state: AutoImportProjectTracker.State) = projectTracker.loadState(state) protected fun enableAutoReloadExternalChanges() { projectTracker.isAutoReloadExternalChanges = true } protected fun disableAutoReloadExternalChanges() { projectTracker.isAutoReloadExternalChanges = false } protected fun initialize() = projectTracker.initializeComponent() protected fun getState() = projectTracker.state protected fun assertProjectAware(projectAware: MockProjectAware, refresh: Int? = null, subscribe: Int? = null, unsubscribe: Int? = null, event: String) { if (refresh != null) assertCountEvent(refresh, projectAware.refreshCounter.get(), "project refresh", event) if (subscribe != null) assertCountEvent(subscribe, projectAware.subscribeCounter.get(), "subscribe", event) if (unsubscribe != null) assertCountEvent(unsubscribe, projectAware.unsubscribeCounter.get(), "unsubscribe", event) } private fun assertCountEvent(expected: Int, actual: Int, countEvent: String, event: String) { val message = when { actual > expected -> "Unexpected $countEvent event" actual < expected -> "Expected $countEvent event" else -> "" } assertEquals("$message on $event", expected, actual) } protected fun assertProjectTracker(isAutoReload: Boolean, event: String) { val message = when (isAutoReload) { true -> "Auto reload must be enabled" false -> "Auto reload must be disabled" } assertEquals("$message on $event", isAutoReload, projectTracker.isAutoReloadExternalChanges) } protected fun assertNotificationAware(vararg projects: ExternalSystemProjectId, event: String) { val message = when (projects.isEmpty()) { true -> "Notification must be expired" else -> "Notification must be notified" } assertEquals("$message on $event", projects.toSet(), notificationAware.getProjectsWithNotification()) } protected fun modification(action: () -> Unit) { BackgroundTaskUtil.syncPublisher(BatchFileChangeListener.TOPIC).batchChangeStarted(myProject, "modification") action() BackgroundTaskUtil.syncPublisher(BatchFileChangeListener.TOPIC).batchChangeCompleted(myProject) } private fun <S : Any, R> ComponentManager.replaceService(aClass: Class<S>, service: S, action: () -> R): R { Disposer.newDisposable().use { replaceService(aClass, service, it) return action() } } override fun setUp() { super.setUp() testDisposable = Disposer.newDisposable() myProject.replaceService(ExternalSystemProjectTracker::class.java, AutoImportProjectTracker(myProject), testDisposable) } override fun tearDown() { Disposer.dispose(testDisposable) super.tearDown() } protected fun simpleTest(fileRelativePath: String, content: String? = null, state: AutoImportProjectTracker.State = AutoImportProjectTracker.State(), test: SimpleTestBench.(VirtualFile) -> Unit): AutoImportProjectTracker.State { return myProject.replaceService(ExternalSystemProjectTracker::class.java, AutoImportProjectTracker(myProject)) { val systemId = ProjectSystemId("External System") val projectId = ExternalSystemProjectId(systemId, projectPath) val projectAware = MockProjectAware(projectId) loadState(state) initialize() val file = findOrCreateVirtualFile(fileRelativePath) content?.let { file.replaceContent(it) } projectAware.settingsFiles.add(file.path) register(projectAware) SimpleTestBench(projectAware).test(file) val newState = getState() remove(projectAware.projectId) newState } } protected inner class SimpleTestBench(private val projectAware: MockProjectAware) { fun registerProjectAware() = register(projectAware) fun removeProjectAware() = remove(projectAware.projectId) fun registerSettingsFile(file: VirtualFile) = projectAware.settingsFiles.add(file.path) fun registerSettingsFile(relativePath: String) = projectAware.settingsFiles.add(getPath(relativePath)) fun setRefreshStatus(status: ExternalSystemRefreshStatus) { projectAware.refreshStatus = status } fun withLinkedProject(fileRelativePath: String, test: SimpleTestBench.(VirtualFile) -> Unit) { val projectId = ExternalSystemProjectId(projectAware.projectId.systemId, "$projectPath/$name") val projectAware = MockProjectAware(projectId) register(projectAware) val file = findOrCreateVirtualFile("$name/$fileRelativePath") projectAware.settingsFiles.add(file.path) SimpleTestBench(projectAware).test(file) remove(projectId) } fun assertState(refresh: Int? = null, subscribe: Int? = null, unsubscribe: Int? = null, enabled: Boolean = true, notified: Boolean, event: String) { assertProjectAware(projectAware, refresh, subscribe, unsubscribe, event) assertProjectTracker(enabled, event = event) when (notified) { true -> assertNotificationAware(projectAware.projectId, event = event) else -> assertNotificationAware(event = event) } } } }
apache-2.0
cc4083c1315295923dca81d8c3d37e4b
39.728758
140
0.733028
4.951132
false
true
false
false
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/params/PublishToFacebookPost.kt
1
1519
package com.vimeo.networking2.params import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * Represents the required data for a Facebook post. * * @param title The title of the post as it will appear on Facebook. * @param description The description of the post as it will appear on Facebook. * @param destination The destination identifier (page id) of the page being posted to on Facebook. * @param categoryId An optional Facebook category of the video. * @param allowEmbedding Whether or not this Facebook post should be embeddable. * @param shouldAppearOnNewsFeed Whether or not this post should appear on the Facebook News Feed. * @param isSecretVideo Whether or not this video should be searchable and show up in the user's video library on * Facebook. * @param allowSocialActions Whether or not to allow social actions on the post on Facebook. */ @JsonClass(generateAdapter = true) data class PublishToFacebookPost( @Json(name = "title") val title: String? = null, @Json(name = "description") val description: String? = null, @Json(name = "destination") val destination: Long, @Json(name = "category_id") val categoryId: String? = null, @Json(name = "allow_embedding") val allowEmbedding: Boolean, @Json(name = "should_appear_on_news_feed") val shouldAppearOnNewsFeed: Boolean, @Json(name = "is_secret_video") val isSecretVideo: Boolean, @Json(name = "allow_social_actions") val allowSocialActions: Boolean )
mit
7de7c5078bff9219927bdc2199d52fe9
32.755556
113
0.728111
4.050667
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowPaneNewButtonManager.kt
1
3500
// 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.openapi.wm.impl import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowAnchor import java.awt.BorderLayout import java.awt.Dimension import java.awt.Point import javax.swing.JComponent internal class ToolWindowPaneNewButtonManager : ToolWindowButtonManager { private val left = ToolwindowLeftToolbar() private val right = ToolwindowRightToolbar() override fun add(pane: JComponent) { pane.add(left, BorderLayout.WEST) pane.add(right, BorderLayout.EAST) } override fun updateToolStripesVisibility(showButtons: Boolean, state: ToolWindowPaneState): Boolean { val oldSquareVisible = left.isVisible && right.isVisible left.isVisible = showButtons right.isVisible = showButtons return oldSquareVisible != showButtons } override fun layout(size: Dimension, layeredPane: JComponent) { layeredPane.setBounds(0, 0, size.width, size.height) } override fun validateAndRepaint() { } override fun revalidateNotEmptyStripes() { } override fun getBottomHeight() = 0 override fun getStripeFor(anchor: ToolWindowAnchor): AbstractDroppableStripe { return when (anchor) { ToolWindowAnchor.LEFT, ToolWindowAnchor.BOTTOM -> left.getStripeFor(anchor) ToolWindowAnchor.RIGHT, ToolWindowAnchor.TOP -> right.getStripeFor(anchor) else -> throw IllegalArgumentException("Anchor=$anchor") } } override fun getStripeFor(screenPoint: Point, preferred: AbstractDroppableStripe, pane: JComponent): AbstractDroppableStripe? { if (preferred.containsPoint(screenPoint)) { return preferred } else { return left.getStripeFor(screenPoint) ?: right.getStripeFor(screenPoint) } } fun getSquareStripeFor(anchor: ToolWindowAnchor): ToolwindowToolbar { return when(anchor) { ToolWindowAnchor.TOP, ToolWindowAnchor.RIGHT -> right ToolWindowAnchor.BOTTOM, ToolWindowAnchor.LEFT -> left else -> throw java.lang.IllegalArgumentException("Anchor=$anchor") } } override fun startDrag() { if (right.isVisible) { right.startDrag() } if (left.isVisible) { left.startDrag() } } override fun stopDrag() { if (right.isVisible) { right.stopDrag() } if (left.isVisible) { left.stopDrag() } } override fun reset() { left.reset() right.reset() } private fun findToolbar(anchor: ToolWindowAnchor): ToolwindowToolbar? { when(anchor) { ToolWindowAnchor.LEFT, ToolWindowAnchor.BOTTOM -> return left ToolWindowAnchor.RIGHT -> return right else -> return null } } override fun onStripeButtonAdded(toolWindow: ToolWindowImpl) { findToolbar(toolWindow.largeStripeAnchor)?.addStripeButton(toolWindow) } override fun onStripeButtonRemoved(toolWindow: ToolWindowImpl) { if (!toolWindow.isAvailable) { return } val anchor = toolWindow.largeStripeAnchor findToolbar(anchor)?.removeStripeButton(toolWindow, anchor) } override fun onStripeButtonUpdate(toolWindow: ToolWindow, property: ToolWindowProperty, entry: ToolWindowEntry?) { val button = findToolbar(toolWindow.largeStripeAnchor)?.getButtonFor(toolWindow.id) ?: return ToolWindowButtonManager.updateStripeButton(toolWindow, property, button.button) if (property == ToolWindowProperty.ICON) { button.syncIcon() } } }
apache-2.0
532a2cf6b997a07baa59c2d5a4cf45d1
29.443478
129
0.728
4.611331
false
false
false
false
smmribeiro/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/grammar/LanguageToolRule.kt
1
1834
package com.intellij.grazie.grammar import com.intellij.grazie.GrazieBundle import com.intellij.grazie.jlanguage.Lang import com.intellij.grazie.jlanguage.LangTool import com.intellij.grazie.text.Rule import com.intellij.grazie.utils.* import kotlinx.html.style import kotlinx.html.table import kotlinx.html.td import kotlinx.html.tr import java.net.URL internal class LanguageToolRule( private val lang: Lang, private val ltRule: org.languagetool.rules.Rule ) : Rule(LangTool.globalIdPrefix(lang) + ltRule.id, ltRule.description, ltRule.category.name) { override fun isEnabledByDefault(): Boolean = LangTool.isRuleEnabledByDefault(lang, ltRule.id) override fun getUrl(): URL? = ltRule.url override fun getDescription(): String = html { table { cellpading = "0" cellspacing = "0" style = "width:100%;" ltRule.incorrectExamples.forEach { example -> tr { td { valign = "top" style = "padding-bottom: 5px; padding-right: 5px; color: gray;" +GrazieBundle.message("grazie.settings.grammar.rule.incorrect") } td { style = "padding-bottom: 5px; width: 100%;" toIncorrectHtml(example) } } if (example.corrections.any { it.isNotBlank() }) { tr { td { valign = "top" style = "padding-bottom: 10px; padding-right: 5px; color: gray;" +GrazieBundle.message("grazie.settings.grammar.rule.correct") } td { style = "padding-bottom: 10px; width: 100%;" toCorrectHtml(example) } } } } } +GrazieBundle.message("grazie.tooltip.powered-by-language-tool") } override fun getSearchableDescription(): String = "LanguageTool" }
apache-2.0
d913aa874841d529fddefc73c89cce70
29.583333
95
0.624864
4.130631
false
false
false
false
android/compose-samples
Jetcaster/app/src/main/java/com/example/jetcaster/data/room/CategoriesDao.kt
1
2342
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.jetcaster.data.room import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update import com.example.jetcaster.data.Category import kotlinx.coroutines.flow.Flow /** * [Room] DAO for [Category] related operations. */ @Dao abstract class CategoriesDao { @Query( """ SELECT categories.* FROM categories INNER JOIN ( SELECT category_id, COUNT(podcast_uri) AS podcast_count FROM podcast_category_entries GROUP BY category_id ) ON category_id = categories.id ORDER BY podcast_count DESC LIMIT :limit """ ) abstract fun categoriesSortedByPodcastCount( limit: Int ): Flow<List<Category>> @Query("SELECT * FROM categories WHERE name = :name") abstract suspend fun getCategoryWithName(name: String): Category? /** * The following methods should really live in a base interface. Unfortunately the Kotlin * Compiler which we need to use for Compose doesn't work with that. * TODO: remove this once we move to a more recent Kotlin compiler */ @Insert(onConflict = OnConflictStrategy.REPLACE) abstract suspend fun insert(entity: Category): Long @Insert(onConflict = OnConflictStrategy.REPLACE) abstract suspend fun insertAll(vararg entity: Category) @Insert(onConflict = OnConflictStrategy.REPLACE) abstract suspend fun insertAll(entities: Collection<Category>) @Update(onConflict = OnConflictStrategy.REPLACE) abstract suspend fun update(entity: Category) @Delete abstract suspend fun delete(entity: Category): Int }
apache-2.0
b838fe463302455635eb85baadc1808d
31.985915
97
0.721178
4.565302
false
false
false
false
smmribeiro/intellij-community
java/java-impl/src/com/intellij/ide/JavaDependencyCollector.kt
6
1682
// 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.ide import com.intellij.ide.plugins.DependencyCollector import com.intellij.openapi.application.runReadAction import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.rootManager import com.intellij.openapi.roots.LibraryOrderEntry import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import org.jetbrains.idea.maven.utils.library.RepositoryLibraryProperties class JavaDependencyCollector : DependencyCollector { override fun collectDependencies(project: Project): List<String> { val result = mutableSetOf<String>() runReadAction { val projectLibraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project) for (library in projectLibraryTable.libraries) { val properties = (library as? LibraryEx)?.properties as? RepositoryLibraryProperties ?: continue result.add(properties.groupId + ":" + properties.artifactId) } for (module in ModuleManager.getInstance(project).modules) { for (orderEntry in module.rootManager.orderEntries) { if (orderEntry is LibraryOrderEntry && orderEntry.isModuleLevel) { val library = orderEntry.library val properties = (library as? LibraryEx)?.properties as? RepositoryLibraryProperties ?: continue result.add(properties.groupId + ":" + properties.artifactId) } } } } return result.toList() } }
apache-2.0
747547138afb882cab7cd35ce43d352f
47.085714
140
0.75327
4.961652
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/handlers/WithTailInsertHandler.kt
1
4398
// 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.completion.handlers import com.intellij.codeInsight.AutoPopupController import com.intellij.codeInsight.completion.InsertHandler import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.Lookup import com.intellij.codeInsight.lookup.LookupElement import com.intellij.openapi.editor.Document import com.intellij.psi.PsiDocumentManager import org.jetbrains.kotlin.idea.completion.KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY import org.jetbrains.kotlin.idea.completion.smart.SmartCompletion import org.jetbrains.kotlin.idea.completion.tryGetOffset class WithTailInsertHandler( val tailText: String, val spaceBefore: Boolean, val spaceAfter: Boolean, val overwriteText: Boolean = true ) : InsertHandler<LookupElement> { override fun handleInsert(context: InsertionContext, item: LookupElement) { item.handleInsert(context) postHandleInsert(context, item) } val asPostInsertHandler: InsertHandler<LookupElement> get() = InsertHandler { context, item -> postHandleInsert(context, item) } fun postHandleInsert(context: InsertionContext, item: LookupElement) { val completionChar = context.completionChar if (completionChar == tailText.singleOrNull() || (spaceAfter && completionChar == ' ')) { context.setAddCompletionChar(false) } //TODO: what if completion char is different? val document = context.document PsiDocumentManager.getInstance(context.project).doPostponedOperationsAndUnblockDocument(document) var tailOffset = context.tailOffset if (completionChar == Lookup.REPLACE_SELECT_CHAR && item.getUserData(KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY) != null) { context.offsetMap.tryGetOffset(SmartCompletion.OLD_ARGUMENTS_REPLACEMENT_OFFSET) ?.let { tailOffset = it } } val moveCaret = context.editor.caretModel.offset == tailOffset //TODO: analyze parenthesis balance to decide whether to replace or not var insert = true if (overwriteText) { var offset = tailOffset if (tailText != " ") { offset = document.charsSequence.skipSpacesAndLineBreaks(offset) } if (shouldOverwriteChar(document, offset)) { insert = false offset += tailText.length tailOffset = offset if (spaceAfter && document.charsSequence.isCharAt(offset, ' ')) { document.deleteString(offset, offset + 1) } } } var textToInsert = "" if (insert) { textToInsert = tailText if (spaceBefore) textToInsert = " " + textToInsert } if (spaceAfter) textToInsert += " " document.insertString(tailOffset, textToInsert) if (moveCaret) { context.editor.caretModel.moveToOffset(tailOffset + textToInsert.length) if (tailText == ",") { AutoPopupController.getInstance(context.project)?.autoPopupParameterInfo(context.editor, null) } } } private fun shouldOverwriteChar(document: Document, offset: Int): Boolean { if (!document.isTextAt(offset, tailText)) return false if (tailText == " " && document.charsSequence.isCharAt(offset + 1, '}')) return false // do not overwrite last space before '}' return true } companion object { val COMMA = WithTailInsertHandler(",", spaceBefore = false, spaceAfter = true /*TODO: use code style option*/) val RPARENTH = WithTailInsertHandler(")", spaceBefore = false, spaceAfter = false) val RBRACKET = WithTailInsertHandler("]", spaceBefore = false, spaceAfter = false) val RBRACE = WithTailInsertHandler("}", spaceBefore = true, spaceAfter = false) val ELSE = WithTailInsertHandler("else", spaceBefore = true, spaceAfter = true) val EQ = WithTailInsertHandler("=", spaceBefore = true, spaceAfter = true) /*TODO: use code style options*/ val SPACE = WithTailInsertHandler(" ", spaceBefore = false, spaceAfter = false, overwriteText = true) } }
apache-2.0
5af006ab7112312849a31df8c5200a06
42.544554
158
0.670077
4.875831
false
false
false
false
korotyx/VirtualEntity
src/main/kotlin/com/korotyx/virtualentity/base/VirtualEntity.kt
1
3039
@file:JvmName("VirtualEntity") package com.korotyx.virtualentity.base import com.google.gson.* import com.korotyx.virtualentity.util.VirtualEntityUtil import com.korotyx.virtualentity.system.GenericIdentity import com.korotyx.virtualentity.system.TypeRegister import java.lang.reflect.Method import java.util.* import java.util.ArrayList @Suppress("UNCHECKED_CAST") open class VirtualEntity<E : VirtualEntity<E>>(private val uniqueId : String = UUID.randomUUID().toString()) : GenericIdentity<E>() { @Transient private lateinit var collector : VirtualEntityCollector<*> protected fun getEntityCollection() : VirtualEntityCollector<*> = collector @Transient private lateinit var gson : Gson @Transient private val requirementAdapters : List<Class<*>> = ArrayList() private var lastUpdated : Long = -1L fun getUniqueId() : String = uniqueId open fun create() : Boolean = create(this) @Synchronized private fun create(obj : Any) : Boolean { val classes : Array<Class<*>> = VirtualEntityUtil.getClasses(this.javaClass.`package`.name.split(".")[0]) val gsonBuilder = GsonBuilder() try { for (clazz in classes) { clazz.annotations.filterIsInstance<TypeRegister>().forEach { if (getAdapterBaseType(clazz.newInstance().javaClass) != null) { val clazzAdapterType : AdapterBase<*> = clazz.newInstance() as AdapterBase<*> gsonBuilder.registerTypeAdapter(clazzAdapterType.getGenericBaseType(), clazzAdapterType) } } if (VirtualEntityCollector::class.java.isAssignableFrom(clazz) && VirtualEntityCollector::class.java != clazz) { if ((clazz.newInstance() as VirtualEntityCollector<*>).getGenericBaseType() != obj.javaClass) continue val met: Method = clazz.getDeclaredMethod("access\$getCollector\$cp") val referCollection: VirtualEntityCollector<*> = met.invoke(clazz.newInstance()) as VirtualEntityCollector<*> collector = referCollection } } } catch(e : ClassCastException) { return false } collector.register(obj) gson = gsonBuilder.serializeNulls().setPrettyPrinting().create() return true } private fun <C> getAdapterBaseType(clazz : Class<C>) : C? { return if(JsonDeserializer::class.java.isAssignableFrom(clazz) && JsonSerializer::class.java.isAssignableFrom(clazz)) { return clazz.newInstance() } else null } fun serialize() : String { val jsonObject = JsonObject() val element : JsonElement = getJsonElement(gson.toJson(this)) jsonObject.add(this.getGenericBaseType().name, element) return gson.toJson(jsonObject) } private infix fun getJsonElement(json : String) : JsonElement = Gson().fromJson(json, JsonElement::class.java) }
mit
0a28b4a54c73187303cf8c1a8d7ca862
38.467532
131
0.650543
4.957586
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/Typewriter.kt
1
2123
package com.habitrpg.android.habitica.ui.views import android.content.Context import android.os.Handler import androidx.core.content.ContextCompat import android.text.Spannable import android.text.SpannableStringBuilder import android.text.style.ForegroundColorSpan import android.util.AttributeSet import com.habitrpg.android.habitica.R // http://stackoverflow.com/a/6700718/1315039 class Typewriter : androidx.appcompat.widget.AppCompatTextView { private var stringBuilder: SpannableStringBuilder? = null private var visibleSpan: Any? = null private var hiddenSpan: Any? = null private var index: Int = 0 private var delay: Long = 30 private val textHandler = Handler() private val characterAdder = object : Runnable { override fun run() { stringBuilder?.setSpan(visibleSpan, 0, index++, Spannable.SPAN_INCLUSIVE_INCLUSIVE) text = stringBuilder if (index <= stringBuilder?.length ?: 0) { textHandler.postDelayed(this, delay) } } } val isAnimating: Boolean get() = index < stringBuilder?.length ?: 0 constructor(context: Context) : super(context) { setupTextColors(context) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { setupTextColors(context) } private fun setupTextColors(context: Context) { visibleSpan = ForegroundColorSpan(ContextCompat.getColor(context, R.color.textColorLight)) hiddenSpan = ForegroundColorSpan(ContextCompat.getColor(context, R.color.transparent)) } fun animateText(text: CharSequence) { stringBuilder = SpannableStringBuilder(text) stringBuilder?.setSpan(hiddenSpan, 0, stringBuilder?.length ?: 0, Spannable.SPAN_INCLUSIVE_EXCLUSIVE) index = 0 setText(stringBuilder) textHandler.removeCallbacks(characterAdder) textHandler.postDelayed(characterAdder, delay) } fun setCharacterDelay(millis: Long) { delay = millis } fun stopTextAnimation() { index = stringBuilder?.length ?: 0 } }
gpl-3.0
cd940814da9662a30e682635edca53f1
30.220588
109
0.695243
4.665934
false
false
false
false
siosio/intellij-community
platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/EntityWithPersistentIdInPStorageTest.kt
1
4636
// 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 import com.intellij.testFramework.UsefulTestCase.assertEmpty import com.intellij.testFramework.UsefulTestCase.assertOneElement import com.intellij.workspaceModel.storage.entities.* import com.intellij.workspaceModel.storage.impl.WorkspaceEntityStorageBuilderImpl import com.intellij.workspaceModel.storage.impl.exceptions.PersistentIdAlreadyExistsException import org.hamcrest.CoreMatchers import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.ExpectedException class EntityWithPersistentIdInPStorageTest { @JvmField @Rule val expectedException = ExpectedException.none() private lateinit var builder: WorkspaceEntityStorageBuilderImpl @Before fun setUp() { builder = createEmptyBuilder() } @Test fun `add remove entity`() { val foo = builder.addLinkedListEntity("foo", LinkedListEntityId("bar")) builder.assertConsistency() assertNull(foo.next.resolve(builder)) assertNull(foo.next.resolve(builder.toStorage())) val bar = builder.addLinkedListEntity("bar", LinkedListEntityId("baz")) builder.assertConsistency() assertEquals(bar, foo.next.resolve(builder)) assertEquals(bar, foo.next.resolve(builder.toStorage())) builder.removeEntity(bar) builder.assertConsistency() assertNull(foo.next.resolve(builder)) } @Test fun `change target entity name`() { val foo = builder.addLinkedListEntity("foo", LinkedListEntityId("bar")) val bar = builder.addLinkedListEntity("bar", LinkedListEntityId("baz")) builder.assertConsistency() assertEquals(bar, foo.next.resolve(builder)) builder.modifyEntity(ModifiableLinkedListEntity::class.java, bar) { name = "baz" } builder.assertConsistency() assertNull(foo.next.resolve(builder)) } @Test fun `change name in reference`() { val foo = builder.addLinkedListEntity("foo", LinkedListEntityId("bar")) val bar = builder.addLinkedListEntity("bar", LinkedListEntityId("baz")) val baz = builder.addLinkedListEntity("baz", LinkedListEntityId("foo")) builder.assertConsistency() assertEquals(bar, foo.next.resolve(builder)) val newFoo = builder.modifyEntity(ModifiableLinkedListEntity::class.java, foo) { next = LinkedListEntityId("baz") } builder.assertConsistency() assertEquals(baz, newFoo.next.resolve(builder)) } @Test fun `remove child entity with parent entity`() { val parent = builder.addParentEntity("parent") builder.addChildEntity(parent) builder.assertConsistency() builder.removeEntity(parent) builder.assertConsistency() assertEmpty(builder.entities(ChildEntity::class.java).toList()) } @Test fun `add entity with existing persistent id`() { builder = WorkspaceEntityStorageBuilderImpl.create() expectedException.expectCause(CoreMatchers.isA(PersistentIdAlreadyExistsException::class.java)) builder.addNamedEntity("MyName") builder.addNamedEntity("MyName") } @Test fun `add entity with existing persistent id - restoring after exception`() { builder = WorkspaceEntityStorageBuilderImpl.create() try { builder.addNamedEntity("MyName") builder.addNamedEntity("MyName") } catch (e: AssertionError) { assert(e.cause is PersistentIdAlreadyExistsException) assertOneElement(builder.entities(NamedEntity::class.java).toList()) } } @Test fun `modify entity to repeat persistent id`() { builder = WorkspaceEntityStorageBuilderImpl.create() expectedException.expectCause(CoreMatchers.isA(PersistentIdAlreadyExistsException::class.java)) builder.addNamedEntity("MyName") val namedEntity = builder.addNamedEntity("AnotherId") builder.modifyEntity(ModifiableNamedEntity::class.java, namedEntity) { this.name = "MyName" } } @Test fun `modify entity to repeat persistent id - restoring after exception`() { builder = WorkspaceEntityStorageBuilderImpl.create() try { builder.addNamedEntity("MyName") val namedEntity = builder.addNamedEntity("AnotherId") builder.modifyEntity(ModifiableNamedEntity::class.java, namedEntity) { this.name = "MyName" } } catch (e: AssertionError) { assert(e.cause is PersistentIdAlreadyExistsException) assertOneElement(builder.entities(NamedEntity::class.java).toList().filter { it.name == "MyName" }) } } }
apache-2.0
daa2c3d4c9818009eba62b0df87f4bbf
34.945736
140
0.743097
4.711382
false
true
false
false
K0zka/kerub
src/test/kotlin/com/github/kerubistan/kerub/model/alerts/NetworkLinkDownAlertTest.kt
2
631
package com.github.kerubistan.kerub.model.alerts import com.github.kerubistan.kerub.model.AbstractDataRepresentationTest import com.github.kerubistan.kerub.testHost import io.github.kerubistan.kroki.time.now import java.util.UUID.randomUUID internal class NetworkLinkDownAlertTest : AbstractDataRepresentationTest<NetworkLinkDownAlert>() { override val testInstances: Collection<NetworkLinkDownAlert> get() = listOf( NetworkLinkDownAlert( id = randomUUID(), open = true, resolved = null, created = now(), hostId = testHost.id ) ) override val clazz = NetworkLinkDownAlert::class.java }
apache-2.0
52f71e93746ab0466dcdd9a0ba335881
30.6
98
0.763867
3.968553
false
true
false
false
androidx/androidx
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/Surface.kt
3
24255
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3 import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.layout.Box import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.selection.toggleable import androidx.compose.material.ripple.rememberRipple import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.NonRestartableComposable import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.Shape import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp // TODO(b/197880751): Add url to spec on Material.io. /** * Material surface is the central metaphor in material design. Each surface exists at a given * elevation, which influences how that piece of surface visually relates to other surfaces and how * that surface is modified by tonal variance. * * See the other overloads for clickable, selectable, and toggleable surfaces. * * The Surface is responsible for: * * 1) Clipping: Surface clips its children to the shape specified by [shape] * * 2) Borders: If [shape] has a border, then it will also be drawn. * * 3) Background: Surface fills the shape specified by [shape] with the [color]. If [color] is * [ColorScheme.surface] a color overlay will be applied. The color of the overlay depends on the * [tonalElevation] of this Surface, and the [LocalAbsoluteTonalElevation] set by any parent * surfaces. This ensures that a Surface never appears to have a lower elevation overlay than its * ancestors, by summing the elevation of all previous Surfaces. * * 4) Content color: Surface uses [contentColor] to specify a preferred color for the content of * this surface - this is used by the [Text] and [Icon] components as a default color. * * If no [contentColor] is set, this surface will try and match its background color to a color * defined in the theme [ColorScheme], and return the corresponding content color. For example, if * the [color] of this surface is [ColorScheme.surface], [contentColor] will be set to * [ColorScheme.onSurface]. If [color] is not part of the theme palette, [contentColor] will keep * the same value set above this Surface. * * To manually retrieve the content color inside a surface, use [LocalContentColor]. * * 5) Blocking touch propagation behind the surface. * * Surface sample: * @sample androidx.compose.material3.samples.SurfaceSample * * @param modifier Modifier to be applied to the layout corresponding to the surface * @param shape Defines the surface's shape as well its shadow. * @param color The background color. Use [Color.Transparent] to have no color. * @param contentColor The preferred content color provided by this Surface to its children. * Defaults to either the matching content color for [color], or if [color] is not a color from the * theme, this will keep the same value set above this Surface. * @param tonalElevation When [color] is [ColorScheme.surface], a higher the elevation will result * in a darker color in light theme and lighter color in dark theme. * @param shadowElevation The size of the shadow below the surface. To prevent shadow creep, only * apply shadow elevation when absolutely necessary, such as when the surface requires visual * separation from a patterned background. Note that It will not affect z index of the Surface. * If you want to change the drawing order you can use `Modifier.zIndex`. * @param border Optional border to draw on top of the surface */ @Composable @NonRestartableComposable fun Surface( modifier: Modifier = Modifier, shape: Shape = RectangleShape, color: Color = MaterialTheme.colorScheme.surface, contentColor: Color = contentColorFor(color), tonalElevation: Dp = 0.dp, shadowElevation: Dp = 0.dp, border: BorderStroke? = null, content: @Composable () -> Unit ) { val absoluteElevation = LocalAbsoluteTonalElevation.current + tonalElevation CompositionLocalProvider( LocalContentColor provides contentColor, LocalAbsoluteTonalElevation provides absoluteElevation ) { Box( modifier = modifier .surface( shape = shape, backgroundColor = surfaceColorAtElevation( color = color, elevation = absoluteElevation ), border = border, shadowElevation = shadowElevation ) .semantics(mergeDescendants = false) {} .pointerInput(Unit) {}, propagateMinConstraints = true ) { content() } } } /** * Material surface is the central metaphor in material design. Each surface exists at a given * elevation, which influences how that piece of surface visually relates to other surfaces and how * that surface is modified by tonal variance. * * This version of Surface is responsible for a click handling as well as everything else that a * regular Surface does: * * This clickable Surface is responsible for: * * 1) Clipping: Surface clips its children to the shape specified by [shape] * * 2) Borders: If [shape] has a border, then it will also be drawn. * * 3) Background: Surface fills the shape specified by [shape] with the [color]. If [color] is * [ColorScheme.surface] a color overlay may be applied. The color of the overlay depends on the * [tonalElevation] of this Surface, and the [LocalAbsoluteTonalElevation] set by any * parent surfaces. This ensures that a Surface never appears to have a lower elevation overlay than * its ancestors, by summing the elevation of all previous Surfaces. * * 4) Content color: Surface uses [contentColor] to specify a preferred color for the content of * this surface - this is used by the [Text] and [Icon] components as a default color. If no * [contentColor] is set, this surface will try and match its background color to a color defined in * the theme [ColorScheme], and return the corresponding content color. For example, if the [color] * of this surface is [ColorScheme.surface], [contentColor] will be set to [ColorScheme.onSurface]. * If [color] is not part of the theme palette, [contentColor] will keep the same value set above * this Surface. * * 5) Click handling. This version of surface will react to the clicks, calling [onClick] lambda, * updating the [interactionSource] when [PressInteraction] occurs, and showing ripple indication in * response to press events. If you don't need click handling, consider using the Surface function * that doesn't require [onClick] param. If you need to set a custom label for the [onClick], apply * a `Modifier.semantics { onClick(label = "YOUR_LABEL", action = null) }` to the Surface. * * 6) Semantics for clicks. Just like with [Modifier.clickable], clickable version of Surface will * produce semantics to indicate that it is clicked. Also, by default, accessibility services will * describe the element as [Role.Button]. You may change this by passing a desired [Role] with a * [Modifier.semantics]. * * To manually retrieve the content color inside a surface, use [LocalContentColor]. * * Clickable surface sample: * @sample androidx.compose.material3.samples.ClickableSurfaceSample * * @param onClick callback to be called when the surface is clicked * @param modifier Modifier to be applied to the layout corresponding to the surface * @param enabled Controls the enabled state of the surface. When `false`, this surface will not be * clickable * @param shape Defines the surface's shape as well its shadow. A shadow is only displayed if the * [tonalElevation] is greater than zero. * @param color The background color. Use [Color.Transparent] to have no color. * @param contentColor The preferred content color provided by this Surface to its children. * Defaults to either the matching content color for [color], or if [color] is not a color from the * theme, this will keep the same value set above this Surface. * @param border Optional border to draw on top of the surface * @param tonalElevation When [color] is [ColorScheme.surface], a higher the elevation will result * in a darker color in light theme and lighter color in dark theme. * @param shadowElevation The size of the shadow below the surface. Note that It will not affect z * index of the Surface. If you want to change the drawing order you can use `Modifier.zIndex`. * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this Surface. You can create and pass in your own remembered [MutableInteractionSource] if * you want to observe [Interaction]s and customize the appearance / behavior of this Surface in * different [Interaction]s. */ @ExperimentalMaterial3Api @Composable @NonRestartableComposable fun Surface( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = RectangleShape, color: Color = MaterialTheme.colorScheme.surface, contentColor: Color = contentColorFor(color), tonalElevation: Dp = 0.dp, shadowElevation: Dp = 0.dp, border: BorderStroke? = null, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable () -> Unit ) { val absoluteElevation = LocalAbsoluteTonalElevation.current + tonalElevation CompositionLocalProvider( LocalContentColor provides contentColor, LocalAbsoluteTonalElevation provides absoluteElevation ) { Box( modifier = modifier .minimumTouchTargetSize() .surface( shape = shape, backgroundColor = surfaceColorAtElevation( color = color, elevation = absoluteElevation ), border = border, shadowElevation = shadowElevation ) .clickable( interactionSource = interactionSource, indication = rememberRipple(), enabled = enabled, role = Role.Button, onClick = onClick ), propagateMinConstraints = true ) { content() } } } /** * Material surface is the central metaphor in material design. Each surface exists at a given * elevation, which influences how that piece of surface visually relates to other surfaces and how * that surface is modified by tonal variance. * * This version of Surface is responsible for a selection handling as well as everything else that * a regular Surface does: * * This selectable Surface is responsible for: * * 1) Clipping: Surface clips its children to the shape specified by [shape] * * 2) Borders: If [shape] has a border, then it will also be drawn. * * 3) Background: Surface fills the shape specified by [shape] with the [color]. If [color] is * [ColorScheme.surface] a color overlay may be applied. The color of the overlay depends on the * [tonalElevation] of this Surface, and the [LocalAbsoluteTonalElevation] set by any * parent surfaces. This ensures that a Surface never appears to have a lower elevation overlay than * its ancestors, by summing the elevation of all previous Surfaces. * * 4) Content color: Surface uses [contentColor] to specify a preferred color for the content of * this surface - this is used by the [Text] and [Icon] components as a default color. If no * [contentColor] is set, this surface will try and match its background color to a color defined in * the theme [ColorScheme], and return the corresponding content color. For example, if the [color] * of this surface is [ColorScheme.surface], [contentColor] will be set to [ColorScheme.onSurface]. * If [color] is not part of the theme palette, [contentColor] will keep the same value set above * this Surface. * * 5) Click handling. This version of surface will react to the clicks, calling [onClick] lambda, * updating the [interactionSource] when [PressInteraction] occurs, and showing ripple indication in * response to press events. If you don't need click handling, consider using the Surface function * that doesn't require [onClick] param. * * 6) Semantics for selection. Just like with [Modifier.selectable], selectable version of Surface * will produce semantics to indicate that it is selected. Also, by default, accessibility services * will describe the element as [Role.Tab]. You may change this by passing a desired [Role] with a * [Modifier.semantics]. * * To manually retrieve the content color inside a surface, use [LocalContentColor]. * * Selectable surface sample: * @sample androidx.compose.material3.samples.SelectableSurfaceSample * * @param selected whether or not this Surface is selected * @param onClick callback to be called when the surface is clicked * @param modifier Modifier to be applied to the layout corresponding to the surface * @param enabled Controls the enabled state of the surface. When `false`, this surface will not be * clickable * @param shape Defines the surface's shape as well its shadow. A shadow is only displayed if the * [tonalElevation] is greater than zero. * @param color The background color. Use [Color.Transparent] to have no color. * @param contentColor The preferred content color provided by this Surface to its children. * Defaults to either the matching content color for [color], or if [color] is not a color from the * theme, this will keep the same value set above this Surface. * @param border Optional border to draw on top of the surface * @param tonalElevation When [color] is [ColorScheme.surface], a higher the elevation will result * in a darker color in light theme and lighter color in dark theme. * @param shadowElevation The size of the shadow below the surface. Note that It will not affect z * index of the Surface. If you want to change the drawing order you can use `Modifier.zIndex`. * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this Surface. You can create and pass in your own remembered [MutableInteractionSource] if * you want to observe [Interaction]s and customize the appearance / behavior of this Surface in * different [Interaction]s. */ @ExperimentalMaterial3Api @Composable @NonRestartableComposable fun Surface( selected: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = RectangleShape, color: Color = MaterialTheme.colorScheme.surface, contentColor: Color = contentColorFor(color), tonalElevation: Dp = 0.dp, shadowElevation: Dp = 0.dp, border: BorderStroke? = null, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable () -> Unit ) { val absoluteElevation = LocalAbsoluteTonalElevation.current + tonalElevation CompositionLocalProvider( LocalContentColor provides contentColor, LocalAbsoluteTonalElevation provides absoluteElevation ) { Box( modifier = modifier .minimumTouchTargetSize() .surface( shape = shape, backgroundColor = surfaceColorAtElevation( color = color, elevation = absoluteElevation ), border = border, shadowElevation = shadowElevation ) .selectable( selected = selected, interactionSource = interactionSource, indication = rememberRipple(), enabled = enabled, role = Role.Tab, onClick = onClick ), propagateMinConstraints = true ) { content() } } } /** * Material surface is the central metaphor in material design. Each surface exists at a given * elevation, which influences how that piece of surface visually relates to other surfaces and how * that surface is modified by tonal variance. * * This version of Surface is responsible for a toggling its checked state as well as everything * else that a regular Surface does: * * This toggleable Surface is responsible for: * * 1) Clipping: Surface clips its children to the shape specified by [shape] * * 2) Borders: If [shape] has a border, then it will also be drawn. * * 3) Background: Surface fills the shape specified by [shape] with the [color]. If [color] is * [ColorScheme.surface] a color overlay may be applied. The color of the overlay depends on the * [tonalElevation] of this Surface, and the [LocalAbsoluteTonalElevation] set by any * parent surfaces. This ensures that a Surface never appears to have a lower elevation overlay than * its ancestors, by summing the elevation of all previous Surfaces. * * 4) Content color: Surface uses [contentColor] to specify a preferred color for the content of * this surface - this is used by the [Text] and [Icon] components as a default color. If no * [contentColor] is set, this surface will try and match its background color to a color defined in * the theme [ColorScheme], and return the corresponding content color. For example, if the [color] * of this surface is [ColorScheme.surface], [contentColor] will be set to [ColorScheme.onSurface]. * If [color] is not part of the theme palette, [contentColor] will keep the same value set above * this Surface. * * 5) Click handling. This version of surface will react to the check toggles, calling * [onCheckedChange] lambda, updating the [interactionSource] when [PressInteraction] occurs, and * showing ripple indication in response to press events. If you don't need check * handling, consider using a Surface function that doesn't require [onCheckedChange] param. * * 6) Semantics for toggle. Just like with [Modifier.toggleable], toggleable version of Surface * will produce semantics to indicate that it is checked. Also, by default, accessibility services * will describe the element as [Role.Switch]. You may change this by passing a desired [Role] with * a [Modifier.semantics]. * * To manually retrieve the content color inside a surface, use [LocalContentColor]. * * Toggleable surface sample: * @sample androidx.compose.material3.samples.ToggleableSurfaceSample * * @param checked whether or not this Surface is toggled on or off * @param onCheckedChange callback to be invoked when the toggleable Surface is clicked * @param modifier Modifier to be applied to the layout corresponding to the surface * @param enabled Controls the enabled state of the surface. When `false`, this surface will not be * clickable * @param shape Defines the surface's shape as well its shadow. A shadow is only displayed if the * [tonalElevation] is greater than zero. * @param color The background color. Use [Color.Transparent] to have no color. * @param contentColor The preferred content color provided by this Surface to its children. * Defaults to either the matching content color for [color], or if [color] is not a color from the * theme, this will keep the same value set above this Surface. * @param border Optional border to draw on top of the surface * @param tonalElevation When [color] is [ColorScheme.surface], a higher the elevation will result * in a darker color in light theme and lighter color in dark theme. * @param shadowElevation The size of the shadow below the surface. Note that It will not affect z * index of the Surface. If you want to change the drawing order you can use `Modifier.zIndex`. * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this Surface. You can create and pass in your own remembered [MutableInteractionSource] if * you want to observe [Interaction]s and customize the appearance / behavior of this Surface in * different [Interaction]s. */ @ExperimentalMaterial3Api @Composable @NonRestartableComposable fun Surface( checked: Boolean, onCheckedChange: (Boolean) -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = RectangleShape, color: Color = MaterialTheme.colorScheme.surface, contentColor: Color = contentColorFor(color), tonalElevation: Dp = 0.dp, shadowElevation: Dp = 0.dp, border: BorderStroke? = null, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable () -> Unit ) { val absoluteElevation = LocalAbsoluteTonalElevation.current + tonalElevation CompositionLocalProvider( LocalContentColor provides contentColor, LocalAbsoluteTonalElevation provides absoluteElevation ) { Box( modifier = modifier .minimumTouchTargetSize() .surface( shape = shape, backgroundColor = surfaceColorAtElevation( color = color, elevation = absoluteElevation ), border = border, shadowElevation = shadowElevation ) .toggleable( value = checked, interactionSource = interactionSource, indication = rememberRipple(), enabled = enabled, role = Role.Switch, onValueChange = onCheckedChange ), propagateMinConstraints = true ) { content() } } } private fun Modifier.surface( shape: Shape, backgroundColor: Color, border: BorderStroke?, shadowElevation: Dp ) = this.shadow(shadowElevation, shape, clip = false) .then(if (border != null) Modifier.border(border, shape) else Modifier) .background(color = backgroundColor, shape = shape) .clip(shape) @Composable private fun surfaceColorAtElevation(color: Color, elevation: Dp): Color { return if (color == MaterialTheme.colorScheme.surface) { MaterialTheme.colorScheme.surfaceColorAtElevation(elevation) } else { color } } /** * CompositionLocal containing the current absolute elevation provided by [Surface] components. This * absolute elevation is a sum of all the previous elevations. Absolute elevation is only used for * calculating surface tonal colors, and is *not* used for drawing the shadow in a [Surface]. */ // TODO(b/179787782): Add sample after catalog app lands in aosp. val LocalAbsoluteTonalElevation = compositionLocalOf { 0.dp }
apache-2.0
e1617eb90be26415a4819b4592fcf001
47.90121
100
0.715976
4.762419
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/IDELightClassContexts.kt
2
22259
// 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.caches.lightClasses import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.psi.search.EverythingGlobalScope import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.stubs.StubIndex import org.jetbrains.kotlin.asJava.builder.LightClassConstructionContext import org.jetbrains.kotlin.config.JvmTarget import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.container.get import org.jetbrains.kotlin.container.useImpl import org.jetbrains.kotlin.container.useInstance import org.jetbrains.kotlin.context.ModuleContext import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.descriptors.impl.CompositePackageFragmentProvider import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl import org.jetbrains.kotlin.frontend.di.configureModule import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.caches.lightClasses.IDELightClassConstructionContext.Mode.EXACT import org.jetbrains.kotlin.idea.caches.lightClasses.IDELightClassConstructionContext.Mode.LIGHT import org.jetbrains.kotlin.idea.caches.lightClasses.annotations.KOTLINX_SERIALIZABLE_FQ_NAME import org.jetbrains.kotlin.idea.caches.lightClasses.annotations.KOTLINX_SERIALIZER_FQ_NAME import org.jetbrains.kotlin.idea.caches.project.getModuleInfo import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.compiler.IDELanguageSettingsProvider import org.jetbrains.kotlin.idea.project.IdeaEnvironment import org.jetbrains.kotlin.idea.project.ResolveElementCache import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.stubindex.KotlinOverridableInternalMembersShortNameIndex import org.jetbrains.kotlin.incremental.components.ExpectActualTracker import org.jetbrains.kotlin.incremental.components.LookupTracker import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.resolve.* import org.jetbrains.kotlin.resolve.calls.CallResolver import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext import org.jetbrains.kotlin.resolve.calls.context.CheckArgumentTypesMode import org.jetbrains.kotlin.resolve.calls.context.ContextDependency import org.jetbrains.kotlin.resolve.calls.results.OverloadResolutionResults import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfoFactory import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory import org.jetbrains.kotlin.resolve.calls.util.CallMaker import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.jvm.annotations.JVM_SYNTHETIC_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatformAnalyzerServices import org.jetbrains.kotlin.resolve.lazy.FileScopeProviderImpl import org.jetbrains.kotlin.resolve.lazy.ForceResolveUtil import org.jetbrains.kotlin.resolve.lazy.ResolveSession import org.jetbrains.kotlin.resolve.lazy.declarations.FileBasedDeclarationProviderFactory import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.storage.LockBasedStorageManager import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.types.ErrorUtils import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.WrappedTypeFactory import org.jetbrains.kotlin.utils.sure class IDELightClassConstructionContext( bindingContext: BindingContext, module: ModuleDescriptor, languageVersionSettings: LanguageVersionSettings, jvmTarget: JvmTarget, val mode: Mode ) : LightClassConstructionContext(bindingContext, module, languageVersionSettings, jvmTarget) { enum class Mode { LIGHT, EXACT } override fun toString() = "${this.javaClass.simpleName}:$mode" } internal object IDELightClassContexts { private val LOG = Logger.getInstance(this::class.java) fun contextForNonLocalClassOrObject(classOrObject: KtClassOrObject): LightClassConstructionContext { val resolutionFacade = classOrObject.getResolutionFacade() val bindingContext = if (classOrObject is KtClass && classOrObject.isAnnotation()) { // need to make sure default values for parameters are resolved // because java resolve depends on whether there is a default value for an annotation attribute @OptIn(FrontendInternals::class) resolutionFacade.getFrontendService(ResolveElementCache::class.java) .resolvePrimaryConstructorParametersDefaultValues(classOrObject) } else { resolutionFacade.analyze(classOrObject) } val classDescriptor = bindingContext.get(BindingContext.CLASS, classOrObject).sure { "Class descriptor was not found for ${classOrObject.getElementTextWithContext()}" } ForceResolveUtil.forceResolveAllContents(classDescriptor) return IDELightClassConstructionContext( bindingContext, resolutionFacade.moduleDescriptor, classOrObject.languageVersionSettings, resolutionFacade.jvmTarget, EXACT ) } fun contextForLocalClassOrObject(classOrObject: KtClassOrObject): LightClassConstructionContext { val resolutionFacade = classOrObject.getResolutionFacade() val bindingContext = resolutionFacade.analyze(classOrObject) val descriptor = bindingContext.get(BindingContext.CLASS, classOrObject) if (descriptor == null) { LOG.warn("No class descriptor in context for class: " + classOrObject.getElementTextWithContext()) return IDELightClassConstructionContext( bindingContext, resolutionFacade.moduleDescriptor, classOrObject.languageVersionSettings, resolutionFacade.jvmTarget, EXACT ) } ForceResolveUtil.forceResolveAllContents(descriptor) return IDELightClassConstructionContext( bindingContext, resolutionFacade.moduleDescriptor, classOrObject.languageVersionSettings, resolutionFacade.jvmTarget, EXACT ) } fun contextForFacade(files: List<KtFile>): LightClassConstructionContext { val resolutionFacade = files.first().getResolutionFacade() @OptIn(FrontendInternals::class) val resolveSession = resolutionFacade.getFrontendService(ResolveSession::class.java) forceResolvePackageDeclarations(files, resolveSession) return IDELightClassConstructionContext( resolveSession.bindingContext, resolveSession.moduleDescriptor, files.first().languageVersionSettings, resolutionFacade.jvmTarget, EXACT ) } fun contextForScript(script: KtScript): LightClassConstructionContext { val resolutionFacade = script.getResolutionFacade() val bindingContext = resolutionFacade.analyze(script) val descriptor = bindingContext[BindingContext.SCRIPT, script] if (descriptor == null) { LOG.warn("No script descriptor in context for script: " + script.getElementTextWithContext()) return IDELightClassConstructionContext( bindingContext, resolutionFacade.moduleDescriptor, script.languageVersionSettings, resolutionFacade.jvmTarget, EXACT ) } ForceResolveUtil.forceResolveAllContents(descriptor) return IDELightClassConstructionContext( bindingContext, resolutionFacade.moduleDescriptor, script.languageVersionSettings, resolutionFacade.jvmTarget, EXACT ) } fun lightContextForClassOrObject(classOrObject: KtClassOrObject): LightClassConstructionContext? { if (!isDummyResolveApplicable(classOrObject)) return null val resolutionFacade = classOrObject.getResolutionFacade() val resolveSession = setupAdHocResolve( classOrObject.project, resolutionFacade.moduleDescriptor, listOf(classOrObject.containingKtFile) ) val descriptor = resolveSession.resolveToDescriptor(classOrObject) as? ClassDescriptor ?: return null if (!isDummyResolveApplicableByDescriptor(descriptor)) return null ForceResolveUtil.forceResolveAllContents(descriptor) return IDELightClassConstructionContext( resolveSession.bindingContext, resolveSession.moduleDescriptor, classOrObject.languageVersionSettings, resolutionFacade.jvmTarget, LIGHT ) } fun lightContextForFacade(files: List<KtFile>): LightClassConstructionContext { val representativeFile = files.first() val resolutionFacade = representativeFile.getResolutionFacade() val resolveSession = setupAdHocResolve(representativeFile.project, resolutionFacade.moduleDescriptor, files) forceResolvePackageDeclarations(files, resolveSession) return IDELightClassConstructionContext( resolveSession.bindingContext, resolveSession.moduleDescriptor, files.first().languageVersionSettings, resolutionFacade.jvmTarget, LIGHT ) } @OptIn(FrontendInternals::class) private val ResolutionFacade.jvmTarget: JvmTarget get() = getFrontendService(JvmTarget::class.java) private fun isDummyResolveApplicable(classOrObject: KtClassOrObject): Boolean { if (classOrObject.hasModifier(KtTokens.INLINE_KEYWORD)) return false if (classOrObject.hasLightClassMatchingErrors) return false if (hasDelegatedSupertypes(classOrObject)) return false if (isDataClassWithGeneratedMembersOverridden(classOrObject)) return false if (isDataClassWhichExtendsOtherClass(classOrObject)) return false if (hasMembersOverridingInternalMembers(classOrObject)) return false if (hasSerializationLikeAnnotations(classOrObject)) return false if (hasJvmSyntheticMembers(classOrObject)) return false return classOrObject.declarations.filterIsInstance<KtClassOrObject>().all { isDummyResolveApplicable(it) } } private fun hasSerializationLikeAnnotations(classOrObject: KtClassOrObject) = classOrObject.annotationEntries.any { isSerializableOrSerializerShortName(it.shortName) } private fun isDummyResolveApplicableByDescriptor(classDescriptor: ClassDescriptor): Boolean { if (classDescriptor.annotations.any { isSerializableOrSerializerFqName(it.fqName) }) return false return classDescriptor .unsubstitutedInnerClassesScope .getContributedDescriptors() .filterIsInstance<ClassDescriptor>() .all(::isDummyResolveApplicableByDescriptor) } private fun isSerializableOrSerializerShortName(shortName: Name?) = shortName == KOTLINX_SERIALIZABLE_FQ_NAME.shortName() || shortName == KOTLINX_SERIALIZER_FQ_NAME.shortName() private fun isSerializableOrSerializerFqName(fqName: FqName?) = fqName == KOTLINX_SERIALIZABLE_FQ_NAME || fqName == KOTLINX_SERIALIZER_FQ_NAME private fun hasJvmSyntheticMembers(classOrObject: KtClassOrObject) = classOrObject.declarations.filterIsInstance<KtFunction>().any { isJvmSynthetic(it) } private fun isJvmSynthetic(fn: KtFunction) = fn.annotationEntries.any { it.shortName == JVM_SYNTHETIC_ANNOTATION_FQ_NAME.shortName() } private fun hasDelegatedSupertypes(classOrObject: KtClassOrObject) = classOrObject.superTypeListEntries.any { it is KtDelegatedSuperTypeEntry } private fun isDataClassWithGeneratedMembersOverridden(classOrObject: KtClassOrObject): Boolean { return classOrObject.hasModifier(KtTokens.DATA_KEYWORD) && classOrObject.declarations.filterIsInstance<KtFunction>().any { isGeneratedForDataClass(it.nameAsSafeName) } } private fun isGeneratedForDataClass(name: Name): Boolean { return name == FunctionsFromAny.EQUALS_METHOD_NAME || // known failure is related to equals override, checking for other methods 'just in case' name == DataClassDescriptorResolver.COPY_METHOD_NAME || name == FunctionsFromAny.HASH_CODE_METHOD_NAME || name == FunctionsFromAny.TO_STRING_METHOD_NAME || DataClassDescriptorResolver.isComponentLike(name) } private fun isDataClassWhichExtendsOtherClass(classOrObject: KtClassOrObject): Boolean { return classOrObject.hasModifier(KtTokens.DATA_KEYWORD) && classOrObject.superTypeListEntries.isNotEmpty() } private fun hasMembersOverridingInternalMembers(classOrObject: KtClassOrObject): Boolean { return classOrObject.declarations.filterIsInstance<KtCallableDeclaration>().any { possiblyOverridesInternalMember(it) } } private fun possiblyOverridesInternalMember(declaration: KtCallableDeclaration): Boolean { if (!declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return false return declaration.name?.let { anyInternalMembersWithThisName(it, declaration.project) } ?: false } private fun anyInternalMembersWithThisName(name: String, project: Project): Boolean { var result = false StubIndex.getInstance().processElements( KotlinOverridableInternalMembersShortNameIndex.Instance.key, name, project, EverythingGlobalScope(project), KtCallableDeclaration::class.java ) { result = true false // stop processing at first matching result } return result } fun forceResolvePackageDeclarations(files: Collection<KtFile>, session: ResolveSession) { for (file in files) { if (file.isScript()) continue val packageFqName = file.packageFqName // make sure we create a package descriptor val packageDescriptor = session.moduleDescriptor.getPackage(packageFqName) if (packageDescriptor.isEmpty()) { LOG.warn("No descriptor found for package " + packageFqName + " in file " + file.name + "\n" + file.text) session.forceResolveAll() continue } for (declaration in file.declarations) { when (declaration) { is KtFunction -> { val name = declaration.nameAsSafeName val functions = packageDescriptor.memberScope.getContributedFunctions(name, NoLookupLocation.FROM_IDE) for (descriptor in functions) { ForceResolveUtil.forceResolveAllContents(descriptor) } } is KtProperty -> { val name = declaration.nameAsSafeName val properties = packageDescriptor.memberScope.getContributedVariables(name, NoLookupLocation.FROM_IDE) for (descriptor in properties) { ForceResolveUtil.forceResolveAllContents(descriptor) } } is KtClassOrObject, is KtTypeAlias, is KtDestructuringDeclaration -> { // Do nothing: we are not interested in classes or type aliases, // and all destructuring declarations are erroneous at top level } else -> LOG.error("Unsupported declaration kind: " + declaration + " in file " + file.name + "\n" + file.text) } } ForceResolveUtil.forceResolveAllContents(session.getFileAnnotations(file)) } } private fun setupAdHocResolve(project: Project, realWorldModule: ModuleDescriptor, files: List<KtFile>): ResolveSession { val trace = BindingTraceContext() val sm = LockBasedStorageManager.NO_LOCKS val moduleDescriptor = ModuleDescriptorImpl(realWorldModule.name, sm, realWorldModule.builtIns, stableName = realWorldModule.stableName) moduleDescriptor.setDependencies(moduleDescriptor, moduleDescriptor.builtIns.builtInsModule) val moduleInfo = files.first().getModuleInfo() val container = createContainer("LightClassStub", JvmPlatformAnalyzerServices) { val jvmTarget = IDELanguageSettingsProvider.getTargetPlatform(moduleInfo, project) as? JvmTarget ?: JvmTarget.DEFAULT configureModule( ModuleContext(moduleDescriptor, project, "ad hoc resolve"), JvmPlatforms.jvmPlatformByTargetVersion(jvmTarget), JvmPlatformAnalyzerServices, trace, IDELanguageSettingsProvider.getLanguageVersionSettings(moduleInfo, project) ) useInstance(GlobalSearchScope.EMPTY_SCOPE) useInstance(LookupTracker.DO_NOTHING) useInstance(ExpectActualTracker.DoNothing) useImpl<FileScopeProviderImpl>() useInstance(FileBasedDeclarationProviderFactory(sm, files)) useInstance(CodegenAffectingAnnotations(realWorldModule)) useImpl<AdHocAnnotationResolver>() useInstance(object : WrappedTypeFactory(sm) { override fun createDeferredType(trace: BindingTrace, computation: () -> KotlinType) = errorType() override fun createRecursionIntolerantDeferredType(trace: BindingTrace, computation: () -> KotlinType) = errorType() private fun errorType() = ErrorUtils.createErrorType("Error type in ad hoc resolve for lighter classes") }) IdeaEnvironment.configure(this) useImpl<ResolveSession>() } val resolveSession = container.get<ResolveSession>() moduleDescriptor.initialize(CompositePackageFragmentProvider(listOf(resolveSession.packageFragmentProvider))) return resolveSession } class CodegenAffectingAnnotations(private val realModule: ModuleDescriptor) { fun get(name: String): ClassDescriptor? { val annotationFqName = annotationsThatAffectCodegen.firstOrNull { it.shortName().asString() == name } ?: return null return realModule.getPackage(annotationFqName.parent()).memberScope .getContributedClassifier(annotationFqName.shortName(), NoLookupLocation.FROM_IDE) as? ClassDescriptor } // see JvmPlatformAnnotations.kt, JvmFlagAnnotations.kt, also PsiModifier.MODIFIERS private val annotationsThatAffectCodegen = listOf( "JvmField", "JvmOverloads", "JvmName", "JvmStatic", "Synchronized", "Transient", "Volatile", "Strictfp" ).map { FqName("kotlin.jvm").child(Name.identifier(it)) } + FqName("kotlin.PublishedApi") + FqName("kotlin.Deprecated") + FqName("kotlin.internal.InlineOnly") + FqName("kotlinx.android.parcel.Parcelize") + KOTLINX_SERIALIZABLE_FQ_NAME + KOTLINX_SERIALIZER_FQ_NAME } class AdHocAnnotationResolver( private val codegenAffectingAnnotations: CodegenAffectingAnnotations, private val callResolver: CallResolver, private val languageVersionSettings: LanguageVersionSettings, private val dataFlowValueFactory: DataFlowValueFactory, constantExpressionEvaluator: ConstantExpressionEvaluator, storageManager: StorageManager ) : AnnotationResolverImpl(callResolver, constantExpressionEvaluator, storageManager) { override fun resolveAnnotationType(scope: LexicalScope, entryElement: KtAnnotationEntry, trace: BindingTrace): KotlinType { return annotationClassByEntry(entryElement)?.defaultType ?: super.resolveAnnotationType(scope, entryElement, trace) } private fun annotationClassByEntry(entryElement: KtAnnotationEntry): ClassDescriptor? { val annotationTypeReferencePsi = entryElement.calleeExpression?.constructorReferenceExpression ?: return null val referencedName = annotationTypeReferencePsi.getReferencedName() return codegenAffectingAnnotations.get(referencedName) } override fun resolveAnnotationCall( annotationEntry: KtAnnotationEntry, scope: LexicalScope, trace: BindingTrace ): OverloadResolutionResults<FunctionDescriptor> { val annotationConstructor = annotationClassByEntry(annotationEntry)?.constructors?.singleOrNull() ?: return super.resolveAnnotationCall(annotationEntry, scope, trace) @Suppress("UNCHECKED_CAST") return callResolver.resolveConstructorCall( BasicCallResolutionContext.create( trace, scope, CallMaker.makeCall(null, null, annotationEntry), TypeUtils.NO_EXPECTED_TYPE, DataFlowInfoFactory.EMPTY, ContextDependency.INDEPENDENT, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS, true, languageVersionSettings, dataFlowValueFactory ), annotationEntry.calleeExpression!!.constructorReferenceExpression!!, annotationConstructor.returnType ) as OverloadResolutionResults<FunctionDescriptor> } } }
apache-2.0
77b18aae1c2a226f8297e33f353e9d0b
46.766094
158
0.71899
5.771066
false
false
false
false
smmribeiro/intellij-community
plugins/ide-features-trainer/src/training/featuresSuggester/listeners/EditorActionsListener.kt
1
7443
package training.featuresSuggester.listeners import com.intellij.codeInsight.completion.actions.CodeCompletionAction import com.intellij.codeInsight.lookup.impl.actions.ChooseItemAction import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.AnActionResult import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.ex.AnActionListener import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.actions.* import com.intellij.openapi.ide.CopyPasteManager import training.featuresSuggester.actions.* import training.featuresSuggester.asString import training.featuresSuggester.getSelection import training.featuresSuggester.handleAction import training.featuresSuggester.isActionsProcessingEnabled class EditorActionsListener : AnActionListener { override fun afterActionPerformed(action: AnAction, event: AnActionEvent, result: AnActionResult) { if (!isActionsProcessingEnabled || !action.isSupportedAction()) return val editor = event.getData(CommonDataKeys.EDITOR) ?: return val project = event.getData(CommonDataKeys.PROJECT) ?: return val psiFile = event.getData(CommonDataKeys.PSI_FILE) ?: return when (action) { is CopyAction -> { val copiedText = CopyPasteManager.getInstance().contents?.asString() ?: return handleAction( project, EditorCopyAction( text = copiedText, editor = editor, psiFile = psiFile, timeMillis = System.currentTimeMillis() ) ) } is CutAction -> { val text = CopyPasteManager.getInstance().contents?.asString() ?: return handleAction( project, EditorCutAction( text = text, editor = editor, psiFile = psiFile, timeMillis = System.currentTimeMillis() ) ) } is PasteAction -> { val pastedText = CopyPasteManager.getInstance().contents?.asString() ?: return val caretOffset = editor.getCaretOffset() handleAction( project, EditorPasteAction( text = pastedText, caretOffset = caretOffset, editor = editor, psiFile = psiFile, timeMillis = System.currentTimeMillis() ) ) } is BackspaceAction -> { handleAction( project, EditorBackspaceAction( textFragment = editor.getSelection(), caretOffset = editor.getCaretOffset(), editor = editor, psiFile = psiFile, timeMillis = System.currentTimeMillis() ) ) } is IncrementalFindAction -> { handleAction( project, EditorFindAction( editor = editor, psiFile = psiFile, timeMillis = System.currentTimeMillis() ) ) } is CodeCompletionAction -> { handleAction( project, EditorCodeCompletionAction( caretOffset = editor.caretModel.offset, editor = editor, psiFile = psiFile, timeMillis = System.currentTimeMillis() ) ) } is ChooseItemAction.FocusedOnly -> { handleAction( project, CompletionChooseItemAction( caretOffset = editor.caretModel.offset, editor = editor, psiFile = psiFile, timeMillis = System.currentTimeMillis() ) ) } is EscapeAction -> { handleAction( project, EditorEscapeAction( caretOffset = editor.caretModel.offset, editor = editor, psiFile = psiFile, timeMillis = System.currentTimeMillis() ) ) } } } override fun beforeActionPerformed(action: AnAction, event: AnActionEvent) { if (!isActionsProcessingEnabled || !action.isSupportedAction()) return val editor = event.getData(CommonDataKeys.EDITOR) ?: return val project = event.getData(CommonDataKeys.PROJECT) ?: return val psiFile = event.getData(CommonDataKeys.PSI_FILE) ?: return when (action) { is CopyAction -> { val selectedText = editor.getSelectedText() ?: return handleAction( project, BeforeEditorCopyAction( text = selectedText, editor = editor, psiFile = psiFile, timeMillis = System.currentTimeMillis() ) ) } is CutAction -> { handleAction( project, BeforeEditorCutAction( textFragment = editor.getSelection(), editor = editor, psiFile = psiFile, timeMillis = System.currentTimeMillis() ) ) } is PasteAction -> { val pastedText = CopyPasteManager.getInstance().contents?.asString() ?: return val caretOffset = editor.getCaretOffset() handleAction( project, BeforeEditorPasteAction( text = pastedText, caretOffset = caretOffset, editor = editor, psiFile = psiFile, timeMillis = System.currentTimeMillis() ) ) } is BackspaceAction -> { handleAction( project, BeforeEditorBackspaceAction( textFragment = editor.getSelection(), caretOffset = editor.getCaretOffset(), editor = editor, psiFile = psiFile, timeMillis = System.currentTimeMillis() ) ) } is IncrementalFindAction -> { handleAction( project, BeforeEditorFindAction( editor = editor, psiFile = psiFile, timeMillis = System.currentTimeMillis() ) ) } is CodeCompletionAction -> { handleAction( project, BeforeEditorCodeCompletionAction( caretOffset = editor.caretModel.offset, editor = editor, psiFile = psiFile, timeMillis = System.currentTimeMillis() ) ) } is ChooseItemAction.FocusedOnly -> { handleAction( project, BeforeCompletionChooseItemAction( caretOffset = editor.caretModel.offset, editor = editor, psiFile = psiFile, timeMillis = System.currentTimeMillis() ) ) } is EscapeAction -> { handleAction( project, BeforeEditorEscapeAction( caretOffset = editor.caretModel.offset, editor = editor, psiFile = psiFile, timeMillis = System.currentTimeMillis() ) ) } } } private fun Editor.getSelectedText(): String? { return selectionModel.selectedText } private fun Editor.getCaretOffset(): Int { return caretModel.offset } private fun AnAction.isSupportedAction(): Boolean { return this is CopyAction || this is CutAction || this is PasteAction || this is BackspaceAction || this is IncrementalFindAction || this is CodeCompletionAction || this is ChooseItemAction.FocusedOnly || this is EscapeAction } }
apache-2.0
7a60caec8fdfd56c7536101d3303c2d6
30.405063
101
0.592234
5.638636
false
false
false
false
TimePath/launcher
src/main/kotlin/com/timepath/swing/ThemeSelector.kt
1
2565
package com.timepath.swing import com.timepath.launcher.LauncherUtils import java.awt.Window import java.awt.event.ActionEvent import java.awt.event.ActionListener import java.util.logging.Level import java.util.logging.Logger import javax.swing.* public class ThemeSelector : JComboBox<String>() { init { val model = DefaultComboBoxModel<String>() setModel(model) val currentLafClass = UIManager.getLookAndFeel().javaClass.getName() for (lafInfo in UIManager.getInstalledLookAndFeels()) { try { Class.forName(lafInfo.getClassName()) } catch (ignored: ClassNotFoundException) { continue // Registered but not found on classpath } val name = lafInfo.getName() model.addElement(name) if (lafInfo.getClassName() == currentLafClass) { model.setSelectedItem(name) } } addActionListener(object : ActionListener { override fun actionPerformed(evt: ActionEvent) { val target = model.getSelectedItem() as String for (info in UIManager.getInstalledLookAndFeels()) { if (target == info.getName()) { LOG.log(Level.INFO, "Setting L&F: {0}", info.getClassName()) try { val usrTheme = info.getClassName() UIManager.setLookAndFeel(usrTheme) for (w in Window.getWindows()) { // TODO: Instrumentation to access detached components SwingUtilities.updateComponentTreeUI(w) } LauncherUtils.SETTINGS.put("laf", usrTheme) return } catch (e: InstantiationException) { LOG.log(Level.SEVERE, null, e) } catch (e: IllegalAccessException) { LOG.log(Level.SEVERE, null, e) } catch (e: UnsupportedLookAndFeelException) { LOG.log(Level.SEVERE, null, e) } catch (e: ClassNotFoundException) { LOG.log(Level.WARNING, "Unable to load user L&F", e) } } } } }) } companion object { private val LOG = Logger.getLogger(javaClass<ThemeSelector>().getName()) } }
artistic-2.0
c8139ab57a3c2b153d250a0685148032
38.461538
86
0.517349
5.457447
false
false
false
false
mewebstudio/Kotlin101
src/Functions/Infix.kt
1
556
package Kotlin101.Functions.Infix public fun main(args : Array<String>){ //using a function val say = "Hello " add "world" //infix function call println(say) val say2 = "Hello ".add("world 2") println(say2) //using a method val hello = HelloWorld() var say3 = hello say "world 3" println(say3) var say4 = hello.say("world 4") println(say4) } fun String.add(more : String) : String = this + more class HelloWorld(){ fun say(more : String) : String{ return "Hello " + more } }
bsd-3-clause
beb1be55a78a409b129c8e53b3586cff
19.384615
55
0.597122
3.453416
false
false
false
false
egf2-guide/guide-android
app/src/main/kotlin/com/eigengraph/egf2/guide/ui/anko/CommentItemUI.kt
1
1609
package com.eigengraph.egf2.guide.ui.anko import android.graphics.Color import android.text.TextUtils import android.view.Gravity import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import com.eigengraph.egf2.guide.R import org.jetbrains.anko.* import org.jetbrains.anko.appcompat.v7.tintedTextView class CommentItemUI { fun bind(parent: ViewGroup): View = parent.context.UI { verticalLayout { val p = dip(8) lparams(width = matchParent, height = wrapContent) tintedTextView { id = R.id.post_item_creator singleLine = true ellipsize = TextUtils.TruncateAt.END topPadding = p leftPadding = p rightPadding = p textSize = 12f }.lparams(width = matchParent, height = wrapContent) tintedTextView { id = R.id.post_item_text singleLine = true ellipsize = TextUtils.TruncateAt.END leftPadding = p rightPadding = p textSize = 16f }.lparams(width = matchParent, height = wrapContent) { bottomMargin = dip(24) } linearLayout { orientation = LinearLayout.HORIZONTAL gravity = Gravity.RIGHT button { text = "EDIT" padding = dip(4) id = R.id.comment_item_edit }.lparams(wrapContent, dip(36)) button { text = "DELETE" padding = dip(4) id = R.id.comment_item_delete }.lparams(wrapContent, dip(36)) }.lparams(width = matchParent, height = wrapContent) view { backgroundColor = Color.LTGRAY }.lparams(width = matchParent, height = dip(1)) } }.view }
mit
19c39aad7da10fc4ebec538d4e3ab57f
27.245614
59
0.655065
3.724537
false
false
false
false
DuckDeck/AndroidDemo
app/src/main/java/stan/androiddemo/project/petal/Module/Search/SearchPetalResultPeopleFragment.kt
1
4714
package stan.androiddemo.project.petal.Module.Search import android.content.Context import android.graphics.Color import android.os.Bundle import android.support.v7.widget.CardView import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.widget.ImageButton import com.chad.library.adapter.base.BaseViewHolder import com.facebook.drawee.view.SimpleDraweeView import rx.Subscriber import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import stan.androiddemo.R import stan.androiddemo.UI.BasePetalRecyclerFragment import stan.androiddemo.project.petal.API.SearchAPI import stan.androiddemo.project.petal.Config.Config import stan.androiddemo.project.petal.Event.OnPeopleFragmentInteraction import stan.androiddemo.project.petal.HttpUtiles.RetrofitClient import stan.androiddemo.project.petal.Observable.ErrorHelper import stan.androiddemo.tool.CompatUtils import stan.androiddemo.tool.ImageLoad.ImageLoadBuilder class SearchPetalResultPeopleFragment : BasePetalRecyclerFragment<SearchPeopleBean.UsersBean>() { var mLimit = Config.LIMIT lateinit var mFansFormat: String lateinit var mHttpRoot: String private var mListener: OnPeopleFragmentInteraction<SearchPeopleBean.UsersBean>? = null override fun getTheTAG(): String { return this.toString() } companion object { fun newInstance(type:String): SearchPetalResultPeopleFragment { val fragment = SearchPetalResultPeopleFragment() val bundle = Bundle() bundle.putString("key",type) fragment.arguments = bundle return fragment } } override fun onAttach(context: Context?) { super.onAttach(context) if (context is OnPeopleFragmentInteraction<*>){ mListener = context as OnPeopleFragmentInteraction<SearchPeopleBean.UsersBean> } } override fun initView() { super.initView() mFansFormat = context.resources.getString(R.string.text_fans_number) mHttpRoot = context.resources.getString(R.string.httpRoot) } override fun getLayoutManager(): RecyclerView.LayoutManager { return LinearLayoutManager(context) } override fun getItemLayoutId(): Int { return R.layout.petal_cardview_user_item } override fun itemLayoutConvert(helper: BaseViewHolder, t: SearchPeopleBean.UsersBean) { helper.getView<ImageButton>(R.id.ibtn_image_user_chevron_right).setImageDrawable( CompatUtils.getTintListDrawable(context,R.drawable.ic_chevron_right_black_36dp,R.color.tint_list_grey) ) helper.getView<CardView>(R.id.card_view_people).setOnClickListener { mListener?.onClickItemUser(t,it) } helper.setText(R.id.txt_image_user,t.username) helper.setText(R.id.txt_image_about,String.format(mFansFormat,t.follower_count)) var url = t.avatar val img = helper.getView<SimpleDraweeView>(R.id.img_petal_user) if (!url.isNullOrEmpty()){ if (!url!!.contains(mHttpRoot)){ url = String.format(mUrlSmallFormat,url) } ImageLoadBuilder.Start(context,img,url).setPlaceHolderImage(CompatUtils.getTintDrawable(context, R.drawable.ic_account_circle_gray_48dp, Color.GRAY)) .setIsCircle(true) .build() } else{ img.hierarchy.setPlaceholderImage(R.drawable.ic_account_circle_gray_48dp) } } override fun requestListData(page: Int): Subscription { return RetrofitClient.createService(SearchAPI::class.java).httpsPeopleSearchRx(mAuthorization!!,mKey,page, mLimit) .subscribeOn(Schedulers.io()) .flatMap { ErrorHelper.getCheckNetError(it) }.map { it.users } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(object: Subscriber<List<SearchPeopleBean.UsersBean>>(){ override fun onCompleted() { } override fun onError(e: Throwable?) { e?.printStackTrace() loadError() checkException(e) } override fun onNext(t: List<SearchPeopleBean.UsersBean>?) { if (t == null){ loadError() return } loadSuccess(t!!) } }) } }
mit
afadebf9c1ab15b4a650ba3497ba8fbe
36.712
122
0.649767
4.667327
false
false
false
false
dreampany/framework
frame/src/main/kotlin/com/dreampany/network/api/Wifi.kt
1
1046
package com.dreampany.network.api import android.content.Context import android.net.wifi.WifiManager import com.dreampany.network.data.model.Network import javax.inject.Inject /** * Created by Roman-372 on 7/1/2019 * Copyright (c) 2019 bjit. All rights reserved. * [email protected] * Last modified $file.lastModified */ class Wifi @Inject constructor(val context: Context) : NetworkApi() { private val wifi: WifiManager init { wifi = context.getSystemService(Context.WIFI_SERVICE) as WifiManager } override fun isEnabled(): Boolean { return wifi.isWifiEnabled() } override fun isConnected(): Boolean { if (isEnabled()) { val info = wifi.getConnectionInfo(); return info.getNetworkId() != -1; } else { return false; } } override fun getNetwork(): Network { val network = Network(Network.Type.WIFI) network.enabled = isEnabled() network.connected = isConnected() return network } }
apache-2.0
2e7b26eee929b41a0eea45eef58def6a
25.175
76
0.652964
4.451064
false
false
false
false
sksamuel/ktest
kotest-runner/kotest-runner-junit5/src/jvmTest/kotlin/com/sksamuel/kotest/runner/junit5/AfterProjectListenerExceptionHandlingTest.kt
1
6718
package com.sksamuel.kotest.runner.junit5 import io.kotest.core.config.configuration import io.kotest.core.listeners.ProjectListener import io.kotest.core.spec.Isolate import io.kotest.core.spec.style.FunSpec import io.kotest.extensions.system.withEnvironment import io.mockk.every import io.mockk.mockkObject import io.mockk.unmockkObject import org.junit.platform.engine.discovery.DiscoverySelectors import org.junit.platform.testkit.engine.EngineTestKit @Isolate class AfterProjectListenerExceptionHandlingTest : FunSpec({ beforeTest { mockkObject(configuration) } afterTest { unmockkObject(configuration) } test("an AfterProjectListenerException should add marker spec") { every { configuration.listeners() } returns listOf( object : ProjectListener { override suspend fun afterProject() { if (System.getenv("foo") == "true") error("too") } } ) // use an env so that we only trigger the after all failure in the test, not while running the overall test suite withEnvironment("foo", "true") { EngineTestKit .engine("kotest") .selectors(DiscoverySelectors.selectClass(AfterProjectListenerExceptionSample::class.java)) .configurationParameter("allow_private", "true") .execute() .allEvents().apply { started().shouldHaveNames( "Kotest", "com.sksamuel.kotest.runner.junit5.AfterProjectListenerExceptionSample", "foo", "defaultProjectListener" ) aborted().shouldBeEmpty() skipped().shouldBeEmpty() failed().shouldHaveNames("defaultProjectListener") succeeded().shouldHaveNames( "foo", "com.sksamuel.kotest.runner.junit5.AfterProjectListenerExceptionSample", "Kotest" ) finished().shouldHaveNames( "foo", "com.sksamuel.kotest.runner.junit5.AfterProjectListenerExceptionSample", "defaultProjectListener", "Kotest" ) dynamicallyRegistered().shouldHaveNames( "com.sksamuel.kotest.runner.junit5.AfterProjectListenerExceptionSample", "foo", "defaultProjectListener" ) } } } test("an AfterProjectListenerException should add 2 markers spec") { every { configuration.listeners() } returns listOf( object : ProjectListener { override suspend fun afterProject() { if (System.getenv("coo") == "true") error("moo") } }, object : ProjectListener { override suspend fun afterProject() { if (System.getenv("coo") == "true") error("boo") } } ) // use an env so that we only trigger the after all failure in the test, not while running the overall test suite withEnvironment("coo", "true") { EngineTestKit .engine("kotest") .selectors(DiscoverySelectors.selectClass(AfterProjectListenerExceptionSample::class.java)) .configurationParameter("allow_private", "true") .execute() .allEvents().apply { started().shouldHaveNames( "Kotest", "com.sksamuel.kotest.runner.junit5.AfterProjectListenerExceptionSample", "foo", "defaultProjectListener_0", "defaultProjectListener_1" ) aborted().shouldBeEmpty() skipped().shouldBeEmpty() failed().shouldHaveNames("defaultProjectListener_0", "defaultProjectListener_1") succeeded().shouldHaveNames( "foo", "com.sksamuel.kotest.runner.junit5.AfterProjectListenerExceptionSample", "Kotest" ) finished().shouldHaveNames( "foo", "com.sksamuel.kotest.runner.junit5.AfterProjectListenerExceptionSample", "defaultProjectListener_0", "defaultProjectListener_1", "Kotest" ) dynamicallyRegistered().shouldHaveNames( "com.sksamuel.kotest.runner.junit5.AfterProjectListenerExceptionSample", "foo", "defaultProjectListener_0", "defaultProjectListener_1" ) } } } test("an AfterProjectListenerException should add named markers spec") { every { configuration.listeners() } returns listOf( object : ProjectListener { override val name: String get() = "MyAfterProjectListenerName" override suspend fun afterProject() { if (System.getenv("foo") == "true") error("moo") } } ) // use an env so that we only trigger the after all failure in the test, not while running the overall test suite withEnvironment("foo", "true") { EngineTestKit .engine("kotest") .selectors(DiscoverySelectors.selectClass(AfterProjectListenerExceptionSample::class.java)) .configurationParameter("allow_private", "true") .execute() .allEvents().apply { started().shouldHaveNames( "Kotest", "com.sksamuel.kotest.runner.junit5.AfterProjectListenerExceptionSample", "foo", "MyAfterProjectListenerName" ) aborted().shouldBeEmpty() skipped().shouldBeEmpty() failed().shouldHaveNames("MyAfterProjectListenerName") succeeded().shouldHaveNames( "foo", "com.sksamuel.kotest.runner.junit5.AfterProjectListenerExceptionSample", "Kotest" ) finished().shouldHaveNames( "foo", "com.sksamuel.kotest.runner.junit5.AfterProjectListenerExceptionSample", "MyAfterProjectListenerName", "Kotest" ) dynamicallyRegistered().shouldHaveNames( "com.sksamuel.kotest.runner.junit5.AfterProjectListenerExceptionSample", "foo", "MyAfterProjectListenerName" ) } } } }) private class AfterProjectListenerExceptionSample : FunSpec({ test("foo") {} })
mit
55047a236bf00e76b82a6b26605708dd
38.751479
119
0.56624
5.479608
false
true
false
false
migafgarcia/programming-challenges
leetcode/LongestSubstringWithoutRepeatingCharacters.kt
1
594
class Solution { fun lengthOfLongestSubstring(s: String): Int { var maxLength = 0 val currentSubstring = HashMap<Char,Int>() var i = 0 while(i < s.length) { if(currentSubstring.contains(s[i]) ) { i = currentSubstring.getOrDefault(s[i], 0) + 1 currentSubstring.clear() continue } currentSubstring.put(s[i], i) maxLength = if(currentSubstring.size > maxLength) currentSubstring.size else maxLength i++ } return maxLength } }
mit
6e4dda08393196cc342f17065a8b6f98
21.884615
98
0.530303
4.534351
false
false
false
false
ademar111190/bitkointlin
bitkointlin/src/test/kotlin/se/simbio/bitkointlin/Fixture.kt
1
2609
package se.simbio.bitkointlin import com.google.gson.JsonElement import se.simbio.bitkointlin.http.HttpClient // Bitkointlin val USER = "User" val PASSWORD = "Password" val HTTP_ADDRESS = "http://127.0.0.1:8332/" val HTTP_CLIENT = object : HttpClient { override fun post(bitkointlin: Bitkointlin, method: String, success: (JsonElement) -> Unit, error: (String) -> Unit) { } } // Balance val BALANCE_RESULT = 0.0 val BALANCE_GET_BALANCE_METHOD_NAME = "getbalance" val BALANCE_GET_BALANCE_ERROR_RETURN_EXAMPLE = "Balance Error" val BALANCE_GET_BALANCE_SUCCESS_RETURN_EXAMPLE = """ {"result": $BALANCE_RESULT, "error":null, "id":"sentId"} """ // Best Block Hash val BEST_BLOCK_HASH_RESULT = "000000000000000002e7469aa3f6f2a2c5d99f986cb56804b745b21e86567a0e" val BEST_BLOCK_HASH_GET_BEST_BLOCK_HASH_METHOD_NAME = "getbestblockhash" val BEST_BLOCK_HASH_GET_BEST_BLOCK_HASH_ERROR_RETURN_EXAMPLE = "Best Block Error" val BEST_BLOCK_HASH_GET_BEST_BLOCK_HASH_SUCCESS_RETURN_EXAMPLE = """ {"result": "$BEST_BLOCK_HASH_RESULT", "error":null, "id":"sentId"} """ // Difficulty val DIFFICULTY_RESULT = 163491654908.95925903 val DIFFICULTY_GET_DIFFICULTY_METHOD_NAME = "getdifficulty" val DIFFICULTY_GET_DIFFICULTY_ERROR_RETURN_EXAMPLE = "Difficulty Error" val DIFFICULTY_GET_DIFFICULTY_SUCCESS_RETURN_EXAMPLE = """ {"result": $DIFFICULTY_RESULT, "error":null, "id":"sentId"} """ // Info val INFO_BALANCE = 4.5 val INFO_BLOCKS = 6L val INFO_CONNECTIONS = 8L val INFO_DIFFICULTY = 9.10 val INFO_ERRORS = "" val INFO_KEY_POOL_OLDEST = 11L val INFO_KEY_POOL_SIZE = 12L val INFO_PAY_TX_FEE = 13.14 val INFO_PROTOCOL_VERSION = 2L val INFO_PROXY = "Some Proxy" val INFO_RELAY_FEE = 15.16 val INFO_TEST_NET = false val INFO_TIME_OFFSET = 7L val INFO_VERSION = 1L val INFO_WALLET_VERSION = 3L val INFO_GET_INFO_METHOD_NAME = "getinfo" val INFO_GET_INFO_ERROR_RETURN_EXAMPLE = "Info Error" val INFO_GET_INFO_SUCCESS_RESULT_EXAMPLE = """ {"result":{ "version": $INFO_VERSION, "protocolversion": $INFO_PROTOCOL_VERSION, "walletversion": $INFO_WALLET_VERSION, "balance": $INFO_BALANCE, "blocks": $INFO_BLOCKS, "timeoffset": $INFO_TIME_OFFSET, "connections": $INFO_CONNECTIONS, "proxy": "$INFO_PROXY", "difficulty": $INFO_DIFFICULTY, "testnet": $INFO_TEST_NET, "keypoololdest": $INFO_KEY_POOL_OLDEST, "keypoolsize": $INFO_KEY_POOL_SIZE, "paytxfee": $INFO_PAY_TX_FEE, "relayfee": $INFO_RELAY_FEE, "errors": "$INFO_ERRORS"}, "error":null, "id":"sentId"} """
mit
fcfc5ed1ead47788bf52bd3c2b6626f9
30.829268
122
0.682637
2.981714
false
false
false
false
ZoranPandovski/al-go-rithms
backtracking/sudoku/kotlin/Sudoku.kt
1
3582
/** * @author https://github.com/jeffament/ */ private const val EMPTY_CELL = 0 fun main(args: Array<String>) { val board = arrayOf( intArrayOf(8, 0, 0, 0, 0, 0, 0, 0, 0), intArrayOf(0, 0, 3, 6, 0, 0, 0, 0, 0), intArrayOf(0, 7, 0, 0, 9, 0, 2, 0, 0), intArrayOf(0, 5, 0, 0, 0, 7, 0, 0, 0), intArrayOf(0, 0, 0, 0, 4, 5, 7, 0, 0), intArrayOf(0, 0, 0, 1, 0, 0, 0, 3, 0), intArrayOf(0, 0, 1, 0, 0, 0, 0, 6, 8), intArrayOf(0, 0, 8, 5, 0, 0, 0, 1, 0), intArrayOf(0, 9, 0, 0, 0, 0, 4, 0, 0) ) if (solvePuzzle(board)) { println("Puzzle solved successfully!\n") printPuzzle(board) } else print("No solution is available for this puzzle!") } // solves the puzzle by recursively backtracking until a solution is found or all possibilities have been exhausted private fun solvePuzzle(array: Array<IntArray>): Boolean { val locationOfEmptyCell = arrayOf(0, 0) if (!findNextEmptyCell(array, locationOfEmptyCell)) return true val row = locationOfEmptyCell[0] val column = locationOfEmptyCell[1] for (numChoice in 1..9) { if (isValidMove(array, row, column, numChoice)) { array[row][column] = numChoice if (solvePuzzle(array)) return true array[row][column] = EMPTY_CELL } } return false } // returns true if there are still empty cells and updates the locationOfEmptyCell array, returns false when puzzle // is solved private fun findNextEmptyCell(sudokuArray: Array<IntArray>, locationOfEmptyCell: Array<Int>): Boolean { for (row in 0..8) { for (column in 0..8) { if (sudokuArray[row][column] == EMPTY_CELL) { locationOfEmptyCell[0] = row locationOfEmptyCell[1] = column return true } } } return false } // returns true if the chosen number does not occur in the row, column and quadrant, false otherwise private fun isValidMove(array: Array<IntArray>, row: Int, column: Int, numChoice: Int): Boolean { return checkRow(array, row, numChoice) && checkColumn(array, column, numChoice) && checkBox(array, row, column, numChoice) } // returns false if the chosen number is already in the box, true otherwise private fun checkBox(array: Array<IntArray>, row: Int, column: Int, numChoice: Int): Boolean { val startingRowIndex = (row / 3) * 3 val startingColumnIndex = (column / 3) * 3 for (row in startingRowIndex..startingRowIndex + 2) { for (column in startingColumnIndex..startingColumnIndex + 2) { if (array[row][column] == numChoice) return false } } return true } // returns false if the chosen number is already in the row, true otherwise private fun checkRow(array: Array<IntArray>, row: Int, numChoice: Int): Boolean { for (column in 0..8) { if (array[row][column] == numChoice) return false } return true } // returns false if the chosen number is already in the column, true otherwise private fun checkColumn(array: Array<IntArray>, column: Int, numChoice: Int): Boolean { for (row in 0..8) { if (array[row][column] == numChoice) return false } return true } // prints the 9x9 grid with sudoku formatting private fun printPuzzle(array: Array<IntArray>) { for (i in 0..8) { for (j in 0..8) { print("${array[i][j]} ") } println() } }
cc0-1.0
7335e57c87823bc6dfe91287d977a0e5
33.114286
115
0.597432
3.625506
false
false
false
false
jdigger/gradle-defaults
src/main/kotlin/com/mooregreatsoftware/gradle/util/xml/NodeBuilder.kt
1
1507
/* * Copyright 2014-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mooregreatsoftware.gradle.util.xml import com.mooregreatsoftware.gradle.util.compareMaps import java.util.Comparator.nullsFirst import java.util.Objects.compare data class NodeBuilder(val name: String, val attrs: Map<String, String>?, val textVal: String?, val children: Iterable<NodeBuilder>) : Comparable<NodeBuilder> { override fun toString(): String { return super.toString() } override fun compareTo(other: NodeBuilder): Int { if (this === other) return 0 val nameComp = this.name.compareTo(other.name, ignoreCase = true) if (nameComp != 0) return nameComp val textValComp = compare<String>(textVal, other.textVal, nullsFirst({ obj, str -> obj.compareTo(str, ignoreCase = true) })) if (textValComp != 0) return textValComp return compareMaps(attrs, other.attrs) } }
apache-2.0
9f5bbff5ee2969023f32ba86c688adfe
35.756098
132
0.706038
4.128767
false
false
false
false
kvnxiao/meirei
meirei-d4j/src/main/kotlin/com/github/kvnxiao/discord/meirei/d4j/command/CommandBuilder.kt
1
10748
/* * Copyright (C) 2017-2018 Ze Hao Xiao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.kvnxiao.discord.meirei.d4j.command import com.github.kvnxiao.discord.meirei.command.CommandContext import com.github.kvnxiao.discord.meirei.command.CommandDefaults import com.github.kvnxiao.discord.meirei.command.CommandPackage import com.github.kvnxiao.discord.meirei.command.CommandProperties import com.github.kvnxiao.discord.meirei.d4j.permission.LevelDefaults import com.github.kvnxiao.discord.meirei.d4j.permission.PermissionPropertiesD4J import com.github.kvnxiao.discord.meirei.permission.PermissionData import com.github.kvnxiao.discord.meirei.permission.PermissionDefaults import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent import sx.blah.discord.handle.obj.Permissions import java.util.Arrays import java.util.HashSet /** * Builder class to help create a (D4J) command package for adding to the command registry */ class CommandBuilder /** * Creates a command builder instance with the specified unique command id. * @param id the unique identifier (name) for the command */ (private val id: String) { // Command properties private val aliases = HashSet<String>() private var prefix = CommandDefaults.PREFIX private var parentId = CommandDefaults.PARENT_ID // Settings private var execWithSubCommands = CommandDefaults.EXEC_ALONGSIDE_SUBCOMMANDS private var isDisabled = CommandDefaults.IS_DISABLED // Metadata private var description = CommandDefaults.NO_DESCRIPTION private var usage = CommandDefaults.NO_USAGE // Permission properties private var allowDm = PermissionDefaults.ALLOW_DIRECT_MSGING private var forceDm = PermissionDefaults.FORCE_DIRECT_MSGING private var forceDmReply = PermissionDefaults.FORCE_DIRECT_REPLY private var removeCallMsg = PermissionDefaults.REMOVE_CALL_MSG private var rateLimitPeriodMs = PermissionDefaults.RATE_LIMIT_PERIOD_MS private var tokensPerPeriod = PermissionDefaults.TOKENS_PER_PERIOD private var rateLimitOnGuild = PermissionDefaults.RATE_LIMIT_ON_GUILD private var reqBotOwner = PermissionDefaults.REQUIRE_BOT_OWNER private var reqGuildOwner = PermissionDefaults.REQUIRE_GUILD_OWNER private var reqMention = PermissionDefaults.REQUIRE_MENTION // Command registry settings private var isRegistryAware = CommandDefaults.IS_REGISTRY_AWARE // Discord permissions private val permissionLevel = LevelDefaults.DEFAULT_PERMS_RW /** * Sets the alias(es) for the command. * @param aliases the command alias(es) * @return the current command builder */ fun aliases(vararg aliases: String): CommandBuilder { this.aliases.addAll(Arrays.asList(*aliases)) return this } /** * Sets the prefix for the command. * @param prefix the command prefix * @return the current command builder */ fun prefix(prefix: String): CommandBuilder { this.prefix = prefix return this } /** * Sets the parentId for this command. * @param parentId the parent command's id * @return the current command builder */ fun parentId(parentId: String): CommandBuilder { this.parentId = parentId return this } /** * Sets whether the command should execute along with its sub-commands. * @param execWithSubCommands a boolean * @return the current command builder */ fun execWithSubCommands(execWithSubCommands: Boolean): CommandBuilder { this.execWithSubCommands = execWithSubCommands return this } /** * Sets whether the command is disabled or not. * @param isDisabled a boolean * @return the current command builder */ fun isDisabled(isDisabled: Boolean): CommandBuilder { this.isDisabled = isDisabled return this } /** * Sets the description for the command. * @param description the description string * @return the current command builder */ fun description(description: String): CommandBuilder { this.description = description return this } /** * Sets the usage details for the command. * @param usage the usage string * @return the current command builder */ fun usage(usage: String): CommandBuilder { this.usage = usage return this } /** * Sets whether the command is allowed to be executed through direct messages to the bot (otherwise it is guild only). * @param allowDm a boolean * @return the current command builder */ fun allowDirectMessages(allowDm: Boolean): CommandBuilder { this.allowDm = allowDm return this } /** * Sets whether the command can only be executed through direct messages to the bot from the user. * @param forceDm a boolean * @return the current command builder */ fun forceDirectMessages(forceDm: Boolean): CommandBuilder { this.forceDm = forceDm return this } /** * Sets whether the bot is forced to reply with a direct message to the user during command execution. * @param forceDmReply a boolean * @return the current command builder */ fun forceDirectMessageReply(forceDmReply: Boolean): CommandBuilder { this.forceDmReply = forceDmReply return this } /** * Sets whether or not the user's message that executed the command should be deleted upon execution. * @param removeCallMsg a boolean * @return the current command builder */ fun removeCallMessage(removeCallMsg: Boolean): CommandBuilder { this.removeCallMsg = removeCallMsg return this } /** * Sets the rate limit period in milliseconds for the command call, before the rate limits are reset on a per-period basis. * @param rateLimitPeriodMs the period in milliseconds * @return the current command builder */ fun rateLimitPeriodMs(rateLimitPeriodMs: Long): CommandBuilder { this.rateLimitPeriodMs = rateLimitPeriodMs return this } /** * Sets the number of tokens (number of calls to the command) allowed per rate limit period. * @param tokensPerPeriod the number of tokens per period * @return the current command builder */ fun tokensPerPeriod(tokensPerPeriod: Long): CommandBuilder { this.tokensPerPeriod = tokensPerPeriod return this } /** * Sets whether the rate limiting for the command should be done on a per-guild basis, or a per-user basis. * @param rateLimitOnGuild a boolean * @return the current command builder */ fun rateLimitOnGuild(rateLimitOnGuild: Boolean): CommandBuilder { this.rateLimitOnGuild = rateLimitOnGuild return this } /** * Sets whether the command requires bot owner privileges in order to be successfully executed. * @param reqBotOwner a boolean * @return the current command builder */ fun requireBotOwner(reqBotOwner: Boolean): CommandBuilder { this.reqBotOwner = reqBotOwner return this } /** * Sets whether the command requires guild owner privileges in order to be successfully executed. * @param reqGuildOwner a boolean * @return the current command builder */ fun requireGuildOwner(reqGuildOwner: Boolean): CommandBuilder { this.reqGuildOwner = reqGuildOwner return this } /** * Sets whether the command requires an '@' mention before the command prefix and alias in order to be executed. * @param reqMention a boolean * @return the current command builder */ fun requireMention(reqMention: Boolean): CommandBuilder { this.reqMention = reqMention return this } /** * Sets the command's discord permissions that are required for a user to execute the command * @param permissions the required discord permissions * @return the current command builder */ fun permissionLevel(vararg permissions: Permissions): CommandBuilder { this.permissionLevel.clear() this.permissionLevel.addAll(permissions) return this } /** * Sets whether the command is capable of reading the command registry to retrieve information regarding other commands. * @param isRegistryAware whether the command is registry aware * @return the current command builder */ fun isRegistryAware(isRegistryAware: Boolean): CommandBuilder { this.isRegistryAware = isRegistryAware return this } /** * Builds the D4J command package using the values set in the builder. * @param executable the command method * @return the (D4J) command package containing the executable, command properties, and permission properties */ fun build(executable: CommandExecutable): CommandPackage { if (this.aliases.isEmpty()) { this.aliases.add(this.id) } return CommandPackage( object : CommandD4J(this.id, this.isRegistryAware) { override fun execute(context: CommandContext, event: MessageReceivedEvent) { executable.execute(context, event) } }, CommandProperties(this.id, this.aliases, this.prefix, this.description, this.usage, this.execWithSubCommands, this.isDisabled, this.parentId), PermissionPropertiesD4J(PermissionData(this.allowDm, this.forceDm, this.forceDmReply, this.removeCallMsg, this.rateLimitPeriodMs, this.tokensPerPeriod, this.rateLimitOnGuild, this.reqGuildOwner, this.reqBotOwner, this.reqMention), this.permissionLevel) ) } } /** * Kotlin-based lambda helper for building CommandPackages */ fun CommandBuilder.build(execute: (context: CommandContext, event: MessageReceivedEvent) -> Unit): CommandPackage { return this.build(object : CommandExecutable { override fun execute(context: CommandContext, event: MessageReceivedEvent) { execute.invoke(context, event) } }) }
apache-2.0
21b44d597c2408ed4786227407b1cf07
35.934708
141
0.698269
4.736888
false
false
false
false
spinnaker/kork
kork-sql/src/test/kotlin/com/netflix/spinnaker/kork/sql/PagedIteratorSpec.kt
3
5121
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.kork.sql import com.nhaarman.mockito_kotlin.anyOrNull import com.nhaarman.mockito_kotlin.doAnswer import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.reset import com.nhaarman.mockito_kotlin.times import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions import com.nhaarman.mockito_kotlin.whenever import org.assertj.core.api.AbstractAssert import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.spekframework.spek2.Spek import org.spekframework.spek2.style.gherkin.Feature internal object PagedIteratorSpec : Spek({ Feature("fetching paged data") { val pageSize = 3 val nextPage = mock<(Int, String?) -> Iterable<String>>() Scenario("there is no data") { val subject = PagedIterator(pageSize, String::toString, nextPage) beforeScenario { whenever(nextPage(eq(pageSize), anyOrNull())) doReturn emptyList<String>() } afterScenario { reset(nextPage) } Then("has no elements") { assertThat(subject.hasNext()).isFalse() } Then("won't return anything") { assertThatThrownBy { subject.next() } .isInstanceOf<NoSuchElementException>() } } Scenario("there is less than one full page of data") { val subject = PagedIterator(pageSize, String::toString, nextPage) beforeScenario { whenever(nextPage(eq(pageSize), anyOrNull())) doAnswer { val (_, cursor) = it.arguments when (cursor) { null -> listOf("ONE", "TWO") else -> emptyList() } } } afterScenario { reset(nextPage) } Given("has some elements") { assertThat(subject.hasNext()).isTrue() } val results = mutableListOf<String>() When("draining the iterator") { subject.forEachRemaining { results.add(it) } } Then("iterates over the available elements") { assertThat(results).containsExactly("ONE", "TWO") } Then("does not try to fetch another page") { verify(nextPage).invoke(pageSize, null) verifyNoMoreInteractions(nextPage) } } Scenario("there is exactly one full page of data") { val subject = PagedIterator(pageSize, String::toString, nextPage) beforeScenario { whenever(nextPage(eq(pageSize), anyOrNull())) doAnswer { val (_, cursor) = it.arguments when (cursor) { null -> listOf("ONE", "TWO", "THREE") else -> emptyList() } } } afterScenario { reset(nextPage) } Given("has some elements") { assertThat(subject.hasNext()).isTrue() } val results = mutableListOf<String>() When("draining the iterator") { subject.forEachRemaining { results.add(it) } } Then("iterates over the available elements") { assertThat(results).containsExactly("ONE", "TWO", "THREE") } Then("tries to fetch the next page before stopping") { verify(nextPage).invoke(pageSize, null) verify(nextPage).invoke(pageSize, "THREE") verifyNoMoreInteractions(nextPage) } } Scenario("there are multiple pages of data") { val subject = PagedIterator(pageSize, String::toString, nextPage) beforeScenario { whenever(nextPage(eq(pageSize), anyOrNull())) doAnswer { val (_, cursor) = it.arguments when (cursor) { null -> listOf("ONE", "TWO", "THREE") "THREE" -> listOf("FOUR", "FIVE", "SIX") "SIX" -> listOf("SEVEN") else -> emptyList() } } } afterScenario { reset(nextPage) } Given("has some elements") { assertThat(subject.hasNext()).isTrue() } val results = mutableListOf<String>() When("draining the iterator") { subject.forEachRemaining { results.add(it) } } Then("iterates over the available elements") { assertThat(results) .containsExactly("ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN") } Then("does not try to fetch additional pages") { verify(nextPage, times(3)).invoke(eq(pageSize), anyOrNull()) } } } }) private inline fun <reified T> AbstractAssert<*, *>.isInstanceOf() = isInstanceOf(T::class.java)
apache-2.0
eaffa78ff9bd796b16dac7459c431f4f
29.664671
82
0.637376
4.441457
false
false
false
false
Esri/arcgis-runtime-samples-android
kotlin/display-feature-layers/src/main/java/com/esri/arcgisruntime/sample/displayfeaturelayers/MainActivity.kt
1
10928
/* Copyright 2022 Esri * * 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.esri.arcgisruntime.sample.displayfeaturelayers import android.os.Bundle import android.util.Log import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.esri.arcgisruntime.ArcGISRuntimeEnvironment import com.esri.arcgisruntime.data.GeoPackage import com.esri.arcgisruntime.data.Geodatabase import com.esri.arcgisruntime.data.ServiceFeatureTable import com.esri.arcgisruntime.data.ShapefileFeatureTable import com.esri.arcgisruntime.layers.FeatureLayer import com.esri.arcgisruntime.loadable.LoadStatus import com.esri.arcgisruntime.mapping.ArcGISMap import com.esri.arcgisruntime.mapping.BasemapStyle import com.esri.arcgisruntime.mapping.Viewpoint import com.esri.arcgisruntime.mapping.view.MapView import com.esri.arcgisruntime.portal.Portal import com.esri.arcgisruntime.portal.PortalItem import com.esri.arcgisruntime.sample.displayfeaturelayers.databinding.ActivityMainBinding import com.esri.arcgisruntime.security.UserCredential import java.io.File class MainActivity : AppCompatActivity() { // enum to keep track of the selected source to display the feature layer enum class FeatureLayerSource(val menuPosition: Int) { SERVICE_FEATURE_TABLE(0), PORTAL_ITEM(1), GEODATABASE(2), GEOPACKAGE(3), SHAPEFILE(4) } private val TAG = MainActivity::class.java.simpleName // keeps track of the previously selected feature layer source private var previousSource: FeatureLayerSource? = null private val activityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) } private val mapView: MapView by lazy { activityMainBinding.mapView } private val bottomListItems: AutoCompleteTextView by lazy { activityMainBinding.bottomListItems } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(activityMainBinding.root) // authentication with an API key or named user is required to // access basemaps and other location services ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY) // create a map with the BasemapStyle topographic val map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC) // set the map to be displayed in the layout's MapView mapView.map = map setUpBottomUI() } /** * Load a feature layer with a URL */ private fun loadFeatureServiceURL() { // initialize the service feature table using a URL val serviceFeatureTable = ServiceFeatureTable(resources.getString(R.string.sample_service_url)).apply { // set user credentials to authenticate with the service credential = UserCredential("viewer01", "I68VGU^nMurF") // NOTE: Never hardcode login information in a production application // This is done solely for the sake of the sample } // create a feature layer with the feature table val featureLayer = FeatureLayer(serviceFeatureTable) val viewpoint = Viewpoint(41.773519, -88.143104, 4000.0) // set the feature layer on the map setFeatureLayer(featureLayer, viewpoint) } /** * Load a feature layer with a portal item */ private fun loadPortalItem() { // set the portal val portal = Portal("https://www.arcgis.com", false) // create the portal item with the item ID for the Portland tree service data val portalItem = PortalItem(portal, "1759fd3e8a324358a0c58d9a687a8578") portalItem.addDoneLoadingListener { if(portalItem.loadStatus == LoadStatus.LOADED){ // create the feature layer with the item val featureLayer = FeatureLayer(portalItem) // set the viewpoint to Portland, Oregon val viewpoint = Viewpoint(45.5266, -122.6219, 2500.0) // set the feature layer on the map setFeatureLayer(featureLayer, viewpoint) }else{ showError("Error loading portal item: ${portalItem.loadError.message}") } } portalItem.loadAsync() } /** * Load a feature layer with a local geodatabase file */ private fun loadGeodatabase() { // locate the .geodatabase file in the device val geodatabaseFile = File(getExternalFilesDir(null), "/LA_Trails.geodatabase") // instantiate the geodatabase with the file path val geodatabase = Geodatabase(geodatabaseFile.path) // load the geodatabase geodatabase.loadAsync() geodatabase.addDoneLoadingListener { if (geodatabase.loadStatus == LoadStatus.LOADED) { // get the feature table with the name val geodatabaseFeatureTable = geodatabase.getGeodatabaseFeatureTable("Trailheads") // create a feature layer with the feature table val featureLayer = FeatureLayer(geodatabaseFeatureTable) // set the viewpoint to Malibu, California val viewpoint = Viewpoint(34.0772, -118.7989, 600000.0) // set the feature layer on the map setFeatureLayer(featureLayer, viewpoint) } else { showError("Error loading geodatabase: ${geodatabase.loadError.message}") } } } /** * Load a feature layer with a local geopackage file */ private fun loadGeopackage() { // locate the .gpkg file in the device val geopackageFile = File(getExternalFilesDir(null), "/AuroraCO.gpkg") // instantiate the geopackage with the file path val geoPackage = GeoPackage(geopackageFile.path) // load the geopackage geoPackage.loadAsync() geoPackage.addDoneLoadingListener { if (geoPackage.loadStatus == LoadStatus.LOADED) { // get the first feature table in the geopackage val geoPackageFeatureTable = geoPackage.geoPackageFeatureTables.first() // create a feature layer with the feature table val featureLayer = FeatureLayer(geoPackageFeatureTable) // set the viewpoint to Denver, CO val viewpoint = Viewpoint(39.7294, -104.8319, 500000.0) // set the feature layer on the map setFeatureLayer(featureLayer, viewpoint) } else { showError("Error loading geopackage: ${geoPackage.loadError.message}") } } } /** * Load a feature layer with a local shapefile file */ private fun loadShapefile() { try { // locate the shape file in device val file = File( getExternalFilesDir(null), "/ScottishWildlifeTrust_ReserveBoundaries_20201102.shp" ) // create a shapefile feature table from a named bundle resource val shapeFileTable = ShapefileFeatureTable(file.path) // create a feature layer for the shapefile feature table val featureLayer = FeatureLayer(shapeFileTable) // set the viewpoint to Scotland val viewpoint = Viewpoint(56.641344, -3.889066, 6000000.0) // set the feature layer on the map setFeatureLayer(featureLayer, viewpoint) } catch (e: Exception) { showError("Error loading shapefile: ${e.message}") } } /** * Sets the map using the [layer] at the given [viewpoint] */ private fun setFeatureLayer(layer: FeatureLayer, viewpoint: Viewpoint) { // clears the existing layer on the map mapView.map.operationalLayers.clear() // adds the new layer to the map mapView.map.operationalLayers.add(layer) // updates the viewpoint to the given viewpoint mapView.setViewpoint(viewpoint) } private fun showError(message: String?) { Toast.makeText(this@MainActivity, message, Toast.LENGTH_SHORT).show() Log.e(TAG, message.toString()) } /** * Sets up the bottom UI selector to switch between * different ways to load a feature layers */ private fun setUpBottomUI() { // create an adapter with the types of feature layer // sources to be displayed in menu val adapter = ArrayAdapter( this, android.R.layout.simple_list_item_1, resources.getStringArray(R.array.feature_layer_sources) ) bottomListItems.apply { // populate the bottom list with the feature layer sources setAdapter(adapter) // click listener when feature layer source is selected setOnItemClickListener { _, _, i, _ -> // get the selected feature layer source val selectedSource = FeatureLayerSource.values().find { it.menuPosition == i } // check if the same feature is selected if (previousSource != null && (previousSource == selectedSource)) { // same feature layer selected, return return@setOnItemClickListener } // set the feature layer source using the selected source when (selectedSource) { FeatureLayerSource.SERVICE_FEATURE_TABLE -> loadFeatureServiceURL() FeatureLayerSource.PORTAL_ITEM -> loadPortalItem() FeatureLayerSource.GEODATABASE -> loadGeodatabase() FeatureLayerSource.GEOPACKAGE -> loadGeopackage() FeatureLayerSource.SHAPEFILE -> loadShapefile() } // update the previous feature layer source previousSource = selectedSource } } } override fun onPause() { mapView.pause() super.onPause() } override fun onResume() { super.onResume() mapView.resume() // update UI if screen rotates or resumes setUpBottomUI() } override fun onDestroy() { mapView.dispose() super.onDestroy() } }
apache-2.0
75efdbed65d9e013c72c483537b47abb
38.738182
98
0.645589
4.828988
false
false
false
false
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/api/policy/proto/PolicyProto.kt
1
6506
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package com.google.android.libraries.pcc.chronicle.api.policy.proto import arcs.core.data.proto.PolicyConfigProto import arcs.core.data.proto.PolicyFieldProto import arcs.core.data.proto.PolicyProto import arcs.core.data.proto.PolicyRetentionProto import arcs.core.data.proto.PolicyTargetProto import com.google.android.libraries.pcc.chronicle.api.policy.FieldName import com.google.android.libraries.pcc.chronicle.api.policy.Policy import com.google.android.libraries.pcc.chronicle.api.policy.PolicyField import com.google.android.libraries.pcc.chronicle.api.policy.PolicyRetention import com.google.android.libraries.pcc.chronicle.api.policy.PolicyTarget import com.google.android.libraries.pcc.chronicle.api.policy.StorageMedium import com.google.android.libraries.pcc.chronicle.api.policy.UsageType import com.google.android.libraries.pcc.chronicle.api.policy.contextrules.All fun PolicyProto.decode(): Policy { require(name.isNotEmpty()) { "Policy name is missing." } require(egressType.isNotEmpty()) { "Egress type is missing." } return Policy( name = name, description = description, egressType = egressType, targets = targetsList.map { it.decode() }, configs = configsList.associateBy(keySelector = { it.name }, valueTransform = { it.metadataMap }), annotations = annotationsList.map { it.decode() } ) } fun Policy.encode(): PolicyProto { require(allowedContext is All) { "allowedContext must allow all contexts." } return PolicyProto.newBuilder() .setName(name) .setDescription(description) .setEgressType(egressType) .addAllTargets(targets.map { it.encode() }) .addAllConfigs( configs.map { (name, metadata) -> PolicyConfigProto.newBuilder().setName(name).putAllMetadata(metadata).build() } ) .addAllAnnotations(annotations.map { it.encode() }) .build() } private fun PolicyTargetProto.decode(): PolicyTarget { return PolicyTarget( schemaName = schemaType, maxAgeMs = maxAgeMs, retentions = retentionsList.map { it.decode() }, fields = fieldsList.map { it.decode() }, annotations = annotationsList.map { it.decode() } ) } fun PolicyTarget.encode(): PolicyTargetProto { return PolicyTargetProto.newBuilder() .setSchemaType(schemaName) .setMaxAgeMs(maxAgeMs) .addAllRetentions(retentions.map { it.encode() }) .addAllFields(fields.map { it.encode() }) .addAllAnnotations(annotations.map { it.encode() }) .build() } private fun PolicyFieldProto.decode(parentFieldPath: List<FieldName> = emptyList()): PolicyField { val rawUsages = mutableSetOf<UsageType>() val redactedUsages = mutableMapOf<String, MutableSet<UsageType>>() for (usage in usagesList) { if (usage.redactionLabel.isEmpty()) { rawUsages.add(usage.usage.decode()) } else { redactedUsages.getOrPut(usage.redactionLabel) { mutableSetOf() }.add(usage.usage.decode()) } } val fieldPath = parentFieldPath + name return PolicyField( fieldPath = fieldPath, rawUsages = rawUsages, redactedUsages = redactedUsages, subfields = subfieldsList.map { it.decode(fieldPath) }, annotations = annotationsList.map { it.decode() } ) } fun PolicyField.encode(): PolicyFieldProto { val rawUsages = rawUsages.map { usage -> PolicyFieldProto.AllowedUsage.newBuilder().setUsage(usage.encode()).build() } val redactedUsages = redactedUsages.flatMap { (label, usages) -> usages.map { usage -> PolicyFieldProto.AllowedUsage.newBuilder() .setRedactionLabel(label) .setUsage(usage.encode()) .build() } } val allUsages = rawUsages + redactedUsages return PolicyFieldProto.newBuilder() .setName(fieldPath.last()) .addAllUsages(allUsages) .addAllSubfields(subfields.map { it.encode() }) .addAllAnnotations(annotations.map { it.encode() }) .build() } private fun PolicyRetentionProto.decode(): PolicyRetention { return PolicyRetention(medium = medium.decode(), encryptionRequired = encryptionRequired) } private fun PolicyRetention.encode(): PolicyRetentionProto { return PolicyRetentionProto.newBuilder() .setMedium(medium.encode()) .setEncryptionRequired(encryptionRequired) .build() } private fun PolicyFieldProto.UsageType.decode() = when (this) { PolicyFieldProto.UsageType.ANY -> UsageType.ANY PolicyFieldProto.UsageType.EGRESS -> UsageType.EGRESS PolicyFieldProto.UsageType.JOIN -> UsageType.JOIN PolicyFieldProto.UsageType.USAGE_TYPE_UNSPECIFIED, PolicyFieldProto.UsageType.UNRECOGNIZED -> throw UnsupportedOperationException("Unknown usage type: $this") } private fun UsageType.encode() = when (this) { UsageType.ANY -> PolicyFieldProto.UsageType.ANY UsageType.EGRESS -> PolicyFieldProto.UsageType.EGRESS UsageType.JOIN -> PolicyFieldProto.UsageType.JOIN // TODO(b/200086957): Change this once proto is forked and updated. UsageType.SANDBOX -> throw java.lang.UnsupportedOperationException("SANDBOX isn't supported in the proto") } private fun PolicyRetentionProto.Medium.decode() = when (this) { PolicyRetentionProto.Medium.RAM -> StorageMedium.RAM PolicyRetentionProto.Medium.DISK -> StorageMedium.DISK PolicyRetentionProto.Medium.MEDIUM_UNSPECIFIED, PolicyRetentionProto.Medium.UNRECOGNIZED -> throw UnsupportedOperationException("Unknown retention medium: $this") } private fun StorageMedium.encode() = when (this) { StorageMedium.RAM -> PolicyRetentionProto.Medium.RAM StorageMedium.DISK -> PolicyRetentionProto.Medium.DISK }
apache-2.0
cc70910bf4a03fe693d6a74d80433440
34.944751
98
0.73363
4.183923
false
false
false
false
Camano/CoolKotlin
math/quadratic.kt
1
1512
/* Equation: a(x^2) + bx + c * Discriminant = b^2 – 4*a*c * if D>0 * Root1 = [-b + (D^(1/2))]/(2*a) * Root2 = [-b – (D^(1/2))]/(2*a) * if D<0 * Root1 = [-b + (D^(1/2))*i]/(2*a) * Root2 = [-b - (D^(1/2))*i]/(2*a) */ import java.util.* fun main(args: Array<String>) { val sc = Scanner(System.`in`) //User input for `a b c` println("Give numbers for the coefficients in the format `a b c` \n") val a = sc.nextDouble() val b = sc.nextDouble() val c = sc.nextDouble() println("Your quadratic equation is:($a)(x^2)+($b)x+($c)=0 \n") val D = Math.pow(b, 2.0) - 4.0 * a * c println("D=[($b)^2]-[4*($a)*($c)]=$D") val x1 = (-b + Math.sqrt(D)) / (2 * a) val x2 = (-b - Math.sqrt(D)) / (2 * a) if (D > 0) { println("D>0") println("x1=" + x1) println("x2=" + x2) println("($a)(x^2)+($b)x+($c)=($a)*[x-($x1)][x-($x2)]") } else if (D < 0) { println("D<0") println("We don't have solutions in real numbers, but we do in complex numbers!") println("(Note: i^2=-1)\n") println("z1=[(" + b + ")+[" + Math.abs(D) + "^(1/2)]*i]/[2*(" + a + ")]") println("z2=[(" + b + ")-[" + Math.abs(D) + "^(1/2)]*i]/[2*(" + a + ")] \n") println("($a)(x^2)+($b)x+($c)=($a)*(x-z1)(x-z2)") } else { println("D=0") println("We get two solutions which are the same") println("x1=" + x1) println("x2=" + x2) println("($a)(x^2)+($b)x+($c)=($a)*[[x-($x1)]^2]") } }
apache-2.0
019551409b9838083b7c460e849b6467
34.069767
89
0.442308
2.389857
false
false
false
false
SoulBeaver/Arena--7DRL-
src/main/java/com/sbg/arena/core/input/ShootRequest.kt
1
1637
package com.sbg.arena.core.input import com.sbg.arena.core.Level import com.sbg.arena.core.Player import com.sbg.arena.core.geom.Point import com.sbg.arena.core.enemy.Enemies import com.sbg.arena.core.Direction import kotlin.properties.Delegates import com.sbg.arena.core.enemy.Enemy class ShootRequest(val level: Level, val player: Player, val enemies: Enemies): InputRequest { var start: Point by Delegates.notNull() var targets: Map<Direction, Point> by Delegates.notNull() var enemiesHit: List<Enemy> by Delegates.notNull() override fun initialize() { start = level.playerCoordinates targets = hashMapOf(Direction.North to shoot(start, Direction.North, { Point(it.x, it.y - 1) }), Direction.East to shoot(start, Direction.East, { Point(it.x + 1, it.y) }), Direction.South to shoot(start, Direction.South, { Point(it.x, it.y + 1) }), Direction.West to shoot(start, Direction.West, { Point(it.x - 1, it.y) })) enemiesHit = targets.values() filter { level[it].isEnemy() } map { enemies[it] } } override fun isValid() = true override fun execute() { enemiesHit.forEach { it.takeDamage(10) } } private fun shoot(point: Point, direction: Direction, increment: (Point) -> Point): Point { return if (!level[point].isObstacle()) { val next = increment(point) if (level.isWithinBounds(next)) shoot(next, direction, increment) else point } else point } }
apache-2.0
678daeff68f9e0c6ea7b8d2c7b7d7798
36.227273
104
0.613928
3.916268
false
false
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/preferences/NotificationThresholdDialogFragment.kt
1
5959
package com.battlelancer.seriesguide.preferences import android.app.Dialog import android.content.DialogInterface import android.content.res.Resources import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.widget.RadioGroup import androidx.annotation.PluralsRes import androidx.appcompat.app.AppCompatDialogFragment import androidx.preference.PreferenceManager import com.battlelancer.seriesguide.R import com.battlelancer.seriesguide.databinding.DialogNotificationThresholdBinding import com.battlelancer.seriesguide.settings.NotificationSettings import com.google.android.material.dialog.MaterialAlertDialogBuilder import timber.log.Timber import java.util.regex.Pattern /** * Dialog which allows to select the number of minutes, hours or days when a notification should * appear before an episode is released. */ class NotificationThresholdDialogFragment : AppCompatDialogFragment() { private var binding: DialogNotificationThresholdBinding? = null private var value = 0 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val binding = DialogNotificationThresholdBinding.inflate(layoutInflater) this.binding = binding binding.editTextThresholdValue.addTextChangedListener(textWatcher) binding.radioGroupThreshold.setOnCheckedChangeListener { _: RadioGroup?, _: Int -> // trigger text watcher, takes care of validating the value based on the new unit this.binding?.editTextThresholdValue?.let { it.text = it.text } } val minutes = NotificationSettings.getLatestToIncludeTreshold(requireContext()) val value: Int if (minutes != 0 && minutes % (24 * 60) == 0) { value = minutes / (24 * 60) binding.radioGroupThreshold.check(R.id.radioButtonThresholdDays) } else if (minutes != 0 && minutes % 60 == 0) { value = minutes / 60 binding.radioGroupThreshold.check(R.id.radioButtonThresholdHours) } else { value = minutes binding.radioGroupThreshold.check(R.id.radioButtonThresholdMinutes) } binding.editTextThresholdValue.setText(value.toString()) // radio buttons are updated by text watcher return MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.pref_notifications_treshold) .setView(binding.root) .setPositiveButton(android.R.string.ok) { _: DialogInterface, _: Int -> saveAndDismiss() } .create() } override fun onDestroyView() { super.onDestroyView() binding = null } private val textWatcher: TextWatcher = object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {} override fun afterTextChanged(s: Editable) { parseAndUpdateValue(s) } } private fun parseAndUpdateValue(s: Editable) { var value = 0 try { value = s.toString().toInt() } catch (ignored: NumberFormatException) { } val binding = binding ?: return // do not allow values bigger than a threshold, based on the selected unit var resetValue = false if (binding.radioGroupThreshold.checkedRadioButtonId == binding.radioButtonThresholdMinutes.id && value > 600) { resetValue = true value = 600 } else if (binding.radioGroupThreshold.checkedRadioButtonId == binding.radioButtonThresholdHours.id && value > 120) { resetValue = true value = 120 } else if (binding.radioGroupThreshold.checkedRadioButtonId == binding.radioButtonThresholdDays.id && value > 7) { resetValue = true value = 7 } else if (value < 0) { // should never happen due to text filter, but better safe than sorry resetValue = true value = 0 } if (resetValue) { s.replace(0, s.length, value.toString()) } this.value = value updateRadioButtons(value) } private fun updateRadioButtons(value: Int) { val binding = binding ?: return val placeholderPattern = Pattern.compile("%d\\s*") val res = resources binding.radioButtonThresholdMinutes.text = getQuantityStringWithoutPlaceholder( placeholderPattern, res, R.plurals.minutes_before_plural, value ) binding.radioButtonThresholdHours.text = getQuantityStringWithoutPlaceholder( placeholderPattern, res, R.plurals.hours_before_plural, value ) binding.radioButtonThresholdDays.text = getQuantityStringWithoutPlaceholder( placeholderPattern, res, R.plurals.days_before_plural, value ) } private fun getQuantityStringWithoutPlaceholder( pattern: Pattern, res: Resources, @PluralsRes pluralsRes: Int, value: Int ): String { return pattern.matcher(res.getQuantityString(pluralsRes, value)).replaceAll("") } private fun saveAndDismiss() { val binding = binding ?: return var minutes = value // if not already, convert to minutes if (binding.radioGroupThreshold.checkedRadioButtonId == binding.radioButtonThresholdHours.id) { minutes *= 60 } else if (binding.radioGroupThreshold.checkedRadioButtonId == binding.radioButtonThresholdDays.id) { minutes *= 60 * 24 } PreferenceManager.getDefaultSharedPreferences(requireContext()).edit() .putString(NotificationSettings.KEY_THRESHOLD, minutes.toString()) .apply() Timber.i("Notification threshold set to %d minutes", minutes) dismiss() } }
apache-2.0
4be96b0e869db9afc601c3318edc427f
36.961783
109
0.665548
5.05
false
false
false
false
arcao/Geocaching4Locus
app/src/main/java/com/arcao/geocaching4locus/import_bookmarks/fragment/BookmarkFragment.kt
1
6789
package com.arcao.geocaching4locus.import_bookmarks.fragment import android.app.Activity import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.core.os.bundleOf import androidx.core.view.MenuProvider import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.paging.LoadState import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import com.arcao.geocaching4locus.R import com.arcao.geocaching4locus.base.paging.handleErrors import com.arcao.geocaching4locus.base.usecase.entity.GeocacheListEntity import com.arcao.geocaching4locus.base.util.exhaustive import com.arcao.geocaching4locus.base.util.invoke import com.arcao.geocaching4locus.base.util.withObserve import com.arcao.geocaching4locus.databinding.FragmentBookmarkBinding import com.arcao.geocaching4locus.error.hasPositiveAction import com.arcao.geocaching4locus.import_bookmarks.ImportBookmarkViewModel import com.arcao.geocaching4locus.import_bookmarks.adapter.BookmarkGeocachesAdapter import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import org.koin.androidx.viewmodel.ext.android.sharedViewModel import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf class BookmarkFragment : BaseBookmarkFragment() { private val bookmarkList by lazy<GeocacheListEntity> { requireNotNull(arguments?.getParcelable(ARG_BOOKMARK_LIST)) } private val viewModel by viewModel<BookmarkViewModel> { parametersOf(bookmarkList) } private val activityViewModel by sharedViewModel<ImportBookmarkViewModel>() private val adapter = BookmarkGeocachesAdapter() private val toolbar get() = (activity as? AppCompatActivity)?.supportActionBar private val menuProvider = object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.toolbar_select_deselect, menu) } override fun onMenuItemSelected(menuItem: MenuItem) = when (menuItem.itemId) { R.id.selectAll -> { adapter.selectAll() true } R.id.deselectAll -> { adapter.selectNone() true } else -> false } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { toolbar?.subtitle = bookmarkList.name val binding = FragmentBookmarkBinding.inflate( inflater, container, false ) binding.lifecycleOwner = viewLifecycleOwner binding.vm = viewModel binding.isLoading = true binding.list.apply { adapter = [email protected] layoutManager = LinearLayoutManager(context) addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) } adapter.tracker.addSelectionChangeListener { _: Int, _: Int -> viewModel.selection(adapter.selected) } var savedState = savedInstanceState viewLifecycleOwner.lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.RESUMED) { viewModel.pagerFlow.collectLatest { data -> adapter.submitData(data) if (savedState != null) { adapter.tracker.onRestoreInstanceState(savedState) savedState = null } } } } viewLifecycleOwner.lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.RESUMED) { adapter.loadStateFlow.collect { state -> val isListEmpty = state.refresh is LoadState.NotLoading && adapter.itemCount == 0 binding.isEmpty = isListEmpty binding.isLoading = state.source.refresh is LoadState.Loading state.handleErrors(viewModel::handleLoadError) } } } viewModel.action.withObserve(viewLifecycleOwner, ::handleAction) viewModel.progress.withObserve(viewLifecycleOwner) { state -> activityViewModel.progress(state) } return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) requireActivity().addMenuProvider(menuProvider, viewLifecycleOwner) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) adapter.tracker.onSaveInstanceState(outState) } @Suppress("IMPLICIT_CAST_TO_ANY") fun handleAction(action: BookmarkAction) { when (action) { is BookmarkAction.Error -> { startActivity(action.intent) requireActivity().apply { setResult( if (action.intent.hasPositiveAction()) { Activity.RESULT_OK } else { Activity.RESULT_CANCELED } ) finish() } } is BookmarkAction.Finish -> { startActivity(action.intent) requireActivity().apply { setResult(Activity.RESULT_OK) finish() } } BookmarkAction.Cancel -> { requireActivity().apply { setResult(Activity.RESULT_CANCELED) finish() } } is BookmarkAction.LoadingError -> { startActivity(action.intent) requireActivity().apply { if (adapter.itemCount == 0) { setResult(Activity.RESULT_CANCELED) finish() } } } }.exhaustive } override fun onProgressCancel(requestId: Int) { viewModel.cancelProgress() } companion object { private const val ARG_BOOKMARK_LIST = "bookmarkList" fun newInstance(geocacheList: GeocacheListEntity) = BookmarkFragment().apply { arguments = bundleOf( ARG_BOOKMARK_LIST to geocacheList ) } } }
gpl-3.0
203a9990a5e884ed298b82163ff884d8
34.731579
93
0.625865
5.546569
false
false
false
false
GoogleCloudPlatform/kotlin-samples
run/grpc-hello-world-mvn/src/main/kotlin/io/grpc/examples/helloworld/HelloWorldServer.kt
2
1705
/* * Copyright 2020 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.grpc.examples.helloworld import io.grpc.Server import io.grpc.ServerBuilder class HelloWorldServer(val port: Int) { val server: Server = ServerBuilder .forPort(port) .addService(HelloWorldService()) .build() fun start() { server.start() println("Server started, listening on $port") Runtime.getRuntime().addShutdownHook( Thread { println("*** shutting down gRPC server since JVM is shutting down") stop() println("*** server shut down") } ) } private fun stop() { server.shutdown() } fun blockUntilShutdown() { server.awaitTermination() } private class HelloWorldService : GreeterGrpcKt.GreeterCoroutineImplBase() { override suspend fun sayHello(request: HelloRequest) = helloReply { message = "Hello ${request.name}" } } } fun main() { val port = System.getenv("PORT")?.toInt() ?: 50051 val server = HelloWorldServer(port) server.start() server.blockUntilShutdown() }
apache-2.0
1d9d86451ed0582990a4cc5a258278ba
27.416667
83
0.646921
4.475066
false
false
false
false
proxer/ProxerAndroid
src/main/kotlin/me/proxer/app/profile/ProfileViewModel.kt
1
1310
package me.proxer.app.profile import com.gojuno.koptional.None import com.gojuno.koptional.Optional import io.reactivex.Single import io.reactivex.rxkotlin.plusAssign import me.proxer.app.base.BaseViewModel import me.proxer.app.profile.ProfileViewModel.UserInfoWrapper import me.proxer.app.util.extension.buildSingle import me.proxer.library.entity.user.UserInfo /** * @author Ruben Gees */ class ProfileViewModel( private val userId: String?, private val username: String? ) : BaseViewModel<UserInfoWrapper>() { override val dataSingle: Single<UserInfoWrapper> get() = Single.fromCallable { validate() } .flatMap { api.user.info(userId, username).buildSingle() } .flatMap { userInfo -> val maybeUcpSingle = when (storageHelper.user?.matches(userId, username) == true) { true -> api.ucp.watchedEpisodes().buildSingle().map { Optional.toOptional(it) } false -> Single.just(None) } maybeUcpSingle.map { watchedEpisodes -> UserInfoWrapper(userInfo, watchedEpisodes.toNullable()) } } init { disposables += storageHelper.isLoggedInObservable.subscribe { reload() } } data class UserInfoWrapper(val info: UserInfo, val watchedEpisodes: Int?) }
gpl-3.0
212f223c7706af6249d3d8b24f929cda
34.405405
113
0.683206
4.440678
false
false
false
false
MaibornWolff/codecharta
analysis/import/CodeMaatImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/codemaat/CodeMaatImporter.kt
1
3147
package de.maibornwolff.codecharta.importer.codemaat import de.maibornwolff.codecharta.model.AttributeType import de.maibornwolff.codecharta.model.AttributeTypes import de.maibornwolff.codecharta.serialization.ProjectSerializer import de.maibornwolff.codecharta.tools.interactiveparser.InteractiveParser import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface import de.maibornwolff.codecharta.translator.MetricNameTranslator import picocli.CommandLine import java.io.File import java.io.IOException import java.io.InputStream import java.io.PrintStream import java.util.concurrent.Callable @CommandLine.Command( name = "codemaatimport", description = ["generates cc.json from codemaat coupling csv"], footer = ["Copyright(c) 2022, MaibornWolff GmbH"] ) class CodeMaatImporter( private val output: PrintStream = System.out) : Callable<Void>, InteractiveParser { @CommandLine.Option(names = ["-h", "--help"], usageHelp = true, description = ["displays this help and exits"]) private var help = false @CommandLine.Option(names = ["-o", "--output-file"], description = ["output File"]) private var outputFile: String? = null @CommandLine.Option(names = ["-nc", "--not-compressed"], description = ["save uncompressed output File"]) private var compress = true @CommandLine.Parameters(arity = "1..*", paramLabel = "FILE", description = ["codemaat coupling csv files"]) private var files: List<File> = mutableListOf() private val pathSeparator = '/' private val csvDelimiter = ',' @Throws(IOException::class) override fun call(): Void? { val csvProjectBuilder = CSVProjectBuilder(pathSeparator, csvDelimiter, codemaatReplacement, attributeTypes, getAttributeDescriptors()) files.map { it.inputStream() }.forEach<InputStream> { csvProjectBuilder.parseCSVStream(it) } val project = csvProjectBuilder.build() ProjectSerializer.serializeToFileOrStream(project, outputFile, output, compress) return null } private val codemaatReplacement: MetricNameTranslator get() { val prefix = "" val replacementMap = mutableMapOf<String, String>() replacementMap["entity"] = "fromNodename" replacementMap["coupled"] = "toNodeName" replacementMap["degree"] = "pairingRate" replacementMap["average-revs"] = "avgCommits" return MetricNameTranslator(replacementMap.toMap(), prefix) } private val attributeTypes: AttributeTypes get() { val type = "edges" val attributeTypes = mutableMapOf<String, AttributeType>() attributeTypes["pairingRate"] = AttributeType.relative attributeTypes["avgCommits"] = AttributeType.absolute return AttributeTypes(attributeTypes.toMutableMap(), type) } companion object { @JvmStatic fun main(args: Array<String>) { CommandLine(CodeMaatImporter()).execute(*args) } } override fun getDialog(): ParserDialogInterface = ParserDialog }
bsd-3-clause
e85a2f0eb8429d6c9023534bd34cac76
37.378049
126
0.695901
4.848998
false
false
false
false
nt-ca-aqe/library-app
library-service/src/test/kotlin/library/service/api/books/payload/CreateBookRequestTest.kt
1
3873
package library.service.api.books.payload import library.service.business.books.domain.types.Title import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource import utils.classification.UnitTest @UnitTest internal class CreateBookRequestTest : AbstractPayloadTest<CreateBookRequest>() { override val payloadType = CreateBookRequest::class override val jsonExample: String = """ { "isbn": "0123456789", "title": "Hello World" } """ override val deserializedExample = CreateBookRequest("0123456789", "Hello World") @Nested inner class `bean validation` { @Nested inner class `for isbn` { @ValueSource(strings = ["0575081244", "978-0575081244", "9780575081244"]) @ParameterizedTest fun `valid value examples`(isbn: String) { assertThat(validate(isbn)).isEmpty() } @Nested inner class `invalid value examples` { private val blankError = "must not be blank" private val patternError = """must match "(\d{3}-?)?\d{10}"""" @Test fun `null`() { assertThat(validate(null)).containsOnly(blankError) } @ValueSource(strings = ["", " ", "\t", "\n"]) @ParameterizedTest fun `blank strings`(isbn: String) { assertThat(validate(isbn)).containsOnly(patternError, blankError) } @ValueSource(strings = ["123456789", "12345678901", "123456789012", "12345678901234"]) @ParameterizedTest fun `wrong number of digits`(isbn: String) { assertThat(validate(isbn)).containsOnly(patternError) } @ValueSource(strings = ["a1b2c3d4e5", "1a2-1234567890", "1a21234567890"]) @ParameterizedTest fun `alpha numeric characters`(isbn: String) { assertThat(validate(isbn)).containsOnly(patternError) } } } private fun validate(isbn: String?) = validate(CreateBookRequest(isbn = isbn, title = "Hello World")) } @Nested inner class `title property validation` { @Test fun `any values between 1 and 256 characters are valid`() = (1..256) .forEach { assertThat(validate(titleOfLength(it))).isEmpty() } @ValueSource(strings = [ "abc", "ABC", "The Martian", "The Dark Tower I: The Gunslinger", "Loer Saguzaz-Vocle", "Lülöla", "Ètien", """"_ !"#$%&'()*+,-./:;<=>?@`\~[]^|{} _""", "1234567890" ]) @ParameterizedTest fun `valid value examples`(title: String) { assertThat(validate(title)).isEmpty() } @Nested inner class `invalid value examples` { private val blankError = "must not be blank" private val sizeError = "size must be between 1 and 256" private val patternError = """must match "${Title.VALID_TITLE_PATTERN}"""" @Test fun `null`() { assertThat(validate(null)).containsOnly(blankError) } @Test fun `empty string`() { assertThat(validate("")).containsOnly(sizeError, blankError, patternError) } @Test fun `blank string`() { assertThat(validate(" ")).containsOnly(blankError) } @Test fun `more than 256 characters string`() { assertThat(validate(titleOfLength(257))).containsOnly(sizeError) } } private fun titleOfLength(length: Int) = "".padEnd(length, 'a') private fun validate(title: String?) = validate(CreateBookRequest(isbn = "0123456789", title = title)) } }
apache-2.0
34118d225dd42ef42d71642c8039b6fe
36.221154
110
0.591473
4.5
false
true
false
false
carlphilipp/chicago-commutes
android-app/src/main/kotlin/fr/cph/chicago/core/activity/station/StationActivity.kt
1
5516
/** * Copyright 2021 Carl-Philipp Harmant * * * 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 fr.cph.chicago.core.activity.station import android.annotation.SuppressLint import android.view.View import android.widget.ImageView import android.widget.LinearLayout import android.widget.ProgressBar import android.widget.TextView import androidx.appcompat.widget.Toolbar import androidx.appcompat.app.AppCompatActivity import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import fr.cph.chicago.R import fr.cph.chicago.client.GoogleStreetClient import fr.cph.chicago.core.App import fr.cph.chicago.core.model.Position import fr.cph.chicago.service.PreferenceService import fr.cph.chicago.util.Color import fr.cph.chicago.util.Util import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import timber.log.Timber abstract class StationActivity : AppCompatActivity() { companion object { private const val TAG_ERROR = "error" private const val TAG_DEFAULT = "default" private const val TAG_STREET_VIEW = "streetview" private val googleStreetClient = GoogleStreetClient @JvmStatic protected val preferenceService = PreferenceService @JvmStatic protected val util = Util } protected lateinit var swipeRefreshLayout: SwipeRefreshLayout protected var position: Position = Position() protected var applyFavorite: Boolean = false protected lateinit var streetViewImage: ImageView protected lateinit var streetViewProgressBar: ProgressBar private lateinit var streetViewText: TextView protected lateinit var favoritesImage: ImageView protected lateinit var mapImage: ImageView protected lateinit var toolbar: Toolbar fun setupView( swipeRefreshLayout: SwipeRefreshLayout, streetViewImage: ImageView, streetViewProgressBar: ProgressBar, streetViewText: TextView, favoritesImage: ImageView, mapImage: ImageView, favoritesImageContainer: LinearLayout) { this.swipeRefreshLayout = swipeRefreshLayout.apply { setOnRefreshListener { refresh() } setColorSchemeColors(preferenceService.getColorSchemeColors(resources.configuration)) setProgressBackgroundColorSchemeResource(preferenceService.getProgressBackgroundColorSchemeResource(resources.configuration)) } this.streetViewImage = streetViewImage this.streetViewProgressBar = streetViewProgressBar this.streetViewText = streetViewText this.favoritesImage = favoritesImage this.mapImage = mapImage favoritesImageContainer.setOnClickListener{ switchFavorite() } } @SuppressLint("CheckResult") fun loadGoogleStreetImage(position: Position) { if (streetViewImage.tag == TAG_DEFAULT || streetViewImage.tag == TAG_ERROR) { googleStreetClient.getImage(position.latitude, position.longitude) .observeOn(AndroidSchedulers.mainThread()) .doFinally { streetViewProgressBar.visibility = View.GONE } .subscribe( { drawable -> streetViewImage.setImageDrawable(drawable) streetViewImage.tag = TAG_STREET_VIEW streetViewImage.scaleType = ImageView.ScaleType.CENTER_CROP streetViewText.visibility = View.VISIBLE }, { error -> Timber.e(error, "Error while loading street view image") failStreetViewImage(streetViewImage) } ) } } protected fun failStreetViewImage(streetViewImage: ImageView) { val placeHolder = App.instance.streetViewPlaceHolder streetViewImage.setImageDrawable(placeHolder) streetViewImage.scaleType = ImageView.ScaleType.CENTER streetViewImage.tag = TAG_ERROR } protected abstract fun isFavorite(): Boolean protected fun handleFavorite() { if (isFavorite()) { favoritesImage.setColorFilter(Color.yellowLineDark) } else { favoritesImage.drawable.colorFilter = mapImage.drawable.colorFilter } } protected open fun refresh() { swipeRefreshLayout.isRefreshing = true swipeRefreshLayout.setColorSchemeColors(util.randomColor) } protected fun stopRefreshing() { if (swipeRefreshLayout.isRefreshing) { swipeRefreshLayout.isRefreshing = false } } protected open fun switchFavorite() { applyFavorite = true } protected open fun buildToolbar(toolbar: Toolbar) { this.toolbar = toolbar toolbar.inflateMenu(R.menu.main) toolbar.setOnMenuItemClickListener { refresh(); false } toolbar.elevation = 4f toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp) toolbar.setOnClickListener { finish() } } }
apache-2.0
a1b7cac9b356c5d15b4af2803893f6a2
36.27027
137
0.69797
5.233397
false
false
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/Transceiver.kt
1
15017
/* * Copyright @ 2018 - Present, 8x8 Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.nlj import org.jitsi.nlj.format.PayloadType import org.jitsi.nlj.rtcp.RtcpEventNotifier import org.jitsi.nlj.rtp.RtpExtension import org.jitsi.nlj.rtp.bandwidthestimation.BandwidthEstimator import org.jitsi.nlj.srtp.SrtpTransformers import org.jitsi.nlj.srtp.SrtpUtil import org.jitsi.nlj.srtp.TlsRole import org.jitsi.nlj.stats.EndpointConnectionStats import org.jitsi.nlj.stats.NodeStatsBlock import org.jitsi.nlj.stats.PacketIOActivity import org.jitsi.nlj.stats.TransceiverStats import org.jitsi.nlj.transform.NodeStatsProducer import org.jitsi.nlj.util.Bandwidth import org.jitsi.nlj.util.LocalSsrcAssociation import org.jitsi.nlj.util.ReadOnlyStreamInformationStore import org.jitsi.nlj.util.SsrcAssociation import org.jitsi.nlj.util.StreamInformationStoreImpl import org.jitsi.utils.MediaType import org.jitsi.utils.logging.DiagnosticContext import org.jitsi.utils.logging2.Logger import org.jitsi.utils.logging2.cdebug import org.jitsi.utils.logging2.cinfo import org.jitsi.utils.logging2.createChildLogger import java.time.Clock import java.util.concurrent.ExecutorService import java.util.concurrent.ScheduledExecutorService // This is an API class, so its usages will largely be outside of this library @Suppress("unused") /** * Handles all packets (incoming and outgoing) for a particular stream. * (TODO: 'stream' defined as what, exactly, here?) * Handles the DTLS negotiation * * Incoming packets should be written via [handleIncomingPacket]. Outgoing * packets are put in [outgoingQueue] (and should be read by something) * TODO: maybe we want to have this 'push' the outgoing packets somewhere * else instead (then we could have all senders push to a single queue and * have the one thread just read from the queue and send, rather than that thread * having to read from a bunch of individual queues) */ class Transceiver( private val id: String, receiverExecutor: ExecutorService, senderExecutor: ExecutorService, /** * A [ScheduledExecutorService] which can be used for less important * background tasks, or tasks that need to execute at some fixed delay/rate */ backgroundExecutor: ScheduledExecutorService, diagnosticContext: DiagnosticContext, parentLogger: Logger, /** * The handler for events coming out of this [Transceiver]. Note that these events are fired synchronously, * potentially in one of the threads in the CPU pool, and it is up to the user of the library to handle the * transition to another thread if necessary. */ private val eventHandler: TransceiverEventHandler, private val clock: Clock = Clock.systemUTC() ) : Stoppable, NodeStatsProducer { private val logger = createChildLogger(parentLogger) val packetIOActivity = PacketIOActivity() private val endpointConnectionStats = EndpointConnectionStats(logger) private val streamInformationStore = StreamInformationStoreImpl() val readOnlyStreamInformationStore: ReadOnlyStreamInformationStore = streamInformationStore /** * A central place to subscribe to be notified on the reception or transmission of RTCP packets for * this transceiver. This is intended to be used by internal entities: mainly logic for things like generating * SRs and RRs and calculating RTT. Since it is used for both send and receive, it is held here and passed to * the sender and receive so each can push or subscribe to updates. */ val rtcpEventNotifier = RtcpEventNotifier() private var mediaSources = MediaSources() var srtpTransformers: SrtpTransformers? = null /** Whether the srtpTransformers were created inside this object, or passed in externally. * For external transformers it's the external owner's responsibility to close them. */ var internalTransformers = false /** * Whether this [Transceiver] is receiving audio from the remote endpoint. */ fun isReceivingAudio(): Boolean = rtpReceiver.isReceivingAudio() /** * Whether this [Transceiver] is receiving video from the remote endpoint. */ fun isReceivingVideo(): Boolean = rtpReceiver.isReceivingVideo() private val rtpSender: RtpSender = RtpSenderImpl( id, rtcpEventNotifier, senderExecutor, backgroundExecutor, streamInformationStore, logger, diagnosticContext ) private val rtpReceiver: RtpReceiver = RtpReceiverImpl( id, { rtcpPacket -> if (rtcpPacket.length >= 1500) { logger.warn( "Sending large locally-generated RTCP packet of size ${rtcpPacket.length}, " + "first packet of type ${rtcpPacket.packetType} rc ${rtcpPacket.reportCount}." ) } rtpSender.processPacket(PacketInfo(rtcpPacket)) }, rtcpEventNotifier, receiverExecutor, backgroundExecutor, streamInformationStore, eventHandler, logger, diagnosticContext ) init { rtpSender.bandwidthEstimator.addListener( object : BandwidthEstimator.Listener { override fun bandwidthEstimationChanged(newValue: Bandwidth) { eventHandler.bandwidthEstimationChanged(newValue) } } ) rtpReceiver.addLossListener(endpointConnectionStats.incomingLossTracker) rtpSender.addLossListener(endpointConnectionStats.outgoingLossTracker) rtcpEventNotifier.addRtcpEventListener(endpointConnectionStats) endpointConnectionStats.addListener(rtpSender) endpointConnectionStats.addListener(rtpReceiver) } /** * Handle an incoming [PacketInfo] (that is, a packet received by the endpoint * this transceiver is associated with) to be processed by the receiver pipeline. */ fun handleIncomingPacket(p: PacketInfo) { packetIOActivity.lastRtpPacketReceivedInstant = clock.instant() rtpReceiver.enqueuePacket(p) } /** * Send packets to the endpoint this transceiver is associated with by * passing them out the sender's outgoing pipeline */ fun sendPacket(packetInfo: PacketInfo) { packetIOActivity.lastRtpPacketSentInstant = clock.instant() rtpSender.processPacket(packetInfo) } fun sendProbing(mediaSsrcs: Collection<Long>, numBytes: Int): Int = rtpSender.sendProbing(mediaSsrcs, numBytes) /** * Set a handler to be invoked when incoming RTP packets have finished * being processed. */ fun setIncomingPacketHandler(rtpHandler: PacketHandler) { rtpReceiver.packetHandler = rtpHandler } /** * Set a handler to be invoked when outgoing packets have finished * being processed (and are ready to be sent) */ fun setOutgoingPacketHandler(outgoingPacketHandler: PacketHandler) { rtpSender.onOutgoingPacket(outgoingPacketHandler) } fun addReceiveSsrc(ssrc: Long, mediaType: MediaType) { logger.cdebug { "${hashCode()} adding receive ssrc $ssrc of type $mediaType" } streamInformationStore.addReceiveSsrc(ssrc, mediaType) } fun removeReceiveSsrc(ssrc: Long) { logger.cinfo { "Transceiver ${hashCode()} removing receive ssrc $ssrc" } streamInformationStore.removeReceiveSsrc(ssrc) } /** * Set the 'local' bridge SSRC to [ssrc] for [mediaType] */ fun setLocalSsrc(mediaType: MediaType, ssrc: Long) { val localSsrcSetEvent = SetLocalSsrcEvent(mediaType, ssrc) rtpSender.handleEvent(localSsrcSetEvent) rtpReceiver.handleEvent(localSsrcSetEvent) } fun receivesSsrc(ssrc: Long): Boolean = streamInformationStore.receiveSsrcs.contains(ssrc) val receiveSsrcs: Set<Long> get() = streamInformationStore.receiveSsrcs fun setMediaSources(mediaSources: Array<MediaSourceDesc>): Boolean { logger.cdebug { "$id setting media sources: ${mediaSources.joinToString()}" } val ret = this.mediaSources.setMediaSources(mediaSources) val mergedMediaSources = this.mediaSources.getMediaSources() val signaledMediaSources = mediaSources.copy() rtpReceiver.handleEvent(SetMediaSourcesEvent(mergedMediaSources, signaledMediaSources)) return ret } // TODO(brian): we should only expose an immutable version of this, but Array doesn't have that. Go in // and change all the storage of the media sources to use a list fun getMediaSources(): Array<MediaSourceDesc> = mediaSources.getMediaSources() @JvmOverloads fun requestKeyFrame(mediaSsrc: Long? = null) = rtpSender.requestKeyframe(mediaSsrc) fun addPayloadType(payloadType: PayloadType) { logger.cdebug { "Payload type added: $payloadType" } streamInformationStore.addRtpPayloadType(payloadType) } fun clearPayloadTypes() { logger.cinfo { "All payload types being cleared" } streamInformationStore.clearRtpPayloadTypes() } fun addRtpExtension(rtpExtension: RtpExtension) { logger.cdebug { "Adding RTP extension: $rtpExtension" } streamInformationStore.addRtpExtensionMapping(rtpExtension) } fun clearRtpExtensions() { logger.cinfo { "Clearing all RTP extensions" } // TODO: ignoring this for now, since we'll have conflicts from each channel calling it // val rtpExtensionClearEvent = RtpExtensionClearEvent() // rtpReceiver.handleEvent(rtpExtensionClearEvent) // rtpSender.handleEvent(rtpExtensionClearEvent) // rtpExtensions.clear() } // TODO(brian): we may want to handle local and remote ssrc associations differently, as different parts of the // code care about one or the other, but currently there is no issue treating them the same. fun addSsrcAssociation(ssrcAssociation: SsrcAssociation) { logger.cdebug { val location = if (ssrcAssociation is LocalSsrcAssociation) "local" else "remote" "Adding $location SSRC association: $ssrcAssociation" } streamInformationStore.addSsrcAssociation(ssrcAssociation) } fun setSrtpInformation(chosenSrtpProtectionProfile: Int, tlsRole: TlsRole, keyingMaterial: ByteArray) { val srtpProfileInfo = SrtpUtil.getSrtpProfileInformationFromSrtpProtectionProfile(chosenSrtpProtectionProfile) logger.cdebug { "Transceiver $id creating transformers with:\n" + "profile info:\n$srtpProfileInfo\n" + "tls role: $tlsRole" } srtpTransformers = SrtpUtil.initializeTransformer( srtpProfileInfo, keyingMaterial, tlsRole, logger ).also { setSrtpInformationInternal(it, true) } } private fun setSrtpInformationInternal(srtpTransformers: SrtpTransformers, internal: Boolean) { rtpReceiver.setSrtpTransformers(srtpTransformers) rtpSender.setSrtpTransformers(srtpTransformers) internalTransformers = internal } fun setSrtpInformation(srtpTransformers: SrtpTransformers) = setSrtpInformationInternal(srtpTransformers, false) /** * Forcibly mute or unmute the incoming audio stream */ fun forceMuteAudio(shouldMute: Boolean) { when (shouldMute) { true -> logger.info("Muting incoming audio") false -> logger.info("Unmuting incoming audio") } rtpReceiver.forceMuteAudio(shouldMute) } fun forceMuteVideo(shouldMute: Boolean) { when (shouldMute) { true -> logger.info("Muting incoming video") false -> logger.info("Unmuting incoming video") } rtpReceiver.forceMuteVideo(shouldMute) } /** * Get stats about this transceiver's pipeline nodes */ override fun getNodeStats(): NodeStatsBlock { return NodeStatsBlock("Transceiver $id").apply { addBlock(streamInformationStore.getNodeStats()) addBlock(mediaSources.getNodeStats()) addJson("endpointConnectionStats", endpointConnectionStats.getSnapshot().toJson()) addBlock(rtpReceiver.getNodeStats()) addBlock(rtpSender.getNodeStats()) } } /** * Get various media and network stats */ fun getTransceiverStats(): TransceiverStats { return TransceiverStats( endpointConnectionStats.getSnapshot(), rtpReceiver.getStats(), rtpSender.getStreamStats(), rtpSender.getPacketStreamStats(), rtpSender.bandwidthEstimator.getStats(clock.instant()), rtpSender.getTransportCcEngineStats() ) } fun addEndpointConnectionStatsListener(listener: EndpointConnectionStats.EndpointConnectionStatsListener) = endpointConnectionStats.addListener(listener) fun removeEndpointConnectionStatsListener(listener: EndpointConnectionStats.EndpointConnectionStatsListener) = endpointConnectionStats.removeListener(listener) override fun stop() { rtpReceiver.stop() rtpSender.stop() if (internalTransformers) { srtpTransformers?.close() } } fun teardown() { logger.info("Tearing down") rtpReceiver.tearDown() rtpSender.tearDown() } fun setFeature(feature: Features, enabled: Boolean) { rtpReceiver.setFeature(feature, enabled) rtpSender.setFeature(feature, enabled) } fun isFeatureEnabled(feature: Features): Boolean { // As of now, the only feature we have (pcap) is always enabled on both // the RTP sender and RTP receiver at the same time, so returning // the state of one of them is sufficient. If that were to change // in the future we'd have to rethink this API return rtpReceiver.isFeatureEnabled(feature) } companion object { init { // Node.plugins.add(BufferTracePlugin) // Node.PLUGINS_ENABLED = true } } } /** * Interface for handling events coming from a [Transceiver] * The intention is to extend if needed (e.g. merge with EndpointConnectionStats or a potential RtpSenderEventHandler). */ interface TransceiverEventHandler : RtpReceiverEventHandler
apache-2.0
c6e8b2bc3718d945fd55374bd476acf9
38.208877
119
0.699274
4.633446
false
false
false
false
ReactiveCircus/FlowBinding
flowbinding-android/src/main/java/reactivecircus/flowbinding/android/view/ViewLayoutChangeEventFlow.kt
1
1964
@file:Suppress("MatchingDeclarationName") package reactivecircus.flowbinding.android.view import android.view.View import androidx.annotation.CheckResult import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.conflate import reactivecircus.flowbinding.common.checkMainThread /** * Create a [Flow] of view layout change events on the [View] instance. * * Note: Created flow keeps a strong reference to the [View] instance * until the coroutine that launched the flow collector is cancelled. * * Example of usage: * * ``` * view.layoutChangeEvents() * .onEach { event -> * // handle layout change event * } * .launchIn(uiScope) * ``` */ @CheckResult @OptIn(ExperimentalCoroutinesApi::class) public fun View.layoutChangeEvents(): Flow<LayoutChangeEvent> = callbackFlow { checkMainThread() val listener = View.OnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom -> trySend( LayoutChangeEvent( view = v, left = left, top = top, right = right, bottom = bottom, oldLeft = oldLeft, oldTop = oldTop, oldRight = oldRight, oldBottom = oldBottom ) ) } addOnLayoutChangeListener(listener) awaitClose { removeOnLayoutChangeListener(listener) } }.conflate() @Suppress("LongParameterList") public data class LayoutChangeEvent( public val view: View, public val left: Int, public val top: Int, public val right: Int, public val bottom: Int, public val oldLeft: Int, public val oldTop: Int, public val oldRight: Int, public val oldBottom: Int )
apache-2.0
d170fcef2a746e819d99a5d34558dc57
29.215385
106
0.645112
4.873449
false
false
false
false
clarkcb/xsearch
kotlin/ktsearch/src/test/kotlin/ktsearch/SearchFileTest.kt
1
1060
package ktsearch import org.junit.Assert.assertEquals import org.junit.Test import java.io.File class SearchFileTest { @Test fun test_searchfile_abs_path() { val path = "/Users/cary/src/xsearch/kotlin/ktsearch/src/main/kotlin/ktsearch/SearchFile.kt" val searchFile = SearchFile(File(path), FileType.CODE) assertEquals(path, searchFile.toString()) } @Test fun test_searchfile_tilde_path() { val path = "~/src/xsearch/kotlin/ktsearch/src/main/kotlin/ktsearch/SearchFile.kt" val searchFile = SearchFile(File(path), FileType.CODE) assertEquals(path, searchFile.toString()) } @Test fun test_searchfile_rel_path1() { val path = "./SearchFile.kt" val searchFile = SearchFile(File(path), FileType.CODE) assertEquals(path, searchFile.toString()) } @Test fun test_searchfile_rel_path2() { val path = "../SearchFile.kt" val searchFile = SearchFile(File(path), FileType.CODE) assertEquals(path, searchFile.toString()) } }
mit
b69aaf4bff8ade01a742ac96bae11cef
28.444444
99
0.659434
3.826715
false
true
false
false
inorichi/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryController.kt
1
20868
package eu.kanade.tachiyomi.ui.library import android.content.res.Configuration import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import androidx.appcompat.view.ActionMode import androidx.core.view.isVisible import com.bluelinelabs.conductor.ControllerChangeHandler import com.bluelinelabs.conductor.ControllerChangeType import com.google.android.material.tabs.TabLayout import com.jakewharton.rxrelay.BehaviorRelay import com.jakewharton.rxrelay.PublishRelay import com.tfcporciuncula.flow.Preference import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Category import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.library.LibraryUpdateService import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.databinding.LibraryControllerBinding import eu.kanade.tachiyomi.source.LocalSource import eu.kanade.tachiyomi.ui.base.controller.RootController import eu.kanade.tachiyomi.ui.base.controller.SearchableNucleusController import eu.kanade.tachiyomi.ui.base.controller.TabbedController import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction import eu.kanade.tachiyomi.ui.browse.source.globalsearch.GlobalSearchController import eu.kanade.tachiyomi.ui.main.MainActivity import eu.kanade.tachiyomi.ui.manga.MangaController import eu.kanade.tachiyomi.util.preference.asImmediateFlow import eu.kanade.tachiyomi.util.system.getResourceColor import eu.kanade.tachiyomi.util.system.openInBrowser import eu.kanade.tachiyomi.util.system.toast import eu.kanade.tachiyomi.widget.ActionModeWithToolbar import eu.kanade.tachiyomi.widget.EmptyView import eu.kanade.tachiyomi.widget.materialdialogs.QuadStateTextView import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import reactivecircus.flowbinding.android.view.clicks import reactivecircus.flowbinding.viewpager.pageSelections import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.util.concurrent.TimeUnit class LibraryController( bundle: Bundle? = null, private val preferences: PreferencesHelper = Injekt.get() ) : SearchableNucleusController<LibraryControllerBinding, LibraryPresenter>(bundle), RootController, TabbedController, ActionModeWithToolbar.Callback, ChangeMangaCategoriesDialog.Listener, DeleteLibraryMangasDialog.Listener { /** * Position of the active category. */ private var activeCategory: Int = preferences.lastUsedCategory().get() /** * Action mode for selections. */ private var actionMode: ActionModeWithToolbar? = null /** * Currently selected mangas. */ val selectedMangas = mutableSetOf<Manga>() /** * Relay to notify the UI of selection updates. */ val selectionRelay: PublishRelay<LibrarySelectionEvent> = PublishRelay.create() /** * Relay to notify search query changes. */ val searchRelay: BehaviorRelay<String> = BehaviorRelay.create() /** * Relay to notify the library's viewpager for updates. */ val libraryMangaRelay: BehaviorRelay<LibraryMangaEvent> = BehaviorRelay.create() /** * Relay to notify the library's viewpager to select all manga */ val selectAllRelay: PublishRelay<Int> = PublishRelay.create() /** * Relay to notify the library's viewpager to select the inverse */ val selectInverseRelay: PublishRelay<Int> = PublishRelay.create() /** * Number of manga per row in grid mode. */ var mangaPerRow = 0 private set /** * Adapter of the view pager. */ private var adapter: LibraryAdapter? = null /** * Sheet containing filter/sort/display items. */ private var settingsSheet: LibrarySettingsSheet? = null private var tabsVisibilityRelay: BehaviorRelay<Boolean> = BehaviorRelay.create(false) private var mangaCountVisibilityRelay: BehaviorRelay<Boolean> = BehaviorRelay.create(false) private var tabsVisibilitySubscription: Subscription? = null private var mangaCountVisibilitySubscription: Subscription? = null init { setHasOptionsMenu(true) retainViewMode = RetainViewMode.RETAIN_DETACH } private var currentTitle: String? = null set(value) { if (field != value) { field = value setTitle() } } override fun getTitle(): String? { return currentTitle ?: resources?.getString(R.string.label_library) } private fun updateTitle() { val showCategoryTabs = preferences.categoryTabs().get() val currentCategory = adapter?.categories?.getOrNull(binding.libraryPager.currentItem) var title = if (showCategoryTabs) { resources?.getString(R.string.label_library) } else { currentCategory?.name } if (preferences.categoryNumberOfItems().get() && libraryMangaRelay.hasValue()) { libraryMangaRelay.value.mangas.let { mangaMap -> if (!showCategoryTabs || adapter?.categories?.size == 1) { title += " (${mangaMap[currentCategory?.id]?.size ?: 0})" } } } currentTitle = title } override fun createPresenter(): LibraryPresenter { return LibraryPresenter() } override fun createBinding(inflater: LayoutInflater) = LibraryControllerBinding.inflate(inflater) override fun onViewCreated(view: View) { super.onViewCreated(view) adapter = LibraryAdapter(this) binding.libraryPager.adapter = adapter binding.libraryPager.pageSelections() .drop(1) .onEach { preferences.lastUsedCategory().set(it) activeCategory = it updateTitle() } .launchIn(viewScope) getColumnsPreferenceForCurrentOrientation().asImmediateFlow { mangaPerRow = it } .drop(1) // Set again the adapter to recalculate the covers height .onEach { reattachAdapter() } .launchIn(viewScope) if (selectedMangas.isNotEmpty()) { createActionModeIfNeeded() } settingsSheet = LibrarySettingsSheet(router) { group -> when (group) { is LibrarySettingsSheet.Filter.FilterGroup -> onFilterChanged() is LibrarySettingsSheet.Sort.SortGroup -> onSortChanged() is LibrarySettingsSheet.Display.DisplayGroup -> { val delay = if (preferences.categorizedDisplaySettings().get()) 125L else 0L Observable.timer(delay, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()) .subscribe { reattachAdapter() } } is LibrarySettingsSheet.Display.BadgeGroup -> onBadgeSettingChanged() is LibrarySettingsSheet.Display.TabsGroup -> onTabsSettingsChanged() } } binding.btnGlobalSearch.clicks() .onEach { router.pushController( GlobalSearchController(presenter.query).withFadeTransaction() ) } .launchIn(viewScope) } override fun onChangeStarted(handler: ControllerChangeHandler, type: ControllerChangeType) { super.onChangeStarted(handler, type) if (type.isEnter) { (activity as? MainActivity)?.binding?.tabs?.setupWithViewPager(binding.libraryPager) presenter.subscribeLibrary() } } override fun onDestroyView(view: View) { destroyActionModeIfNeeded() adapter?.onDestroy() adapter = null settingsSheet = null tabsVisibilitySubscription?.unsubscribe() tabsVisibilitySubscription = null super.onDestroyView(view) } override fun configureTabs(tabs: TabLayout) { with(tabs) { tabGravity = TabLayout.GRAVITY_START tabMode = TabLayout.MODE_SCROLLABLE } tabsVisibilitySubscription?.unsubscribe() tabsVisibilitySubscription = tabsVisibilityRelay.subscribe { visible -> tabs.isVisible = visible } mangaCountVisibilitySubscription?.unsubscribe() mangaCountVisibilitySubscription = mangaCountVisibilityRelay.subscribe { adapter?.notifyDataSetChanged() } } override fun cleanupTabs(tabs: TabLayout) { tabsVisibilitySubscription?.unsubscribe() tabsVisibilitySubscription = null } fun showSettingsSheet() { if (adapter?.categories?.isNotEmpty() == true) { adapter?.categories?.get(binding.libraryPager.currentItem)?.let { category -> settingsSheet?.show(category) } } else { settingsSheet?.show() } } fun onNextLibraryUpdate(categories: List<Category>, mangaMap: Map<Int, List<LibraryItem>>) { val view = view ?: return val adapter = adapter ?: return // Show empty view if needed if (mangaMap.isNotEmpty()) { binding.emptyView.hide() } else { binding.emptyView.show( R.string.information_empty_library, listOf( EmptyView.Action(R.string.getting_started_guide, R.drawable.ic_help_24dp) { activity?.openInBrowser("https://tachiyomi.org/help/guides/getting-started") } ), ) (activity as? MainActivity)?.ready = true } // Get the current active category. val activeCat = if (adapter.categories.isNotEmpty()) { binding.libraryPager.currentItem } else { activeCategory } // Set the categories adapter.categories = categories adapter.itemsPerCategory = adapter.categories .map { (it.id ?: -1) to (mangaMap[it.id]?.size ?: 0) } .toMap() // Restore active category. binding.libraryPager.setCurrentItem(activeCat, false) // Trigger display of tabs onTabsSettingsChanged() // Delay the scroll position to allow the view to be properly measured. view.post { if (isAttached) { (activity as? MainActivity)?.binding?.tabs?.setScrollPosition(binding.libraryPager.currentItem, 0f, true) } } // Send the manga map to child fragments after the adapter is updated. libraryMangaRelay.call(LibraryMangaEvent(mangaMap)) // Finally update the title updateTitle() } /** * Returns a preference for the number of manga per row based on the current orientation. * * @return the preference. */ private fun getColumnsPreferenceForCurrentOrientation(): Preference<Int> { return if (resources?.configuration?.orientation == Configuration.ORIENTATION_PORTRAIT) { preferences.portraitColumns() } else { preferences.landscapeColumns() } } private fun onFilterChanged() { presenter.requestFilterUpdate() activity?.invalidateOptionsMenu() } private fun onBadgeSettingChanged() { presenter.requestBadgesUpdate() } private fun onTabsSettingsChanged() { tabsVisibilityRelay.call(preferences.categoryTabs().get() && adapter?.categories?.size ?: 0 > 1) mangaCountVisibilityRelay.call(preferences.categoryNumberOfItems().get()) updateTitle() } /** * Called when the sorting mode is changed. */ private fun onSortChanged() { presenter.requestSortUpdate() } /** * Reattaches the adapter to the view pager to recreate fragments */ private fun reattachAdapter() { val adapter = adapter ?: return val position = binding.libraryPager.currentItem adapter.recycle = false binding.libraryPager.adapter = adapter binding.libraryPager.currentItem = position adapter.recycle = true } /** * Creates the action mode if it's not created already. */ fun createActionModeIfNeeded() { val activity = activity if (actionMode == null && activity is MainActivity) { actionMode = activity.startActionModeAndToolbar(this) activity.showBottomNav(false) } } /** * Destroys the action mode. */ private fun destroyActionModeIfNeeded() { actionMode?.finish() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { createOptionsMenu(menu, inflater, R.menu.library, R.id.action_search) // Mutate the filter icon because it needs to be tinted and the resource is shared. menu.findItem(R.id.action_filter).icon.mutate() } fun search(query: String) { presenter.query = query } private fun performSearch() { searchRelay.call(presenter.query) if (presenter.query.isNotEmpty()) { binding.btnGlobalSearch.isVisible = true binding.btnGlobalSearch.text = resources?.getString(R.string.action_global_search_query, presenter.query) } else { binding.btnGlobalSearch.isVisible = false } } override fun onPrepareOptionsMenu(menu: Menu) { val settingsSheet = settingsSheet ?: return val filterItem = menu.findItem(R.id.action_filter) // Tint icon if there's a filter active if (settingsSheet.filters.hasActiveFilters()) { val filterColor = activity!!.getResourceColor(R.attr.colorFilterActive) filterItem.icon.setTint(filterColor) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_search -> expandActionViewFromInteraction = true R.id.action_filter -> showSettingsSheet() R.id.action_update_library -> { activity?.let { if (LibraryUpdateService.start(it)) { it.toast(R.string.updating_library) } } } } return super.onOptionsItemSelected(item) } /** * Invalidates the action mode, forcing it to refresh its content. */ fun invalidateActionMode() { actionMode?.invalidate() } override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.menuInflater.inflate(R.menu.generic_selection, menu) return true } override fun onCreateActionToolbar(menuInflater: MenuInflater, menu: Menu) { menuInflater.inflate(R.menu.library_selection, menu) } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { val count = selectedMangas.size if (count == 0) { // Destroy action mode if there are no items selected. destroyActionModeIfNeeded() } else { mode.title = count.toString() } return true } override fun onPrepareActionToolbar(toolbar: ActionModeWithToolbar, menu: Menu) { if (selectedMangas.isEmpty()) return toolbar.findToolbarItem(R.id.action_download_unread)?.isVisible = selectedMangas.any { it.source != LocalSource.ID } } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { when (item.itemId) { R.id.action_move_to_category -> showChangeMangaCategoriesDialog() R.id.action_download_unread -> downloadUnreadChapters() R.id.action_mark_as_read -> markReadStatus(true) R.id.action_mark_as_unread -> markReadStatus(false) R.id.action_delete -> showDeleteMangaDialog() R.id.action_select_all -> selectAllCategoryManga() R.id.action_select_inverse -> selectInverseCategoryManga() else -> return false } return true } override fun onDestroyActionMode(mode: ActionMode) { // Clear all the manga selections and notify child views. selectedMangas.clear() selectionRelay.call(LibrarySelectionEvent.Cleared()) (activity as? MainActivity)?.showBottomNav(true) actionMode = null } fun openManga(manga: Manga) { // Notify the presenter a manga is being opened. presenter.onOpenManga() router.pushController(MangaController(manga).withFadeTransaction()) } /** * Sets the selection for a given manga. * * @param manga the manga whose selection has changed. * @param selected whether it's now selected or not. */ fun setSelection(manga: Manga, selected: Boolean) { if (selected) { if (selectedMangas.add(manga)) { selectionRelay.call(LibrarySelectionEvent.Selected(manga)) } } else { if (selectedMangas.remove(manga)) { selectionRelay.call(LibrarySelectionEvent.Unselected(manga)) } } } /** * Toggles the current selection state for a given manga. * * @param manga the manga whose selection to change. */ fun toggleSelection(manga: Manga) { if (selectedMangas.add(manga)) { selectionRelay.call(LibrarySelectionEvent.Selected(manga)) } else if (selectedMangas.remove(manga)) { selectionRelay.call(LibrarySelectionEvent.Unselected(manga)) } } /** * Clear all of the manga currently selected, and * invalidate the action mode to revert the top toolbar */ fun clearSelection() { selectedMangas.clear() selectionRelay.call(LibrarySelectionEvent.Cleared()) invalidateActionMode() } /** * Move the selected manga to a list of categories. */ private fun showChangeMangaCategoriesDialog() { // Create a copy of selected manga val mangas = selectedMangas.toList() // Hide the default category because it has a different behavior than the ones from db. val categories = presenter.categories.filter { it.id != 0 } // Get indexes of the common categories to preselect. val common = presenter.getCommonCategories(mangas) // Get indexes of the mix categories to preselect. val mix = presenter.getMixCategories(mangas) var preselected = categories.map { when (it) { in common -> QuadStateTextView.State.CHECKED.ordinal in mix -> QuadStateTextView.State.INDETERMINATE.ordinal else -> QuadStateTextView.State.UNCHECKED.ordinal } }.toTypedArray() ChangeMangaCategoriesDialog(this, mangas, categories, preselected) .showDialog(router) } private fun downloadUnreadChapters() { val mangas = selectedMangas.toList() presenter.downloadUnreadChapters(mangas) destroyActionModeIfNeeded() } private fun markReadStatus(read: Boolean) { val mangas = selectedMangas.toList() presenter.markReadStatus(mangas, read) destroyActionModeIfNeeded() } private fun showDeleteMangaDialog() { DeleteLibraryMangasDialog(this, selectedMangas.toList()).showDialog(router) } override fun updateCategoriesForMangas(mangas: List<Manga>, addCategories: List<Category>, removeCategories: List<Category>) { presenter.updateMangasToCategories(mangas, addCategories, removeCategories) destroyActionModeIfNeeded() } override fun deleteMangas(mangas: List<Manga>, deleteFromLibrary: Boolean, deleteChapters: Boolean) { presenter.removeMangas(mangas, deleteFromLibrary, deleteChapters) destroyActionModeIfNeeded() } private fun selectAllCategoryManga() { adapter?.categories?.getOrNull(binding.libraryPager.currentItem)?.id?.let { selectAllRelay.call(it) } } private fun selectInverseCategoryManga() { adapter?.categories?.getOrNull(binding.libraryPager.currentItem)?.id?.let { selectInverseRelay.call(it) } } override fun onSearchViewQueryTextChange(newText: String?) { // Ignore events if this controller isn't at the top to avoid query being reset if (router.backstack.lastOrNull()?.controller == this) { presenter.query = newText ?: "" performSearch() } } }
apache-2.0
b5cf4dbe337675a5742a9b17ecb4a169
33.209836
130
0.649415
4.966207
false
false
false
false
Kiskae/Twitch-Archiver
ui/src/main/kotlin/net/serverpeon/twitcharchiver/ReactiveFx.kt
1
3025
package net.serverpeon.twitcharchiver import com.sun.javafx.binding.ExpressionHelper import javafx.application.Platform import javafx.beans.InvalidationListener import javafx.beans.value.ChangeListener import javafx.beans.value.ObservableValue import rx.Observable import rx.Scheduler import rx.Subscriber import rx.Subscription import rx.functions.Action0 import rx.functions.Action1 import rx.schedulers.Schedulers import rx.subscriptions.Subscriptions import java.util.concurrent.atomic.AtomicReference private class ReactiveFxObservable<T>(val base: Observable<T>, default: T) : ObservableValue<T>, Action1<T> { override fun call(t: T) { ref.set(t) ExpressionHelper.fireValueChangedEvent(helper) } private val ref: AtomicReference<T> = AtomicReference(default) private val sub: AtomicReference<Subscription?> = AtomicReference(null) private var helper: ExpressionHelper<T>? = null override fun getValue(): T { return ref.get() } override fun addListener(listener: ChangeListener<in T>) { ensureSubscription() helper = ExpressionHelper.addListener(helper, this, listener) } override fun removeListener(listener: ChangeListener<in T>) { if (helper == null) return helper = ExpressionHelper.removeListener(helper, listener) clearSubscription() } override fun addListener(listener: InvalidationListener?) { ensureSubscription() helper = ExpressionHelper.addListener(helper, this, listener) } override fun removeListener(listener: InvalidationListener?) { if (helper == null) return helper = ExpressionHelper.removeListener(helper, listener) clearSubscription() } private fun ensureSubscription() { if (helper == null) { check(sub.compareAndSet(null, base.subscribe(this))) } } private fun clearSubscription() { if (helper == null) { checkNotNull(sub.getAndSet(null)).unsubscribe() } } } object ReactiveFx { val scheduler: Scheduler = Schedulers.from { Platform.runLater(it) } } fun <T> Observable<T>.toFx(def: T): ObservableValue<T> { return ReactiveFxObservable(this, def) } fun <T : javafx.beans.Observable> T.observeInvalidation(): Observable<T> { return observeInvalidation { it } } private class SubscriptionInvalidator<T : javafx.beans.Observable, O>( val sub: Subscriber<O>, val obs: T, val extractor: (T) -> O ) : InvalidationListener, Action0 { init { sub.add(Subscriptions.create(this)) } override fun invalidated(observable: javafx.beans.Observable?) { sub.onNext(extractor(obs)) } override fun call() { //Subscription ended obs.removeListener(this) } } fun <T : javafx.beans.Observable, O> T.observeInvalidation(extractor: (T) -> O): Observable<O> { return Observable.create { sub -> this.addListener(SubscriptionInvalidator(sub, this, extractor)) } }
mit
60ad064c2d5f3a80789b0516a21a2be1
28.378641
109
0.692562
4.35879
false
false
false
false
Zhuinden/simple-stack
samples/advanced-samples/mvvm-sample/src/main/java/com/zhuinden/simplestackexamplemvvm/features/tasks/TaskItem.kt
1
1506
package com.zhuinden.simplestackexamplemvvm.features.tasks import android.view.View import android.widget.CompoundButton import com.xwray.groupie.viewbinding.BindableItem import com.zhuinden.simplestackexamplemvvm.R import com.zhuinden.simplestackexamplemvvm.data.Task import com.zhuinden.simplestackexamplemvvm.databinding.TaskItemBinding import com.zhuinden.simplestackexamplemvvm.features.taskdetail.TaskDetailKey import com.zhuinden.simplestackextensions.navigatorktx.backstack class TaskItem( private val task: Task, private val listener: Listener ) : BindableItem<TaskItemBinding>() { interface Listener { fun onTaskCheckChanged(task: Task, isChecked: Boolean) } private val onCheckChanged = CompoundButton.OnCheckedChangeListener { view, isChecked -> listener.onTaskCheckChanged(task, isChecked) } private val onClick = View.OnClickListener { view -> view.backstack.goTo(TaskDetailKey(task)) } override fun getLayout(): Int = R.layout.task_item override fun initializeViewBinding(view: View): TaskItemBinding = TaskItemBinding.bind(view) override fun bind(viewBinding: TaskItemBinding, position: Int) { with(viewBinding) { this.title.text = task.titleForList this.complete.setOnCheckedChangeListener(null) this.complete.isChecked = task.isCompleted this.complete.setOnCheckedChangeListener(onCheckChanged) root.setOnClickListener(onClick) } } }
apache-2.0
1fe68ba2bb194227f347725191121938
35.756098
96
0.754316
4.986755
false
false
false
false
beyama/winter
android-sample-app/src/main/java/io/jentz/winter/android/sample/quotes/QuotesAdapter.kt
1
1154
package io.jentz.winter.android.sample.quotes import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import io.jentz.winter.android.sample.R import io.jentz.winter.android.sample.model.Quote import io.jentz.winter.androidx.inject.ActivityScope import io.jentz.winter.inject.InjectConstructor @ActivityScope @InjectConstructor class QuotesAdapter( private val inflater: LayoutInflater ) : RecyclerView.Adapter<QuotesAdapter.ViewHolder>() { class ViewHolder( val quoteItemView: QuoteItemView ) : RecyclerView.ViewHolder(quoteItemView) var list: List<Quote>? = null set(value) { field = value notifyDataSetChanged() } override fun getItemCount(): Int = list?.count() ?: 0 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder(inflater.inflate(R.layout.quote_item_view, parent, false) as QuoteItemView) override fun onBindViewHolder(holder: ViewHolder, position: Int) { val quote = list?.get(position) ?: return holder.quoteItemView.render(quote) } }
apache-2.0
6d60831b891d0f321a7c43e2a501af9c
30.216216
94
0.733969
4.40458
false
false
false
false
noties/Markwon
app-sample/src/main/java/io/noties/markwon/app/samples/editor/shared/MarkwonEditTextSample.kt
1
3703
package io.noties.markwon.app.samples.editor.shared import android.content.Context import android.text.SpannableStringBuilder import android.text.Spanned import android.text.style.StrikethroughSpan import android.view.View import android.widget.Button import android.widget.EditText import android.widget.TextView import io.noties.markwon.app.R import io.noties.markwon.app.sample.ui.MarkwonSample import io.noties.markwon.core.spans.EmphasisSpan import io.noties.markwon.core.spans.StrongEmphasisSpan import java.util.ArrayList abstract class MarkwonEditTextSample : MarkwonSample() { protected lateinit var context: Context protected lateinit var editText: EditText override val layoutResId: Int get() = R.layout.sample_edit_text override fun onViewCreated(view: View) { context = view.context editText = view.findViewById(R.id.edit_text) initBottomBar(view) render() } abstract fun render() private fun initBottomBar(view: View) { // all except block-quote wraps if have selection, or inserts at current cursor position val bold: Button = view.findViewById(R.id.bold) val italic: Button = view.findViewById(R.id.italic) val strike: Button = view.findViewById(R.id.strike) val quote: Button = view.findViewById(R.id.quote) val code: Button = view.findViewById(R.id.code) addSpan(bold, StrongEmphasisSpan()) addSpan(italic, EmphasisSpan()) addSpan(strike, StrikethroughSpan()) bold.setOnClickListener(InsertOrWrapClickListener(editText, "**")) italic.setOnClickListener(InsertOrWrapClickListener(editText, "_")) strike.setOnClickListener(InsertOrWrapClickListener(editText, "~~")) code.setOnClickListener(InsertOrWrapClickListener(editText, "`")) quote.setOnClickListener { val start = editText.selectionStart val end = editText.selectionEnd if (start < 0) { return@setOnClickListener } if (start == end) { editText.text.insert(start, "> ") } else { // wrap the whole selected area in a quote val newLines: MutableList<Int> = ArrayList(3) newLines.add(start) val text = editText.text.subSequence(start, end).toString() var index = text.indexOf('\n') while (index != -1) { newLines.add(start + index + 1) index = text.indexOf('\n', index + 1) } for (i in newLines.indices.reversed()) { editText.text.insert(newLines[i], "> ") } } } } private fun addSpan(textView: TextView, vararg spans: Any) { val builder = SpannableStringBuilder(textView.text) val end = builder.length for (span in spans) { builder.setSpan(span, 0, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } textView.text = builder } private class InsertOrWrapClickListener( private val editText: EditText, private val text: String ) : View.OnClickListener { override fun onClick(v: View) { val start = editText.selectionStart val end = editText.selectionEnd if (start < 0) { return } if (start == end) { // insert at current position editText.text.insert(start, text) } else { editText.text.insert(end, text) editText.text.insert(start, text) } } } }
apache-2.0
b24adbbd132663d0b771c73f72a2acaa
34.615385
96
0.610586
4.675505
false
false
false
false
roylanceMichael/yaorm
yaorm/src/main/java/org/roylance/yaorm/services/jdbc/JDBCCursor.kt
1
2400
package org.roylance.yaorm.services.jdbc import org.roylance.yaorm.YaormModel import org.roylance.yaorm.services.ICursor import org.roylance.yaorm.services.IStreamer import org.roylance.yaorm.utilities.YaormUtils import java.sql.ResultSet import java.sql.SQLException import java.util.* class JDBCCursor(private val definitionModel: YaormModel.TableDefinition, private val resultSet: ResultSet): ICursor { private val namesToAvoid = HashSet<String>() fun moveNext(): Boolean { return this.resultSet.next() } fun getRecord(): YaormModel.Record { val newInstance = YaormModel.Record.newBuilder() // set all the properties that we can this.definitionModel .columnDefinitionsList .distinctBy { it.name } .forEach { if (this.namesToAvoid.contains(it.name)) { val propertyHolder = YaormUtils.buildColumn(YaormUtils.EmptyString, it) newInstance.addColumns(propertyHolder) } else { try { val newValue = resultSet.getString(it.name) val propertyHolder = YaormUtils.buildColumn(newValue, it) newInstance.addColumns(propertyHolder) } catch (e:SQLException) { // if we can't see this name for w/e reason, we'll print to the console, but continue on // e.printStackTrace() this.namesToAvoid.add(it.name) val propertyHolder = YaormUtils.buildColumn(YaormUtils.EmptyString, it) newInstance.addColumns(propertyHolder) } } } return newInstance.build() } override fun getRecords(): YaormModel.Records { val returnItems = YaormModel.Records.newBuilder() while (this.moveNext()) { returnItems.addRecords(this.getRecord()) } this.resultSet.close() return returnItems.build() } override fun getRecordsStream(streamer: IStreamer) { while (this.moveNext()) { streamer.stream(this.getRecord()) } this.resultSet.close() } }
mit
1054875765f6b6a7780929d3f242f54a
35.363636
116
0.5625
5.217391
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/util/sharedPrefs/UserPrefs.kt
1
1499
/* * Copyright (c) 2017. Toshi Inc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.toshi.util.sharedPrefs import android.content.Context import com.toshi.util.FileNames import com.toshi.view.BaseApplication class UserPrefs : UserPrefsInterface { companion object { private const val OLD_USER_ID = "uid" private const val USER_ID = "uid_v2" } private val prefs by lazy { BaseApplication.get().getSharedPreferences(FileNames.USER_PREFS, Context.MODE_PRIVATE) } override fun getOldUserId(): String? = prefs.getString(OLD_USER_ID, null) override fun getUserId(): String? = prefs.getString(USER_ID, null) override fun setUserId(userId: String) = prefs.edit().putString(USER_ID, userId).apply() override fun clear() { prefs.edit() .clear() .apply() } }
gpl-3.0
69334844b51531e729ebb33acdc6161e
33.090909
120
0.685791
4.062331
false
false
false
false
tfcbandgeek/SmartReminders-android
app/src/main/java/jgappsandgames/smartreminderslite/tasks/TagEditorActivity.kt
1
5396
package jgappsandgames.smartreminderslite.tasks // Android import android.app.Activity import android.content.Intent import android.os.Bundle // Views import android.text.Editable import android.text.TextWatcher import android.view.View import androidx.appcompat.app.AppCompatActivity // JSON import org.json.JSONArray import org.json.JSONException // App import jgappsandgames.smartreminderslite.R import jgappsandgames.smartreminderslite.adapter.TagAdapter import jgappsandgames.smartreminderslite.utility.* // KotlinX import kotlinx.android.synthetic.main.activity_tag_editpr.* // Save import jgappsandgames.smartreminderssave.tags.TagManager import jgappsandgames.smartreminderssave.tasks.Task /** * TagEditorActivity * Created by joshua on 1/19/2018. */ class TagEditorActivity: AppCompatActivity(), TextWatcher, View.OnClickListener, TagAdapter.TagSwitcher { // Data ---------------------------------------------------------------------------------------- private lateinit var task: Task // LifeCycle Methods -------------------------------------------------------------------------- override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_tag_editpr) // Set Result Intent setResult(RESPONSE_NONE) // Load Data task = Task(intent.getStringExtra(TASK_NAME)) // Set Listeners tag_editor_search_enter.setOnClickListener(this) tag_editor_search_text.addTextChangedListener(this) // Set Adapters tag_editor_selected.adapter = TagAdapter(this, this, task.getTags(), true) tag_editor_unselected.adapter = TagAdapter(this, this, task.getTags(), false) } // Text Watcher Methods ------------------------------------------------------------------------ override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {} override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) { if (tag_editor_search_text.text.toString().isEmpty()) { tag_editor_selected!!.adapter = TagAdapter(this, this, task.getTags(), true) tag_editor_unselected!!.adapter = TagAdapter(this, this, task.getTags(), false) } else { tag_editor_selected!!.adapter = TagAdapter(this, this, task.getTags(), true, tag_editor_search_text.text.toString()) tag_editor_unselected!!.adapter = TagAdapter(this, this, task.getTags(), false, tag_editor_search_text.text.toString()) } if (TagManager.contains(tag_editor_search_text.text.toString())) tag_editor_search_enter.setText(R.string.select) else tag_editor_search_enter.setText(R.string.add) } override fun afterTextChanged(editable: Editable) {} // Click Listeners ----------------------------------------------------------------------------- override fun onClick(view: View) { // Tag is Not in the List And is addable if (TagManager.addTag(tag_editor_search_text.text.toString())) { task.addTag(tag_editor_search_text.text.toString()) tag_editor_search_text.setText("") tag_editor_selected!!.adapter = TagAdapter(this, this, task.getTags(), true) tag_editor_unselected!!.adapter = TagAdapter(this, this, task.getTags(), false) // Set new Result Intent try { val tags = JSONArray() for (tag in task.getTags()) tags.put(tag) setResult(RESPONSE_CHANGE, Intent().putExtra(TAG_LIST, tags.toString())) } catch (e: JSONException) { e.printStackTrace() } catch (e: NullPointerException) { e.printStackTrace() } } else if (tag_editor_search_text.text.toString() != "") { task.addTag(tag_editor_search_text.text.toString()) tag_editor_search_text.setText("") tag_editor_selected!!.adapter = TagAdapter(this, this, task.getTags(), true) tag_editor_unselected!!.adapter = TagAdapter(this, this, task.getTags(), false) // Set new Result Intent try { val tags = JSONArray() for (tag in task.getTags()) tags.put(tag) setResult(RESPONSE_CHANGE, Intent().putExtra(TAG_LIST, tags.toString())) } catch (e: JSONException) { e.printStackTrace() } catch (e: NullPointerException) { e.printStackTrace() } } } // TagSwitcher --------------------------------------------------------------------------------- override fun moveTag(tag: String, selected: Boolean) { if (selected) task.addTag(tag) else task.removeTag(tag) // Set Adapters this.tag_editor_selected!!.adapter = TagAdapter(this, this, task.getTags(), true) this.tag_editor_unselected!!.adapter = TagAdapter(this, this, task.getTags(), false) // Set New Result Intent try { val tags = JSONArray() for (ta in task.getTags()) tags.put(ta) setResult(RESPONSE_CHANGE, Intent().putExtra(TAG_LIST, tags.toString())) } catch (e: JSONException) { e.printStackTrace() } catch (e: NullPointerException) { e.printStackTrace() } } }
apache-2.0
94bdda54677364aaefc55f19fd483230
39.276119
131
0.593958
4.643718
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/livedata/CommentsPagingSource.kt
1
1644
package com.boardgamegeek.livedata import androidx.paging.PagingSource import androidx.paging.PagingState import com.boardgamegeek.entities.GameCommentEntity import com.boardgamegeek.provider.BggContract import com.boardgamegeek.repository.GameRepository import retrofit2.HttpException import timber.log.Timber class CommentsPagingSource(val gameId: Int, private val sortByRating: Boolean = false, val repository: GameRepository) : PagingSource<Int, GameCommentEntity>() { override fun getRefreshKey(state: PagingState<Int, GameCommentEntity>): Int? { return null // not sure this is correct, but I hope this will have paging start over from 1 } override suspend fun load(params: LoadParams<Int>): LoadResult<Int, GameCommentEntity> { return try { if (gameId == BggContract.INVALID_ID) return LoadResult.Error(Exception("Invalid ID")) val page = params.key ?: 1 val entity = if (sortByRating) repository.loadRatings(gameId, page) else repository.loadComments(gameId, page) val nextPage = getNextPage(page, params.loadSize, entity?.numberOfRatings ?: 0) LoadResult.Page(entity?.ratings.orEmpty(), null, nextPage) } catch (e: Exception) { if (e is HttpException) { Timber.w("Error code: ${e.code()}\n${e.response()?.body()}") } else { Timber.w(e) } LoadResult.Error(e) } } private fun getNextPage(currentPage: Int, pageSize: Int, totalCount: Int): Int? { return if (currentPage * pageSize < totalCount) currentPage + 1 else null } }
gpl-3.0
d6eb98fc629c21731c96ed4a41064e5b
42.263158
122
0.67944
4.617978
false
false
false
false
aCoder2013/general
general-server/src/main/java/com/song/middleware/server/web/api/ServiceInfoCollectorApi.kt
1
4061
package com.song.middleware.server.web.api import com.song.middleware.server.domain.ServiceDO import com.song.middleware.server.storage.ServiceStorageComponent import com.song.middleware.server.storage.exception.StorageException import com.song.middleware.server.web.support.ApiResult import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController /** * Created by song on 2017/8/5. */ @RestController @RequestMapping(value = "/api/v1/service") class ServiceInfoCollectorApi @Autowired constructor(private val storageComponent: ServiceStorageComponent) { @PostMapping(value = "/query") fun query( @RequestParam(value = "name", required = false) name: String): ApiResult<List<ServiceDO>> { val apiResult = ApiResult.create<List<ServiceDO>>() if (StringUtils.isEmpty(name)) { apiResult.data = emptyList<ServiceDO>() } try { val serviceDOS = storageComponent.syncQuery(name) if (serviceDOS != null) { apiResult.isSuccess = true apiResult.data = serviceDOS } } catch (e: Exception) { apiResult.message = "query failed, " + e.message log.error("query failed_" + e.message, e) } return apiResult } @PostMapping(value = "/register") fun register( @RequestParam(value = "name", required = false) name: String, @RequestParam(value = "description", required = false) description: String, @RequestParam(value = "ip", required = false) ip: String, @RequestParam(value = "port", required = false) port: String, @RequestParam(value = "healthCheckUrl", required = false) healthCheckUrl: String): ApiResult<ServiceDO> { var name = name val apiResult = ApiResult.create<ServiceDO>() if (StringUtils.isEmpty(name)) { name = DEFAULT_SERVICE_NAME } if (StringUtils.isEmpty(ip) || StringUtils.isEmpty(port)) { apiResult.message = "Either ip or port is empty,please check!" return apiResult } val serviceDO = ServiceDO() serviceDO.name = name serviceDO.description = description serviceDO.ip = ip serviceDO.port = port serviceDO.healthCheckUrl = healthCheckUrl try { storageComponent.syncRegister(serviceDO) apiResult.isSuccess = true } catch (e: Exception) { apiResult.message = "save into storage failed ,please check the server log,detail:" + e.message log.error("Save service info failed_" + e.message, e) } return apiResult } @PostMapping(value = "/unregister") fun unregister( @RequestParam(value = "name", required = false) name: String, @RequestParam(value = "ip", required = false) ip: String, @RequestParam(value = "port", required = false) port: String): ApiResult<Void> { val apiResult = ApiResult.create<Void>() if (StringUtils.isNotBlank(name) || StringUtils.isBlank(ip) || StringUtils.isBlank(port)) { apiResult.message = "Either name、ip or port is empty,please check." return apiResult } try { storageComponent.syncUnregister(name, ip, port) apiResult.isSuccess = true } catch (e: StorageException) { log.error(name + "/" + ip + ":" + port + " unregister failed_" + e.message, e) } return apiResult } companion object { private val log = LoggerFactory.getLogger(ServiceInfoCollectorApi.javaClass) private val DEFAULT_SERVICE_NAME = "unknown" } }
apache-2.0
9329bbf62018602ea522151f62a72f13
36.943925
117
0.637349
4.591629
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/cause/entity/damage/source/LanternIndirectEntityDamageSourceBuilder.kt
1
1507
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.cause.entity.damage.source import org.spongepowered.api.entity.Entity import org.spongepowered.api.event.cause.entity.damage.source.IndirectEntityDamageSource class LanternIndirectEntityDamageSourceBuilder : AbstractEntityDamageSourceBuilder<IndirectEntityDamageSource, IndirectEntityDamageSource.Builder>(), IndirectEntityDamageSource.Builder { internal var indirect: Entity? = null override fun proxySource(proxy: Entity): IndirectEntityDamageSource.Builder = apply { this.indirect = proxy } override fun from(value: IndirectEntityDamageSource): IndirectEntityDamageSource.Builder = apply { super.from(value) this.indirect = value.indirectSource } override fun reset(): IndirectEntityDamageSource.Builder = apply { super.reset() this.indirect = null } override fun build(): IndirectEntityDamageSource { checkNotNull(this.damageType) { "The damage type must be set" } checkNotNull(this.source) { "The entity must be set" } checkNotNull(this.indirect) { "The proxy source must be set" } return LanternIndirectEntityDamageSource(this) } }
mit
bbce2a191d72daec40811e451913e194
37.641026
149
0.737226
4.380814
false
false
false
false
kazhida/surroundcalc
src/com/abplus/surroundcalc/models/Drawing.kt
1
3284
package com.abplus.surroundcalc.models import java.util.ArrayList import android.util.Log import android.graphics.PointF import android.graphics.Paint /** * Created by kazhida on 2013/12/27. */ class Drawing private (val keyColor: Drawing.KeyColor) { enum class KeyColor { BLUE GREEN RED YELLOW } public trait KeyHolder { fun get(color: KeyColor): Drawing } public val freeHands: MutableList<FreeHand> = ArrayList<FreeHand>() public val regions: MutableList<Region> = ArrayList<Region>() public val valueLabels: MutableList<ValueLabel> = ArrayList<ValueLabel>() fun detect(stroke: Stroke): Unit { // todo: いろいろ検出 Log.d("SurroundCALC", "Start: (" + stroke.x + ", " + stroke.y) val origin = stroke.origin Log.d("SurroundCALC", "Origin: (" + origin.x + ", " + origin.y) val bounds = stroke.bounds val width = bounds.right - bounds.left val height = bounds.bottom - bounds.top val limit = if (width > height) { height / 4 } else { width / 4 } Log.d("SurroundCALC", "Bounds = (" + bounds.left + ", " + bounds.top + ")-(" + bounds.right + "," + bounds.bottom) Log.d("SurroundCALC", "Limit = " + limit) val distance = stroke.nearestDistance(origin, 3) Log.d("SurroundCALC", "Distance = " + distance) if (stroke.distance(origin) < limit) { regions.add(Region(stroke).bind(valueLabels)) } else { freeHands.add(FreeHand(stroke)) } } public fun pick(p: PointF): Pickable? { for (label in valueLabels) { if (label.picked(p)) return label } for (region in regions) { if (region.picked(p)) return region } return null } public fun addLabel(p: PointF, value: Double, paint: Paint) : ValueLabel { val label = ValueLabel(p, value, paint).bind(regions) valueLabels.add(label) return label } public fun clear(): Unit { freeHands.clear() regions.clear() valueLabels.clear() } public fun unbind(picked: Pickable) { if (picked is Region) { picked.unbind() } if (picked is ValueLabel) { picked.unbind(regions) } } public fun bind(picked: Pickable) { if (picked is Region) { picked.bind(valueLabels) } if (picked is ValueLabel) { picked.bind(regions) } } public fun undo() : Unit { if (!freeHands.isEmpty()) { freeHands.remove(freeHands.size() - 1) } } public class object { private val drawings = { (): List<Drawing> -> val builder = ImmutableArrayListBuilder<Drawing>() builder.add(Drawing(KeyColor.BLUE)) builder.add(Drawing(KeyColor.GREEN)) builder.add(Drawing(KeyColor.RED)) builder.add(Drawing(KeyColor.YELLOW)) builder.build() }() val holder = object: KeyHolder { override fun get(color: KeyColor): Drawing { return drawings.get(color.ordinal()) } } } }
bsd-2-clause
3256c01ad6da2f7c459ea666d9481139
26.049587
122
0.557457
4.064596
false
false
false
false
Mithrandir21/Duopoints
app/src/main/java/com/duopoints/android/fragments/userprofile/UserImageFrag.kt
1
9381
package com.duopoints.android.fragments.userprofile import android.Manifest import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import co.chatsdk.core.session.NM import co.chatsdk.core.session.StorageManager import co.chatsdk.firebase.wrappers.UserWrapper import com.bumptech.glide.load.engine.DiskCacheStrategy import com.duopoints.android.R import com.duopoints.android.fragments.base.BaseFrag import com.duopoints.android.fragments.splash.SplashFrag import com.duopoints.android.logistics.cloudstorage.GlideApp import com.duopoints.android.logistics.cloudstorage.Storage import com.duopoints.android.rest.models.dbviews.UserData import com.duopoints.android.utils.ReactiveUtils import com.duopoints.android.utils.UiUtils import com.duopoints.android.utils.logging.LogLevel import com.evernote.android.state.State import com.theartofdev.edmodo.cropper.CropImage import io.reactivex.functions.Action import io.reactivex.functions.Consumer import kotlinx.android.synthetic.main.frag_user_image_layout.* import me.echodev.resizer.Resizer import java.io.File class UserImageFrag : BaseFrag() { @State lateinit var userData: UserData private var avatarUri: Uri? = null private var drawableUri: Uri? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return createAndBindView(R.layout.frag_user_image_layout, inflater, container) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) GlideApp.with(context) .asDrawable() .placeholder(R.drawable.empty_user_icon) .error(R.drawable.empty_user_icon) .load(Storage.getAvatarRef(userData.userUuid)) .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true) .into(userMainImage) userMainImageAction.setOnClickListener { CropImage.startPickImageActivity(context, this) } stockFemaleImage.setOnClickListener { userMainImage.setImageResource(R.drawable.user_female) avatarUri = null // Clear AvatarUri drawableUri = UiUtils.getUriToDrawable(context, R.drawable.user_female) } stockMaleImage.setOnClickListener { userMainImage.setImageResource(R.drawable.user_male) avatarUri = null // Clear AvatarUri drawableUri = UiUtils.getUriToDrawable(context, R.drawable.user_male) } userImageContinue.setOnClickListener { saveAndContinue() } } /*********************** * ANDROID CALL BACKS ***********************/ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { // handle result of pick image chooser if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) { val imageUri = CropImage.getPickImageResultUri(context, data) if (CropImage.isReadExternalStoragePermissionsRequired(context, imageUri)) { // request permissions and handle the result in onRequestPermissionsResult() avatarUri = imageUri requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE) } else { startCroppingImage(imageUri) // no permissions required or already granted, can start crop image activity } } else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { val result = CropImage.getActivityResult(data) if (resultCode == Activity.RESULT_OK) { avatarUri = result.uri setUriAsAvatar() } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) { result.error.printStackTrace() } } else { log(LogLevel.DEBUG, "Result not handled here.") } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode == CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE) { if (avatarUri != null && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { startCroppingImage(avatarUri)// required permissions granted, start crop image activity } else { Toast.makeText(context, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show() } } } /*********************** * CLASS FUNCTIONS ***********************/ private fun startCroppingImage(imageUri: Uri?) { CropImage.activity(imageUri) .setAspectRatio(1, 1) .setFixAspectRatio(true) .start(context, this) } private fun setUriAsAvatar() { if (avatarUri == null) { Toast.makeText(context, "Something very wrong happened!", Toast.LENGTH_SHORT).show() return } drawableUri = null // Clear drawableUri log(LogLevel.DEBUG, "Avatar:" + avatarUri!!.path) GlideApp.with(this) .load(avatarUri) .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true) .error(R.drawable.user_female) .into(userMainImage) } private fun saveAndContinue() { when { avatarUri != null -> avatarUri?.let { userUri -> showSpinner(true) log(LogLevel.DEBUG, "Saving image avatar:" + userUri.path) val imageWidth = getImageWidth(userUri) Resizer(context) .setTargetLength(if (imageWidth > 540) 540 else imageWidth) .setOutputFormat("WEBP") .setOutputDirPath(context.cacheDir.path) .setOutputFilename("scaled_image_" + System.nanoTime()) .setSourceImage(File(userUri.path)) .resizedFileAsFlowable .compose(ReactiveUtils.commonFlowableTransformation(this, true)) .subscribe({ resizedFile -> val uploadTask = Storage.getAvatarRef(userData.userUuid).putFile(Uri.fromFile(resizedFile)) Storage.addLoggingToUploadTask(uploadTask) uploadTask .addOnCompleteListener { showSpinner(false) } .addOnFailureListener { Toast.makeText(context, "Upload failed. Sorry!", Toast.LENGTH_SHORT).show() } .addOnSuccessListener { updateFirebaseUserImageUri(it.downloadUrl, Action { mainActivity.replaceFragment(SplashFrag.newInstance(userData), false, true) }) } }, { throwable -> Toast.makeText(context, "Image Resizing Failed!", Toast.LENGTH_SHORT).show() showSpinner(false) throwable.printStackTrace() }) } drawableUri != null -> drawableUri?.let { showSpinner(true) log(LogLevel.DEBUG, "Saving drawable avatar:" + it.path) val uploadTask = Storage.getAvatarRef(userData.userUuid).putFile(it) Storage.addLoggingToUploadTask(uploadTask) uploadTask .addOnCompleteListener { showSpinner(false) } .addOnFailureListener { Toast.makeText(context, "Upload failed. Sorry!", Toast.LENGTH_SHORT).show() } .addOnSuccessListener { updateFirebaseUserImageUri(it.downloadUrl, Action { mainActivity.replaceFragment(SplashFrag.newInstance(userData), false, true) }) } } else -> Toast.makeText(context, "Please choose an avatar", Toast.LENGTH_SHORT).show() } } private fun updateFirebaseUserImageUri(uri: Uri?, completedAction: Action) { NM.currentUser()?.let { val currentUser = StorageManager.shared().fetchUserWithEntityID(it.entityID) currentUser.avatarURL = uri.toString() currentUser.update() // Do a once() on the user to push its details to firebase. val userWrapper = UserWrapper.initWithModel(currentUser) userWrapper.model.update() userWrapper.push().subscribe(completedAction, Consumer(Throwable::printStackTrace)) } } private fun getImageWidth(uri: Uri): Int { val options = BitmapFactory.Options() options.inJustDecodeBounds = true BitmapFactory.decodeFile(File(uri.path).absolutePath, options) return options.outHeight } companion object { @JvmStatic fun newInstance(userData: UserData): UserImageFrag { val frag = UserImageFrag() frag.userData = userData return frag } } }
gpl-3.0
56244f574582c3eaaf9b03a9d5f9aaf2
41.452489
192
0.629784
4.981944
false
false
false
false
timusus/Shuttle
app/src/main/java/com/simplecity/amp_library/ui/screens/playlist/dialog/CreatePlaylistDialog.kt
1
11841
package com.simplecity.amp_library.ui.screens.playlist.dialog import android.annotation.SuppressLint import android.app.Dialog import android.content.ContentUris import android.content.ContentValues import android.content.Context import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.support.annotation.WorkerThread import android.support.v4.app.DialogFragment import android.support.v4.app.FragmentManager import android.text.Editable import android.text.TextUtils import android.text.TextWatcher import android.view.LayoutInflater import android.widget.EditText import android.widget.Toast import com.afollestad.materialdialogs.DialogAction import com.afollestad.materialdialogs.MaterialDialog import com.simplecity.amp_library.R import com.simplecity.amp_library.data.SongsRepository import com.simplecity.amp_library.model.Playlist import com.simplecity.amp_library.model.Playlist.Type import com.simplecity.amp_library.model.Query import com.simplecity.amp_library.model.Song import com.simplecity.amp_library.sql.SqlUtils import com.simplecity.amp_library.sql.sqlbrite.SqlBriteUtils import com.simplecity.amp_library.utils.LogUtils import com.simplecity.amp_library.utils.SettingsManager import com.simplecity.amp_library.utils.playlists.PlaylistManager import dagger.android.support.AndroidSupportInjection import io.reactivex.Observable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import java.io.Serializable import javax.inject.Inject class CreatePlaylistDialog : DialogFragment() { private val disposable = CompositeDisposable() @Inject lateinit var songsRepository: SongsRepository @Inject lateinit var settingsManager: SettingsManager @Inject lateinit var playlistManager: PlaylistManager interface OnSavePlaylistListener { fun onSave(playlist: Playlist) } override fun onAttach(context: Context?) { AndroidSupportInjection.inject(this) super.onAttach(context) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val songsToAdd: List<Song>? = arguments!!.getSerializable(ARG_SONGS) as? List<Song> @SuppressLint("InflateParams") val customView = LayoutInflater.from(context).inflate(R.layout.dialog_playlist, null) val editText = customView.findViewById<EditText>(R.id.editText) disposable.add(Observable.fromCallable<String> { makePlaylistName() } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { name -> editText.setText(name) if (!TextUtils.isEmpty(name)) { editText.setSelection(name.length) } }, { error -> LogUtils.logException(TAG, "PlaylistManager: Error Setting playlist name", error) } )) val activity = activity val builder = MaterialDialog.Builder(context!!) .customView(customView, false) .title(R.string.menu_playlist) .positiveText(R.string.create_playlist_create_text) .onPositive { materialDialog, dialogAction -> val name = editText.text.toString() if (!name.isEmpty()) { idForPlaylistObservable(name) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { id -> val uri: Uri? if (id >= 0) { uri = ContentUris.withAppendedId(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, id!!.toLong()) val uri1 = MediaStore.Audio.Playlists.Members.getContentUri("external", id as Long) context!!.contentResolver.delete(uri1, null, null) } else { val values = ContentValues(1) values.put(MediaStore.Audio.Playlists.NAME, name) uri = try { context!!.contentResolver.insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, values) } catch (e: IllegalArgumentException) { if (activity != null) { Toast.makeText(activity, R.string.dialog_create_playlist_error, Toast.LENGTH_LONG).show() } null } catch (e: NullPointerException) { if (activity != null) { Toast.makeText(activity, R.string.dialog_create_playlist_error, Toast.LENGTH_LONG).show() } null } } if (uri != null) { val playlist = Playlist(Type.USER_CREATED, uri.lastPathSegment!!.toLong(), name, true, false, true, true, true) songsToAdd?.let { playlistManager.addToPlaylist(playlist, songsToAdd) { numSongs -> if (activity != null) { Toast.makeText(activity, activity.resources.getQuantityString(R.plurals.NNNtrackstoplaylist, numSongs, numSongs), Toast.LENGTH_LONG).show() } (parentFragment as? OnSavePlaylistListener)?.onSave(playlist) } } ?: run { if (activity != null) { Toast.makeText(activity, activity.resources.getQuantityString(R.plurals.NNNtrackstoplaylist, 0, 0), Toast.LENGTH_LONG).show() } (parentFragment as? OnSavePlaylistListener)?.onSave(playlist) } } }, { error -> LogUtils.logException( TAG, "PlaylistManager: Error Saving playlist", error ) } ) } } .negativeText(R.string.cancel) val dialog = builder.build() val textWatcher = object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { // don't care about this one } //Fixme: It's probably best to just query all playlist names first, and then check against hat list, rather than requerying for each char change. override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { val newText = editText.text.toString() if (newText.trim { it <= ' ' }.isEmpty()) { dialog.getActionButton(DialogAction.POSITIVE).isEnabled = false } else { dialog.getActionButton(DialogAction.POSITIVE).isEnabled = true // check if playlist with current name exists already, and warn the user if so. disposable.add(idForPlaylistObservable(newText) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { id -> if (id >= 0) { dialog.getActionButton(DialogAction.POSITIVE).setText(R.string.create_playlist_overwrite_text) } else { dialog.getActionButton(DialogAction.POSITIVE).setText(R.string.create_playlist_create_text) } }, { error -> LogUtils.logException( TAG, "PlaylistManager: Error handling text change", error ) } )) } } override fun afterTextChanged(s: Editable) { // don't care about this one } } editText.addTextChangedListener(textWatcher) return dialog } fun idForPlaylistObservable(name: String): Single<Int> { val query = Query.Builder() .uri(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI) .projection(arrayOf(MediaStore.Audio.Playlists._ID)) .selection(MediaStore.Audio.Playlists.NAME + "='" + name.replace("'".toRegex(), "\''") + "'") .sort(MediaStore.Audio.Playlists.NAME) .build() return SqlBriteUtils.createSingle(context!!, { cursor -> cursor.getInt(0) }, query, -1) } @WorkerThread fun makePlaylistName(): String? { val template = context!!.getString(R.string.new_playlist_name_template) var num = 1 val query = Query.Builder() .uri(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI) .projection(arrayOf(MediaStore.Audio.Playlists.NAME)) .sort(MediaStore.Audio.Playlists.NAME) .build() SqlUtils.createQuery(context, query)?.use { cursor -> var suggestedName = String.format(template, num++) // Need to loop until we've made 1 full pass through without finding a match. // Looping more than once shouldn't happen very often, but will happen // if you have playlists named "New Playlist 1"/10/2/3/4/5/6/7/8/9, where // making only one pass would result in "New Playlist 10" being erroneously // picked for the new name. var done = false while (!done) { done = true cursor.moveToFirst() while (!cursor.isAfterLast) { val playlistName = cursor.getString(0) if (playlistName.compareTo(suggestedName, ignoreCase = true) == 0) { suggestedName = String.format(template, num++) done = false } cursor.moveToNext() } } return suggestedName } return null } fun show(fragmentManager: FragmentManager) { show(fragmentManager, TAG) } companion object { private const val TAG = "CreatePlaylistDialog" private const val ARG_SONGS = "songs" fun newInstance(songsToAdd: List<Song>?): CreatePlaylistDialog { val dialogFragment = CreatePlaylistDialog() songsToAdd?.let { val args = Bundle() args.putSerializable(ARG_SONGS, songsToAdd as Serializable) dialogFragment.arguments = args } return dialogFragment } } }
gpl-3.0
ab0fe7013f6f40a71727d788ec8fe240
43.35206
187
0.531881
5.692788
false
false
false
false
ruediger-w/opacclient
opacclient/libopac/src/main/java/de/geeksfactory/opacclient/apis/Arena.kt
1
18746
package de.geeksfactory.opacclient.apis import de.geeksfactory.opacclient.i18n.StringProvider import de.geeksfactory.opacclient.networking.HttpClientFactory import de.geeksfactory.opacclient.networking.NotReachableException import de.geeksfactory.opacclient.objects.* import de.geeksfactory.opacclient.searchfields.DropdownSearchField import de.geeksfactory.opacclient.searchfields.SearchField import de.geeksfactory.opacclient.searchfields.SearchQuery import de.geeksfactory.opacclient.searchfields.TextSearchField import de.geeksfactory.opacclient.utils.get import de.geeksfactory.opacclient.utils.html import de.geeksfactory.opacclient.utils.text import okhttp3.FormBody import org.joda.time.format.DateTimeFormat import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.net.URL /** * OpacApi implementation for the Arena OPAC developed by Axiell. https://www.axiell.de/arena/ * * @author Johan von Forstner, January 2019 */ open class Arena : OkHttpBaseApi() { protected lateinit var opacUrl: String protected val ENCODING = "UTF-8" protected var searchDoc: Document? = null override fun init(library: Library, factory: HttpClientFactory) { super.init(library, factory) opacUrl = library.data.getString("baseurl") } override fun parseSearchFields(): List<SearchField> { val doc = httpGet("$opacUrl/extended-search", ENCODING).html // text fields val textFields = doc.select(".arena-extended-search-original-field-container") .map { container -> TextSearchField().apply { id = container.select("input").first()["name"] displayName = container.select("span").first().text() } } // dropdown fields val dropdownFields = listOf("category", "media-class", "target-audience", "accession-date").map { doc.select(".arena-extended-search-$it-container") }.filter { it.size > 0 }.map { it.first() }.map { container -> DropdownSearchField().apply { val select = container.select("select").first() id = select["name"] displayName = container.select("label").first().text() val options = select.select("option").map { option -> DropdownSearchField.Option( option["value"], option.text) }.toMutableList() if (select.hasAttr("multiple")) { options.add(0, DropdownSearchField.Option("", "")) } dropdownValues = options } } // year field val yearFields = listOf("from", "to").map { doc.select(".arena-extended-search-publication-year-$it-container") }.filter { it.size > 0 }.map { it.first() }.mapIndexed {i, container -> TextSearchField().apply { id = container.select("input").first()["name"] displayName = container.parent().child(0).ownText() hint = container.select("label").first().text() isHalfWidth = i == 1 } } return textFields + dropdownFields + yearFields } override fun search(query: MutableList<SearchQuery>): SearchRequestResult { val searchForm = httpGet("$opacUrl/extended-search", ENCODING).html .select(".arena-extended-search-original").first() val formData = FormBody.Builder().apply { searchForm.select("input[type=hidden]").forEach { hidden -> add(hidden["name"], hidden["value"]) } val submit = searchForm.select("input[type=submit]").first() add(submit["name"], submit["value"]) query.forEach { q -> add(q.key, q.value) } }.build() val doc = httpPost(searchForm["action"], formData, ENCODING).html return parseSearch(doc) } protected open fun parseSearch(doc: Document, page: Int = 1): SearchRequestResult { searchDoc = doc val countRegex = Regex("\\d+-\\d+ (?:von|of|av) (\\d+)") val count = countRegex.find(doc.select(".arena-record-counter").text)?.groups?.get(1)?.value?.toInt() ?: 0 val coverAjaxUrls = getAjaxUrls(doc) val results = doc.select(".arena-record").map{ record -> parseSearchResult(record, coverAjaxUrls) } return SearchRequestResult(results, count, page) } protected fun parseSearchResult(record: Element, coverAjaxUrls: Map<String, String>): SearchResult { return SearchResult().apply { val title = record.select(".arena-record-title").text val year = record.select(".arena-record-year .arena-value").first()?.text val author = record.select(".arena-record-author .arena-value").map { it.text }.joinToString(", ") innerhtml = "<b>$title</b><br>$author ${year ?: ""}" id = record.select(".arena-record-id").first().text cover = getCover(record, coverAjaxUrls) } } internal fun getCover(record: Element, coverAjaxUrls: Map<String, String>? = null): String? { val coverHolder = record.select(".arena-record-cover").first() if (coverHolder != null) { val id = coverHolder["id"] if (coverAjaxUrls != null && coverAjaxUrls.containsKey(id)) { // get cover via ajax val xml = httpGet(coverAjaxUrls[id], ENCODING) val url = Regex("<img src=\"([^\"]+)").find(xml)?.groups?.get(1) ?.value?.replace("&amp;", "&") return if (url != null) URL(URL(opacUrl), url).toString() else null } else if (coverHolder.select("img:not([src*=indicator.gif])").size > 0) { // cover is included as img tag val url = coverHolder.select("img:not([src*=indicator.gif])").first()["src"] return URL(URL(opacUrl), url).toString() } } return null } internal fun getAjaxUrls(doc: Document): Map<String, String> { val regex = Regex(Regex.escape( "<script type=\"text/javascript\">Wicket.Event.add(window,\"domready\",function(b){var a=wicketAjaxGet(\"") + "([^\"]+)" + Regex.escape("\",function(){}.bind(this),function(){}.bind(this),function(){return Wicket.\$(\"") + "([^\"]+)" + Regex.escape("\")!=null}.bind(this))});</script>")) return regex.findAll(doc.html()).associate { match -> Pair(match.groups[2]!!.value, match.groups[1]!!.value) } } override fun filterResults(filter: Filter, option: Filter.Option): SearchRequestResult { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun searchGetPage(page: Int): SearchRequestResult { val doc = searchDoc ?: throw NotReachableException() val pageLinks = doc.select(".arena-record-navigation").first() .select(".arena-page-number > a, .arena-page-number > span") // determining the link to get to the right page is not straightforward, so we try to find // the link to the right page. val from = Integer.valueOf(pageLinks.first().text()) val to = Integer.valueOf(pageLinks.last().text()) val linkToClick: Element val willBeCorrectPage: Boolean if (page < from) { linkToClick = pageLinks.first() willBeCorrectPage = false } else if (page > to) { linkToClick = pageLinks.last() willBeCorrectPage = false } else { linkToClick = pageLinks.get(page - from) willBeCorrectPage = true } if (linkToClick.tagName() == "span") { // we are trying to get the page we are already on return parseSearch(doc, page) } val newDoc = httpGet(linkToClick["href"], ENCODING).html if (willBeCorrectPage) { return parseSearch(newDoc, page) } else { searchDoc = newDoc return searchGetPage(page) } } override fun getResultById(id: String, homebranch: String?): DetailedItem { val url = getUrl(id) val doc = httpGet(url, ENCODING).html doc.setBaseUri(url) return parseDetail(doc) } private fun parseDetail(doc: Document): DetailedItem { val urls = getAjaxUrls(doc).filterKeys { it.contains("crDetailWicket") } val holdingsUrl = if (urls.isNotEmpty()) urls.values.iterator().next() else null val holdingsDoc = if (holdingsUrl != null) { val ajaxResp = httpGet(URL(URL(opacUrl), holdingsUrl).toString(), ENCODING).html ajaxResp.select("component").first().text.html } else null return DetailedItem().apply { title = doc.select(".arena-detail-title").text doc.select(".arena-catalogue-detail .arena-field").forEach { field -> addDetail(Detail(field.text, field.nextElementSibling().text)) } doc.select(".arena-detail-link > a").forEach { link -> val href = link["href"] if (href.contains("onleihe") && href.contains("mediaInfo")) { addDetail(Detail(link.text(), href)); } } id = doc.select(".arena-record-id").first().text cover = doc.select(".arena-detail-cover img").first()?.absUrl("href") copies = holdingsDoc?.select(".arena-row")?.map { row -> Copy().apply { department = row.select(".arena-holding-department .arena-value").text shelfmark = row.select(".arena-holding-shelf-mark .arena-value").text status = row.select(".arena-availability-right").text } } ?: emptyList() isReservable = doc.select(".arena-reservation-button-login, a[href*=reservationButton]").first() != null reservation_info = if (isReservable) id else null } } override fun getResult(position: Int): DetailedItem? { return null } override fun reservation(item: DetailedItem, account: Account, useraction: Int, selection: String?): OpacApi.ReservationResult { login(account) val details = httpGet(getUrl(item.id), ENCODING).html val url = details.select(" a[href*=reservationButton]").first()?.attr("href") val doc = httpGet(url, ENCODING).html val form = doc.select("form[action*=reservationForm]").first() if (selection == null) { return OpacApi.ReservationResult(OpacApi.MultiStepResult.Status.SELECTION_NEEDED).apply { actionIdentifier = OpacApi.ReservationResult.ACTION_BRANCH this.selection = form.select(".arena-select").first().select("option").map { option -> hashMapOf( "key" to option["value"], "value" to option.text ) } } } val formData = FormBody.Builder() form.select("input[type=hidden]").forEach { input -> formData.add(input["name"], input["value"]) } formData.add("branch", selection) val resultDoc = httpPost(form["action"], formData.build(), ENCODING).html val errorPanel = resultDoc.select(".feedbackPanelWARNING").first() if (errorPanel != null) { return OpacApi.ReservationResult(OpacApi.MultiStepResult.Status.ERROR, errorPanel.text) } else { return OpacApi.ReservationResult(OpacApi.MultiStepResult.Status.OK) } } override fun prolong(media: String, account: Account, useraction: Int, selection: String?): OpacApi.ProlongResult { login(account) val loansDoc = httpGet("$opacUrl/protected/loans", ENCODING).html val internalError = OpacApi.ProlongResult(OpacApi.MultiStepResult.Status.ERROR, stringProvider.getString(StringProvider.INTERNAL_ERROR)) val row = loansDoc.select("tr:has(.arena-record-id:contains($media)").first() ?: return internalError val js = row.select(".arena-renewal-status input[type=submit]").first()["onclick"] val url = Regex("window\\.location\\.href='([^']+)'").find(js)?.groups?.get(1)?.value ?: return internalError val doc = httpGet(url, ENCODING).html val error = doc.select(".arena-internal-error-description-value").first() return if (error != null) { OpacApi.ProlongResult(OpacApi.MultiStepResult.Status.ERROR, error.text) } else if (doc.select(".arena-renewal-fail-table").size > 0) { OpacApi.ProlongResult(OpacApi.MultiStepResult.Status.ERROR, stringProvider.getString(StringProvider.PROLONGING_IMPOSSIBLE)) } else { OpacApi.ProlongResult(OpacApi.MultiStepResult.Status.OK) } } override fun prolongAll(account: Account, useraction: Int, selection: String?): OpacApi.ProlongAllResult { // it seems that this does not work without JavaScript, and I couldn't find out why. return OpacApi.ProlongAllResult(OpacApi.MultiStepResult.Status.ERROR) } override fun cancel(media: String, account: Account, useraction: Int, selection: String?): OpacApi.CancelResult { val resDoc = httpGet("$opacUrl/protected/reservations", ENCODING).html val internalError = OpacApi.CancelResult(OpacApi.MultiStepResult.Status.ERROR, stringProvider.getString(StringProvider.INTERNAL_ERROR)) val record = resDoc.select(".arena-record-container:has(.arena-record-id:contains($media)") .first() ?: return internalError // find the URL that needs to be called to select the item val url = record.select(".arena-select-item a").first()?.attr("href") val selectedDoc = httpGet(url, ENCODING).html val cancelUrl = selectedDoc.select(".arena-delete").first().attr("href") val resultDoc = httpGet(cancelUrl, ENCODING).html val errorPanel = resultDoc.select(".feedbackPanelWARNING").first() if (errorPanel != null) { return OpacApi.CancelResult(OpacApi.MultiStepResult.Status.ERROR, errorPanel.text) } else { return OpacApi.CancelResult(OpacApi.MultiStepResult.Status.OK) } } override fun account(account: Account): AccountData { login(account) val profileDoc = httpGet("$opacUrl/protected/profile", ENCODING).html val feesDoc = httpGet("$opacUrl/protected/debts", ENCODING).html val loansDoc = httpGet("$opacUrl/protected/loans", ENCODING).html val reservationsDoc = httpGet("$opacUrl/protected/reservations", ENCODING).html return AccountData(account.id).apply { pendingFees = parseFees(feesDoc) lent = parseLent(loansDoc) reservations = parseReservations(reservationsDoc) //validUntil = parseValidUntil(profileDoc) } } internal fun parseReservations(doc: Document): List<ReservedItem> { return doc.select(".arena-record").map { record -> ReservedItem().apply { id = record.select(".arena-record-id").first().text title = record.select(".arena-record-title").first()?.text author = record.select(".arena-record-author .arena-value") .map { it.text }.joinToString(", ") format = record.select(".arena-record-media .arena-value").first()?.text cover = getCover(record) branch = record.select(".arena-record-branch .arena-value").first()?.text status = record.select(".arena-result-info .arena-value").first()?.text cancelData = id } } } internal fun parseLent(doc: Document): List<LentItem> { val df = DateTimeFormat.forPattern("dd.MM.yy") return doc.select("#loansTable > tbody > tr").map { tr -> LentItem().apply { id = tr.select(".arena-record-id").first().text title = tr.select(".arena-record-title").first()?.text author = tr.select(".arena-record-author .arena-value") .map { it.text }.joinToString(", ") format = tr.select(".arena-record-media .arena-value").first()?.text lendingBranch = tr.select(".arena-renewal-branch .arena-value").first()?.text deadline = df.parseLocalDate(tr.select(".arena-renewal-date-value").first().text) isRenewable = tr.hasClass("arena-renewal-true") prolongData = id status = tr.select(".arena-renewal-status-message").first()?.text } } } internal fun parseFees(feesDoc: Document): String? { return feesDoc.select(".arena-charges-total-debt span:eq(1)").first()?.text } /*internal fun parseValidUntil(profileDoc: Document): String? { return profileDoc.select(".arena-charges-total-debt span:eq(2)").first()?.text }*/ override fun checkAccountData(account: Account) { login(account) } fun login(account: Account) { val loginForm = httpGet("$opacUrl/welcome", ENCODING).html .select(".arena-patron-signin form").first() ?: return val formData = FormBody.Builder() .add("openTextUsernameContainer:openTextUsername", account.name) .add("textPassword", account.password) loginForm.select("input[type=hidden]").forEach { input -> formData.add(input["name"], input["value"]) } val doc = httpPost(loginForm["action"], formData.build(), ENCODING).html val errorPanel = doc.select(".feedbackPanelWARNING").first() if (errorPanel != null) { throw OpacApi.OpacErrorException(errorPanel.text) } } override fun getShareUrl(id: String, title: String?): String { return getUrl(id) } private fun getUrl(id: String) = "$opacUrl/results?p_p_id=searchResult_WAR_arenaportlets&p_r_p_687834046_search_item_id=$id" override fun getSupportFlags(): Int { return OpacApi.SUPPORT_FLAG_ENDLESS_SCROLLING } override fun getSupportedLanguages(): MutableSet<String>? { return null } override fun setLanguage(language: String) { } }
mit
06e2bcf9f6be7fc7669dd87e656d5f8d
43.110588
144
0.601408
4.279909
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-android
superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/repositories/MoatRepository.kt
1
7874
package tv.superawesome.sdk.publisher.common.repositories import android.webkit.WebView import android.widget.VideoView import com.moat.analytics.mobile.sup.* import tv.superawesome.sdk.publisher.common.components.Logger import tv.superawesome.sdk.publisher.common.components.NumberGeneratorType import tv.superawesome.sdk.publisher.common.models.AdResponse private const val MOAT_SERVER = "https://z.moatads.com" private const val MOAT_URL = "moatad.js" private const val MOAT_DISPLAY_PARTNER_CODE = "superawesomeinappdisplay731223424656" private const val MOAT_VIDEO_PARTNER_CODE = "superawesomeinappvideo467548716573" interface MoatRepositoryType { fun startMoatTrackingForDisplay(webView: WebView, adResponse: AdResponse): String = "" fun stopMoatTrackingForDisplay(): Boolean = false fun startMoatTrackingForVideoPlayer( videoView: VideoView?, duration: Int, adResponse: AdResponse ): Boolean = false fun sendPlayingEvent(position: Int): Boolean = false fun sendStartEvent(position: Int): Boolean = false fun sendFirstQuartileEvent(position: Int): Boolean = false fun sendMidpointEvent(position: Int): Boolean = false fun sendThirdQuartileEvent(position: Int): Boolean = false fun sendCompleteEvent(position: Int): Boolean = false fun stopMoatTrackingForVideoPlayer(): Boolean = false } class MoatRepository( private val moatLimiting: Boolean, private val logger: Logger, private val numberGenerator: NumberGeneratorType ) : MoatRepositoryType, TrackerListener, VideoTrackerListener { private val factory: MoatFactory by lazy { MoatFactory.create() } private var webTracker: WebAdTracker? = null private var videoTracker: ReactiveVideoTracker? = null override fun startMoatTrackingForDisplay(webView: WebView, adResponse: AdResponse): String { if (!isMoatAllowed(adResponse)) { logger.error("Moat is not allowed") return "" } webTracker = factory.createWebAdTracker(webView) webTracker?.setListener(this) if (webTracker == null) { logger.error("Could not start tracking web view since webTracker is null") return "" } // form the proper moat data val ad = adResponse.ad var moatQuery = "" moatQuery += "moatClientLevel1=${ad.advertiserId}" moatQuery += "&moatClientLevel2=${ad.campaignId}" moatQuery += "&moatClientLevel3=${ad.lineItemId}" moatQuery += "&moatClientLevel4=${ad.creative.id}" moatQuery += "&moatClientSlicer1=${ad.app}" moatQuery += "&moatClientSlicer2=${adResponse.placementId}" moatQuery += "&moatClientSlicer3=${ad.publisherId}" webTracker?.startTracking() logger.info("Trying to start tracking web with query $moatQuery") // and return the special moat javascript tag to be loaded in a web view return "<script src=\"$MOAT_SERVER/$MOAT_DISPLAY_PARTNER_CODE/$MOAT_URL?$moatQuery\" type=\"text/javascript\"></script>" } override fun stopMoatTrackingForDisplay(): Boolean { return if (webTracker != null) { webTracker?.stopTracking() webTracker = null true } else { logger.error("Could not stop tracking display since webTracker is null") false } } override fun startMoatTrackingForVideoPlayer( videoView: VideoView?, duration: Int, adResponse: AdResponse ): Boolean { if (!isMoatAllowed(adResponse)) { logger.error("Moat is not allowed") return false } videoTracker = factory.createCustomTracker(ReactiveVideoTrackerPlugin(MOAT_VIDEO_PARTNER_CODE)) videoTracker?.setListener(this) videoTracker?.setVideoListener(this) if (videoTracker == null) { logger.error("Could not start tracking video with duration $duration since videoTracker is null") return false } val ad = adResponse.ad val adIds = HashMap<String, String>() adIds["level1"] = "${ad.advertiserId}" adIds["level2"] = "${ad.campaignId}" adIds["level3"] = "${ad.lineItemId}" adIds["level4"] = "${ad.creative.id}" adIds["slicer1"] = "${ad.app}" adIds["slicer2"] = "${adResponse.placementId}" adIds["slicer3"] = "${ad.publisherId}" logger.info("Trying to start tracking video for duration $duration and level/slicer info $adIds") return videoTracker?.trackVideoAd(adIds, duration, videoView) ?: false } override fun sendPlayingEvent(position: Int): Boolean { if (videoTracker == null) { logger.error("Could not send sendPlayingEvent to Moat since videoTracker is null") return false } videoTracker?.dispatchEvent(MoatAdEvent(MoatAdEventType.AD_EVT_PLAYING, position)) return true } override fun sendStartEvent(position: Int): Boolean { if (videoTracker == null) { logger.error("Could not send sendStartEvent to Moat since videoTracker is null") return false } videoTracker?.dispatchEvent(MoatAdEvent(MoatAdEventType.AD_EVT_START, position)) return true } override fun sendFirstQuartileEvent(position: Int): Boolean { if (videoTracker == null) { logger.error("Could not send sendFirstQuartileEvent to Moat since videoTracker is null") return false } videoTracker?.dispatchEvent(MoatAdEvent(MoatAdEventType.AD_EVT_FIRST_QUARTILE, position)) return true } override fun sendMidpointEvent(position: Int): Boolean { if (videoTracker == null) { logger.error("Could not send sendMidpointEvent to Moat since videoTracker is null") return false } videoTracker?.dispatchEvent(MoatAdEvent(MoatAdEventType.AD_EVT_MID_POINT, position)) return true } override fun sendThirdQuartileEvent(position: Int): Boolean { if (videoTracker == null) { logger.error("Could not send sendThirdQuartileEvent to Moat since videoTracker is null") return false } videoTracker?.dispatchEvent(MoatAdEvent(MoatAdEventType.AD_EVT_THIRD_QUARTILE, position)) return true } override fun sendCompleteEvent(position: Int): Boolean { if (videoTracker == null) { logger.error("Could not send sendCompleteEvent to Moat since videoTracker is null") return false } videoTracker?.dispatchEvent(MoatAdEvent(MoatAdEventType.AD_EVT_COMPLETE, position)) return true } override fun stopMoatTrackingForVideoPlayer(): Boolean { return if (videoTracker != null) { videoTracker?.stopTracking() true } else { logger.error("Could not stop tracking video since videoTracker is null") false } } override fun onTrackingStarted(s: String) { logger.info("Started tracking: $s") } override fun onTrackingFailedToStart(s: String) { logger.error("Failed to start tracking: $s") } override fun onTrackingStopped(s: String) { logger.info("Stopped tracking: $s") } override fun onVideoEventReported(moatAdEventType: MoatAdEventType) { logger.info("Video event $moatAdEventType") } private fun isMoatAllowed(adResponse: AdResponse): Boolean { val moatRand = numberGenerator.nextDoubleForMoat() val ad = adResponse.ad val response = moatRand < ad.moat && moatLimiting || !moatLimiting logger.info("Moat allowed? $response. moatRand: $moatRand ad.moat: ${ad.moat} moatLimiting: $moatLimiting") return response } }
lgpl-3.0
3857abd5e6fa7b6926c164f1c637b8dc
35.453704
128
0.661544
4.265439
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/FileProvider.kt
1
1854
package org.videolan.vlc import android.content.ContentProvider import android.content.ContentValues import android.database.Cursor import android.net.Uri import android.os.ParcelFileDescriptor import org.videolan.resources.AndroidDevices import java.io.File import java.io.FileNotFoundException private const val TAG = "VLC/FileProvider" private const val THUMB_PROVIDER_AUTHORITY = "${BuildConfig.APP_ID}.thumbprovider" class FileProvider : ContentProvider() { override fun insert(uri: Uri, values: ContentValues?) = Uri.EMPTY!! override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor { throw UnsupportedOperationException("Not supported by this provider") } override fun onCreate() = true override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?) = 0 override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?) = 0 override fun getType(uri: Uri) = "image/${uri.path?.substringAfterLast('.')}" override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor { val path = uri.path ?: throw SecurityException("Illegal access") if (path.contains("..")) throw SecurityException("Illegal access") val file = File(path) val canonicalPath = file.canonicalPath if (!AndroidDevices.mountBL.any { canonicalPath.startsWith(it) }) throw SecurityException("Illegal access") if (file.exists()) { return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) } throw FileNotFoundException(path) } } fun getFileUri(path: String) = Uri.Builder() .scheme("content") .authority(THUMB_PROVIDER_AUTHORITY) .path(path) .build()!!
gpl-2.0
2cff39109a0fabc5f9526b6ed3e22c84
38.446809
149
0.713053
4.589109
false
false
false
false
danielgimenes/NasaPicContentFetcher
src/main/java/br/com/dgimenes/nasapiccontentfetcher/service/api/RetrofitFactory.kt
1
1119
package br.com.dgimenes.nasapiccontentfetcher.service.api import com.squareup.okhttp.Cache import com.squareup.okhttp.OkHttpClient import retrofit.Retrofit import retrofit.GsonConverterFactory import java.nio.file.Files import java.nio.file.attribute.FileAttribute object RetrofitFactory { val HTTP_CACHE_SIZE_IN_BYTES = 2048L; var retrofit : Retrofit? = null private fun createOKHttpClient() : OkHttpClient { val okHttpClient = OkHttpClient(); okHttpClient.cache = createHttpClientCache(); return okHttpClient; } private fun createHttpClientCache() : Cache { return Cache(Files.createTempDirectory("nasapic", *arrayOf<FileAttribute<String>>()).toFile(), HTTP_CACHE_SIZE_IN_BYTES); } fun get(apiBaseUrl : String) : Retrofit { if (retrofit == null) { retrofit = Retrofit.Builder() .baseUrl(apiBaseUrl) .client(createOKHttpClient()) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit!!; } }
mit
4fc4067d6d241072902c85bd98f76381
30.971429
87
0.650581
4.823276
false
false
false
false
SpineEventEngine/core-java
buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/LicenseReport.kt
2
2949
/* * Copyright 2022, TeamDev. 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 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.internal.gradle.javascript.task import io.spine.internal.gradle.named import io.spine.internal.gradle.register import io.spine.internal.gradle.report.license.generateLicenseReport import io.spine.internal.gradle.TaskName import org.gradle.api.Task import org.gradle.api.tasks.TaskContainer import org.gradle.api.tasks.TaskProvider /** * Registers [npmLicenseReport] task for including NPM dependencies into license reports. * * The task depends on [generateLicenseReport]. * * Here's an example of how to apply it in `build.gradle.kts`: * * ``` * import io.spine.internal.gradle.javascript.javascript * import io.spine.internal.gradle.javascript.task.clean * * // ... * * javascript { * tasks { * licenseReport() * } * } * ``` */ fun JsTasks.licenseReport() { npmLicenseReport().also { generateLicenseReport.configure { finalizedBy(it) } } } private val npmLicenseReportName = TaskName.of("npmLicenseReport") /** * Locates `npmLicenseReport` task in this [TaskContainer]. * * The task generates the report on NPM dependencies and their licenses. */ val TaskContainer.npmLicenseReport: TaskProvider<Task> get() = named(npmLicenseReportName) private fun JsTasks.npmLicenseReport() = register(npmLicenseReportName) { description = "Generates the report on NPM dependencies and their licenses." group = JsTasks.Group.build doLast { // The script below generates license report for NPM dependencies and appends it // to the report for Java dependencies generated by `generateLicenseReport` task. npm("run", "license-report") } }
apache-2.0
11b00e966c2533d731ac2cef08669ebb
32.511364
93
0.725331
4.182979
false
false
false
false
cout970/Magneticraft
src/main/kotlin/com/cout970/magneticraft/misc/Math.kt
2
1900
@file:Suppress("unused") package com.cout970.magneticraft.misc import com.cout970.magneticraft.misc.vector.minus import com.cout970.magneticraft.misc.vector.xd import com.cout970.magneticraft.misc.vector.yd import com.cout970.magneticraft.misc.vector.zd import net.minecraft.util.math.Vec3d fun ensureNonZero(x: Double, default: Double = 1.0): Double = if (x == 0.0) default else x @Suppress("NOTHING_TO_INLINE") inline fun Number.toRads() = Math.toRadians(this.toDouble()) fun Float.toRadians() = Math.toRadians(this.toDouble()).toFloat() infix fun Int.roundTo(factor: Int) = (this / factor) * factor infix fun Long.roundTo(factor: Long) = (this / factor) * factor fun clamp(value: Double, max: Double, min: Double) = Math.max(Math.min(max, value), min) fun hasIntersection(aFirst: Vec3d, aSecond: Vec3d, bFirst: Vec3d, bSecond: Vec3d): Boolean { val da = aSecond - aFirst val db = bSecond - bFirst val dc = bFirst - aFirst if (dc.dotProduct(da.crossProduct(db)) != 0.0) // lines are not coplanar return false val s = dc.crossProduct(db).dotProduct(da.crossProduct(db)) / norm2(da.crossProduct(db)) if (s in 0.0..1.0) { return true } return false } private fun norm2(v: Vec3d): Double = v.xd * v.xd + v.yd * v.yd + v.zd * v.zd fun interpolate(v: Double, min: Double, max: Double): Double { if (v < min) return 0.0 if (v > max) return 1.0 return (v - min) / (max - min) } inline fun iterateArea(rangeX: IntRange, rangeY: IntRange, func: (x: Int, y: Int) -> Unit) { for (j in rangeY) { for (i in rangeX) { func(i, j) } } } inline fun iterateVolume(rangeX: IntRange, rangeY: IntRange, rangeZ: IntRange, func: (x: Int, y: Int, z: Int) -> Unit) { for (i in rangeX) { for (j in rangeY) { for (z in rangeZ) { func(i, j, z) } } } }
gpl-2.0
b2e3123f6c7a7098af8fbbcd71bdd82b
28.703125
120
0.637895
3.049759
false
false
false
false
antoniolg/Bandhook-Kotlin
app/src/test/java/com/antonioleiva/bandhookkotlin/repository/AlbumRepositoryImplTest.kt
1
4463
/* * Copyright (C) 2016 Alexey Verein * * 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.antonioleiva.bandhookkotlin.repository import com.antonioleiva.bandhookkotlin.domain.entity.Album import com.antonioleiva.bandhookkotlin.domain.entity.Artist import com.antonioleiva.bandhookkotlin.domain.repository.AlbumRepository import com.antonioleiva.bandhookkotlin.repository.dataset.AlbumDataSet import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.`when` import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) class AlbumRepositoryImplTest { @Mock lateinit var firstAlbumDataSet: AlbumDataSet @Mock lateinit var secondAlbumDataSet: AlbumDataSet lateinit var albumInBothDataSets: Album lateinit var albumInSecondDataSet: Album lateinit var albumRepository: AlbumRepository lateinit var albumsInBothDataSets: List<Album> lateinit var albumsInSecondDataSet: List<Album> private val albumIdInBothDataSets = "album id" private val albumIdInSecondDataSet = "second album id" private val artistIdInBothDataSets = "artist id" private val artistIdInSecondDataSet = "second artist id" private val artistName = "artist name" @Before fun setUp() { albumInBothDataSets = Album(albumIdInBothDataSets, "album name", Artist(artistIdInBothDataSets, artistName), "album url", emptyList()) albumInSecondDataSet = Album(albumIdInSecondDataSet, "album name", Artist(artistIdInBothDataSets, artistName), "album url", emptyList()) mockRequestAlbumReturns() albumsInBothDataSets = listOf(albumInBothDataSets) albumsInSecondDataSet = listOf(albumInSecondDataSet) mockRequestTopAlbumsReturns() albumRepository = AlbumRepositoryImpl(listOf(firstAlbumDataSet, secondAlbumDataSet)) } private fun mockRequestTopAlbumsReturns() { `when`(firstAlbumDataSet.requestTopAlbums(null, artistName)).thenReturn(albumsInBothDataSets) `when`(firstAlbumDataSet.requestTopAlbums(artistIdInBothDataSets, null)).thenReturn(albumsInBothDataSets) `when`(secondAlbumDataSet.requestTopAlbums(artistIdInSecondDataSet, null)).thenReturn(albumsInSecondDataSet) } private fun mockRequestAlbumReturns() { `when`(firstAlbumDataSet.requestAlbum(albumIdInBothDataSets)).thenReturn(albumInBothDataSets) `when`(secondAlbumDataSet.requestAlbum(albumIdInSecondDataSet)).thenReturn(albumInSecondDataSet) } @Test fun testGetAlbum_existingInBothDataSets() { // When val album = albumRepository.getAlbum(albumIdInBothDataSets) // Then assertEquals(albumInBothDataSets, album) } @Test fun testGetAlbum_existingOnlyInSecondDataSet() { // When val album = albumRepository.getAlbum(albumIdInSecondDataSet) // Then assertEquals(albumInSecondDataSet, album) } @Test fun testGetTopAlbums_withArtistId() { // When val albums = albumRepository.getTopAlbums(artistIdInBothDataSets, null) // Then assertEquals(albumsInBothDataSets, albums) } @Test fun testGetTopAlbums_withArtistIdExistingOnlyInSecondDataSet() { // When val albums = albumRepository.getTopAlbums(artistIdInSecondDataSet, null) // Then assertEquals(albumsInSecondDataSet, albums) } @Test fun testGetTopAlbums_withArtistName() { // When val albums = albumRepository.getTopAlbums(null, artistName) // Then assertEquals(albumsInBothDataSets, albums) } @Test fun testGetTopAlbums_withArtistIdAndArtistName() { // When val albums = albumRepository.getTopAlbums(null, null) // Then assertTrue(albums.isEmpty()) } }
apache-2.0
c90e8ea6d03670f10f54e4cc0537bad2
32.56391
144
0.736724
4.436382
false
true
false
false