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
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/viewer/GHPRUnifiedDiffViewerReviewThreadsHandler.kt
9
4177
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.comment.viewer import com.intellij.diff.tools.fragmented.UnifiedDiffViewer import com.intellij.diff.util.LineRange import com.intellij.diff.util.Range import com.intellij.diff.util.Side import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.util.component1 import com.intellij.openapi.util.component2 import com.intellij.collaboration.ui.codereview.diff.EditorComponentInlaysManager import org.jetbrains.plugins.github.pullrequest.comment.GHPRDiffReviewThreadMapping import org.jetbrains.plugins.github.pullrequest.comment.ui.* import com.intellij.collaboration.ui.SingleValueModel import kotlin.math.max import kotlin.math.min class GHPRUnifiedDiffViewerReviewThreadsHandler(reviewProcessModel: GHPRReviewProcessModel, commentableRangesModel: SingleValueModel<List<Range>?>, reviewThreadsModel: SingleValueModel<List<GHPRDiffReviewThreadMapping>?>, viewer: UnifiedDiffViewer, componentsFactory: GHPRDiffEditorReviewComponentsFactory, cumulative: Boolean) : GHPRDiffViewerBaseReviewThreadsHandler<UnifiedDiffViewer>(commentableRangesModel, reviewThreadsModel, viewer) { private val commentableRanges = SingleValueModel<List<LineRange>>(emptyList()) private val editorThreads = GHPREditorReviewThreadsModel() override val viewerReady: Boolean get() = viewer.isContentGood init { val inlaysManager = EditorComponentInlaysManager(viewer.editor as EditorImpl) val gutterIconRendererFactory = GHPRDiffEditorGutterIconRendererFactoryImpl(reviewProcessModel, inlaysManager, componentsFactory, cumulative) { fileLine -> val (start, end) = getCommentLinesRange(viewer.editor, fileLine) val (endIndices, side) = viewer.transferLineFromOneside(end) val endLine = side.select(endIndices).takeIf { it >= 0 } ?: return@GHPRDiffEditorGutterIconRendererFactoryImpl null val (startIndices, _) = viewer.transferLineFromOneside(start) val startLine = side.select(startIndices).takeIf { it >= 0 } ?: return@GHPRDiffEditorGutterIconRendererFactoryImpl null GHPRCommentLocation(side, endLine, startLine, fileLine) } GHPREditorCommentableRangesController(commentableRanges, gutterIconRendererFactory, viewer.editor) GHPREditorReviewThreadsController(editorThreads, componentsFactory, inlaysManager) } override fun markCommentableRanges(ranges: List<Range>?) { if (ranges == null) { commentableRanges.value = emptyList() return } val transferredRanges: List<LineRange> = ranges.map { val onesideStartLeft = viewer.transferLineToOnesideStrict(Side.LEFT, it.start1) if (onesideStartLeft < 0) return@map null val onesideStartRight = viewer.transferLineToOnesideStrict(Side.RIGHT, it.start2) if (onesideStartRight < 0) return@map null val onesideEndLeft = viewer.transferLineToOnesideStrict(Side.LEFT, it.end1 - 1) + 1 if (onesideEndLeft < 0) return@map null val onesideEndRight = viewer.transferLineToOnesideStrict(Side.RIGHT, it.end2 - 1) + 1 if (onesideEndRight < 0) return@map null LineRange(min(onesideStartLeft, onesideStartRight), max(onesideEndLeft, onesideEndRight)) }.filterNotNull() commentableRanges.value = transferredRanges } override fun showThreads(threads: List<GHPRDiffReviewThreadMapping>?) { editorThreads.update(threads ?.groupBy({ viewer.transferLineToOneside(it.diffSide, it.fileLineIndex) }, { it.thread }) ?.filterKeys { it >= 0 }.orEmpty()) } }
apache-2.0
0b93cbf42355a40ab2782376043fdace
49.939024
140
0.688293
5.044686
false
false
false
false
android/compose-samples
Jetchat/app/src/main/java/com/example/compose/jetchat/theme/Typography.kt
1
5605
/* * 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.compose.jetchat.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.ExperimentalTextApi import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.googlefonts.Font import androidx.compose.ui.text.googlefonts.GoogleFont import androidx.compose.ui.unit.sp import com.example.compose.jetchat.R @OptIn(ExperimentalTextApi::class) val provider = GoogleFont.Provider( providerAuthority = "com.google.android.gms.fonts", providerPackage = "com.google.android.gms", certificates = R.array.com_google_android_gms_fonts_certs ) @OptIn(ExperimentalTextApi::class) val MontserratFont = GoogleFont(name = "Montserrat") @OptIn(ExperimentalTextApi::class) val KarlaFont = GoogleFont(name = "Karla") @OptIn(ExperimentalTextApi::class) val MontserratFontFamily = FontFamily( Font(googleFont = MontserratFont, fontProvider = provider), Font(resId = R.font.montserrat_regular), Font(googleFont = MontserratFont, fontProvider = provider, weight = FontWeight.Light), Font(resId = R.font.montserrat_light, weight = FontWeight.Light), Font(googleFont = MontserratFont, fontProvider = provider, weight = FontWeight.Medium), Font(resId = R.font.montserrat_medium, weight = FontWeight.Medium), Font(googleFont = MontserratFont, fontProvider = provider, weight = FontWeight.SemiBold), Font(resId = R.font.montserrat_semibold, weight = FontWeight.SemiBold), ) @OptIn(ExperimentalTextApi::class) val KarlaFontFamily = FontFamily( Font(googleFont = KarlaFont, fontProvider = provider), Font(resId = R.font.karla_regular), Font(googleFont = KarlaFont, fontProvider = provider, weight = FontWeight.Bold), Font(resId = R.font.karla_bold, weight = FontWeight.Bold), ) val JetchatTypography = Typography( displayLarge = TextStyle( fontFamily = MontserratFontFamily, fontWeight = FontWeight.Light, fontSize = 57.sp, lineHeight = 64.sp, letterSpacing = 0.sp ), displayMedium = TextStyle( fontFamily = MontserratFontFamily, fontWeight = FontWeight.Light, fontSize = 45.sp, lineHeight = 52.sp, letterSpacing = 0.sp ), displaySmall = TextStyle( fontFamily = MontserratFontFamily, fontWeight = FontWeight.Normal, fontSize = 36.sp, lineHeight = 44.sp, letterSpacing = 0.sp ), headlineLarge = TextStyle( fontFamily = MontserratFontFamily, fontWeight = FontWeight.SemiBold, fontSize = 32.sp, lineHeight = 40.sp, letterSpacing = 0.sp ), headlineMedium = TextStyle( fontFamily = MontserratFontFamily, fontWeight = FontWeight.SemiBold, fontSize = 28.sp, lineHeight = 36.sp, letterSpacing = 0.sp ), headlineSmall = TextStyle( fontFamily = MontserratFontFamily, fontWeight = FontWeight.SemiBold, fontSize = 24.sp, lineHeight = 32.sp, letterSpacing = 0.sp ), titleLarge = TextStyle( fontFamily = MontserratFontFamily, fontWeight = FontWeight.SemiBold, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), titleMedium = TextStyle( fontFamily = MontserratFontFamily, fontWeight = FontWeight.SemiBold, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.15.sp ), titleSmall = TextStyle( fontFamily = KarlaFontFamily, fontWeight = FontWeight.Bold, fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = 0.1.sp ), bodyLarge = TextStyle( fontFamily = KarlaFontFamily, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.15.sp ), bodyMedium = TextStyle( fontFamily = MontserratFontFamily, fontWeight = FontWeight.Medium, fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = 0.25.sp ), bodySmall = TextStyle( fontFamily = KarlaFontFamily, fontWeight = FontWeight.Bold, fontSize = 12.sp, lineHeight = 16.sp, letterSpacing = 0.4.sp ), labelLarge = TextStyle( fontFamily = MontserratFontFamily, fontWeight = FontWeight.SemiBold, fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = 0.1.sp ), labelMedium = TextStyle( fontFamily = MontserratFontFamily, fontWeight = FontWeight.SemiBold, fontSize = 12.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ), labelSmall = TextStyle( fontFamily = MontserratFontFamily, fontWeight = FontWeight.SemiBold, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) )
apache-2.0
1dd91e8fc7552f11a6ecf41518d30717
32.16568
93
0.667618
4.158012
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/printing/JKPrinter.kt
2
4691
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.nj2k.printing import com.intellij.openapi.project.Project import org.jetbrains.kotlin.j2k.ast.Nullability import org.jetbrains.kotlin.nj2k.JKElementInfoStorage import org.jetbrains.kotlin.nj2k.JKImportStorage import org.jetbrains.kotlin.nj2k.symbols.JKSymbol import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.types.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs internal open class JKPrinterBase { private val stringBuilder: StringBuilder = StringBuilder() var currentIndent = 0; private val indentSymbol = " ".repeat(4) private var lastSymbolIsLineBreak = false override fun toString(): String = stringBuilder.toString() fun print(value: String) { if (value.isNotEmpty()) { lastSymbolIsLineBreak = false } stringBuilder.append(value) } fun println() { if (lastSymbolIsLineBreak) return stringBuilder.append('\n') repeat(currentIndent) { stringBuilder.append(indentSymbol) } lastSymbolIsLineBreak = true } inline fun indented(block: () -> Unit) { currentIndent++ block() currentIndent-- } inline fun block(body: () -> Unit) { par(ParenthesisKind.CURVED) { indented(body) } } inline fun par(kind: ParenthesisKind = ParenthesisKind.ROUND, body: () -> Unit) { print(kind.open) body() print(kind.close) } inline fun <T> renderList(list: List<T>, separator: String = ", ", renderElement: (T) -> Unit) = renderList(list, { this.print(separator) }, renderElement) inline fun <T> renderList(list: List<T>, separator: () -> Unit, renderElement: (T) -> Unit) { if (list.isEmpty()) return renderElement(list.first()) for (element in list.subList(1, list.size)) { separator() renderElement(element) } } enum class ParenthesisKind(val open: String, val close: String) { ROUND("(", ")"), CURVED("{", "}"), ANGLE("<", ">") } } internal class JKPrinter( project: Project, importStorage: JKImportStorage, private val elementInfoStorage: JKElementInfoStorage ) : JKPrinterBase() { val symbolRenderer = JKSymbolRenderer(importStorage, project) private fun JKType.renderTypeInfo() { [email protected](elementInfoStorage.getOrCreateInfoForElement(this).render()) } fun renderType(type: JKType, owner: JKTreeElement?) { if (type is JKNoType) return if (type is JKCapturedType) { when (val wildcard = type.wildcardType) { is JKVarianceTypeParameterType -> { renderType(wildcard.boundType, owner) } is JKStarProjectionType -> { type.renderTypeInfo() this.print("Any?") } } return } type.renderTypeInfo() when (type) { is JKClassType -> { renderSymbol(type.classReference, owner) } is JKContextType -> return is JKStarProjectionType -> this.print("*") is JKTypeParameterType -> this.print(type.identifier.name) is JKVarianceTypeParameterType -> { when (type.variance) { JKVarianceTypeParameterType.Variance.IN -> this.print("in ") JKVarianceTypeParameterType.Variance.OUT -> this.print("out ") } renderType(type.boundType, null) } else -> this.print("Unit /* TODO: ${type::class} */") } if (type is JKParametrizedType && type.parameters.isNotEmpty()) { par(ParenthesisKind.ANGLE) { renderList(type.parameters, renderElement = { renderType(it, null) }) } } // we print undefined types as nullable because we need smartcast to work in nullability inference in post-processing if (type !is JKWildCardType && (type.nullability == Nullability.Default && owner?.safeAs<JKLambdaExpression>()?.functionalType?.type != type || type.nullability == Nullability.Nullable) ) { this.print("?") } } fun renderSymbol(symbol: JKSymbol, owner: JKTreeElement?) { print(symbolRenderer.renderSymbol(symbol, owner)) } }
apache-2.0
3424feb1029707f887e941ddcef0a048
33
158
0.597101
4.649158
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/ContainsOperatorReferenceSearcher.kt
3
2410
// 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.search.usagesSearch.operators import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.search.SearchRequestCollector import com.intellij.psi.search.SearchScope import com.intellij.util.Processor import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance class ContainsOperatorReferenceSearcher( targetFunction: PsiElement, searchScope: SearchScope, consumer: Processor<in PsiReference>, optimizer: SearchRequestCollector, options: KotlinReferencesSearchOptions ) : OperatorReferenceSearcher<KtOperationReferenceExpression>( targetFunction, searchScope, consumer, optimizer, options, wordsToSearch = listOf("in") ) { private companion object { private val OPERATION_TOKENS = setOf(KtTokens.IN_KEYWORD, KtTokens.NOT_IN) } override fun processPossibleReceiverExpression(expression: KtExpression) { val parent = expression.parent when (parent) { is KtBinaryExpression -> { if (parent.operationToken in OPERATION_TOKENS && expression == parent.right) { processReferenceElement(parent.operationReference) } } is KtWhenConditionInRange -> { processReferenceElement(parent.operationReference) } } } override fun isReferenceToCheck(ref: PsiReference): Boolean { if (ref !is KtSimpleNameReference) return false val element = ref.element as? KtOperationReferenceExpression ?: return false return element.getReferencedNameElementType() in OPERATION_TOKENS } override fun extractReference(element: KtElement): PsiReference? { val referenceExpression = element as? KtOperationReferenceExpression ?: return null if (referenceExpression.getReferencedNameElementType() !in OPERATION_TOKENS) return null return referenceExpression.references.firstIsInstance<KtSimpleNameReference>() } }
apache-2.0
668af1706c95dc0901cffd39174f37b8
39.183333
158
0.739834
5.527523
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/pipeline/shadermodel/MathNodes.kt
1
6372
package de.fabmax.kool.pipeline.shadermodel import de.fabmax.kool.math.Vec3f abstract class MathOpNode(name: String, graph: ShaderGraph) : ShaderNode("math_${graph.nextNodeId}", graph) { var left = ShaderNodeIoVar(ModelVar3fConst(Vec3f.X_AXIS)) set(value) { output = ShaderNodeIoVar(ModelVar("${name}_out", value.variable.type), this) field = value } var right = ShaderNodeIoVar(ModelVar1fConst(1f)) var output = ShaderNodeIoVar(ModelVar3f("${name}_out"), this) private set override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(left, right) } } class AddNode(graph: ShaderGraph) : MathOpNode("add_${graph.nextNodeId}", graph) { override fun generateCode(generator: CodeGenerator) { generator.appendMain("${output.declare()} = $left + $right;") } } class SubtractNode(graph: ShaderGraph) : MathOpNode("add_${graph.nextNodeId}", graph) { override fun generateCode(generator: CodeGenerator) { generator.appendMain("${output.declare()} = $left - $right;") } } class DivideNode(graph: ShaderGraph) : MathOpNode("divide_${graph.nextNodeId}", graph) { override fun generateCode(generator: CodeGenerator) { generator.appendMain("${output.declare()} = $left / $right;") } } class MultiplyNode(graph: ShaderGraph) : MathOpNode("multiply_${graph.nextNodeId}", graph) { override fun generateCode(generator: CodeGenerator) { generator.appendMain("${output.declare()} = $left * $right;") } } class MinNode(graph: ShaderGraph) : MathOpNode("min_${graph.nextNodeId}", graph) { override fun generateCode(generator: CodeGenerator) { generator.appendMain("${output.declare()} = min($left, $right);") } } class MaxNode(graph: ShaderGraph) : MathOpNode("max_${graph.nextNodeId}", graph) { override fun generateCode(generator: CodeGenerator) { generator.appendMain("${output.declare()} = max($left, $right);") } } class MixNode(graph: ShaderGraph) : MathOpNode("mix_${graph.nextNodeId}", graph) { var mixFac = ShaderNodeIoVar(ModelVar1fConst(0.5f)) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(mixFac) } override fun generateCode(generator: CodeGenerator) { generator.appendMain("${output.declare()} = mix($left, $right, ${mixFac.ref1f()});") } } class VecFromColorNode(graph: ShaderGraph) : ShaderNode("vecFromColor_${graph.nextNodeId}", graph) { var input = ShaderNodeIoVar(ModelVar3fConst(Vec3f.X_AXIS)) val output = ShaderNodeIoVar(ModelVar3f("${name}_out"), this) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(input) } override fun generateCode(generator: CodeGenerator) { generator.appendMain("${output.declare()} = (${input.ref3f()} - 0.5) * 2.0;") } } class DotNode(graph: ShaderGraph) : ShaderNode("dot_${graph.nextNodeId}", graph) { var inA = ShaderNodeIoVar(ModelVar3fConst(Vec3f.ZERO)) var inB = ShaderNodeIoVar(ModelVar3fConst(Vec3f.ZERO)) val output = ShaderNodeIoVar(ModelVar1f("${name}_out"), this) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(inA, inB) } override fun generateCode(generator: CodeGenerator) { generator.appendMain("${output.declare()} = dot($inA, $inB);") } } class DistanceNode(graph: ShaderGraph) : ShaderNode("dist_${graph.nextNodeId}", graph) { var inA = ShaderNodeIoVar(ModelVar3fConst(Vec3f.ZERO)) var inB = ShaderNodeIoVar(ModelVar3fConst(Vec3f.ZERO)) val output = ShaderNodeIoVar(ModelVar1f("${name}_out"), this) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(inA, inB) } override fun generateCode(generator: CodeGenerator) { generator.appendMain("${output.declare()} = length($inA - $inB);") } } class NormalizeNode(graph: ShaderGraph) : ShaderNode("normalize_${graph.nextNodeId}", graph) { var input = ShaderNodeIoVar(ModelVar3fConst(Vec3f.X_AXIS)) val output = ShaderNodeIoVar(ModelVar3f("${name}_out"), this) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(input) } override fun generateCode(generator: CodeGenerator) { generator.appendMain("${output.declare()} = normalize(${input.ref3f()});") } } class ViewDirNode(graph: ShaderGraph) : ShaderNode("viewDir_${graph.nextNodeId}", graph) { var inCamPos = ShaderNodeIoVar(ModelVar3fConst(Vec3f.Z_AXIS)) var inWorldPos = ShaderNodeIoVar(ModelVar3fConst(Vec3f.ZERO)) val output = ShaderNodeIoVar(ModelVar3f("${name}_out"), this) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(inCamPos, inWorldPos) } override fun generateCode(generator: CodeGenerator) { generator.appendMain("${output.declare()} = normalize(${inWorldPos.ref3f()} - ${inCamPos.ref3f()});") } } class ReflectNode(graph: ShaderGraph) : ShaderNode("reflect_${graph.nextNodeId}", graph) { var inDirection = ShaderNodeIoVar(ModelVar3fConst(Vec3f.X_AXIS)) var inNormal = ShaderNodeIoVar(ModelVar3fConst(Vec3f.Y_AXIS)) val outDirection = ShaderNodeIoVar(ModelVar3f("${name}_out"), this) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(inDirection, inNormal) } override fun generateCode(generator: CodeGenerator) { generator.appendMain("${outDirection.declare()} = reflect(${inDirection.ref3f()}, ${inNormal.ref3f()});") } } class RefractNode(graph: ShaderGraph) : ShaderNode("refract_${graph.nextNodeId}", graph) { var inDirection = ShaderNodeIoVar(ModelVar3fConst(Vec3f.X_AXIS)) var inNormal = ShaderNodeIoVar(ModelVar3fConst(Vec3f.Y_AXIS)) var inIor = ShaderNodeIoVar(ModelVar1fConst(1.4f)) val outDirection = ShaderNodeIoVar(ModelVar3f("${name}_out"), this) override fun setup(shaderGraph: ShaderGraph) { super.setup(shaderGraph) dependsOn(inDirection, inNormal) } override fun generateCode(generator: CodeGenerator) { generator.appendMain("${outDirection.declare()} = refract(${inDirection.ref3f()}, ${inNormal.ref3f()}, ${inIor.ref1f()});") } }
apache-2.0
0ca3110d8acca833ff05e572cf7c7f6e
36.046512
131
0.682674
4.063776
false
false
false
false
kivensolo/UiUsingListView
database/src/main/java/com/kingz/database/entity/BaseEntity.kt
1
485
package com.kingz.database.entity import androidx.room.ColumnInfo import androidx.room.Entity import java.io.Serializable @Entity(primaryKeys = ["id"]) open class BaseEntity : Serializable { // @PrimaryKey(autoGenerate = true) // var id = 0 @ColumnInfo(name = "type") var type: String = "" @ColumnInfo(name = "name") var name: String? = null @ColumnInfo(name = "img_url") var pic: String? = null @ColumnInfo(name = "id") var id: String = "" }
gpl-2.0
becf768b5108c6595bfcd29e14b1c20f
22.095238
38
0.651546
3.592593
false
false
false
false
ncoe/rosetta
Line_circle_intersection/Kotlin/src/LineCircleIntersection.kt
1
4215
import kotlin.math.absoluteValue import kotlin.math.sqrt const val eps = 1e-14 class Point(val x: Double, val y: Double) { override fun toString(): String { var xv = x if (xv == 0.0) { xv = 0.0 } var yv = y if (yv == 0.0) { yv = 0.0 } return "($xv, $yv)" } } fun sq(x: Double): Double { return x * x } fun intersects(p1: Point, p2: Point, cp: Point, r: Double, segment: Boolean): MutableList<Point> { val res = mutableListOf<Point>() val x0 = cp.x val y0 = cp.y val x1 = p1.x val y1 = p1.y val x2 = p2.x val y2 = p2.y val A = y2 - y1 val B = x1 - x2 val C = x2 * y1 - x1 * y2 val a = sq(A) + sq(B) val b: Double val c: Double var bnz = true if (B.absoluteValue >= eps) { b = 2 * (A * C + A * B * y0 - sq(B) * x0) c = sq(C) + 2 * B * C * y0 - sq(B) * (sq(r) - sq(x0) - sq(y0)) } else { b = 2 * (B * C + A * B * x0 - sq(A) * y0) c = sq(C) + 2 * A * C * x0 - sq(A) * (sq(r) - sq(x0) - sq(y0)) bnz = false } var d = sq(b) - 4 * a * c // discriminant if (d < 0) { return res } // checks whether a point is within a segment fun within(x: Double, y: Double): Boolean { val d1 = sqrt(sq(x2 - x1) + sq(y2 - y1)) // distance between end-points val d2 = sqrt(sq(x - x1) + sq(y - y1)) // distance from point to one end val d3 = sqrt(sq(x2 - x) + sq(y2 - y)) // distance from point to other end val delta = d1 - d2 - d3 return delta.absoluteValue < eps // true if delta is less than a small tolerance } var x = 0.0 fun fx(): Double { return -(A * x + C) / B } var y = 0.0 fun fy(): Double { return -(B * y + C) / A } fun rxy() { if (!segment || within(x, y)) { res.add(Point(x, y)) } } if (d == 0.0) { // line is tangent to circle, so just one intersect at most if (bnz) { x = -b / (2 * a) y = fx() rxy() } else { y = -b / (2 * a) x = fy() rxy() } } else { // two intersects at most d = sqrt(d) if (bnz) { x = (-b + d) / (2 * a) y = fx() rxy() x = (-b - d) / (2 * a) y = fx() rxy() } else { y = (-b + d) / (2 * a) x = fy() rxy() y = (-b - d) / (2 * a) x = fy() rxy() } } return res } fun main() { println("The intersection points (if any) between:") var cp = Point(3.0, -5.0) var r = 3.0 println(" A circle, center $cp with radius $r, and:") var p1 = Point(-10.0, 11.0) var p2 = Point(10.0, -9.0) println(" a line containing the points $p1 and $p2 is/are:") println(" ${intersects(p1, p2, cp, r, false)}") p2 = Point(-10.0, 12.0) println(" a segment starting at $p1 and ending at $p2 is/are:") println(" ${intersects(p1, p2, cp, r, true)}") p1 = Point(3.0, -2.0) p2 = Point(7.0, -2.0) println(" a horizontal line containing the points $p1 and $p2 is/are:") println(" ${intersects(p1, p2, cp, r, false)}") cp = Point(0.0, 0.0) r = 4.0 println(" A circle, center $cp with radius $r, and:") p1 = Point(0.0, -3.0) p2 = Point(0.0, 6.0) println(" a vertical line containing the points $p1 and $p2 is/are:") println(" ${intersects(p1, p2, cp, r, false)}") println(" a vertical segment containing the points $p1 and $p2 is/are:") println(" ${intersects(p1, p2, cp, r, true)}") cp = Point(4.0, 2.0) r = 5.0 println(" A circle, center $cp with radius $r, and:") p1 = Point(6.0, 3.0) p2 = Point(10.0, 7.0) println(" a line containing the points $p1 and $p2 is/are:") println(" ${intersects(p1, p2, cp, r, false)}") p1 = Point(7.0, 4.0) p2 = Point(11.0, 8.0) println(" a segment starting at $p1 and ending at $p2 is/are:") println(" ${intersects(p1, p2, cp, r, true)}") }
mit
9787568b126737d0c47c5948a1c6f134
26.019231
98
0.46121
2.869299
false
false
false
false
siosio/intellij-community
plugins/git4idea/src/git4idea/branch/GitCompareBranchesUi.kt
1
9386
// 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 git4idea.branch import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.OnePixelSplitter import com.intellij.util.Consumer import com.intellij.util.ContentUtilEx import com.intellij.util.ui.StatusText import com.intellij.vcs.log.VcsLogFilterCollection import com.intellij.vcs.log.VcsLogRangeFilter import com.intellij.vcs.log.VcsLogRootFilter import com.intellij.vcs.log.data.VcsLogData import com.intellij.vcs.log.impl.MainVcsLogUiProperties import com.intellij.vcs.log.impl.VcsLogManager import com.intellij.vcs.log.impl.VcsProjectLog import com.intellij.vcs.log.ui.MainVcsLogUi import com.intellij.vcs.log.ui.VcsLogColorManager import com.intellij.vcs.log.ui.VcsLogPanel import com.intellij.vcs.log.ui.VcsLogUiImpl import com.intellij.vcs.log.ui.filter.VcsLogClassicFilterUi import com.intellij.vcs.log.ui.filter.VcsLogFilterUiEx import com.intellij.vcs.log.visible.VcsLogFiltererImpl import com.intellij.vcs.log.visible.VisiblePackRefresher import com.intellij.vcs.log.visible.VisiblePackRefresherImpl import com.intellij.vcs.log.visible.filters.VcsLogFilterObject.collection import com.intellij.vcs.log.visible.filters.VcsLogFilterObject.fromRange import com.intellij.vcs.log.visible.filters.VcsLogFilterObject.fromRoot import git4idea.GitUtil.HEAD import git4idea.i18n.GitBundle import git4idea.i18n.GitBundleExtensions.html import git4idea.repo.GitRepository import java.util.* import javax.swing.JComponent internal class GitCompareBranchesUi(internal val project: Project, internal val rangeFilter: VcsLogRangeFilter, internal val rootFilter: VcsLogRootFilter?) { @JvmOverloads constructor(project: Project, repositories: List<GitRepository>, branchName: String, otherBranchName: String = "") : this(project, createRangeFilter(repositories, branchName, otherBranchName), createRootFilter(repositories)) companion object { private fun createRangeFilter(repositories: List<GitRepository>, branchName: String, otherBranchName: String = ""): VcsLogRangeFilter { val currentBranchName = repositories.first().currentBranchName val secondRef = when { otherBranchName.isNotBlank() -> otherBranchName repositories.size == 1 && !currentBranchName.isNullOrBlank() -> currentBranchName else -> HEAD } return fromRange(secondRef, branchName) } private fun createRootFilter(repositories: List<GitRepository>): VcsLogRootFilter? { return repositories.singleOrNull()?.let { fromRoot(it.root) } } } fun open() { VcsProjectLog.runWhenLogIsReady(project) { GitCompareBranchesFilesManager.getInstance(project).openFile(this, true) } } internal fun create(logManager: VcsLogManager): JComponent { val topLogUiFactory = MyLogUiFactory("git-compare-branches-top-" + UUID.randomUUID(), MyPropertiesForHardcodedFilters(project.service<GitCompareBranchesTopLogProperties>()), logManager.colorManager, rangeFilter, rootFilter) val bottomLogUiFactory = MyLogUiFactory("git-compare-branches-bottom-" + UUID.randomUUID(), MyPropertiesForHardcodedFilters(project.service<GitCompareBranchesBottomLogProperties>()), logManager.colorManager, rangeFilter.asReversed(), rootFilter) val topLogUi = logManager.createLogUi(topLogUiFactory, VcsLogManager.LogWindowKind.EDITOR) val bottomLogUi = logManager.createLogUi(bottomLogUiFactory, VcsLogManager.LogWindowKind.EDITOR) return OnePixelSplitter(true).apply { firstComponent = VcsLogPanel(logManager, topLogUi) secondComponent = VcsLogPanel(logManager, bottomLogUi) } } private class MyLogUiFactory(val logId: String, val properties: MainVcsLogUiProperties, val colorManager: VcsLogColorManager, val rangeFilter: VcsLogRangeFilter, val rootFilter: VcsLogRootFilter?) : VcsLogManager.VcsLogUiFactory<MainVcsLogUi> { override fun createLogUi(project: Project, logData: VcsLogData): MainVcsLogUi { val vcsLogFilterer = VcsLogFiltererImpl(logData.logProviders, logData.storage, logData.topCommitsCache, logData.commitDetailsGetter, logData.index) val initialSortType = properties.get(MainVcsLogUiProperties.BEK_SORT_TYPE) val refresher = VisiblePackRefresherImpl(project, logData, collection(), initialSortType, vcsLogFilterer, logId) return MyVcsLogUi(logId, logData, colorManager, properties, refresher, rangeFilter, rootFilter) } } private class MyVcsLogUi(id: String, logData: VcsLogData, colorManager: VcsLogColorManager, uiProperties: MainVcsLogUiProperties, refresher: VisiblePackRefresher, rangeFilter: VcsLogRangeFilter, rootFilter: VcsLogRootFilter?) : VcsLogUiImpl(id, logData, colorManager, uiProperties, refresher, collection(rangeFilter, rootFilter)) { override fun createFilterUi(filterConsumer: Consumer<VcsLogFilterCollection>, filters: VcsLogFilterCollection?, parentDisposable: Disposable): VcsLogFilterUiEx { return MyFilterUi(logData, filterConsumer, properties, colorManager, filters, parentDisposable) } override fun applyFiltersAndUpdateUi(filters: VcsLogFilterCollection) { super.applyFiltersAndUpdateUi(filters) val (start, end) = filters.get(VcsLogFilterCollection.RANGE_FILTER).getRange() mainFrame.setExplanationHtml(getExplanationText(start, end)) } } private class MyFilterUi(data: VcsLogData, filterConsumer: Consumer<VcsLogFilterCollection>, properties: MainVcsLogUiProperties, colorManager: VcsLogColorManager, filters: VcsLogFilterCollection?, parentDisposable: Disposable ) : VcsLogClassicFilterUi(data, filterConsumer, properties, colorManager, filters, parentDisposable) { val rangeFilter: VcsLogRangeFilter get() = myBranchFilterModel.rangeFilter!! override fun createBranchComponent(): FilterActionComponent? = null override fun setCustomEmptyText(text: StatusText) { if (filters.filters.any { it !is VcsLogRangeFilter && it !is VcsLogRootFilter }) { // additional filters have been set => display the generic message super.setCustomEmptyText(text) } else { val (start, end) = rangeFilter.getRange() text.text = GitBundle.message("git.compare.branches.empty.status", start, end) } } override fun setFilters(collection: VcsLogFilterCollection) { if (collection.isEmpty) { if (myStructureFilterModel.structureFilter != null) myStructureFilterModel.setFilter(null) myDateFilterModel.setFilter(null) myTextFilterModel.setFilter(null) myUserFilterModel.setFilter(null) } else { collection.get(VcsLogFilterCollection.RANGE_FILTER)?.let(myBranchFilterModel::setRangeFilter) } } } private class MyPropertiesForHardcodedFilters( mainProperties: GitCompareBranchesLogProperties ) : MainVcsLogUiProperties by mainProperties { private val filters = mutableMapOf<String, List<String>>() override fun getFilterValues(filterName: String): List<String>? { return filters[filterName] } override fun saveFilterValues(filterName: String, values: List<String>?) { if (values != null) { filters[filterName] = values } else { filters.remove(filterName) } } } } internal fun getEditorTabName(rangeFilter: VcsLogRangeFilter): String { val (start, end) = rangeFilter.getRange() return ContentUtilEx.getFullName(GitBundle.message("git.compare.branches.tab.name"), StringUtil.shortenTextWithEllipsis(GitBundle.message("git.compare.branches.tab.suffix", end, start), 150, 20)) } private fun VcsLogRangeFilter?.getRange(): VcsLogRangeFilter.RefRange { check(this != null && ranges.size == 1) { "At this point there is one and only one range filter, changing it from the UI is disabled" } return ranges[0] } private fun VcsLogRangeFilter.asReversed(): VcsLogRangeFilter { val (start, end) = getRange() return fromRange(end, start) } @NlsContexts.LinkLabel private fun getExplanationText(@NlsSafe dontExist: String, @NlsSafe existIn: String): String { return html("git.compare.branches.explanation.message", HtmlChunk.tag("code").child(HtmlChunk.text(existIn).bold()), HtmlChunk.tag("code").child(HtmlChunk.text(dontExist).bold())) }
apache-2.0
d468afea3f9eef8a7e0149271108061c
46.165829
158
0.713616
5.076257
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/javac/JavacConstructorElement.kt
3
3146
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing.javac import androidx.room.compiler.processing.XConstructorElement import androidx.room.compiler.processing.XConstructorType import androidx.room.compiler.processing.XType import androidx.room.compiler.processing.XTypeParameterElement import androidx.room.compiler.processing.javac.kotlin.KmConstructor import com.google.auto.common.MoreTypes import javax.lang.model.element.ElementKind import javax.lang.model.element.ExecutableElement internal class JavacConstructorElement( env: JavacProcessingEnv, element: ExecutableElement ) : JavacExecutableElement(env, element), XConstructorElement { init { check(element.kind == ElementKind.CONSTRUCTOR) { "Constructor element is constructed with invalid type: $element" } } override val name: String get() = "<init>" override val typeParameters: List<XTypeParameterElement> by lazy { element.typeParameters.map { // Type parameters are not allowed in Kotlin sources, so if type parameters exist they // must have come from Java sources. Thus, there's no kotlin metadata so just use null. JavacTypeParameterElement(env, this, it, null) } } override val parameters: List<JavacMethodParameter> by lazy { element.parameters.mapIndexed { index, variable -> JavacMethodParameter( env = env, enclosingElement = this, element = variable, kotlinMetadataFactory = { kotlinMetadata?.parameters?.getOrNull(index) }, argIndex = index ) } } override val executableType: XConstructorType by lazy { JavacConstructorType( env = env, element = this, executableType = MoreTypes.asExecutable(element.asType()) ) } override fun asMemberOf(other: XType): XConstructorType { return if (other !is JavacDeclaredType || enclosingElement.type.isSameType(other)) { executableType } else { val asMemberOf = env.typeUtils.asMemberOf(other.typeMirror, element) JavacConstructorType( env = env, element = this, executableType = MoreTypes.asExecutable(asMemberOf) ) } } override val kotlinMetadata: KmConstructor? by lazy { (enclosingElement as? JavacTypeElement)?.kotlinMetadata?.getConstructorMetadata(element) } }
apache-2.0
7b47afc4a5214a4b8b7bafdfabf9bdda
36.011765
99
0.67864
4.885093
false
false
false
false
androidx/androidx
external/paparazzi/paparazzi/src/main/java/app/cash/paparazzi/HtmlReportWriter.kt
3
8937
/* * Copyright (C) 2019 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 app.cash.paparazzi import app.cash.paparazzi.SnapshotHandler.FrameHandler import app.cash.paparazzi.internal.PaparazziJson import com.google.common.base.CharMatcher import okio.BufferedSink import okio.HashingSink import okio.blackholeSink import okio.buffer import okio.sink import okio.source import org.jcodec.api.awt.AWTSequenceEncoder import java.awt.image.BufferedImage import java.io.File import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.UUID import javax.imageio.ImageIO /** * Creates an HTML report that avoids writing files that have already been written. * * Images and videos are named by hashes of their contents. Paparazzi won't write two images or videos with the same * contents. Note that the images/ directory includes the individual frames of each video. * * Runs are named by their date. * * ``` * images * 088c60580f06efa95c37fd8e754074729ee74a06.png * 93f9a81cb594280f4b3898d90dfad8c8ea969b01.png * 22d37abd0841ba2a8d0bd635954baf7cbfaa269b.png * a4769e43cc5901ef28c0d46c46a44ea6429cbccc.png * videos * d1cddc5da2224053f2af51f4e69a76de4e61fc41.mov * runs * 20190626002322_b9854e.js * 20190626002345_b1e882.js * index.html * index.js * paparazzi.js * ``` */ class HtmlReportWriter @JvmOverloads constructor( private val runName: String = defaultRunName(), private val rootDirectory: File = File("build/reports/paparazzi"), snapshotRootDirectory: File = File("src/test/snapshots") ) : SnapshotHandler { private val runsDirectory: File = File(rootDirectory, "runs") private val imagesDirectory: File = File(rootDirectory, "images") private val videosDirectory: File = File(rootDirectory, "videos") private val goldenImagesDirectory = File(snapshotRootDirectory, "images") private val goldenVideosDirectory = File(snapshotRootDirectory, "videos") private val shots = mutableListOf<Snapshot>() private val isRecording: Boolean = System.getProperty("paparazzi.test.record")?.toBoolean() == true init { runsDirectory.mkdirs() imagesDirectory.mkdirs() videosDirectory.mkdirs() writeStaticFiles() writeRunJs() writeIndexJs() } override fun newFrameHandler( snapshot: Snapshot, frameCount: Int, fps: Int ): FrameHandler { return object : FrameHandler { val hashes = mutableListOf<String>() override fun handle(image: BufferedImage) { hashes += writeImage(image) } override fun close() { if (hashes.isEmpty()) return val shot = if (hashes.size == 1) { val original = File(imagesDirectory, "${hashes[0]}.png") if (isRecording) { val goldenFile = File(goldenImagesDirectory, snapshot.toFileName("_", "png")) original.copyTo(goldenFile, overwrite = true) } snapshot.copy(file = original.toJsonPath()) } else { val hash = writeVideo(hashes, fps) if (isRecording) { for ((index, frameHash) in hashes.withIndex()) { val originalFrame = File(imagesDirectory, "$frameHash.png") val frameSnapshot = snapshot.copy(name = "${snapshot.name} $index") val goldenFile = File(goldenImagesDirectory, frameSnapshot.toFileName("_", "png")) if (!goldenFile.exists()) { originalFrame.copyTo(goldenFile) } } } val original = File(videosDirectory, "$hash.mov") if (isRecording) { val goldenFile = File(goldenVideosDirectory, snapshot.toFileName("_", "mov")) if (!goldenFile.exists()) { original.copyTo(goldenFile) } } snapshot.copy(file = original.toJsonPath()) } shots += shot } } } /** Returns the hash of the image. */ private fun writeImage(image: BufferedImage): String { val hash = hash(image) val file = File(imagesDirectory, "$hash.png") if (!file.exists()) { file.writeAtomically(image) } return hash } /** Returns a SHA-1 hash of the pixels of [image]. */ private fun hash(image: BufferedImage): String { val hashingSink = HashingSink.sha1(blackholeSink()) hashingSink.buffer().use { sink -> for (y in 0 until image.height) { for (x in 0 until image.width) { sink.writeInt(image.getRGB(x, y)) } } } return hashingSink.hash.hex() } private fun writeVideo( frameHashes: List<String>, fps: Int ): String { val hash = hash(frameHashes) val file = File(videosDirectory, "$hash.mov") if (!file.exists()) { val tmpFile = File(videosDirectory, "$hash.mov.tmp") val encoder = AWTSequenceEncoder.createSequenceEncoder(tmpFile, fps) for (frameHash in frameHashes) { val frame = ImageIO.read(File(imagesDirectory, "$frameHash.png")) encoder.encodeImage(frame) } encoder.finish() tmpFile.renameTo(file) } return hash } /** Returns a SHA-1 hash of [lines]. */ private fun hash(lines: List<String>): String { val hashingSink = HashingSink.sha1(blackholeSink()) hashingSink.buffer().use { sink -> for (hash in lines) { sink.writeUtf8(hash) sink.writeUtf8("\n") } } return hashingSink.hash.hex() } /** Release all resources and block until everything has been written to the file system. */ override fun close() { writeRunJs() } /** * Emits the all runs index, which reads like JSON with an executable header. * * ``` * window.all_runs = [ * "20190319153912aaab", * "20190319153917bcfe" * ]; * ``` */ private fun writeIndexJs() { val runNames = mutableListOf<String>() val runs = runsDirectory.list().sorted() for (run in runs) { if (run.endsWith(".js")) { runNames += run.substring(0, run.length - 3) } } File(rootDirectory, "index.js").writeAtomically { writeUtf8("window.all_runs = ") PaparazziJson.listOfStringsAdapter.toJson(this, runNames) writeUtf8(";") } } /** * Emits a run index, which reads like JSON with an executable header. * * ``` * window.runs["20190319153912aaab"] = [ * { * "name": "loading", * "testName": "app.cash.CelebrityTest#testSettings", * "timestamp": "2019-03-20T10:27:43Z", * "tags": ["redesign"], * "file": "loading.png" * }, * { * "name": "error", * "testName": "app.cash.CelebrityTest#testSettings", * "timestamp": "2019-03-20T10:27:43Z", * "tags": ["redesign"], * "file": "error.png" * } * ]; * ``` */ private fun writeRunJs() { val runJs = File(runsDirectory, "${runName.sanitizeForFilename()}.js") runJs.writeAtomically { writeUtf8("window.runs[\"$runName\"] = ") PaparazziJson.listOfShotsAdapter.toJson(this, shots) writeUtf8(";") } } private fun writeStaticFiles() { for (staticFile in listOf("index.html", "paparazzi.js")) { File(rootDirectory, staticFile).writeAtomically { writeAll(HtmlReportWriter::class.java.classLoader.getResourceAsStream(staticFile).source()) } } } private fun File.writeAtomically(bufferedImage: BufferedImage) { val tmpFile = File(parentFile, "$name.tmp") ImageIO.write(bufferedImage, "PNG", tmpFile) delete() tmpFile.renameTo(this) } private fun File.writeAtomically(writerAction: BufferedSink.() -> Unit) { val tmpFile = File(parentFile, "$name.tmp") tmpFile.sink() .buffer() .use { sink -> sink.writerAction() } delete() tmpFile.renameTo(this) } private fun File.toJsonPath(): String = relativeTo(rootDirectory).invariantSeparatorsPath } internal fun defaultRunName(): String { val now = Date() val timestamp = SimpleDateFormat("yyyyMMddHHmmss", Locale.US).format(now) val token = UUID.randomUUID().toString().substring(0, 6) return "${timestamp}_$token" } internal val filenameSafeChars = CharMatcher.inRange('a', 'z') .or(CharMatcher.inRange('0', '9')) .or(CharMatcher.anyOf("_-.~@^()[]{}:;,")) internal fun String.sanitizeForFilename(): String? { return filenameSafeChars.negate().replaceFrom(lowercase(Locale.US), '_') }
apache-2.0
13fae671869ae2c434ec998e9e222390
29.397959
116
0.651113
3.812713
false
false
false
false
androidx/androidx
glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/translators/SwitchTranslator.kt
3
3864
/* * 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.glance.appwidget.translators import android.os.Build import android.view.Gravity import android.widget.RemoteViews import androidx.core.widget.RemoteViewsCompat.setSwitchThumbTintList import androidx.core.widget.RemoteViewsCompat.setSwitchTrackTintList import androidx.glance.appwidget.EmittableSwitch import androidx.glance.appwidget.LayoutType import androidx.glance.appwidget.R import androidx.glance.appwidget.TranslationContext import androidx.glance.appwidget.applyModifiers import androidx.glance.appwidget.inflateViewStub import androidx.glance.appwidget.insertView import androidx.glance.appwidget.setViewEnabled import androidx.glance.appwidget.unit.CheckedUncheckedColorProvider import androidx.glance.appwidget.unit.ResourceCheckableColorProvider internal fun RemoteViews.translateEmittableSwitch( translationContext: TranslationContext, element: EmittableSwitch ) { val layoutType = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { LayoutType.Swtch } else { LayoutType.SwtchBackport } val context = translationContext.context val viewDef = insertView(translationContext, layoutType, element.modifier) val textViewId: Int if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { textViewId = viewDef.mainViewId CompoundButtonApi31Impl.setCompoundButtonChecked( this, viewDef.mainViewId, element.checked ) when (val thumbColors = element.colors.thumb) { is CheckedUncheckedColorProvider -> { val (day, night) = thumbColors.toDayNightColorStateList(context) setSwitchThumbTintList(viewDef.mainViewId, notNight = day, night = night) } is ResourceCheckableColorProvider -> { setSwitchThumbTintList(viewDef.mainViewId, thumbColors.resId) } }.let {} when (val trackColors = element.colors.track) { is CheckedUncheckedColorProvider -> { val (day, night) = trackColors.toDayNightColorStateList(context) setSwitchTrackTintList(viewDef.mainViewId, notNight = day, night = night) } is ResourceCheckableColorProvider -> { setSwitchTrackTintList(viewDef.mainViewId, trackColors.resId) } }.let {} } else { textViewId = inflateViewStub(translationContext, R.id.switchText) val thumbId = inflateViewStub(translationContext, R.id.switchThumb) val trackId = inflateViewStub(translationContext, R.id.switchTrack) setViewEnabled(thumbId, element.checked) setViewEnabled(trackId, element.checked) val thumbColor = element.colors.thumb.getColor(context, element.checked) setImageViewColorFilter(thumbId, thumbColor) val trackColor = element.colors.track.getColor(context, element.checked) setImageViewColorFilter(trackId, trackColor) } setText( translationContext, textViewId, element.text, element.style, maxLines = element.maxLines, verticalTextGravity = Gravity.CENTER_VERTICAL, ) applyModifiers(translationContext, this, element.modifier, viewDef) }
apache-2.0
0a87de5dc4a7034a721209a95d02609a
38.428571
89
0.717391
4.589074
false
false
false
false
GunoH/intellij-community
jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/junit/JUnit3SuperTearDownInspection.kt
2
2942
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInspection.test.junit import com.intellij.analysis.JvmAnalysisBundle import com.intellij.codeInspection.AbstractBaseUastLocalInspectionTool import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.registerUProblem import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiFile import com.intellij.psi.util.InheritanceUtil import com.intellij.uast.UastHintedVisitorAdapter import com.siyeh.ig.junit.JUnitCommonClassNames import org.jetbrains.uast.* import org.jetbrains.uast.util.isInFinallyBlock import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor import org.jetbrains.uast.visitor.AbstractUastVisitor class JUnit3SuperTearDownInspection : AbstractBaseUastLocalInspectionTool() { private fun shouldInspect(file: PsiFile) = isJUnit3InScope(file) override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { if (!shouldInspect(holder.file)) return PsiElementVisitor.EMPTY_VISITOR return UastHintedVisitorAdapter.create( holder.file.language, SuperTearDownInFinallyVisitor(holder), arrayOf(UCallExpression::class.java), directOnly = true ) } } private class SuperTearDownInFinallyVisitor(private val holder: ProblemsHolder) : AbstractUastNonRecursiveVisitor() { override fun visitCallExpression(node: UCallExpression): Boolean { if (node.receiver !is USuperExpression || node.methodName != "tearDown") return true val parentMethod = node.getParentOfType( UMethod::class.java, strict = true, terminators = arrayOf(ULambdaExpression::class.java, UDeclaration::class.java) ) ?: return true if (parentMethod.name != "tearDown") return true val containingClass = node.getContainingUClass()?.javaPsi ?: return true if (!InheritanceUtil.isInheritor(containingClass, JUnitCommonClassNames.JUNIT_FRAMEWORK_TEST_CASE)) return true if (node.isInFinallyBlock()) return true if (!hasNonTrivialActivity(parentMethod, node)) return true val message = JvmAnalysisBundle.message("jvm.inspections.junit3.super.teardown.problem.descriptor") holder.registerUProblem(node, message) return true } private fun hasNonTrivialActivity(parentMethod: UElement, node: UCallExpression): Boolean { val visitor = NonTrivialActivityVisitor(node) parentMethod.accept(visitor) return visitor.hasNonTrivialActivity } private class NonTrivialActivityVisitor(private val ignore: UCallExpression) : AbstractUastVisitor() { var hasNonTrivialActivity = false override fun visitCallExpression(node: UCallExpression): Boolean { if (node == ignore) return true hasNonTrivialActivity = true return true } } }
apache-2.0
c0fa258bd375731ae677b59e36d9787b
44.984375
130
0.794697
4.895175
false
false
false
false
GunoH/intellij-community
build/tasks/src/org/jetbrains/intellij/build/io/ZipArchiveOutputStream.kt
7
16152
// 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.intellij.build.io import com.intellij.util.lang.ImmutableZipFile import org.jetbrains.ikv.UniversalHash import org.jetbrains.ikv.builder.IkvIndexBuilder import org.jetbrains.ikv.builder.IkvIndexEntry import org.jetbrains.xxh3.Xxh3 import java.io.IOException import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.channels.FileChannel import java.nio.channels.SeekableByteChannel import java.nio.channels.WritableByteChannel import java.util.zip.CRC32 import java.util.zip.ZipEntry private const val INDEX_FORMAT_VERSION: Byte = 3 const val INDEX_FILENAME = "__index__" internal class ZipArchiveOutputStream(private val channel: WritableByteChannel, private val withOptimizedMetadataEnabled: Boolean) : AutoCloseable { private var classPackages: LongArray? = null private var resourcePackages: LongArray? = null private var finished = false private var entryCount = 0 private var metadataBuffer = ByteBuffer.allocateDirect(2 * 1024 * 1024).order(ByteOrder.LITTLE_ENDIAN) // 1 MB should be enough for end of central directory record private val buffer = ByteBuffer.allocateDirect(1024 * 1024).order(ByteOrder.LITTLE_ENDIAN) private val indexWriter = IkvIndexBuilder(hash = IndexEntryHash()) private var channelPosition = 0L private val fileChannel = channel as? FileChannel fun addDirEntry(name: String) { if (finished) { throw IOException("Stream has already been finished") } val offset = channelPosition entryCount++ assert(!name.endsWith('/')) val key = name.toByteArray() val nameInArchive = key + '/'.code.toByte() buffer.clear() buffer.putInt(0x04034b50) // Version needed to extract (minimum) buffer.putShort(0) // General purpose bit flag buffer.putShort(0) // Compression method buffer.putShort(ZipEntry.STORED.toShort()) // File last modification time buffer.putShort(0) // File last modification date buffer.putShort(0) // CRC-32 of uncompressed data buffer.putInt(0) // Compressed size buffer.putInt(0) // Uncompressed size buffer.putInt(0) // File name length buffer.putShort((nameInArchive.size and 0xffff).toShort()) // Extra field length buffer.putShort(0) buffer.put(nameInArchive) buffer.flip() writeBuffer(buffer) writeCentralFileHeader(0, 0, ZipEntry.STORED, 0, nameInArchive, offset, dataOffset = -1, normalName = key) } fun writeRawEntry(header: ByteBuffer, content: ByteBuffer, name: ByteArray, size: Int, compressedSize: Int, method: Int, crc: Long) { if (finished) { throw IOException("Stream has already been finished") } val offset = channelPosition val dataOffset = offset.toInt() + header.remaining() entryCount++ assert(method != -1) writeBuffer(header) writeBuffer(content) writeCentralFileHeader(size, compressedSize, method, crc, name, offset, dataOffset = dataOffset) } fun writeRawEntry(content: ByteBuffer, name: ByteArray, size: Int, compressedSize: Int, method: Int, crc: Long, headerSize: Int) { if (finished) { throw IOException("Stream has already been finished") } val offset = channelPosition entryCount++ assert(method != -1) writeBuffer(content) writeCentralFileHeader(size, compressedSize, method, crc, name, offset, dataOffset = offset.toInt() + headerSize) } fun writeEntryHeaderAt(name: ByteArray, header: ByteBuffer, position: Long, size: Int, compressedSize: Int, crc: Long, method: Int) { if (finished) { throw IOException("Stream has already been finished") } val dataOffset = position.toInt() + header.remaining() if (fileChannel == null) { val c = channel as SeekableByteChannel c.position(position) do { c.write(header) } while (header.hasRemaining()) c.position(channelPosition) } else { var currentPosition = position do { currentPosition += fileChannel.write(header, currentPosition) } while (header.hasRemaining()) } entryCount++ assert(channelPosition == (dataOffset + compressedSize).toLong()) writeCentralFileHeader(size = size, compressedSize = compressedSize, method = method, crc = crc, name = name, offset = position, dataOffset = dataOffset) } private fun writeIndex(crc32: CRC32): Int { // write one by one to channel to avoid buffer overflow val entries = indexWriter.write { crc32.update(it) it.flip() writeBuffer(it) } val indexDataEnd = channelPosition.toInt() fun writeData(task: (ByteBuffer) -> Unit) { buffer.clear() task(buffer) buffer.flip() crc32.update(buffer) buffer.flip() writeBuffer(buffer) } // write package class and resource hashes writeData { buffer -> val classPackages = classPackages val resourcePackages = resourcePackages if (classPackages == null && resourcePackages == null) { buffer.putInt(0) buffer.putInt(0) } else { buffer.putInt(classPackages!!.size) buffer.putInt(resourcePackages!!.size) useAsLongBuffer(buffer) { it.put(classPackages) it.put(resourcePackages) } } // write fingerprint count buffer.putInt(entries.size) } // write fingerprints // entryCount must be not used here - index contains some dirs, but not zip (see addDirsToIndex) for (chunk in entries.asSequence().chunked(16 * 1024)) { writeData { buffer -> useAsLongBuffer(buffer) { longBuffer -> // bloom filter is not an option - false positive leads to error like "wrong class name" on class define for (entry in chunk) { longBuffer.put(entry.keyHash) } } } } // write names writeData { buffer -> val shortBuffer = buffer.asShortBuffer() for (entry in entries) { shortBuffer.put(entry.key.size.toShort()) } buffer.position(buffer.position() + (shortBuffer.position() * Short.SIZE_BYTES)) } for (list in entries.asSequence().chunked(1024)) { writeData { buffer -> for (indexEntry in list) { buffer.put(indexEntry.key) } } } return indexDataEnd } fun finish() { if (finished) { throw IOException("This archive has already been finished") } val indexOffset: Int if (withOptimizedMetadataEnabled && entryCount != 0) { // ditto on macOS doesn't like arbitrary data in zip file - wrap into zip entry val name = INDEX_FILENAME.toByteArray(Charsets.UTF_8) val headerSize = 30 + name.size val headerPosition = getChannelPositionAndAdd(headerSize) val entryDataPosition = channelPosition val crc32 = CRC32() indexOffset = writeIndex(crc32) val size = (channelPosition - entryDataPosition).toInt() val crc = crc32.value buffer.clear() writeLocalFileHeader(name = name, size = size, compressedSize = size, crc32 = crc, method = ZipEntry.STORED, buffer = buffer) buffer.flip() assert(buffer.remaining() == headerSize) writeEntryHeaderAt(name = name, header = buffer, position = headerPosition, size = size, compressedSize = size, crc = crc, method = ZipEntry.STORED) } else { indexOffset = -1 } val centralDirectoryOffset = channelPosition // write central directory file header metadataBuffer.flip() val centralDirectoryLength = metadataBuffer.limit() writeBuffer(metadataBuffer) buffer.clear() if (entryCount < 65_535) { // write end of central directory record (EOCD) buffer.clear() buffer.putInt(ImmutableZipFile.EOCD) // write 0 to clear reused buffer content // number of this disk (short), disk where central directory starts (short) buffer.putInt(0) // number of central directory records on this disk val shortEntryCount = (entryCount.coerceAtMost(0xffff) and 0xffff).toShort() buffer.putShort(shortEntryCount) // total number of central directory records buffer.putShort(shortEntryCount) buffer.putInt(centralDirectoryLength) // Offset of start of central directory, relative to start of archive buffer.putInt((centralDirectoryOffset and 0xffffffffL).toInt()) // comment length if (withOptimizedMetadataEnabled) { buffer.putShort((Byte.SIZE_BYTES + Integer.BYTES).toShort()) // version buffer.put(INDEX_FORMAT_VERSION) buffer.putInt(indexOffset) } else { buffer.putShort(0) } } else { writeZip64End(centralDirectoryLength, centralDirectoryOffset, indexOffset) } buffer.flip() writeBuffer(buffer) finished = true } private fun writeZip64End(centralDirectoryLength: Int, centralDirectoryOffset: Long, optimizedMetadataOffset: Int) { val eocd64Position = channelPosition buffer.putInt(0x06064b50) // size of - will be written later val eocdSizePosition = buffer.position() buffer.position(eocdSizePosition + Long.SIZE_BYTES) // Version made by buffer.putShort(0) // Version needed to extract (minimum) buffer.putShort(0) // Number of this disk buffer.putInt(0) // Disk where central directory starts buffer.putInt(0) // Number of central directory records on this disk buffer.putLong(entryCount.toLong()) // Total number of central directory records buffer.putLong(entryCount.toLong()) // Size of central directory (bytes) buffer.putLong(centralDirectoryLength.toLong()) // Offset of start of central directory, relative to start of archive buffer.putLong(centralDirectoryOffset) // comment length if (withOptimizedMetadataEnabled) { // version buffer.put(INDEX_FORMAT_VERSION) buffer.putInt(optimizedMetadataOffset) } buffer.putLong(eocdSizePosition, (buffer.position() - 12).toLong()) // Zip64 end of central directory locator buffer.putInt(0x07064b50) // number of the disk with the start of the zip64 end of central directory buffer.putInt(0) // relative offset of the zip64 end of central directory record buffer.putLong(eocd64Position) // total number of disks buffer.putInt(1) // write EOCD (EOCD is required even if we write EOCD64) buffer.putInt(0x06054b50) // number of this disk (short) buffer.putShort(0xffff.toShort()) // disk where central directory starts (short) buffer.putShort(0xffff.toShort()) // number of central directory records on this disk buffer.putShort(0xffff.toShort()) // total number of central directory records buffer.putShort(0xffff.toShort()) // Size of central directory (bytes) (or 0xffffffff for ZIP64) buffer.putInt(0xffffffff.toInt()) // Offset of start of central directory, relative to start of archive buffer.putInt(0xffffffff.toInt()) // comment length buffer.putShort(0) } internal fun getChannelPosition() = channelPosition internal fun getChannelPositionAndAdd(increment: Int): Long { val p = channelPosition channelPosition += increment.toLong() if (fileChannel == null) { (channel as SeekableByteChannel).position(channelPosition) } return p } internal fun writeBuffer(content: ByteBuffer) { if (fileChannel == null) { val size = content.remaining() do { channel.write(content) } while (content.hasRemaining()) channelPosition += size } else { var currentPosition = channelPosition do { currentPosition += fileChannel.write(content, currentPosition) } while (content.hasRemaining()) channelPosition = currentPosition } } override fun close() { try { if (!finished) { channel.use { finish() } } } finally { unmapBuffer(metadataBuffer) unmapBuffer(buffer) } } private class IndexEntry(@JvmField val key: ByteArray, override val offset: Int, override val size: Int, val keyHash: Long) : IkvIndexEntry { override fun equals(other: Any?) = key.contentEquals((other as? IndexEntry)?.key) override fun toString() = "IndexEntryHash(key=${key.toString(Charsets.UTF_8)}, keyHash=$keyHash)" override fun hashCode() = keyHash.toInt() } private class IndexEntryHash : UniversalHash<IndexEntry> { override fun universalHash(key: IndexEntry, index: Long) = Xxh3.seededHash(key.key, index) } fun addDirsToIndex(dirNames: Collection<String>) { assert(withOptimizedMetadataEnabled) for (dirName in dirNames) { val key = dirName.toByteArray(Charsets.UTF_8) indexWriter.add(IndexEntry(key = key, offset = -1, size = 0, keyHash = Xxh3.hash(key))) } } private fun writeCentralFileHeader(size: Int, compressedSize: Int, method: Int, crc: Long, name: ByteArray, offset: Long, dataOffset: Int, normalName: ByteArray = name) { var buffer = metadataBuffer if (buffer.remaining() < (46 + name.size)) { metadataBuffer = ByteBuffer.allocateDirect(buffer.capacity() * 2).order(ByteOrder.LITTLE_ENDIAN) buffer.flip() metadataBuffer.put(buffer) unmapBuffer(buffer) buffer = metadataBuffer } val headerOffset = buffer.position() buffer.putInt(headerOffset, 0x02014b50) // compression method buffer.putShort(headerOffset + 10, method.toShort()) // CRC-32 of uncompressed data buffer.putInt(headerOffset + 16, (crc and 0xffffffffL).toInt()) // compressed size buffer.putInt(headerOffset + 20, compressedSize) // uncompressed size buffer.putInt(headerOffset + 24, size) if (withOptimizedMetadataEnabled) { indexWriter.add(IndexEntry(key = normalName, offset = dataOffset, size = size, keyHash = Xxh3.hash(normalName))) } // file name length buffer.putShort(headerOffset + 28, (name.size and 0xffff).toShort()) // relative offset of local file header buffer.putInt(headerOffset + 42, (offset and 0xffffffffL).toInt()) // file name buffer.position(headerOffset + 46) buffer.put(name) } fun setPackageIndex(classPackages: LongArray, resourcePackages: LongArray) { assert(this.classPackages == null && this.resourcePackages == null) this.classPackages = classPackages this.resourcePackages = resourcePackages } } internal fun writeLocalFileHeader(name: ByteArray, size: Int, compressedSize: Int, crc32: Long, method: Int, buffer: ByteBuffer): Int { buffer.putInt(0x04034b50) // Version needed to extract (minimum) buffer.putShort(0) // General purpose bit flag buffer.putShort(0) // Compression method buffer.putShort(method.toShort()) // File last modification time buffer.putShort(0) // File last modification date buffer.putShort(0) // CRC-32 of uncompressed data buffer.putInt((crc32 and 0xffffffffL).toInt()) val compressedSizeOffset = buffer.position() // Compressed size buffer.putInt(compressedSize) // Uncompressed size buffer.putInt(size) // File name length buffer.putShort((name.size and 0xffff).toShort()) // Extra field length buffer.putShort(0) buffer.put(name) return compressedSizeOffset }
apache-2.0
03a0b8d22577a82a8dd4accc7bf2d73e
31.370741
135
0.655275
4.384365
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/blacklist/BlacklistTagsFragment.kt
1
2097
package io.github.feelfreelinux.wykopmobilny.ui.modules.blacklist import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.base.BaseFragment import io.github.feelfreelinux.wykopmobilny.ui.adapters.BlacklistAdapter import io.github.feelfreelinux.wykopmobilny.utils.preferences.BlacklistPreferences import io.github.feelfreelinux.wykopmobilny.utils.prepare import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.blacklist_fragment.* import javax.inject.Inject class BlacklistTagsFragment : BaseFragment() { companion object { fun createFragment() = BlacklistTagsFragment() } @Inject lateinit var adapter: BlacklistAdapter @Inject lateinit var blacklistPreferences: BlacklistPreferences private val disposable = CompositeDisposable() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.blacklist_fragment, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) adapter.isBlockUser = false adapter.unblockListener = { (activity as BlacklistActivity).unblockTag(it) } adapter.blockListener = { (activity as BlacklistActivity).blockTag(it) } recyclerView.prepare() recyclerView.adapter = adapter updateData() } private fun updateData() { adapter.items.clear() adapter.items.addAll(blacklistPreferences.blockedTags) adapter.notifyDataSetChanged() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) disposable.add((activity as BlacklistActivity).updateDataSubject.subscribe { updateData() }) } override fun onDestroy() { disposable.dispose() super.onDestroy() } }
mit
b5eb9a6c800bbec25e9a1d1ec309a5d1
33.393443
116
0.734382
5.114634
false
false
false
false
siosio/intellij-community
plugins/kotlin/jps/jps-plugin/src/org/jetbrains/kotlin/jps/targets/KotlinJsModuleBuildTarget.kt
1
9429
// 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.jps.targets import org.jetbrains.jps.builders.storage.BuildDataPaths import org.jetbrains.jps.incremental.ModuleBuildTarget import org.jetbrains.jps.model.library.JpsOrderRootType import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.util.JpsPathUtil import org.jetbrains.kotlin.build.GeneratedFile import org.jetbrains.kotlin.build.JsBuildMetaInfo import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments import org.jetbrains.kotlin.compilerRunner.JpsCompilerEnvironment import org.jetbrains.kotlin.compilerRunner.JpsKotlinCompilerRunner import org.jetbrains.kotlin.config.IncrementalCompilation import org.jetbrains.kotlin.config.Services import org.jetbrains.kotlin.incremental.ChangesCollector import org.jetbrains.kotlin.incremental.IncrementalJsCache import org.jetbrains.kotlin.incremental.components.ExpectActualTracker import org.jetbrains.kotlin.incremental.components.LookupTracker import org.jetbrains.kotlin.incremental.js.IncrementalDataProvider import org.jetbrains.kotlin.incremental.js.IncrementalDataProviderFromCache import org.jetbrains.kotlin.incremental.js.IncrementalResultsConsumer import org.jetbrains.kotlin.incremental.js.IncrementalResultsConsumerImpl import org.jetbrains.kotlin.jps.build.KotlinCompileContext import org.jetbrains.kotlin.jps.build.KotlinDirtySourceFilesHolder import org.jetbrains.kotlin.jps.build.ModuleBuildTarget import org.jetbrains.kotlin.jps.incremental.JpsIncrementalCache import org.jetbrains.kotlin.jps.incremental.JpsIncrementalJsCache import org.jetbrains.kotlin.jps.model.k2JsCompilerArguments import org.jetbrains.kotlin.jps.model.kotlinCompilerSettings import org.jetbrains.kotlin.jps.model.productionOutputFilePath import org.jetbrains.kotlin.jps.model.testOutputFilePath import org.jetbrains.kotlin.utils.JsLibraryUtils import org.jetbrains.kotlin.utils.KotlinJavascriptMetadataUtils.JS_EXT import org.jetbrains.kotlin.utils.KotlinJavascriptMetadataUtils.META_JS_SUFFIX import java.io.File import java.net.URI import kotlin.io.path.absolute import kotlin.io.path.exists import kotlin.io.path.pathString private const val JS_BUILD_META_INFO_FILE_NAME = "js-build-meta-info.txt" class KotlinJsModuleBuildTarget(kotlinContext: KotlinCompileContext, jpsModuleBuildTarget: ModuleBuildTarget) : KotlinModuleBuildTarget<JsBuildMetaInfo>(kotlinContext, jpsModuleBuildTarget) { override val globalLookupCacheId: String get() = "js" override val isIncrementalCompilationEnabled: Boolean get() = IncrementalCompilation.isEnabledForJs() override val buildMetaInfoFactory get() = JsBuildMetaInfo override val buildMetaInfoFileName: String get() = JS_BUILD_META_INFO_FILE_NAME val isFirstBuild: Boolean get() { val targetDataRoot = jpsGlobalContext.projectDescriptor.dataManager.dataPaths.getTargetDataRoot(jpsModuleBuildTarget) return !IncrementalJsCache.hasHeaderFile(targetDataRoot) } override fun makeServices( builder: Services.Builder, incrementalCaches: Map<KotlinModuleBuildTarget<*>, JpsIncrementalCache>, lookupTracker: LookupTracker, exceptActualTracer: ExpectActualTracker ) { super.makeServices(builder, incrementalCaches, lookupTracker, exceptActualTracer) with(builder) { register(IncrementalResultsConsumer::class.java, IncrementalResultsConsumerImpl()) if (isIncrementalCompilationEnabled && !isFirstBuild) { val cache = incrementalCaches[this@KotlinJsModuleBuildTarget] as IncrementalJsCache register( IncrementalDataProvider::class.java, IncrementalDataProviderFromCache(cache) ) } } } override fun compileModuleChunk( commonArguments: CommonCompilerArguments, dirtyFilesHolder: KotlinDirtySourceFilesHolder, environment: JpsCompilerEnvironment ): Boolean { require(chunk.representativeTarget == this) if (reportAndSkipCircular(environment)) return false val sources = collectSourcesToCompile(dirtyFilesHolder) if (!sources.logFiles()) { return false } val libraries = libraryFiles + dependenciesMetaFiles JpsKotlinCompilerRunner().runK2JsCompiler( commonArguments, module.k2JsCompilerArguments, module.kotlinCompilerSettings, environment, sources.allFiles, sources.crossCompiledFiles, sourceMapRoots, libraries, friendBuildTargetsMetaFiles, outputFile ) return true } override fun doAfterBuild() { copyJsLibraryFilesIfNeeded() } private fun copyJsLibraryFilesIfNeeded() { if (module.kotlinCompilerSettings.copyJsLibraryFiles) { val outputLibraryRuntimeDirectory = File(outputDir, module.kotlinCompilerSettings.outputDirectoryForJsLibraryFiles).absolutePath JsLibraryUtils.copyJsFilesFromLibraries( libraryFiles, outputLibraryRuntimeDirectory, copySourceMap = module.k2JsCompilerArguments.sourceMap ) } } private val sourceMapRoots: List<File> get() { // Compiler starts to produce path relative to base dirs in source maps if at least one statement is true: // 1) base dirs are specified; // 2) prefix is specified (i.e. non-empty) // Otherwise compiler produces paths relative to source maps location. // We don't have UI to configure base dirs, but we have UI to configure prefix. // If prefix is not specified (empty) in UI, we want to produce paths relative to source maps location return if (module.k2JsCompilerArguments.sourceMapPrefix.isNullOrBlank()) emptyList() else module.contentRootsList.urls .map { URI.create(it) } .filter { it.scheme == "file" } .map { File(it.path) } } val friendBuildTargetsMetaFiles get() = friendBuildTargets.mapNotNull { (it as? KotlinJsModuleBuildTarget)?.outputMetaFile?.absoluteFile?.toString() } val outputFile get() = explicitOutputPath?.let { File(it) } ?: implicitOutputFile private val explicitOutputPath get() = if (isTests) module.testOutputFilePath else module.productionOutputFilePath private val implicitOutputFile: File get() { val suffix = if (isTests) "_test" else "" return File(outputDir, module.name + suffix + JS_EXT) } private val outputFileBaseName: String get() = outputFile.path.substringBeforeLast(".") val outputMetaFile: File get() = File(outputFileBaseName + META_JS_SUFFIX) private val libraryFiles: List<String> get() = mutableListOf<String>().also { result -> for (library in allDependencies.libraries) { for (root in library.getRoots(JpsOrderRootType.COMPILED)) { result.add(JpsPathUtil.urlToPath(root.url)) } } } private val dependenciesMetaFiles: List<String> get() = mutableListOf<String>().also { result -> allDependencies.processModules { module -> if (isTests) addDependencyMetaFile(module, result, isTests = true) // note: production targets should be also added as dependency to test targets addDependencyMetaFile(module, result, isTests = false) } } private fun addDependencyMetaFile( module: JpsModule, result: MutableList<String>, isTests: Boolean ) { val dependencyBuildTarget = kotlinContext.targetsBinding[ModuleBuildTarget(module, isTests)] if (dependencyBuildTarget != this@KotlinJsModuleBuildTarget && dependencyBuildTarget is KotlinJsModuleBuildTarget && dependencyBuildTarget.sources.isNotEmpty() ) { val metaFile = dependencyBuildTarget.outputMetaFile.toPath() if (metaFile.exists()) { result.add(metaFile.absolute().pathString) } } } override fun createCacheStorage(paths: BuildDataPaths) = JpsIncrementalJsCache(jpsModuleBuildTarget, paths, kotlinContext.fileToPathConverter) override fun updateCaches( dirtyFilesHolder: KotlinDirtySourceFilesHolder, jpsIncrementalCache: JpsIncrementalCache, files: List<GeneratedFile>, changesCollector: ChangesCollector, environment: JpsCompilerEnvironment ) { super.updateCaches(dirtyFilesHolder, jpsIncrementalCache, files, changesCollector, environment) val incrementalResults = environment.services[IncrementalResultsConsumer::class.java] as IncrementalResultsConsumerImpl val jsCache = jpsIncrementalCache as IncrementalJsCache jsCache.header = incrementalResults.headerMetadata jsCache.compareAndUpdate(incrementalResults, changesCollector) jsCache.clearCacheForRemovedClasses(changesCollector) } }
apache-2.0
b1b22e996f00e1c4e242129e1fa64104
40
158
0.713968
5.047645
false
false
false
false
SimpleMobileTools/Simple-Calendar
app/src/main/kotlin/com/simplemobiletools/calendar/pro/helpers/IcsImporter.kt
1
19148
package com.simplemobiletools.calendar.pro.helpers import android.provider.CalendarContract.Events import com.simplemobiletools.calendar.pro.R import com.simplemobiletools.calendar.pro.activities.SimpleActivity import com.simplemobiletools.calendar.pro.extensions.eventsDB import com.simplemobiletools.calendar.pro.extensions.eventsHelper import com.simplemobiletools.calendar.pro.helpers.IcsImporter.ImportResult.IMPORT_FAIL import com.simplemobiletools.calendar.pro.helpers.IcsImporter.ImportResult.IMPORT_NOTHING_NEW import com.simplemobiletools.calendar.pro.helpers.IcsImporter.ImportResult.IMPORT_OK import com.simplemobiletools.calendar.pro.helpers.IcsImporter.ImportResult.IMPORT_PARTIAL import com.simplemobiletools.calendar.pro.models.Event import com.simplemobiletools.calendar.pro.models.EventType import com.simplemobiletools.calendar.pro.models.Reminder import com.simplemobiletools.commons.extensions.areDigitsOnly import com.simplemobiletools.commons.extensions.showErrorToast import com.simplemobiletools.commons.helpers.HOUR_SECONDS import org.joda.time.DateTimeZone import java.io.File class IcsImporter(val activity: SimpleActivity) { enum class ImportResult { IMPORT_FAIL, IMPORT_OK, IMPORT_PARTIAL, IMPORT_NOTHING_NEW } private var curStart = -1L private var curEnd = -1L private var curTitle = "" private var curLocation = "" private var curDescription = "" private var curImportId = "" private var curRecurrenceDayCode = "" private var curRrule = "" private var curFlags = 0 private var curReminderMinutes = ArrayList<Int>() private var curReminderActions = ArrayList<Int>() private var curRepeatExceptions = ArrayList<String>() private var curRepeatInterval = 0 private var curRepeatLimit = 0L private var curRepeatRule = 0 private var curEventTypeId = REGULAR_EVENT_TYPE_ID private var curLastModified = 0L private var curCategoryColor = -2 private var curAvailability = Events.AVAILABILITY_BUSY private var isNotificationDescription = false private var isProperReminderAction = false private var isSequence = false private var isParsingEvent = false private var curReminderTriggerMinutes = REMINDER_OFF private var curReminderTriggerAction = REMINDER_NOTIFICATION private val eventsHelper = activity.eventsHelper private var eventsImported = 0 private var eventsFailed = 0 private var eventsAlreadyExist = 0 fun importEvents( path: String, defaultEventTypeId: Long, calDAVCalendarId: Int, overrideFileEventTypes: Boolean, eventReminders: ArrayList<Int>? = null, ): ImportResult { try { val eventTypes = eventsHelper.getEventTypesSync() val existingEvents = activity.eventsDB.getEventsWithImportIds().toMutableList() as ArrayList<Event> val eventsToInsert = ArrayList<Event>() var line = "" val inputStream = if (path.contains("/")) { File(path).inputStream() } else { activity.assets.open(path) } inputStream.bufferedReader().use { while (true) { val curLine = it.readLine() ?: break if (curLine.trim().isEmpty()) { continue } if (curLine.startsWith("\t") || curLine.substring(0, 1) == " ") { line += curLine.removePrefix("\t").removePrefix(" ") continue } if (line.trim() == BEGIN_EVENT) { resetValues() curEventTypeId = defaultEventTypeId isParsingEvent = true } else if (line.startsWith(DTSTART)) { if (isParsingEvent) { curStart = getTimestamp(line.substring(DTSTART.length)) if (curRrule != "") { parseRepeatRule() } } } else if (line.startsWith(DTEND)) { curEnd = getTimestamp(line.substring(DTEND.length)) } else if (line.startsWith(DURATION)) { val duration = line.substring(DURATION.length) curEnd = curStart + Parser().parseDurationSeconds(duration) } else if (line.startsWith(SUMMARY) && !isNotificationDescription) { curTitle = line.substring(SUMMARY.length) curTitle = getTitle(curTitle).replace("\\n", "\n").replace("\\,", ",") } else if (line.startsWith(DESCRIPTION) && !isNotificationDescription) { curDescription = line.substring(DESCRIPTION.length).replace("\\n", "\n").replace("\\,", ",") if (curDescription.trim().isEmpty()) { curDescription = "" } } else if (line.startsWith(UID)) { curImportId = line.substring(UID.length).trim() } else if (line.startsWith(RRULE)) { curRrule = line.substring(RRULE.length) // some RRULEs need to know the events start datetime. If it's yet unknown, postpone RRULE parsing if (curStart != -1L) { parseRepeatRule() } } else if (line.startsWith(ACTION)) { val action = line.substring(ACTION.length).trim() isProperReminderAction = action == DISPLAY || action == EMAIL if (isProperReminderAction) { curReminderTriggerAction = if (action == DISPLAY) REMINDER_NOTIFICATION else REMINDER_EMAIL } } else if (line.startsWith(TRIGGER)) { val value = line.substringAfterLast(":") curReminderTriggerMinutes = Parser().parseDurationSeconds(value) / 60 if (!value.startsWith("-")) { curReminderTriggerMinutes *= -1 } } else if (line.startsWith(CATEGORY_COLOR_LEGACY)) { val color = line.substring(CATEGORY_COLOR_LEGACY.length) if (color.trimStart('-').areDigitsOnly()) { curCategoryColor = Integer.parseInt(color) } } else if (line.startsWith(CATEGORY_COLOR)) { val color = line.substring(CATEGORY_COLOR.length) if (color.trimStart('-').areDigitsOnly()) { curCategoryColor = Integer.parseInt(color) } } else if (line.startsWith(MISSING_YEAR)) { if (line.substring(MISSING_YEAR.length) == "1") { curFlags = curFlags or FLAG_MISSING_YEAR } } else if (line.startsWith(CATEGORIES) && !overrideFileEventTypes) { val categories = line.substring(CATEGORIES.length) tryAddCategories(categories) } else if (line.startsWith(LAST_MODIFIED)) { curLastModified = getTimestamp(line.substring(LAST_MODIFIED.length)) * 1000L } else if (line.startsWith(EXDATE)) { var value = line.substring(EXDATE.length) if (value.endsWith('}')) { value = value.substring(0, value.length - 1) } if (value.contains(",")) { value.split(",").forEach { exdate -> curRepeatExceptions.add(Formatter.getDayCodeFromTS(getTimestamp(exdate))) } } else { curRepeatExceptions.add(Formatter.getDayCodeFromTS(getTimestamp(value))) } } else if (line.startsWith(LOCATION)) { curLocation = getLocation(line.substring(LOCATION.length).replace("\\,", ",")) if (curLocation.trim().isEmpty()) { curLocation = "" } } else if (line.startsWith(RECURRENCE_ID)) { val timestamp = getTimestamp(line.substring(RECURRENCE_ID.length)) curRecurrenceDayCode = Formatter.getDayCodeFromTS(timestamp) } else if (line.startsWith(SEQUENCE)) { isSequence = true } else if (line.startsWith(TRANSP)) { line.substring(TRANSP.length).let { curAvailability = if (it == TRANSPARENT) Events.AVAILABILITY_FREE else Events.AVAILABILITY_BUSY } } else if (line.trim() == BEGIN_ALARM) { isNotificationDescription = true } else if (line.trim() == END_ALARM) { if (isProperReminderAction && curReminderTriggerMinutes != REMINDER_OFF) { curReminderMinutes.add(curReminderTriggerMinutes) curReminderActions.add(curReminderTriggerAction) } isNotificationDescription = false } else if (line.trim() == END_EVENT) { isParsingEvent = false if (curStart != -1L && curEnd == -1L) { curEnd = curStart } if (curTitle.isEmpty() || curStart == -1L) { line = curLine continue } // repeating event exceptions can have the same import id as their parents, so pick the latest event to update val eventToUpdate = existingEvents.filter { curImportId.isNotEmpty() && curImportId == it.importId }.sortedByDescending { it.lastUpdated }.firstOrNull() if (eventToUpdate != null && eventToUpdate.lastUpdated >= curLastModified) { eventsAlreadyExist++ line = curLine continue } var reminders = eventReminders?.map { reminderMinutes -> Reminder(reminderMinutes, REMINDER_NOTIFICATION) } ?: arrayListOf( Reminder(curReminderMinutes.getOrElse(0) { REMINDER_OFF }, curReminderActions.getOrElse(0) { REMINDER_NOTIFICATION }), Reminder(curReminderMinutes.getOrElse(1) { REMINDER_OFF }, curReminderActions.getOrElse(1) { REMINDER_NOTIFICATION }), Reminder(curReminderMinutes.getOrElse(2) { REMINDER_OFF }, curReminderActions.getOrElse(2) { REMINDER_NOTIFICATION }) ) reminders = reminders.sortedBy { it.minutes }.sortedBy { it.minutes == REMINDER_OFF }.toMutableList() as ArrayList<Reminder> val eventType = eventTypes.firstOrNull { it.id == curEventTypeId } val source = if (calDAVCalendarId == 0 || eventType?.isSyncedEventType() == false) SOURCE_IMPORTED_ICS else "$CALDAV-$calDAVCalendarId" val isAllDay = curFlags and FLAG_ALL_DAY != 0 val event = Event( null, curStart, curEnd, curTitle, curLocation, curDescription, reminders[0].minutes, reminders[1].minutes, reminders[2].minutes, reminders[0].type, reminders[1].type, reminders[2].type, curRepeatInterval, curRepeatRule, curRepeatLimit, curRepeatExceptions, "", curImportId, DateTimeZone.getDefault().id, curFlags, curEventTypeId, 0, curLastModified, source, curAvailability ) if (isAllDay && curEnd > curStart) { event.endTS -= TWELVE_HOURS // fix some glitches related to daylight saving shifts if (event.startTS - event.endTS == HOUR_SECONDS.toLong()) { event.endTS += HOUR_SECONDS } else if (event.startTS - event.endTS == -HOUR_SECONDS.toLong()) { event.endTS -= HOUR_SECONDS } } if (event.importId.isEmpty()) { event.importId = event.hashCode().toString() if (existingEvents.map { it.importId }.contains(event.importId)) { eventsAlreadyExist++ line = curLine continue } } if (eventToUpdate == null) { // if an event belongs to a sequence insert it immediately, to avoid some glitches with linked events if (isSequence) { if (curRecurrenceDayCode.isEmpty()) { eventsHelper.insertEvent(event, true, false) } else { // if an event contains the RECURRENCE-ID field, it is an exception to a recurring event, so update its parent too val parentEvent = activity.eventsDB.getEventWithImportId(event.importId) if (parentEvent != null && !parentEvent.repetitionExceptions.contains(curRecurrenceDayCode)) { parentEvent.addRepetitionException(curRecurrenceDayCode) eventsHelper.insertEvent(parentEvent, true, false) event.parentId = parentEvent.id!! eventsToInsert.add(event) } } } else { eventsToInsert.add(event) } } else { event.id = eventToUpdate.id eventsHelper.updateEvent(event, true, false) } eventsImported++ resetValues() } line = curLine } } eventsHelper.insertEvents(eventsToInsert, true) } catch (e: Exception) { activity.showErrorToast(e) eventsFailed++ } return when { eventsImported == 0 -> { if (eventsAlreadyExist > 0) { IMPORT_NOTHING_NEW } else { IMPORT_FAIL } } eventsFailed > 0 -> IMPORT_PARTIAL else -> IMPORT_OK } } private fun getTimestamp(fullString: String): Long { return try { when { fullString.startsWith(';') -> { val value = fullString.substring(fullString.lastIndexOf(':') + 1).replace(" ", "") if (value.isEmpty()) { return 0 } else if (!value.contains("T")) { curFlags = curFlags or FLAG_ALL_DAY } Parser().parseDateTimeValue(value) } fullString.startsWith(":") -> Parser().parseDateTimeValue(fullString.substring(1).trim()) else -> Parser().parseDateTimeValue(fullString) } } catch (e: Exception) { activity.showErrorToast(e) eventsFailed++ -1 } } private fun getLocation(fullString: String): String { return if (fullString.startsWith(":")) { fullString.trimStart(':') } else { fullString.substringAfter(':').trim() } } private fun tryAddCategories(categories: String) { val eventTypeTitle = if (categories.contains(",")) { categories.split(",")[0] } else { categories } val eventId = eventsHelper.getEventTypeIdWithTitle(eventTypeTitle) curEventTypeId = if (eventId == -1L) { val newTypeColor = if (curCategoryColor == -2) activity.resources.getColor(R.color.color_primary) else curCategoryColor val eventType = EventType(null, eventTypeTitle, newTypeColor) eventsHelper.insertOrUpdateEventTypeSync(eventType) } else { eventId } } private fun getTitle(title: String): String { return if (title.startsWith(";") && title.contains(":")) { title.substring(title.lastIndexOf(':') + 1) } else { title.substring(1, Math.min(title.length, 180)) } } private fun parseRepeatRule() { val repeatRule = Parser().parseRepeatInterval(curRrule, curStart) curRepeatRule = repeatRule.repeatRule curRepeatInterval = repeatRule.repeatInterval curRepeatLimit = repeatRule.repeatLimit } private fun resetValues() { curStart = -1L curEnd = -1L curTitle = "" curLocation = "" curDescription = "" curImportId = "" curRecurrenceDayCode = "" curRrule = "" curFlags = 0 curReminderMinutes = ArrayList() curReminderActions = ArrayList() curRepeatExceptions = ArrayList() curRepeatInterval = 0 curRepeatLimit = 0L curRepeatRule = 0 curEventTypeId = REGULAR_EVENT_TYPE_ID curLastModified = 0L curCategoryColor = -2 isNotificationDescription = false isProperReminderAction = false isSequence = false isParsingEvent = false curReminderTriggerMinutes = REMINDER_OFF curReminderTriggerAction = REMINDER_NOTIFICATION } }
gpl-3.0
356724fec12eed219b6913d7fa5e804d
46.750623
160
0.506841
5.5582
false
false
false
false
GunoH/intellij-community
java/idea-ui/src/com/intellij/ide/projectWizard/generators/IntelliJJavaNewProjectWizard.kt
7
2703
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.projectWizard.generators import com.intellij.ide.highlighter.ModuleFileType import com.intellij.ide.projectWizard.NewProjectWizardConstants.BuildSystem.INTELLIJ import com.intellij.ide.projectWizard.generators.IntelliJJavaNewProjectWizardData.Companion.addSampleCode import com.intellij.ide.projectWizard.generators.IntelliJJavaNewProjectWizardData.Companion.contentRoot import com.intellij.ide.starters.local.StandardAssetsProvider import com.intellij.ide.util.projectWizard.JavaModuleBuilder import com.intellij.ide.wizard.GitNewProjectWizardData.Companion.gitData import com.intellij.ide.wizard.chain import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.io.FileUtil import java.nio.file.Paths class IntelliJJavaNewProjectWizard : BuildSystemJavaNewProjectWizard { override val name = INTELLIJ override val ordinal = 0 override fun createStep(parent: JavaNewProjectWizard.Step) = Step(parent).chain(::AssetsStep) class Step(parent: JavaNewProjectWizard.Step) : IntelliJNewProjectWizardStep<JavaNewProjectWizard.Step>(parent), BuildSystemJavaNewProjectWizardData by parent, IntelliJJavaNewProjectWizardData { override fun setupProject(project: Project) { super.setupProject(project) val builder = JavaModuleBuilder() val moduleFile = Paths.get(moduleFileLocation, moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION) builder.name = moduleName builder.moduleFilePath = FileUtil.toSystemDependentName(moduleFile.toString()) builder.contentEntryPath = FileUtil.toSystemDependentName(contentRoot) if (parent.context.isCreatingNewProject) { // New project with a single module: set project JDK parent.context.projectJdk = sdk } else { // New module in an existing project: set module JDK val sameSDK = ProjectRootManager.getInstance(project).projectSdk?.name == sdk?.name builder.moduleJdk = if (sameSDK) null else sdk } builder.commit(project) } init { data.putUserData(IntelliJJavaNewProjectWizardData.KEY, this) } } private class AssetsStep(parent: Step) : AssetsNewProjectWizardStep(parent) { override fun setupAssets(project: Project) { outputDirectory = contentRoot if (gitData?.git == true) { addAssets(StandardAssetsProvider().getIntelliJIgnoreAssets()) } if (addSampleCode) { withJavaSampleCodeAsset("src", "") } } } }
apache-2.0
d908364be3f5bb5a2d81f74a5056a5b0
38.188406
158
0.765816
4.775618
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createTypeParameter/CreateTypeParameterByUnresolvedRefActionFactory.kt
4
6111
// 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.quickfix.createFromUsage.createTypeParameter import com.intellij.psi.PsiElement import com.intellij.psi.SmartPsiElementPointer import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.descriptors.impl.TypeParameterDescriptorImpl import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.quickfix.KotlinIntentionActionFactoryWithDelegate import org.jetbrains.kotlin.idea.quickfix.QuickFixWithDelegateFactory import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.getUnsubstitutedTypeConstraintInfo import org.jetbrains.kotlin.idea.refactoring.canRefactor import org.jetbrains.kotlin.idea.refactoring.introduce.isObjectOrNonInnerClass import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeProjectionImpl import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.typeUtil.containsError data class TypeParameterInfo( val name: String, val upperBoundType: KotlinType?, val fakeTypeParameter: TypeParameterDescriptor ) data class CreateTypeParameterData( val declaration: KtTypeParameterListOwner, val typeParameters: List<TypeParameterInfo> ) object CreateTypeParameterByUnresolvedRefActionFactory : KotlinIntentionActionFactoryWithDelegate<KtUserType, CreateTypeParameterData>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtUserType? { val ktUserType = diagnostic.psiElement.getParentOfTypeAndBranch<KtUserType> { referenceExpression } ?: return null if (ktUserType.getParentOfTypeAndBranch<KtConstructorCalleeExpression> { typeReference } != null) return null if (ktUserType.qualifier != null) return null if (ktUserType.getParentOfTypeAndBranch<KtUserType>(true) { qualifier } != null) return null if (ktUserType.typeArgumentList != null) return null return ktUserType } @OptIn(FrontendInternals::class) fun extractFixData(element: KtTypeElement, newName: String): CreateTypeParameterData? { val declaration = element.parents.firstOrNull { it is KtProperty || it is KtNamedFunction || it is KtClass } as? KtTypeParameterListOwner ?: return null if (!declaration.canRefactor()) return null val containingDescriptor = declaration.resolveToDescriptorIfAny() ?: return null val fakeTypeParameter = createFakeTypeParameterDescriptor( containingDescriptor, newName, declaration.getResolutionFacade().frontendService<StorageManager>() ) val upperBoundType = getUnsubstitutedTypeConstraintInfo(element)?.let { it.performSubstitution(it.typeParameter.typeConstructor to TypeProjectionImpl(fakeTypeParameter.defaultType))?.upperBound } if (upperBoundType != null && upperBoundType.containsError()) return null return CreateTypeParameterData(declaration, listOf(TypeParameterInfo(newName, upperBoundType, fakeTypeParameter))) } override fun extractFixData(element: KtUserType, diagnostic: Diagnostic): CreateTypeParameterData? { val name = element.referencedName ?: return null return extractFixData(element, name) } override fun createFixes( originalElementPointer: SmartPsiElementPointer<KtUserType>, diagnostic: Diagnostic, quickFixDataFactory: (KtUserType) -> CreateTypeParameterData? ): List<QuickFixWithDelegateFactory> { val ktUserType = originalElementPointer.element ?: return emptyList() val name = ktUserType.referencedName ?: return emptyList() return getPossibleTypeParameterContainers(ktUserType) .asSequence() .filter { declaration -> declaration.isWritable && declaration.typeParameters.all { it.name != name } }.map { QuickFixWithDelegateFactory factory@{ val originalElement = originalElementPointer.element ?: return@factory null val data = quickFixDataFactory(originalElement)?.copy(declaration = it) ?: return@factory null CreateTypeParameterFromUsageFix(originalElement, data, presentTypeParameterNames = true) } } .toList() } } fun createFakeTypeParameterDescriptor( containingDescriptor: DeclarationDescriptor, name: String, storageManager: StorageManager ): TypeParameterDescriptor { return TypeParameterDescriptorImpl .createWithDefaultBound( containingDescriptor, Annotations.EMPTY, false, Variance.INVARIANT, Name.identifier(name), -1, storageManager ) } fun getPossibleTypeParameterContainers(startFrom: PsiElement): List<KtTypeParameterListOwner> { val stopAt = startFrom.parents.firstOrNull(::isObjectOrNonInnerClass)?.parent return (if (stopAt != null) startFrom.parents.takeWhile { it != stopAt } else startFrom.parents) .filterIsInstance<KtTypeParameterListOwner>() .filter { ((it is KtClass && !it.isInterface() && it !is KtEnumEntry) || it is KtNamedFunction || (it is KtProperty && !it.isLocal && it.receiverTypeReference != null) || it is KtTypeAlias) && it.nameIdentifier != null } .toList() }
apache-2.0
b8649198d1904c4ddf8736c3f1e13549
49.933333
158
0.749141
5.485637
false
false
false
false
smmribeiro/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/workspaceModel/IdeModifiableModelsProviderBridge.kt
2
9722
// 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 org.jetbrains.idea.maven.importing.workspaceModel import com.intellij.facet.FacetManager import com.intellij.facet.ModifiableFacetModel import com.intellij.openapi.application.ModalityState import com.intellij.openapi.externalSystem.model.project.* import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider.EP_NAME import com.intellij.openapi.externalSystem.service.project.ModifiableModel import com.intellij.openapi.externalSystem.service.project.ModifiableModelsProviderExtension import com.intellij.openapi.module.ModifiableModuleModel import com.intellij.openapi.module.Module import com.intellij.openapi.module.UnloadedModuleDescription import com.intellij.openapi.project.Project import com.intellij.openapi.roots.* import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryTable import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.util.Key import com.intellij.openapi.util.UserDataHolderBase import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.containers.ClassMap import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder import com.intellij.workspaceModel.ide.impl.legacyBridge.facet.FacetManagerBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleRootComponentBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridge import com.intellij.workspaceModel.ide.legacyBridge.ProjectLibraryTableBridge import org.jetbrains.idea.maven.utils.MavenLog class IdeModifiableModelsProviderBridge(val project: Project, builder: WorkspaceEntityStorageBuilder) : IdeModifiableModelsProvider { private val legacyBridgeModuleManagerComponent = ModuleManagerBridgeImpl.getInstance(project) private val myProductionModulesForTestModules = HashMap<Module, String>() private val myModifiableModels = ClassMap<ModifiableModel>() private val myUserData = UserDataHolderBase() private val modifiableFacetsModels = HashMap<Module, ModifiableFacetModel>() var diff = builder init { EP_NAME.forEachExtensionSafe { extension: ModifiableModelsProviderExtension<ModifiableModel?> -> val pair = extension.create( project, this) myModifiableModels.put(pair.first, pair.second) } } private val modifiableModuleModel = lazy { legacyBridgeModuleManagerComponent.getModifiableModel(diff) } private val bridgeProjectLibraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project) as ProjectLibraryTableBridge private val librariesModel = lazy { bridgeProjectLibraryTable.getModifiableModel(diff) } override fun findIdeLibrary(libraryData: LibraryData): Library? { return getAllLibraries().filter { it.name == libraryData.internalName }.firstOrNull() } override fun getAllDependentModules(module: Module): List<Module> { return ModuleRootComponentBridge.getInstance(module).dependencies.toList() } override fun <T : ModifiableModel?> getModifiableModel(instanceOf: Class<T>): T { return myModifiableModels.get(instanceOf) as? T ?: throw NotImplementedError("${instanceOf.canonicalName} not implemented") } override fun getModifiableFacetModel(module: Module): ModifiableFacetModel { return modifiableFacetsModels.computeIfAbsent(module) { (it.getComponent(FacetManager::class.java) as FacetManagerBridge).createModifiableModel(diff) } } override fun findIdeModule(module: ModuleData): Module? { return findIdeModule(module.moduleName) } override fun findIdeModule(ideModuleName: String): Module? { return legacyBridgeModuleManagerComponent.findModuleByName(ideModuleName) } override fun newModule(filePath: String, moduleTypeId: String?): Module { if (moduleTypeId == null) { throw IllegalArgumentException("moduleTypeId") } val modifiableModel = modifiableModuleModel.value legacyBridgeModuleManagerComponent.incModificationCount() val module = modifiableModel.newModule(filePath, moduleTypeId) return module } override fun newModule(moduleData: ModuleData): Module { val modifiableModel = modifiableModuleModel.value legacyBridgeModuleManagerComponent.incModificationCount() val newModule = modifiableModel.newModule(moduleData.moduleFileDirectoryPath, moduleData.moduleTypeId) return newModule } override fun getModifiableProjectLibrariesModel(): LibraryTable.ModifiableModel { return librariesModel.value } override fun getProductionModuleName(module: Module?): String? { return myProductionModulesForTestModules[module] } override fun getModifiableLibraryModel(library: Library?): Library.ModifiableModel { val bridgeLibrary = library as LibraryBridge return bridgeLibrary.getModifiableModel(diff) } override fun getModifiableModuleModel(): ModifiableModuleModel { return modifiableModuleModel.value } override fun commit() { if(modifiableModuleModel.isInitialized()) { modifiableModuleModel.value.commit() } } override fun setTestModuleProperties(testModule: Module, productionModuleName: String) { myProductionModulesForTestModules[testModule] = productionModuleName } override fun trySubstitute(ownerModule: Module?, libraryOrderEntry: LibraryOrderEntry?, publicationId: ProjectCoordinate?): ModuleOrderEntry? { // MavenLog.LOG.error("trySubstitute not implemented") return null } override fun findIdeModuleDependency(dependency: ModuleDependencyData, module: Module): ModuleOrderEntry? { MavenLog.LOG.error("findIdeModuleDependency not implemented") return null } override fun <T : Any?> putUserData(key: Key<T>, value: T?) { myUserData.putUserData(key, value) } override fun getUnloadedModuleDescription(moduleData: ModuleData): UnloadedModuleDescription? { MavenLog.LOG.error("getUnloadedModuleDescription not implemented") return null } override fun createLibrary(name: String?): Library { return bridgeProjectLibraryTable.createLibrary(name) } override fun createLibrary(name: String?, externalSource: ProjectModelExternalSource?): Library { return bridgeProjectLibraryTable.createLibrary(name) } override fun getModules(): Array<Module> { return legacyBridgeModuleManagerComponent.modules } override fun getModules(projectData: ProjectData): Array<Module> { return legacyBridgeModuleManagerComponent.modules } override fun registerModulePublication(module: Module?, modulePublication: ProjectCoordinate?) { //MavenLog.LOG.error("registerModulePublication not implemented") } override fun getAllLibraries(): Array<Library> { return bridgeProjectLibraryTable.libraries + legacyBridgeModuleManagerComponent.modules.map { ModuleRootComponentBridge(it) } .flatMap { it.getModuleLibraryTable().libraries.asIterable() } } override fun removeLibrary(library: Library?) { MavenLog.LOG.error("removeLibrary not implemented") } override fun getSourceRoots(module: Module): Array<VirtualFile> { return ModuleRootComponentBridge.getInstance(module).sourceRoots } override fun getSourceRoots(module: Module, includingTests: Boolean): Array<VirtualFile> { return ModuleRootComponentBridge.getInstance(module).getSourceRoots(includingTests) } override fun getModifiableRootModel(module: Module): ModifiableRootModel { return ModuleRootComponentBridge.getInstance(module).getModifiableModel() } override fun isSubstituted(libraryName: String?): Boolean { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getContentRoots(module: Module): Array<VirtualFile> { return ModuleRootComponentBridge.getInstance(module).contentRoots } override fun <T : ModifiableModel?> findModifiableModel(instanceOf: Class<T>): T? { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun findModuleByPublication(publicationId: ProjectCoordinate?): String? { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun findIdeModuleOrderEntry(data: DependencyData<*>): OrderEntry? { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun findIdeModuleLibraryOrderEntries(moduleData: ModuleData, libraryDependencyDataList: MutableList<LibraryDependencyData>): Map<LibraryOrderEntry, LibraryDependencyData> { TODO("Not yet implemented") } override fun getLibraryUrls(library: Library, type: OrderRootType): Array<String> { return library.getUrls(type) } override fun getLibraryByName(name: String): Library? { return bridgeProjectLibraryTable.getLibraryByName(name) } override fun <T : Any?> getUserData(key: Key<T>): T? { return myUserData.getUserData(key) } override fun getOrderEntries(module: Module): Array<OrderEntry> { return ModuleRootComponentBridge.getInstance(module).orderEntries } override fun getModalityStateForQuestionDialogs(): ModalityState { return ModalityState.NON_MODAL } override fun dispose() { } }
apache-2.0
f68a50d79091c5c4bd55d0ba2c6ef5c1
39.00823
159
0.779572
5.204497
false
false
false
false
smmribeiro/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/dependency/analyzer/DependencyAnalyzerViewImpl.kt
1
19609
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.dependency.analyzer import com.intellij.icons.AllIcons import com.intellij.openapi.Disposable import com.intellij.openapi.application.invokeLater import com.intellij.openapi.application.runInEdt import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.externalSystem.autoimport.ExternalSystemProjectNotificationAware import com.intellij.openapi.externalSystem.autoimport.ProjectRefreshAction import com.intellij.openapi.externalSystem.dependency.analyzer.DependencyAnalyzerView.Companion.ACTION_PLACE import com.intellij.openapi.externalSystem.dependency.analyzer.util.* import com.intellij.openapi.externalSystem.dependency.analyzer.util.bind import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.externalSystem.ui.ExternalSystemIconProvider import com.intellij.openapi.externalSystem.util.ExternalSystemBundle import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace import com.intellij.openapi.observable.operations.asProperty import com.intellij.openapi.observable.operations.whenOperationCompleted import com.intellij.openapi.observable.properties.AtomicObservableProperty import com.intellij.openapi.observable.properties.ObservableProperty import com.intellij.openapi.observable.properties.and import com.intellij.openapi.observable.util.* import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.Project import com.intellij.ui.CollectionListModel import com.intellij.ui.ScrollPaneFactory import com.intellij.ui.SearchTextField import com.intellij.ui.components.JBLoadingPanel import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.ui.JBUI import java.awt.BorderLayout import javax.swing.JComponent import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.DefaultTreeModel import com.intellij.openapi.externalSystem.dependency.analyzer.DependencyAnalyzerDependency as Dependency class DependencyAnalyzerViewImpl( private val project: Project, private val systemId: ProjectSystemId, private val parentDisposable: Disposable ) : DependencyAnalyzerView { override val component: JComponent private val iconsProvider = ExternalSystemIconProvider.getExtension(systemId) private val contributor = DependencyAnalyzerExtension.EP_NAME.extensionList .firstNotNullOf { it.createContributor(project, systemId, parentDisposable) } private val backgroundExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor("DependencyAnalyzerView.backgroundExecutor", 1) private val dependencyLoadingOperation = AnonymousParallelOperationTrace("DA: Dependency loading") private val dependencyLoadingProperty = dependencyLoadingOperation.asProperty() private val externalProjectProperty = AtomicObservableProperty<DependencyAnalyzerProject?>(null) private val dependencyDataFilterProperty = AtomicObservableProperty("") private val dependencyScopeFilterProperty = AtomicObservableProperty(emptyList<ScopeItem>()) private val showDependencyWarningsProperty = AtomicObservableProperty(false) private val showDependencyGroupIdProperty = AtomicObservableProperty(false) .bindBooleanStorage(SHOW_GROUP_ID_PROPERTY) private val dependencyModelProperty = AtomicObservableProperty(emptyList<DependencyGroup>()) private val dependencyProperty = AtomicObservableProperty<Dependency?>(null) private val showDependencyTreeProperty = AtomicObservableProperty(false) .bindBooleanStorage(SHOW_AS_TREE_PROPERTY) private val dependencyEmptyTextProperty = AtomicObservableProperty("") private val usagesTitleProperty = AtomicObservableProperty("") private var externalProject by externalProjectProperty private var dependencyDataFilter by dependencyDataFilterProperty private var dependencyScopeFilter by dependencyScopeFilterProperty private var showDependencyWarnings by showDependencyWarningsProperty private var showDependencyGroupId by showDependencyGroupIdProperty private var dependencyModel by dependencyModelProperty private var dependency by dependencyProperty private var dependencyEmptyState by dependencyEmptyTextProperty private var usagesTitle by usagesTitleProperty private val externalProjects = ArrayList<DependencyAnalyzerProject>() private val dependencyListModel = CollectionListModel<DependencyGroup>() private val dependencyTreeModel = DefaultTreeModel(null) private val usagesTreeModel = DefaultTreeModel(null) override fun setSelectedExternalProject(externalProjectPath: String) { setSelectedExternalProject(externalProjectPath) {} } override fun setSelectedDependency(externalProjectPath: String, dependency: Dependency) { setSelectedExternalProject(externalProjectPath) { this.dependency = dependency } } override fun setSelectedDependency(externalProjectPath: String, data: Dependency.Data) { setSelectedExternalProject(externalProjectPath) { dependency = findDependency { it.data == data } } } override fun setSelectedDependency(externalProjectPath: String, data: Dependency.Data, scope: Dependency.Scope) { setSelectedExternalProject(externalProjectPath) { dependency = findDependency { it.data == data && it.scope == scope } } } private fun setSelectedExternalProject(externalProjectPath: String, onReady: () -> Unit) { whenLoadingOperationCompleted { externalProject = externalProjects.find { it.path == externalProjectPath } whenLoadingOperationCompleted { onReady() } } } private fun findDependency(predicate: (Dependency) -> Boolean): Dependency? { return dependencyListModel.items.flatMap { it.variances }.find(predicate) ?: dependencyModel.flatMap { it.variances }.find(predicate) } override fun getData(dataId: String): Any? { return when (dataId) { DependencyAnalyzerView.VIEW.name -> this DependencyAnalyzerView.PROJECT.name -> project DependencyAnalyzerView.EXTERNAL_SYSTEM_ID.name -> systemId DependencyAnalyzerView.EXTERNAL_PROJECT_PATH.name -> externalProject?.path else -> null } } private fun updateViewModel() { executeLoadingTaskOnEdt { updateExternalProjectsModel() } } private fun Iterable<Dependency>.filterDependencies(): List<Dependency> { val dependencyDataFilter = dependencyDataFilter val dependencyScopeFilter = dependencyScopeFilter .filter { it.isSelected } .map { it.scope } val showDependencyWarnings = showDependencyWarnings return filter { dependency -> dependencyDataFilter in dependency.data.getDisplayText(showDependencyGroupId) } .filter { dependency -> dependency.scope in dependencyScopeFilter } .filter { dependency -> if (showDependencyWarnings) dependency.status.any { it is Dependency.Status.Warning } else true } } private fun updateExternalProjectsModel() { externalProjects.clear() executeLoadingTask( onBackgroundThread = { contributor.getProjects() }, onUiThread = { projects -> externalProjects.addAll(projects) externalProject = externalProjects.find { it == externalProject } ?: externalProjects.firstOrNull() } ) } private fun updateScopesModel() { executeLoadingTask( onBackgroundThread = { externalProject?.path?.let(contributor::getDependencyScopes) ?: emptyList() }, onUiThread = { scopes -> val scopesIndex = dependencyScopeFilter.associate { it.scope to it.isSelected } val isAny = scopesIndex.all { it.value } dependencyScopeFilter = scopes.map { ScopeItem(it, scopesIndex[it] ?: isAny) } } ) } private fun updateDependencyModel() { dependencyModel = emptyList() executeLoadingTask( onBackgroundThread = { externalProject?.path?.let(contributor::getDependencies) ?: emptyList() }, onUiThread = { dependencyModel = it .createDependencyGroups() } ) } private fun updateFilteredDependencyModel() { val filteredDependencyGroups = dependencyModel .map { DependencyGroup(it.variances.filterDependencies()) } .filter { it.variances.isNotEmpty() } dependencyListModel.replaceAll(filteredDependencyGroups) val filteredDependencies = filteredDependencyGroups.flatMap { it.variances } dependencyTreeModel.setRoot(buildTree(filteredDependencies)) dependency = filteredDependencies.find { it == dependency } ?: filteredDependencies.firstOrNull() } private fun updateDependencyEmptyState() { dependencyEmptyState = when { !dependencyLoadingOperation.isOperationCompleted() -> "" else -> ExternalSystemBundle.message("external.system.dependency.analyzer.resolved.empty") } } private fun updateUsagesTitle() { val text = dependency?.data?.getDisplayText(showDependencyGroupId) usagesTitle = if (text == null) "" else ExternalSystemBundle.message("external.system.dependency.analyzer.usages.title", text) } private fun updateUsagesModel() { val dependencies = dependencyModel.asSequence() .filter { group -> dependency?.data in group.variances.map { it.data } } .flatMap { it.variances } .asIterable() usagesTreeModel.setRoot(buildTree(dependencies)) } private fun executeLoadingTaskOnEdt(onUiThread: () -> Unit) { dependencyLoadingOperation.startTask() runInEdt { onUiThread() dependencyLoadingOperation.finishTask() } } private fun <R> executeLoadingTask(onBackgroundThread: () -> R, onUiThread: (R) -> Unit) { dependencyLoadingOperation.startTask() BackgroundTaskUtil.execute(backgroundExecutor, parentDisposable) { val result = onBackgroundThread() invokeLater { onUiThread(result) dependencyLoadingOperation.finishTask() } } } private fun whenLoadingOperationCompleted(onUiThread: () -> Unit) { dependencyLoadingOperation.whenOperationCompleted(parentDisposable) { runInEdt { onUiThread() } } } private fun buildTree(dependencies: Iterable<Dependency>): DefaultMutableTreeNode? { val dependenciesForTree = dependencies.flatMap { getTreePath(it) }.toSet() if (dependenciesForTree.isEmpty()) { return null } val rootDependencyGroup = dependenciesForTree .filter { it.parent == null } .createDependencyGroups() .singleOrNull() if (rootDependencyGroup == null) { val rawTree = dependenciesForTree.joinToString("\n") logger<DependencyAnalyzerView>().error("Cannot determine root of dependency tree:\n$rawTree") return null } val nodeMap = LinkedHashMap<Dependency, MutableList<Dependency>>() for (dependency in dependenciesForTree) { val usage = dependency.parent ?: continue val children = nodeMap.getOrPut(usage) { ArrayList() } children.add(dependency) } val rootNode = DefaultMutableTreeNode(rootDependencyGroup) val queue = ArrayDeque<DefaultMutableTreeNode>() queue.addLast(rootNode) while (queue.isNotEmpty()) { val node = queue.removeFirst() val dependencyGroup = node.userObject as DependencyGroup val children = dependencyGroup.variances .flatMap { nodeMap[it] ?: emptyList() } .createDependencyGroups() for (child in children) { val childNode = DefaultMutableTreeNode(child) node.add(childNode) queue.addLast(childNode) } } return rootNode } private fun getTreePath(dependency: Dependency): List<Dependency> { val dependencyPath = ArrayList<Dependency>() var current: Dependency? = dependency while (current != null) { dependencyPath.add(current) current = current.parent } return dependencyPath } private fun Dependency.Data.getGroup(): String = when (this) { is Dependency.Data.Module -> name is Dependency.Data.Artifact -> "$groupId:$artifactId" } private fun Iterable<Dependency>.createDependencyGroups(): List<DependencyGroup> = groupBy { it.data.getGroup() } .map { DependencyGroup(it.value) } init { val externalProjectSelector = ExternalProjectSelector(externalProjectProperty, externalProjects, iconsProvider) .bindEnabled(dependencyLoadingProperty) val dataFilterField = SearchTextField(SEARCH_HISTORY_PROPERTY) .apply { setPreferredWidth(JBUI.scale(240)) } .apply { textEditor.bind(dependencyDataFilterProperty) } .bindEnabled(dependencyLoadingProperty) val scopeFilterSelector = SearchScopeSelector(dependencyScopeFilterProperty) .bindEnabled(dependencyLoadingProperty) val dependencyInspectionFilterButton = toggleAction(showDependencyWarningsProperty) .apply { templatePresentation.text = ExternalSystemBundle.message("external.system.dependency.analyzer.conflicts.show") } .apply { templatePresentation.icon = AllIcons.General.ShowWarning } .asActionButton(ACTION_PLACE) .bindEnabled(dependencyLoadingProperty) val showDependencyGroupIdAction = toggleAction(showDependencyGroupIdProperty) .apply { templatePresentation.text = ExternalSystemBundle.message("external.system.dependency.analyzer.groupId.show") } val viewOptionsButton = popupActionGroup(showDependencyGroupIdAction) .apply { templatePresentation.icon = AllIcons.Actions.Show } .asActionButton(ACTION_PLACE) .bindEnabled(dependencyLoadingProperty) val reloadNotificationProperty = ProjectReloadNotificationProperty() val projectReloadSeparator = separator() .bindVisible(reloadNotificationProperty) val projectReloadAction = action { ProjectRefreshAction.refreshProject(project) } .apply { templatePresentation.icon = AllIcons.Actions.BuildLoadChanges } .asActionButton(ACTION_PLACE) .bindVisible(reloadNotificationProperty) val dependencyTitle = label(ExternalSystemBundle.message("external.system.dependency.analyzer.resolved.title")) val dependencyList = DependencyList(dependencyListModel, showDependencyGroupIdProperty, this) .bindEmptyText(dependencyEmptyTextProperty) .bindDependency(dependencyProperty) .bindEnabled(dependencyLoadingProperty) val dependencyTree = DependencyTree(dependencyTreeModel, showDependencyGroupIdProperty, this) .bindEmptyText(dependencyEmptyTextProperty) .bindDependency(dependencyProperty) .bindEnabled(dependencyLoadingProperty) val dependencyPanel = cardPanel<Boolean> { if (it) dependencyTree else dependencyList } .bind(showDependencyTreeProperty) val dependencyLoadingPanel = JBLoadingPanel(BorderLayout(), parentDisposable) .apply { add(dependencyPanel, BorderLayout.CENTER) } .apply { setLoadingText(ExternalSystemBundle.message("external.system.dependency.analyzer.dependency.loading")) } .bind(dependencyLoadingOperation) val showDependencyTreeButton = toggleAction(showDependencyTreeProperty) .apply { templatePresentation.text = ExternalSystemBundle.message("external.system.dependency.analyzer.resolved.tree.show") } .apply { templatePresentation.icon = AllIcons.Actions.ShowAsTree } .asActionButton(ACTION_PLACE) .bindEnabled(dependencyLoadingProperty) val expandDependencyTreeButton = expandTreeAction(dependencyTree) .asActionButton(ACTION_PLACE) .bindEnabled(showDependencyTreeProperty and dependencyLoadingProperty) val collapseDependencyTreeButton = collapseTreeAction(dependencyTree) .asActionButton(ACTION_PLACE) .bindEnabled(showDependencyTreeProperty and dependencyLoadingProperty) val usagesTitle = label(usagesTitleProperty) val usagesTree = UsagesTree(usagesTreeModel, showDependencyGroupIdProperty, this) .apply { emptyText.text = "" } .bindEnabled(dependencyLoadingProperty) val expandUsagesTreeButton = expandTreeAction(usagesTree) .asActionButton(ACTION_PLACE) .bindEnabled(dependencyLoadingProperty) val collapseUsagesTreeButton = collapseTreeAction(usagesTree) .asActionButton(ACTION_PLACE) .bindEnabled(dependencyLoadingProperty) component = toolWindowPanel { toolbar = toolbarPanel { addToLeft(horizontalPanel( externalProjectSelector, dataFilterField, scopeFilterSelector, separator(), dependencyInspectionFilterButton, viewOptionsButton, projectReloadSeparator, projectReloadAction )) } setContent(horizontalSplitPanel(SPLIT_VIEW_PROPORTION_PROPERTY, 0.5f) { firstComponent = toolWindowPanel { toolbar = toolbarPanel { addToLeft(dependencyTitle) addToRight(horizontalPanel( showDependencyTreeButton, separator(), expandDependencyTreeButton, collapseDependencyTreeButton )) } setContent(ScrollPaneFactory.createScrollPane(dependencyLoadingPanel, true)) } secondComponent = toolWindowPanel { toolbar = toolbarPanel { addToLeft(usagesTitle) addToRight(horizontalPanel( expandUsagesTreeButton, collapseUsagesTreeButton )) } setContent(ScrollPaneFactory.createScrollPane(usagesTree, true)) } }) } } init { externalProjectProperty.afterChange { updateScopesModel() } externalProjectProperty.afterChange { updateDependencyModel() } dependencyModelProperty.afterChange { updateFilteredDependencyModel() } dependencyDataFilterProperty.afterChange { updateFilteredDependencyModel() } dependencyScopeFilterProperty.afterChange { updateFilteredDependencyModel() } showDependencyWarningsProperty.afterChange { updateFilteredDependencyModel() } showDependencyGroupIdProperty.afterChange { updateFilteredDependencyModel() } dependencyProperty.afterChange { updateUsagesTitle() } dependencyProperty.afterChange { updateUsagesModel() } showDependencyGroupIdProperty.afterChange { updateUsagesTitle() } dependencyLoadingProperty.afterChange { updateDependencyEmptyState() } contributor.whenDataChanged(::updateViewModel, parentDisposable) updateViewModel() } private inner class ProjectReloadNotificationProperty : ObservableProperty<Boolean> { private val notificationAware get() = ExternalSystemProjectNotificationAware.getInstance(project) override fun get() = systemId in notificationAware.getSystemIds() override fun afterChange(listener: (Boolean) -> Unit) = ExternalSystemProjectNotificationAware.whenNotificationChanged(project) { listener(get()) } override fun afterChange(listener: (Boolean) -> Unit, parentDisposable: Disposable) = ExternalSystemProjectNotificationAware.whenNotificationChanged(project, { listener(get()) }, parentDisposable) } companion object { private const val SEARCH_HISTORY_PROPERTY = "ExternalSystem.DependencyAnalyzerView.search" private const val SHOW_GROUP_ID_PROPERTY = "ExternalSystem.DependencyAnalyzerView.showGroupId" private const val SHOW_AS_TREE_PROPERTY = "ExternalSystem.DependencyAnalyzerView.showAsTree" private const val SPLIT_VIEW_PROPORTION_PROPERTY = "ExternalSystem.DependencyAnalyzerView.splitProportion" } }
apache-2.0
aaa39d1e777191ddf41aebfde8077201
42.382743
158
0.757305
5.209617
false
false
false
false
Cognifide/gradle-aem-plugin
src/main/kotlin/com/cognifide/gradle/aem/common/instance/service/pkg/PackageState.kt
1
301
package com.cognifide.gradle.aem.common.instance.service.pkg import java.io.File class PackageState(val file: File, val state: Package?) { val name: String get() = file.name val uploaded: Boolean get() = state != null val installed: Boolean get() = state != null && state.installed }
apache-2.0
eb61ce1661c577dadf8c374f151902fb
24.083333
67
0.697674
3.716049
false
false
false
false
erdo/asaf-project
example-kt-07apollo3/src/main/java/foo/bar/example/foreapollo3/api/CustomGlobalRequestInterceptor.kt
1
1354
package foo.bar.example.foreapollo3.api import co.early.fore.kt.core.logging.Logger import foo.bar.example.foreapollo3.BuildConfig import foo.bar.example.foreapollo3.feature.authentication.Authenticator import foo.bar.example.foreapollo3.feature.authentication.Authenticator.Companion.NO_SESSION import okhttp3.Interceptor import okhttp3.Response import java.io.IOException /** * This will be specific to your own app. */ @ExperimentalStdlibApi class CustomGlobalRequestInterceptor( private val logger: Logger ) : Interceptor { private var authenticator: Authenticator? = null @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val original = chain.request() val requestBuilder = original.newBuilder() requestBuilder.addHeader("Content-Type", "application/json") authenticator?.let { requestBuilder.addHeader("Authorization", if (it.sessionToken == NO_SESSION) "expired" else it.sessionToken) } requestBuilder.addHeader("User-Agent", "fore-example-user-agent-" + BuildConfig.VERSION_NAME) requestBuilder.method(original.method(), original.body()) return chain.proceed(requestBuilder.build()) } fun setAuthenticator(authenticator: Authenticator){ this.authenticator = authenticator } }
apache-2.0
ebcb367806e535bf6568c887bf06cb09
29.088889
120
0.735598
4.589831
false
false
false
false
xmartlabs/bigbang
ui/src/main/java/com/xmartlabs/bigbang/ui/common/recyclerview/RecyclerViewGridSpacingDecoration.kt
1
10054
package com.xmartlabs.bigbang.ui.common.recyclerview import android.graphics.Rect import android.support.annotation.Dimension import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import android.view.View import com.xmartlabs.bigbang.core.extensions.orDo import java.util.ArrayList /** * [RecyclerView.ItemDecoration] subclass designed to add spacing to item controlled by a [GridLayoutManager]. * * This decorator relies on both the [GridLayoutManager.mSpanCount] set and the * [GridLayoutManager.SpanSizeLookup], so both must be defined. * * This decorator allows setting spacing for every item, and different spacing for: * * * First row items * * Last row items * * First column items * * Last column items * * There's another option for which you can set the spacing individually for every item, using the * [.setItemOffsetConsumer] consumer function. * * Note that calculating the first and last column for each row involves some processing and can hurt performance. * Because of that, those values are calculated once and then cached for faster access. * If new items are added to the [RecyclerView], you must invalidate the cache for the decoration to work * properly, using one of the following methods: * * * [.invalidateCache] to invalidate the whole cache * * [.invalidateCacheFromPosition] to invalidate the cache from a given position (if you append items * to the latest position, using this will yield better performance) * * For even faster performance, consider enabling [GridLayoutManager.SpanSizeLookup.setSpanIndexCacheEnabled]. */ class RecyclerViewGridSpacingDecoration : RecyclerView.ItemDecoration() { /** Top spacing for the first row. If null, [.itemSpacing] will be used. */ @Dimension(unit = Dimension.PX) var firstRowTopSpacing: Int? = null /** Bottom spacing for the last row. If null, [.itemSpacing] will be used. */ @Dimension(unit = Dimension.PX) var lastRowBottomSpacing: Int? = null /** Left spacing for the first column. If null, [.itemSpacing] will be used. */ @Dimension(unit = Dimension.PX) var firstColumnLeftSpacing: Int? = null /** Right spacing for the last column. If null, [.itemSpacing] will be used. */ @Dimension(unit = Dimension.PX) var lastColumnRightSpacing: Int? = null /** * Used to manually set the offset for every item. * This will override the automatic calculations. * The [Rect] top, right, bottom, left parameters must be modified to set the offset. */ var itemOffsetConsumer: ((Rect, RecyclerView) -> Unit)? = null /** The default spacing for every item (top, right, bottom, left), unless one of the above spacings apply. */ @Dimension(unit = Dimension.PX) var itemSpacing: Int = 0 private val firstColumns = ArrayList<Int>() private var biggestFirstColumn: Int = 0 private val lastColumns = ArrayList<Int>() private var biggestLastColumn: Int = 0 override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) { if (parent.layoutManager !is GridLayoutManager) { throw IllegalArgumentException("This Item Decoration can only be used with GridLayoutManager") } val layoutManager = parent.layoutManager as GridLayoutManager itemOffsetConsumer?.invoke(outRect, parent) ?: setOffsetForItem(outRect, view, parent, layoutManager) } /** * Sets the offset (spacing) for the `view`. * @param outRect the bounds of the view. The spacing must be set to this object * * * @param view the view to add the spacing * * * @param recyclerView the recycler view that holds the `view` * * * @param gridLayoutManager the layout manager of the recycler view */ private fun setOffsetForItem(outRect: Rect, view: View, recyclerView: RecyclerView, gridLayoutManager: GridLayoutManager) { val position = recyclerView.getChildLayoutPosition(view) val spanCount = gridLayoutManager.spanCount val numberOfItems = recyclerView.adapter.itemCount val spanSizeLookup = gridLayoutManager.spanSizeLookup itemOffsetConsumer?.invoke(outRect, recyclerView).orDo { val firstRowTopSpacing = this.firstRowTopSpacing ?: itemSpacing val firstColumnLeftSpacing = this.firstColumnLeftSpacing ?: itemSpacing val lastColumnRightSpacing = this.lastColumnRightSpacing ?: itemSpacing val lastRowBottomSpacing = this.lastRowBottomSpacing ?: itemSpacing outRect.top = if (isFirstRow(position, spanCount, spanSizeLookup)) firstRowTopSpacing else itemSpacing / 2 outRect.left = if (isFirstColumn(position, spanCount, spanSizeLookup)) firstColumnLeftSpacing else itemSpacing / 2 outRect.right = if (isLastColumn(position, spanCount, numberOfItems, spanSizeLookup)) lastColumnRightSpacing else itemSpacing / 2 outRect.bottom = if (isLastRow(position, spanCount, numberOfItems, spanSizeLookup)) lastRowBottomSpacing else itemSpacing / 2 } } /** * Calculates whether or not the item at `position` belongs to the first row. * @param position the item position * * * @param spanCount the maximum number of items a row can hold * * * @param spanSizeLookup the object that defines how much space an item can take * * * @return whether or not the item belong to the first row */ private fun isFirstRow(position: Int, spanCount: Int, spanSizeLookup: GridLayoutManager.SpanSizeLookup): Boolean { return spanSizeLookup.getSpanGroupIndex(position, spanCount) == FIRST_ROW_GROUP } /** * Calculates whether or not the item at `position` belongs to the last row. * @param position the item position * * * @param spanCount the maximum number of items a row can hold * * * @param numberOfItems the total number of items held by the [RecyclerView] * * * @param spanSizeLookup the object that defines how much space an item can take * * * @return whether or not the item belongs to the last row */ private fun isLastRow(position: Int, initialSpanCount: Int, numberOfItems: Int, spanSizeLookup: GridLayoutManager.SpanSizeLookup): Boolean { var spanCount = initialSpanCount var items = numberOfItems while (position < numberOfItems - 1) { val spanSize = spanSizeLookup.getSpanSize(numberOfItems - 1) spanCount -= spanSize items -= 1 if (spanCount < 0) { return false } } return true } /** * Returns whether the item at `position` belongs to the first column. * @param position the item position * * * @param spanCount the maximum number of items a row can hold * * * @param spanSizeLookup the object that defines how much space an item can take * * * @return whether or not the item belongs to the first column */ private fun isFirstColumn(position: Int, spanCount: Int, spanSizeLookup: GridLayoutManager.SpanSizeLookup): Boolean { if (position == 0 || firstColumns.contains(position)) { biggestFirstColumn = if (biggestFirstColumn < position) position else biggestFirstColumn return true } if (position < biggestFirstColumn) { return false } val isFirstColumn = spanSizeLookup.getSpanGroupIndex(position, spanCount) > spanSizeLookup.getSpanGroupIndex(position - 1, spanCount) if (isFirstColumn) { biggestFirstColumn = if (biggestFirstColumn < position) position else biggestFirstColumn } return isFirstColumn } /** * Returns whether the item at `position` belongs to the last column. * @param position the item position * * * @param spanCount the maximum number of items a row can hold * * * @param numberOfItems the total number of items held by the [RecyclerView] * * * @param spanSizeLookup the object that defines how much space an item can take * * * @return whether or not the item belongs to the last column */ private fun isLastColumn(position: Int, spanCount: Int, numberOfItems: Int, spanSizeLookup: GridLayoutManager.SpanSizeLookup): Boolean { if (position == numberOfItems - 1 || lastColumns.contains(position)) { biggestLastColumn = if (biggestLastColumn < position) position else biggestLastColumn return true } if (position < biggestLastColumn) { return false } val isLastColumn = spanSizeLookup.getSpanGroupIndex(position, spanCount) < spanSizeLookup.getSpanGroupIndex(position + 1, spanCount) if (isLastColumn) { biggestLastColumn = if (biggestLastColumn < position) position else biggestLastColumn } return isLastColumn } /** * Invalidates the cache holding the information about which items belong to the first or last column. * If [GridLayoutManager.SpanSizeLookup.setSpanIndexCacheEnabled] is enabled and the recycler view * adapter did not suffer any change, then you must invalidate the [GridLayoutManager.SpanSizeLookup] cache * calling [GridLayoutManager.SpanSizeLookup.invalidateSpanIndexCache]. */ fun invalidateCache() { firstColumns.clear() biggestFirstColumn = 0 lastColumns.clear() biggestLastColumn = 0 } /** * Invalidates the cache holding the information about which items belong to the first or last column from the * specified `position`. * If [GridLayoutManager.SpanSizeLookup.setSpanIndexCacheEnabled] is enabled and the recycler view * adapter did not suffer any change, then you must invalidate the [GridLayoutManager.SpanSizeLookup] cache * calling [GridLayoutManager.SpanSizeLookup.invalidateSpanIndexCache]. * @param position the position from which the cache should be invalidated */ fun invalidateCacheFromPosition(position: Int) { firstColumns.removeAll(firstColumns.filter { it <= position }) biggestFirstColumn = firstColumns[firstColumns.size - 1] lastColumns.removeAll(lastColumns.filter { it <= position }) biggestLastColumn = lastColumns[lastColumns.size - 1] } companion object { private val FIRST_ROW_GROUP = 0 } }
apache-2.0
8abd37ca836561f788b072fe232d9552
41.066946
137
0.730257
4.624655
false
false
false
false
MyCollab/mycollab
mycollab-services/src/main/java/com/mycollab/aspect/AuditLogAspect.kt
3
8647
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.aspect import com.mycollab.cache.service.CacheService import com.mycollab.common.ActivityStreamConstants import com.mycollab.common.MonitorTypeConstants import com.mycollab.common.domain.AuditLog import com.mycollab.common.domain.MonitorItem import com.mycollab.common.domain.RelayEmailNotificationWithBLOBs import com.mycollab.common.service.ActivityStreamService import com.mycollab.common.service.AuditLogService import com.mycollab.common.service.MonitorItemService import com.mycollab.common.service.RelayEmailNotificationService import com.mycollab.core.utils.BeanUtility import org.apache.commons.beanutils.PropertyUtils import org.aspectj.lang.JoinPoint import org.aspectj.lang.annotation.AfterReturning import org.aspectj.lang.annotation.Aspect import org.aspectj.lang.annotation.Before import org.slf4j.LoggerFactory import org.springframework.aop.framework.Advised import org.springframework.beans.factory.annotation.Configurable import org.springframework.stereotype.Component import java.io.Serializable import java.time.LocalDateTime import java.util.* /** * @author MyCollab Ltd. * @since 1.0 */ @Aspect @Component @Configurable class AuditLogAspect(private var cacheService: CacheService, private var auditLogService: AuditLogService, private var activityStreamService: ActivityStreamService, private var monitorItemService: MonitorItemService, private var relayEmailNotificationService: RelayEmailNotificationService) { @Before("(execution(public * com.mycollab..service..*.updateWithSession(..)) || (execution(public * com.mycollab..service..*.updateSelectiveWithSession(..)))) && args(bean, username)") fun traceBeforeUpdateActivity(joinPoint: JoinPoint, bean: Any, username: String) { val advised = joinPoint.`this` as Advised val cls = advised.targetSource.targetClass!! val auditAnnotation = cls.getAnnotation(Traceable::class.java) if (auditAnnotation != null) { try { val typeId = PropertyUtils.getProperty(bean, "id") as Int val sAccountId = PropertyUtils.getProperty(bean, "saccountid") as Int // store old value to map, wait until the update process // successfully then add to log item // get old value val service = advised.targetSource.target val oldValue: Any val findMethod = try { cls.getMethod("findById", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType) } catch (e: Exception) { cls.getMethod("findByPrimaryKey", Serializable::class.java, Int::class.javaPrimitiveType) } oldValue = findMethod.invoke(service, typeId, sAccountId) val key = bean.toString() + ClassInfoMap.getType(cls) + typeId cacheService.putValue(AUDIT_TEMP_CACHE, key, oldValue) } catch (e: Exception) { LOG.error("Error when save audit for save action of service ${cls.name}", e) } } } @AfterReturning("(execution(public * com.mycollab..service..*.updateWithSession(..)) || (execution(public * com.mycollab..service..*.updateSelectiveWithSession(..)))) && args(bean, username)") fun traceAfterUpdateActivity(joinPoint: JoinPoint, bean: Any, username: String) { val advised = joinPoint.`this` as Advised val cls = advised.targetSource.targetClass!! val isSelective = "updateSelectiveWithSession" == joinPoint.signature.name try { val traceableAnnotation = cls.getAnnotation(Traceable::class.java) if (traceableAnnotation != null) { try { val classInfo = ClassInfoMap.getClassInfo(cls) val changeSet = getChangeSet(this, cls, bean, classInfo!!.getExcludeHistoryFields(), isSelective) if (changeSet != null) { val activity = TraceableCreateAspect.constructActivity(cls, traceableAnnotation, bean, username, ActivityStreamConstants.ACTION_UPDATE) val activityStreamId = activityStreamService.save(activity) val sAccountId = PropertyUtils.getProperty(bean, "saccountid") as Int val auditLogId = saveAuditLog(this, cls, bean, changeSet, username, sAccountId, activityStreamId) val typeId = PropertyUtils.getProperty(bean, "id") as Int // Save notification email val relayNotification = RelayEmailNotificationWithBLOBs() relayNotification.changeby = username relayNotification.changecomment = "" relayNotification.saccountid = sAccountId relayNotification.type = ClassInfoMap.getType(cls) relayNotification.typeid = "" + typeId if (auditLogId != null) { relayNotification.extratypeid = auditLogId } relayNotification.action = MonitorTypeConstants.UPDATE_ACTION relayEmailNotificationService.saveWithSession(relayNotification, username) } } catch (e: Exception) { LOG.error("Error when save activity for save action of service ${cls.name}", e) } } } catch (e: Exception) { LOG.error("Error when save audit for save action of service ${cls.name} and bean: ${BeanUtility.printBeanObj(bean)}", e) } } companion object { private val LOG = LoggerFactory.getLogger(AuditLogAspect::class.java) private const val AUDIT_TEMP_CACHE = "AUDIT_TEMP_CACHE" fun getChangeSet(auditLogAspect: AuditLogAspect, targetCls: Class<*>, bean: Any, excludeHistoryFields: List<String>, isSelective: Boolean): String? { return try { val typeId = PropertyUtils.getProperty(bean, "id") as Int val key = "$bean${ClassInfoMap.getType(targetCls)}$typeId" val oldValue = auditLogAspect.cacheService.getValue(AUDIT_TEMP_CACHE, key) if (oldValue != null) { AuditLogUtil.getChangeSet(oldValue, bean, excludeHistoryFields, isSelective) } else null } catch (e: Exception) { LOG.error("Error while generate changeset", e) null } } fun saveAuditLog(auditLogAspect: AuditLogAspect, targetCls: Class<*>, bean: Any, changeSet: String, username: String, sAccountId: Int?, activityStreamId: Int?): Int? { try { val typeId = PropertyUtils.getProperty(bean, "id") as Int val auditLog = AuditLog() auditLog.createduser = username auditLog.module = ClassInfoMap.getModule(targetCls) auditLog.type = ClassInfoMap.getType(targetCls) auditLog.typeid = typeId auditLog.saccountid = sAccountId auditLog.createdtime = LocalDateTime.now() auditLog.changeset = changeSet auditLog.objectClass = bean.javaClass.name if (activityStreamId != null) { auditLog.activitylogid = activityStreamId } return auditLogAspect.auditLogService.saveWithSession(auditLog, "") } catch (e: Exception) { LOG.error("Error when save audit for save action of service ${targetCls.name} and bean: ${BeanUtility.printBeanObj(bean)} and changeset is $changeSet", e) return null } } } }
agpl-3.0
d7fc7fb9b42dd506477e0ea9e46340ca
47.301676
197
0.636132
4.974684
false
false
false
false
aosp-mirror/platform_frameworks_support
buildSrc/src/main/kotlin/androidx/build/Version.kt
1
3128
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build import java.io.File import java.util.regex.Matcher import java.util.regex.Pattern /** * Utility class which represents a version */ data class Version( val major: Int, val minor: Int, val patch: Int, val extra: String? = null ) : Comparable<Version> { constructor(versionString: String) : this( Integer.parseInt(checkedMatcher(versionString).group(1)), Integer.parseInt(checkedMatcher(versionString).group(2)), Integer.parseInt(checkedMatcher(versionString).group(3)), if (checkedMatcher(versionString).groupCount() == 4) checkedMatcher( versionString).group(4) else null) fun isPatch(): Boolean = patch != 0 fun isSnapshot(): Boolean = "-SNAPSHOT" == extra fun isAlpha(): Boolean = extra?.toLowerCase()?.startsWith("-alpha") ?: false fun isFinalApi(): Boolean = !isSnapshot() && !isAlpha() override fun compareTo(other: Version) = compareValuesBy(this, other, { it.major }, { it.minor }, { it.patch }, { it.extra == null }, // False (no extra) sorts above true (has extra) { it.extra } // gradle uses lexicographic ordering ) override fun toString(): String { return "$major.$minor.$patch${extra ?: ""}" } companion object { private val VERSION_FILE_REGEX = Pattern.compile("^(\\d+\\.\\d+\\.\\d+).txt$") private val VERSION_REGEX = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)(-.+)?$") private fun checkedMatcher(versionString: String): Matcher { val matcher = VERSION_REGEX.matcher(versionString) if (!matcher.matches()) { throw IllegalArgumentException("Can not parse version: " + versionString) } return matcher } /** * @return Version or null, if a name of the given file doesn't match */ fun parseOrNull(file: File): Version? { if (!file.isFile) return null val matcher = VERSION_FILE_REGEX.matcher(file.name) return if (matcher.matches()) Version(matcher.group(1)) else null } /** * @return Version or null, if the given string doesn't match */ fun parseOrNull(versionString: String): Version? { val matcher = VERSION_REGEX.matcher(versionString) return if (matcher.matches()) Version(versionString) else null } } }
apache-2.0
220e0d5ded1fc6928f74e6a1757c291c
34.146067
89
0.617327
4.494253
false
false
false
false
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/domain/usecases/MoveGroupUseCase.kt
1
1318
package com.ivanovsky.passnotes.domain.usecases import com.ivanovsky.passnotes.data.ObserverBus import com.ivanovsky.passnotes.data.entity.OperationResult import com.ivanovsky.passnotes.domain.DispatcherProvider import kotlinx.coroutines.withContext import java.util.UUID class MoveGroupUseCase( private val dispatchers: DispatcherProvider, private val observerBus: ObserverBus, private val getDbUseCase: GetDatabaseUseCase ) { suspend fun moveGroup(groupUid: UUID, newParentGroupUid: UUID): OperationResult<Boolean> { return withContext(dispatchers.IO) { val getDbResult = getDbUseCase.getDatabase() if (getDbResult.isFailed) { return@withContext getDbResult.takeError() } val db = getDbResult.obj val getGroupResult = db.groupRepository.getGroupByUid(groupUid) if (getGroupResult.isFailed) { return@withContext getGroupResult.takeError() } val group = getGroupResult.obj val moveResult = db.groupRepository.update(group, newParentGroupUid) if (moveResult.isFailed) { return@withContext moveResult.takeError(); } observerBus.notifyGroupDataSetChanged() OperationResult.success(true) } } }
gpl-2.0
c63455eab4de65231a3637d89dc29180
32.820513
94
0.689681
4.775362
false
false
false
false
JakeWharton/dex-method-list
diffuse/src/main/kotlin/com/jakewharton/diffuse/Member.kt
1
3264
package com.jakewharton.diffuse sealed class Member : Comparable<Member> { abstract val declaringType: TypeDescriptor abstract val name: String override fun compareTo(other: Member): Int { val typeResult = declaringType.compareTo(other.declaringType) if (typeResult != 0) { return typeResult } if (javaClass == other.javaClass) { return 0 } return if (this is Method) -1 else 1 } } data class Field( override val declaringType: TypeDescriptor, override val name: String, val type: TypeDescriptor ) : Member() { override fun toString() = "${declaringType.sourceName} $name: ${type.simpleName}" override fun compareTo(other: Member): Int { val superResult = super.compareTo(other) if (superResult != 0) { return superResult } return COMPARATOR.compare(this, other as Field) } private companion object { val COMPARATOR = compareBy(Field::name, Field::type) } } data class Method( override val declaringType: TypeDescriptor, override val name: String, val parameterTypes: List<TypeDescriptor>, val returnType: TypeDescriptor ) : Member() { override fun toString() = buildString { append(declaringType.sourceName) append(' ') append(name) append('(') parameterTypes.joinTo(this, ", ", transform = TypeDescriptor::simpleName) append(')') if (returnType != VOID) { append(" → ") append(returnType.simpleName) } } override fun compareTo(other: Member): Int { val superResult = super.compareTo(other) if (superResult != 0) { return superResult } return COMPARATOR.compare(this, other as Method) } private companion object { val VOID = TypeDescriptor("V") val COMPARATOR = compareBy(Method::name) .thenBy(comparingValues(), Method::parameterTypes) .thenBy(Method::returnType) } } internal fun Member.withoutSyntheticSuffix() = when (this) { is Field -> withoutSyntheticSuffix() is Method -> withoutSyntheticSuffix() } private fun Field.withoutSyntheticSuffix(): Field { val newDeclaredType = declaringType.withoutSyntheticSuffix() if (newDeclaredType == declaringType) { return this } return copy(declaringType = newDeclaredType) } private val syntheticMethodSuffix = ".*?\\$\\d+".toRegex() private val lambdaMethodNumber = "\\$\\d+\\$".toRegex() private fun Method.withoutSyntheticSuffix(): Method { val newDeclaredType = declaringType.withoutSyntheticSuffix() val lambdaName = name.startsWith("lambda$") val syntheticName = name.matches(syntheticMethodSuffix) if (declaringType == newDeclaredType && !lambdaName && !syntheticName) { return this } val newName = when { lambdaName -> lambdaMethodNumber.find(name)!!.let { match -> name.removeRange(match.range.first, match.range.last) } syntheticName -> name.substring(0, name.lastIndexOf('$')) else -> name } return copy(declaringType = newDeclaredType, name = newName) } private val lambdaClassSuffix = ".*?\\$\\\$Lambda\\$\\d+;".toRegex() private fun TypeDescriptor.withoutSyntheticSuffix(): TypeDescriptor { return when (value.matches(lambdaClassSuffix)) { true -> TypeDescriptor(value.substringBeforeLast('$') + ";") false -> this } }
apache-2.0
057ba5097d2109450f4e9ff05b656b5a
27.12069
83
0.690067
4.332005
false
false
false
false
grote/Transportr
app/src/main/java/de/grobox/transportr/ui/TimeDateFragment.kt
1
6837
/* * Transportr * * Copyright (c) 2013 - 2021 Torsten Grote * * This program is Free Software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.grobox.transportr.ui import android.app.DatePickerDialog import android.app.DatePickerDialog.OnDateSetListener import android.os.Bundle import android.text.format.DateFormat.getDateFormat import android.view.LayoutInflater import android.view.View import android.view.View.GONE import android.view.ViewGroup import android.widget.DatePicker import android.widget.TimePicker import android.widget.TimePicker.OnTimeChangedListener import androidx.fragment.app.DialogFragment import de.grobox.transportr.R import kotlinx.android.synthetic.main.fragment_time_date.* import java.util.* import java.util.Calendar.* class TimeDateFragment : DialogFragment(), OnDateSetListener, OnTimeChangedListener { private var listener: TimeDateListener? = null private var departure: Boolean? = null // null means no departure/arrival selection will be possible private lateinit var calendar: Calendar companion object { @JvmField val TAG: String = TimeDateFragment::class.java.simpleName private val CALENDAR = "calendar" private val DEPARTURE = "departure" @JvmStatic fun newInstance(calendar: Calendar, departure: Boolean? = null): TimeDateFragment { val f = TimeDateFragment() val args = Bundle() args.putSerializable(CALENDAR, calendar) args.putSerializable(DEPARTURE, departure) f.arguments = args return f } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { arguments?.let { calendar = it.getSerializable(CALENDAR) as Calendar departure = it.getSerializable(DEPARTURE) as Boolean? } ?: throw IllegalArgumentException("Arguments missing") } else { calendar = savedInstanceState.getSerializable(CALENDAR) as Calendar departure = savedInstanceState.getSerializable(DEPARTURE) as Boolean? } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_time_date, container) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Time timePicker.setIs24HourView(android.text.format.DateFormat.is24HourFormat(context)) timePicker.setOnTimeChangedListener(this) showTime(calendar) // Date dateView.setOnClickListener { DatePickerDialog(context!!, this@TimeDateFragment, calendar.get(YEAR), calendar.get(MONTH), calendar.get(DAY_OF_MONTH)) .show() } showDate(calendar) // Previous and Next Date prevDateButton.setOnClickListener { calendar.add(DAY_OF_MONTH, -1) showDate(calendar) } nextDateButton.setOnClickListener { calendar.add(DAY_OF_MONTH, 1) showDate(calendar) } // Departure or Arrival departure?.let { departureButton.isChecked = it arrivalButton.isChecked = !it departureButton.setOnClickListener { departure = departureButton.isChecked arrivalButton.isChecked = !departure!! } arrivalButton.setOnClickListener { departure = !arrivalButton.isChecked departureButton.isChecked = departure!! } } ?: run { departureButton.visibility = GONE arrivalButton.visibility = GONE } // Buttons okButton.setOnClickListener { listener?.onTimeAndDateSet(calendar) departure?.let { listener?.onDepartureOrArrivalSet(it) } dismiss() } nowButton.setOnClickListener { listener?.onTimeAndDateSet(Calendar.getInstance()) departure?.let { listener?.onDepartureOrArrivalSet(it) } dismiss() } cancelButton.setOnClickListener { dismiss() } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putSerializable(CALENDAR, calendar) outState.putSerializable(DEPARTURE, departure) } override fun onTimeChanged(timePicker: TimePicker, hourOfDay: Int, minute: Int) { calendar.set(HOUR_OF_DAY, hourOfDay) calendar.set(MINUTE, minute) } override fun onDateSet(datePicker: DatePicker, year: Int, month: Int, day: Int) { calendar.set(YEAR, year) calendar.set(MONTH, month) calendar.set(DAY_OF_MONTH, day) showDate(calendar) } fun setTimeDateListener(listener: TimeDateListener) { this.listener = listener } @Suppress("DEPRECATION") private fun showTime(c: Calendar) { timePicker.currentHour = c.get(HOUR_OF_DAY) timePicker.currentMinute = c.get(MINUTE) } private fun showDate(c: Calendar) { val now = Calendar.getInstance() dateView.text = when { c.isYesterday(now) -> getString(R.string.yesterday) c.isToday(now) -> getString(R.string.today) c.isTomorrow(now) -> getString(R.string.tomorrow) else -> getDateFormat(context?.applicationContext).format(calendar.time) } } private fun Calendar.isSameMonth(c: Calendar) = c.get(YEAR) == get(YEAR) && c.get(MONTH) == get(MONTH) private fun Calendar.isYesterday(now: Calendar) = isSameMonth(now) && get(DAY_OF_MONTH) == now.get(DAY_OF_MONTH) - 1 private fun Calendar.isToday(now: Calendar) = isSameMonth(now) && get(DAY_OF_MONTH) == now.get(DAY_OF_MONTH) private fun Calendar.isTomorrow(now: Calendar) = isSameMonth(now) && get(DAY_OF_MONTH) == now.get(DAY_OF_MONTH) + 1 interface TimeDateListener { fun onTimeAndDateSet(calendar: Calendar) fun onDepartureOrArrivalSet(departure: Boolean) { } } }
gpl-3.0
3f8801332196c6679cb65eac605fe8a3
35.174603
131
0.65833
4.654187
false
false
false
false
grote/Liberario
app/src/main/java/de/grobox/transportr/trips/detail/TripMapFragment.kt
1
3276
/* * Transportr * * Copyright (c) 2013 - 2018 Torsten Grote * * This program is Free Software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.grobox.transportr.trips.detail import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import android.os.Bundle import androidx.annotation.LayoutRes import android.util.DisplayMetrics import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.mapbox.mapboxsdk.geometry.LatLng import com.mapbox.mapboxsdk.maps.MapboxMap import de.grobox.transportr.R import de.grobox.transportr.map.GpsMapFragment import de.schildbach.pte.dto.Trip import javax.inject.Inject class TripMapFragment : GpsMapFragment() { companion object { @JvmField val TAG: String = TripMapFragment::class.java.simpleName } override val layout: Int @LayoutRes get() = R.layout.fragment_trip_map @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var viewModel: TripDetailViewModel override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val v = super.onCreateView(inflater, container, savedInstanceState) component.inject(this) viewModel = ViewModelProviders.of(activity!!, viewModelFactory).get(TripDetailViewModel::class.java) gpsController = viewModel.gpsController return v } override fun onMapReady(mapboxMap: MapboxMap) { super.onMapReady(mapboxMap) // set padding, so everything gets centered in top half of screen val metrics = DisplayMetrics() activity!!.windowManager.defaultDisplay.getMetrics(metrics) val topPadding = mapPadding / 2 val bottomPadding = mapView.height / 4 map!!.setPadding(0, topPadding, 0, bottomPadding) viewModel.getTrip().observe(this, Observer { onTripChanged(it) }) viewModel.getZoomLocation().observe(this, Observer { this.animateTo(it) }) viewModel.getZoomLeg().observe(this, Observer { this.animateToBounds(it) }) } private fun onTripChanged(trip: Trip?) { if (trip == null) return val tripDrawer = TripDrawer(context) val zoom = viewModel.isFreshStart.value ?: throw IllegalStateException() tripDrawer.draw(map!!, trip, zoom) if (zoom) { // do not zoom again when returning to this Fragment viewModel.isFreshStart.value = false } } private fun animateTo(latLng: LatLng?) { animateTo(latLng, 16) } }
gpl-3.0
449c987c9013328073a3adeaa90a61a3
33.484211
116
0.709707
4.50619
false
false
false
false
google/taqo-paco
taqo_client/android/app/src/main/kotlin/com/taqo/survey/taqosurvey/MainActivity.kt
1
2214
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.taqo.survey.taqosurvey import android.content.Intent import android.net.Uri import androidx.annotation.NonNull import androidx.annotation.UiThread import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel import io.flutter.plugins.GeneratedPluginRegistrant class MainActivity: FlutterActivity() { private val channel = "com.taqo.survey.taqosurvey/email" private val sendEmailMethod = "send_email" private val toArg = "to" private val subjectArg = "subject" override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) { GeneratedPluginRegistrant.registerWith(flutterEngine) MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channel) .setMethodCallHandler { call, result -> if (sendEmailMethod == call.method) { val to = call.argument<String>(toArg) val subject = call.argument<String>(subjectArg) if (to != null && subject != null) { sendEmail(to, subject) } } else { result.notImplemented() } } } @UiThread private fun sendEmail(to: String, subject: String) { val intent = Intent(Intent.ACTION_SENDTO) intent.type = "text/html" intent.data = Uri.parse("mailto:$to?subject=${Uri.encode(subject)}") startActivity(Intent.createChooser(intent, "Choose your email client")) } }
apache-2.0
6427547e0f472b9c8ef72b1a6e64410a
39.254545
80
0.665763
4.680761
false
false
false
false
hwki/SimpleBitcoinWidget
bitcoin/src/main/java/com/brentpanther/bitcoinwidget/Repository.kt
1
4772
package com.brentpanther.bitcoinwidget import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.util.Log import androidx.core.content.edit import androidx.preference.PreferenceManager import com.brentpanther.bitcoinwidget.db.Widget import com.brentpanther.bitcoinwidget.exchange.CustomExchangeData import com.brentpanther.bitcoinwidget.exchange.ExchangeData import com.brentpanther.bitcoinwidget.exchange.ExchangeHelper import com.google.gson.JsonParseException import okhttp3.ConnectionPool import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.internal.closeQuietly import java.io.ByteArrayOutputStream import java.io.File import java.io.IOException import java.io.InputStream import java.util.concurrent.TimeUnit object Repository { internal const val LAST_MODIFIED = "last_modified" const val CURRENCY_FILE_NAME = "coins.json" private val TAG = Repository::class.java.simpleName fun downloadJSON() { val context = WidgetApplication.instance try { val prefs = PreferenceManager.getDefaultSharedPreferences(context) val lastModified = prefs.getString(LAST_MODIFIED, context.getString(R.string.json_last_modified)) val url = context.getString(R.string.json_url) val client = OkHttpClient.Builder() .followRedirects(true) .followSslRedirects(true) .readTimeout(60, TimeUnit.SECONDS) .connectTimeout(30, TimeUnit.SECONDS) .retryOnConnectionFailure(true) .connectionPool(ConnectionPool(0, 1, TimeUnit.NANOSECONDS)) .build() val request = Request.Builder() .addHeader("If-Modified-Since", lastModified!!) .url(url) .build() val response = client.newCall(request).execute() when (response.code) { 304 -> Log.d(TAG, "No changes found in JSON file.") 200 -> { Log.d(TAG, "Updated JSON file found.") response.body?.byteStream()?.use { val os = context.openFileOutput(CURRENCY_FILE_NAME, Context.MODE_PRIVATE) it.copyTo(os) os.closeQuietly() } prefs.edit().putString(LAST_MODIFIED, response.header("Last-Modified")).apply() Log.d(TAG, "JSON downloaded.") } else -> Log.d(TAG, "Retrieved status code: " + response.code) } } catch (e: IOException) { Log.e(TAG, "Error downloading JSON.", e) } } fun downloadCustomIcon(widget: Widget) { val context = WidgetApplication.instance widget.customIcon?.let { url -> val dir = File(context.filesDir, "icons") if (!dir.exists()) { dir.mkdir() } val id = widget.coinCustomId ?: return@let val file = File(dir, id) if (file.exists()) { return } ExchangeHelper.getStream(url).use { stream -> ByteArrayOutputStream().use { os -> BitmapFactory.decodeStream(stream)?.let { image -> image.compress(Bitmap.CompressFormat.PNG, 100, os) file.writeBytes(os.toByteArray()) } } } } } fun getExchangeData(widget: Widget): ExchangeData { val context = WidgetApplication.instance return try { if (widget.coin == Coin.CUSTOM) { CustomExchangeData(widget.coinName(), widget.coin, getJson(context)) } else { val data = ExchangeData(widget.coin, getJson(context)) if (data.numberExchanges == 0) { throw JsonParseException("No exchanges found.") } data } } catch(e: JsonParseException) { Log.e("SettingsViewModel", "Error parsing JSON file, falling back to original.", e) context.deleteFile(CURRENCY_FILE_NAME) PreferenceManager.getDefaultSharedPreferences(context).edit { remove(LAST_MODIFIED) } ExchangeData(widget.coin, getJson(context)) } } private fun getJson(context: Context): InputStream { return if (File(context.filesDir, CURRENCY_FILE_NAME).exists()) { context.openFileInput(CURRENCY_FILE_NAME) } else { context.resources.openRawResource(R.raw.cryptowidgetcoins_v2) } } }
mit
bba70a3a4d6e412e6d194066cc581cfc
37.483871
109
0.585289
4.84467
false
false
false
false
VerifAPS/verifaps-lib
symbex/src/main/kotlin/edu/kit/iti/formal/automation/il/ilsymbex.kt
1
13167
package edu.kit.iti.formal.automation.il import edu.kit.iti.formal.automation.SymbExFacade import edu.kit.iti.formal.automation.rvt.SymbolicState import edu.kit.iti.formal.automation.rvt.translators.DefaultTypeTranslator import edu.kit.iti.formal.automation.rvt.translators.DefaultValueTranslator import edu.kit.iti.formal.automation.rvt.translators.TypeTranslator import edu.kit.iti.formal.automation.rvt.translators.ValueTranslator import edu.kit.iti.formal.automation.scope.Scope import edu.kit.iti.formal.automation.st.DefaultInitValue import edu.kit.iti.formal.automation.st.InitValueTranslator import edu.kit.iti.formal.automation.st.ast.Invoked import edu.kit.iti.formal.automation.st.ast.Literal import edu.kit.iti.formal.automation.st.ast.SymbolicReference import edu.kit.iti.formal.smv.SMVFacade import edu.kit.iti.formal.smv.ast.* import edu.kit.iti.formal.smv.joinToExpr import java.util.concurrent.Callable import java.util.concurrent.atomic.AtomicInteger /** * * @author Alexander Weigl * @version 1 (21.02.19) */ class IlSymbex(ilBody: IlBody, maximalSteps: Int = 1000, scope: Scope, val state: SymbolicState = SymbolicState()) : Callable<SymbolicState> { private val context = IlSymbexContext(scope) fun initState() { context.scope.variables.forEach { vd -> val v = context.varCache.computeIfAbsent(vd.name) { SVariable(vd.name, context.typeTranslator.translate(vd.dataType!!)) } state.assign(v, context.assignCounter.incrementAndGet(), v) } } init { context.onFork(Path(0, maximalSteps, ilBody, context, state = state)) } override fun call(): SymbolicState { while (context.running.isNotEmpty()) { val p = context.running.first() context.running.remove(p) p.run() } if (context.terminated.size == 1) { return context.terminated.first().state } else { return SymbolicState().also { case -> for (vd in context.scope) { val v = context.varCache[vd.name]!! val states = context.terminated.map { path -> val cond = path.pathCondition.joinToExpr(default = SLiteral.TRUE) val expr = path.state[v] ?: v cond to expr } val ve = if (states.all { (a, b) -> b == states.first().second }) states.first().second else { SCaseExpression().also { states.forEach { (a, b) -> it.addCase(a, b) } it.addCase(SLiteral.TRUE, v) } } case[v] = ve } } } } } internal class IlSymbexContext(val scope: Scope) { val assignCounter = AtomicInteger(-1) val running = arrayListOf<Path>() val terminated = arrayListOf<Path>() val errorVariable: SVariable = SVariable.bool("PATH_DIVERGED") val varCache = java.util.HashMap<String, SVariable>() //var operationMap: OperationMap = DefaultOperationMap() val typeTranslator: TypeTranslator = DefaultTypeTranslator() val valueTranslator: ValueTranslator = DefaultValueTranslator() var initValueTranslator: InitValueTranslator = DefaultInitValue fun onFinish(p: Path) { //p.pc = ilBody.size + 1 terminated += p } fun onFork(p: Path) { running += p } fun translateToSmv(lit: Literal) = valueTranslator.translate(lit) fun translateToSmv(ref: SymbolicReference): SVariable = varCache.computeIfAbsent(ref.identifier) { typeTranslator.translate(scope.getVariable(ref)) } fun translateToSmv(e: ExprOperand): SBinaryOperator = when (e) { ExprOperand.AND -> SBinaryOperator.AND ExprOperand.OR -> SBinaryOperator.OR ExprOperand.XOR -> SBinaryOperator.XOR ExprOperand.ANDN -> SBinaryOperator.AND ExprOperand.ORN -> SBinaryOperator.OR ExprOperand.XORN -> SBinaryOperator.XOR ExprOperand.ADD -> SBinaryOperator.PLUS ExprOperand.SUB -> SBinaryOperator.MINUS ExprOperand.MUL -> SBinaryOperator.MUL ExprOperand.DIV -> SBinaryOperator.DIV ExprOperand.MOD -> SBinaryOperator.MOD ExprOperand.GT -> SBinaryOperator.GREATER_THAN ExprOperand.GE -> SBinaryOperator.GREATER_EQUAL ExprOperand.EQ -> SBinaryOperator.EQUAL ExprOperand.LT -> SBinaryOperator.LESS_THAN ExprOperand.LE -> SBinaryOperator.LESS_EQUAL ExprOperand.NE -> SBinaryOperator.NOT_EQUAL } } internal data class Path( internal var currentIdx: Int = 0, private var remainingSteps: Int = 0, private val ilBody: IlBody, private val context: IlSymbexContext, private val subMode: Boolean = false, internal val state: SymbolicState = SymbolicState(), private var accumulator: SMVExpr = SLiteral.TRUE, internal var pathCondition: Set<SMVExpr> = hashSetOf()) : Runnable, IlTraversalVisitor() { private val remainingJumps = HashMap<Int, Int>() private val current: IlInstr get() = ilBody[currentIdx] private val ended: Boolean get() = //(current as? RetInstr).type == ReturnOperand.RET|| currentIdx >= ilBody.size override fun run() { while (!ended && remainingSteps > 0) { //execute current state remainingSteps-- current.accept(this) } if (!subMode) { if (currentIdx >= ilBody.size) { state.assign(context.errorVariable, context.assignCounter.incrementAndGet(), SLiteral.FALSE) } else if (remainingSteps <= 0) { state[context.errorVariable] = SLiteral.TRUE } context.onFinish(this) } } private fun fork(cond: SMVExpr, forkedPC: Int) { val other = copy( currentIdx = forkedPC, state = SymbolicState(state), //TODO check for deep copy pathCondition = HashSet(pathCondition) + cond) pathCondition = pathCondition + cond.not() context.onFork(other) } //region instruction handling fun load(operand: IlOperand, N: Boolean = false) { val loadedValue = when (operand) { is IlOperand.Variable -> context.translateToSmv(operand.ref) is IlOperand.Constant -> context.translateToSmv(operand.literal) } val oldValue = accumulator if (N) { accumulator = SMVFacade.caseexpr( oldValue.not(), loadedValue, SLiteral.TRUE, oldValue) } else { accumulator = loadedValue } } fun store(operand: IlOperand, N: Boolean = false, test: Boolean = false) { if (test) TODO(" ?= is current not supported") if (operand is IlOperand.Constant) throw IllegalStateException("constant as storage target") val variable = context.translateToSmv((operand as IlOperand.Variable).ref) val varValue = if (N) { val oldValue = state[variable]!! SMVFacade.caseexpr( accumulator.not(), SLiteral.FALSE, SLiteral.TRUE, oldValue) } else { accumulator } state.assign(variable, context.assignCounter.incrementAndGet(), varValue) } fun not() { accumulator = accumulator.not() } fun reset(operand: IlOperand) { val ref = (operand as IlOperand.Variable).ref val variable = context.translateToSmv(ref) val oldValue = state[variable]!! val varValue = SMVFacade.caseexpr( accumulator, SLiteral.FALSE, SLiteral.TRUE, oldValue) state[variable] = varValue } fun set(operand: IlOperand) { val ref = (operand as IlOperand.Variable).ref val variable = context.translateToSmv(ref) val oldValue = state[variable]!! val varValue = SMVFacade.caseexpr( accumulator, SLiteral.TRUE, SLiteral.TRUE, oldValue) state[variable] = varValue } fun shortcall(type: SimpleOperand, operand: IlOperand) { //TODO Handle calls /* val func = (operand as IlOperand.Variable).ref val p = arrayListOf(InvocationParameter(type.name, false, accumulator)) return InvocationStatement(func, p) */ } fun makeCall(call: CallInstr, C: Boolean = false, N: Boolean = false) { //TODO Handle calls /*val args = call.parameters.map { val e = when (it.right) { is IlOperand.Variable -> it.right.ref is IlOperand.Constant -> it.right.literal } InvocationParameter(it.left, it.input, e) }.toMutableList() val invoke = InvocationStatement(call.ref, args) return when { N -> Statements.ifthen(accumulator.not(), invoke) C -> Statements.ifthen(accumulator, invoke) else -> invoke } */ } //endregion //region visitor dispatching override fun defaultVisit(top: IlAst) {} override fun visit(ret: RetInstr) { val C = ret.type == ReturnOperand.RETC val N = ret.type == ReturnOperand.RETC if (C || N) { var cond = accumulator if (N) cond = cond.not() fork(cond, ilBody.size + 1) } else { currentIdx = ilBody.size + 1 } } override fun visit(jump: JumpInstr) { val C = jump.type == JumpOperand.JMPC val N = jump.type == JumpOperand.JMPCN val pos = ilBody.posMarked(jump.target) ?: throw IllegalStateException("illegal jump position") if (C || N) { //TODO check the jump map var cond = accumulator if (N) cond = cond.not() fork(cond, pos) currentIdx++ } else { currentIdx = pos } } override fun visit(simple: SimpleInstr) { when (simple.type) { SimpleOperand.NOT -> accumulator else -> when (simple.type) { SimpleOperand.LD -> load(simple.operand!!) SimpleOperand.LDN -> load(simple.operand!!, N = true) SimpleOperand.ST -> store(simple.operand!!) SimpleOperand.STN -> store(simple.operand!!, N = true) SimpleOperand.STQ -> store(simple.operand!!, test = true) SimpleOperand.S -> set(simple.operand!!) SimpleOperand.R -> reset(simple.operand!!) else -> shortcall(simple.type, simple.operand!!) } } currentIdx++ } override fun visit(funCall: FunctionCallInstr) { val decl = (funCall.invoked as? Invoked.Function) ?: throw IllegalStateException("No function resolved for $funCall") val args = funCall.operands.map { when (it) { is IlOperand.Variable -> { val ref = context.translateToSmv(it.ref) as SVariable state[ref] ?: throw IllegalStateException("Variable not defined: $ref") } is IlOperand.Constant -> context.translateToSmv(it.literal) } } val ret = SymbExFacade.evaluateFunction(decl.function, args) accumulator = ret currentIdx++ } override fun visit(expr: ExprInstr) { val sub = expr.instr ?: IlBody() expr.operandi?.also { //rewrite sub.add(0, SimpleInstr(SimpleOperand.LD, it)) expr.operandi = null } val operator = context.translateToSmv(expr.operand) val left = accumulator val right: SMVExpr = exec(sub) //TODO Deal with side effects! accumulator = left.op(operator, right) if (expr.operand == ExprOperand.XORN || expr.operand == ExprOperand.ORN || expr.operand == ExprOperand.ANDN) accumulator = accumulator.not() currentIdx++ } private fun exec(sub: IlBody): SMVExpr { val other = copy(0, subMode = true, ilBody = sub, pathCondition = hashSetOf()) other.run() return other.accumulator } override fun visit(call: CallInstr) { when (call.type) { CallOperand.CAL -> makeCall(call) CallOperand.CALC -> makeCall(call, C = true) CallOperand.CALCN -> makeCall(call, N = true) CallOperand.IMPLICIT_CALLED -> makeCall(call) } currentIdx++ } //endregion }
gpl-3.0
645dcdb4cb4dcc3404fb6f3bab6589c6
35.372928
108
0.576821
4.372966
false
false
false
false
systemallica/ValenBisi
app/src/main/kotlin/com/systemallica/valenbisi/fragments/MapsFragment.kt
1
39063
package com.systemallica.valenbisi.fragments import android.Manifest import android.annotation.SuppressLint import android.content.SharedPreferences import android.content.pm.PackageManager import android.content.res.Configuration import android.content.res.Resources import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Color import android.graphics.Typeface import android.location.Location import android.os.Bundle import android.util.Log import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.activity.result.contract.ActivityResultContracts import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.preference.PreferenceManager.getDefaultSharedPreferences import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.UiSettings import com.google.android.gms.maps.model.* import com.google.android.material.snackbar.Snackbar import com.google.maps.android.clustering.ClusterManager import com.google.maps.android.data.geojson.* import com.systemallica.valenbisi.BikeStation import com.systemallica.valenbisi.R import com.systemallica.valenbisi.clustering.ClusterPoint import com.systemallica.valenbisi.clustering.IconRenderer import com.systemallica.valenbisi.databinding.FragmentMainBinding import kotlinx.coroutines.* import okhttp3.* import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.io.IOException import java.util.* import kotlin.coroutines.CoroutineContext const val PREFS_NAME = "MyPrefsFile" const val LOG_TAG = "Valenbisi error" class MapsFragment : Fragment(), OnMapReadyCallback, CoroutineScope { private var job: Job = Job() private var _binding: FragmentMainBinding? = null private val binding get() = _binding!! override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job private lateinit var settings: SharedPreferences private lateinit var userSettings: SharedPreferences private lateinit var clusterManager: ClusterManager<ClusterPoint> private lateinit var fusedLocationClient: FusedLocationProviderClient private var stations: GeoJsonLayer? = null private var lanes: GeoJsonLayer? = null private var parking: GeoJsonLayer? = null private var mMap: GoogleMap? = null private val isApplicationReady: Boolean get() = isAdded && activity != null private val isLocationPermissionGranted: Boolean get() = activity?.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED // Add warning that data may be unreliable private val warningMessage: String get() = "\n\n" + getString(R.string.data_old) + "\n" + getString(R.string.data_unreliable) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentMainBinding.inflate(inflater, container, false) return binding.root } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (!isLocationPermissionGranted) { requestLocationPermission() } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding.mapView.onCreate(savedInstanceState) binding.mapView.onResume() binding.mapView.getMapAsync(this) } override fun onMapReady(map: GoogleMap) { // Store map in member variable mMap = map onMapReadyHandler() } private fun onMapReadyHandler() { if (isApplicationReady) { initPreferences() initMap() val isClusteringActivated = userSettings.getBoolean("isClusteringActivated", true) if (isClusteringActivated) { initClusterManager() } setInitialPosition() setInitialButtonState() setButtonBackground() restoreOptionalLayers() } } private fun initClusterManager() { // Load ClusterManager to the Map clusterManager = ClusterManager(context, mMap) // Set custom renderer clusterManager.renderer = IconRenderer( requireContext(), mMap!!, clusterManager ) } private fun initPreferences() { // Settings from the map buttons settings = requireContext().getSharedPreferences(PREFS_NAME, 0) // Settings from the menu userSettings = getDefaultSharedPreferences(context) } private fun initMap() { mMap!!.setMinZoomPreference(10f) setMapSettings() setMapBasemap() setMapTheme() initLocationButton() } private fun setMapTheme(){ when (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) { Configuration.UI_MODE_NIGHT_NO -> { // Night mode is not active, we're using the light theme try { mMap!!.setMapStyle(MapStyleOptions.loadRawResourceStyle(requireContext(), R.raw.light_style)) } catch (e: Resources.NotFoundException) { Log.e("Valenbisi", "Error parsing light map style", e) } } Configuration.UI_MODE_NIGHT_YES -> { // Night mode is active, we're using dark theme try { mMap!!.setMapStyle(MapStyleOptions.loadRawResourceStyle(requireContext(), R.raw.dark_style)) } catch (e: Resources.NotFoundException) { Log.e("Valenbisi", "Error parsing dark map style", e) } } } } private fun setMapSettings() { val mapSettings: UiSettings = mMap!!.uiSettings mapSettings.isZoomControlsEnabled = true mapSettings.isCompassEnabled = false mapSettings.isRotateGesturesEnabled = false mapSettings.isScrollGesturesEnabledDuringRotateOrZoom = false } private fun setMapBasemap() { val isSatellite = userSettings.getBoolean("isSatellite", false) if (!isSatellite) { mMap!!.mapType = GoogleMap.MAP_TYPE_NORMAL } else { mMap!!.mapType = GoogleMap.MAP_TYPE_HYBRID } } private fun requestLocationPermission(){ val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { setLocationButtonEnabled(true) } else { setLocationButtonEnabled(false) safeSnackBar(R.string.no_location_permission) } } requestPermissionLauncher.launch( Manifest.permission.ACCESS_FINE_LOCATION) } private fun initLocationButton() { if (isLocationPermissionGranted) { setLocationButtonEnabled(true) } else { setLocationButtonEnabled(false) safeSnackBar(R.string.no_location_permission) } } private fun setLocationButtonEnabled(mode: Boolean) { try { mMap!!.isMyLocationEnabled = mode } catch (e: SecurityException) { Log.e(LOG_TAG, e.message!!) } } private fun isValenciaArea(location: LatLng): Boolean { return (location.latitude in 39.420..39.515) && (location.longitude in -0.572..-0.272) } private fun setInitialPosition() { fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireContext()) if (isLocationPermissionGranted) { try { fusedLocationClient.lastLocation .addOnSuccessListener { location: Location? -> // Got last known location. In some rare situations this can be null. if (location != null) { val longitude = location.longitude val latitude = location.latitude val currentLocation = LatLng(latitude, longitude) moveToLocationOrValencia(currentLocation) } else { moveToLocationOrValencia() } } .addOnFailureListener { moveToLocationOrValencia() } } catch (e: SecurityException) { Log.e(LOG_TAG, e.message!!) } } else { moveToLocationOrValencia() } } private fun moveToLocationOrValencia(currentLocation: LatLng = LatLng(39.479, -0.372)) { val initialZoom = userSettings.getBoolean("initialZoom", true) if (isLocationPermissionGranted && initialZoom && isValenciaArea(currentLocation)) { mMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 16.0f)) } else { mMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(39.479, -0.372), 13.0f)) } } private fun restoreOptionalLayers() { val isStationsLayerAdded = settings.getBoolean("showStationsLayer", true) if (isStationsLayerAdded) { getStations() } val isDrawVoronoiCellsChecked = userSettings.getBoolean("voronoiCell", false) if (isDrawVoronoiCellsChecked) { drawVoronoiCells() } val isCarrilLayerAdded = settings.getBoolean("isCarrilLayerAdded", false) if (isCarrilLayerAdded) { getLanes() } val isDrawParkingSpotsChecked = settings.getBoolean("isParkingLayerAdded", false) if (isDrawParkingSpotsChecked) { getParkings() } if (!isStationsLayerAdded && !isCarrilLayerAdded && !isDrawParkingSpotsChecked) { setListeners() } } private fun drawVoronoiCells() { try { val voronoi = GeoJsonLayer(mMap, R.raw.voronoi, context) for (feature in voronoi.features) { val stringStyle = voronoi.defaultLineStringStyle stringStyle.color = -16776961 stringStyle.width = 2f feature.lineStringStyle = stringStyle } voronoi.addLayerToMap() } catch (e: JSONException) { Log.e(LOG_TAG, "JSONArray could not be created") } catch (e: IOException) { Log.e(LOG_TAG, "GeoJSON file could not be read") } } private fun getStations() { // Show loading message safeSnackBar(R.string.load_stations) val client = OkHttpClient() val url = "https://api.jcdecaux.com/vls/v1/stations?contract=Valence&apiKey=adcac2d5b367dacef9846586d12df1bf7e8c7fcd" val request = Request.Builder() .url(url) .build() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { Log.e(LOG_TAG, "error with http call(no internet?)") } override fun onResponse(call: Call, response: Response) { try { handleApiResponse(response) } catch (e: IOException) { Log.e(LOG_TAG, "error with http request") } finally { response.close() } } }) } private fun resetStationsLayer() { val isClusteringActivated = userSettings.getBoolean("isClusteringActivated", true) if (isClusteringActivated) { clusterManager.clearItems() clusterManager.cluster() } else { stations?.removeLayerFromMap() } } @Throws(IOException::class) private fun handleApiResponse(response: Response) { if (!response.isSuccessful) throw IOException("Unexpected code $response") val responseBody = response.body if (responseBody != null) { addDataToMap(responseBody.string()) } else { Log.e(LOG_TAG, "Empty server response") requireActivity().runOnUiThread { // Show message if API response is empty safeSnackBar(R.string.no_data) } } } private fun addDataToMap(jsonData: String) { val isClusteringActivated = userSettings.getBoolean("isClusteringActivated", true) if (isApplicationReady) { try { val jsonDataArray = JSONArray(jsonData) if (isClusteringActivated) { addPointsToCluster(jsonDataArray) requireActivity().runOnUiThread { clusterManager.cluster() } } else { addPointsToLayer(jsonDataArray) requireActivity().runOnUiThread { stations?.addLayerToMap() } } settings.edit().putBoolean("showStationsLayer", true).apply() setListeners() } catch (e: JSONException) { Log.e(LOG_TAG, "JSONArray could not be created") } } } @Throws(JSONException::class) private fun addPointsToCluster(jsonDataArray: JSONArray) { val showOnlyFavoriteStations = userSettings.getBoolean("showFavorites", false) // Parse data from API for (i in 0 until jsonDataArray.length()) { // Get current station val jsonStation = jsonDataArray.getJSONObject(i) var station = BikeStation(jsonStation) station = generateCompleteStationData(station) // If station is not favourite and "Display only favourites" is enabled-> Do not add station if (showOnlyFavoriteStations && !station.isFavourite) { continue } val clusterPoint = ClusterPoint(station) clusterManager.addItem(clusterPoint) } } @Throws(JSONException::class) private fun addPointsToLayer(jsonDataArray: JSONArray) { val showOnlyFavoriteStations = userSettings.getBoolean("showFavorites", false) val dummy = JSONObject() stations = GeoJsonLayer(mMap, dummy) // Parse data from API for (i in 0 until jsonDataArray.length()) { // Get current station val jsonStation = jsonDataArray.getJSONObject(i) var station = BikeStation(jsonStation) station = generateCompleteStationData(station) // If station is not favourite and "Display only favourites" is enabled-> Do not add station if (showOnlyFavoriteStations && !station.isFavourite) { continue } // Create Point val point = GeoJsonPoint(LatLng(station.lat, station.lng)) // Add properties val properties = getStationProperties(station) // Create feature val pointFeature = GeoJsonFeature(point, "Origin", properties, null) val pointStyle = generatePointStyle(station) pointFeature.pointStyle = pointStyle stations?.addFeature(pointFeature) } } private fun generateCompleteStationData(station: BikeStation): BikeStation { val showOnlyAvailableStations = userSettings.getBoolean("showAvailable", false) val isOnFoot = settings.getBoolean("isOnFoot", true) station.isFavourite = settings.getBoolean(station.address, false) if (station.status == "OPEN") { // Set markers colors depending on station availability station.icon = getMarkerIcon(isOnFoot, station.bikes, station.spots) // Get markers visibility depending on station availability if (showOnlyAvailableStations) { station.visibility = getMarkerVisibility(isOnFoot, station.bikes, station.spots) } station.snippet = getMarkerSnippet(station.bikes, station.spots, station.lastUpdate) } else { station.icon = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET) station.snippet = if (isAdded) getString(R.string.closed) else "" if (showOnlyAvailableStations) { station.visibility = false } } station.alpha = getMarkerAlpha(station.isFavourite) return station } private fun getStationProperties(station: BikeStation): HashMap<String, String> { val properties = HashMap<String, String>() properties["name"] = station.name properties["number"] = station.number properties["address"] = station.address properties["status"] = station.status properties["available_bike_stands"] = station.spots.toString() properties["available_bikes"] = station.bikes.toString() properties["last_updated"] = station.lastUpdate return properties } private fun generatePointStyle(station: BikeStation): GeoJsonPointStyle { val pointStyle = GeoJsonPointStyle() pointStyle.title = station.address pointStyle.snippet = station.snippet pointStyle.icon = station.icon pointStyle.alpha = station.alpha!! pointStyle.isVisible = station.visibility return pointStyle } private fun getMarkerIcon(isOnFoot: Boolean, bikes: Int, spots: Int): BitmapDescriptor { // Load default marker icons val iconGreen = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN) val iconOrange = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE) val iconYellow = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW) val iconRed = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED) return if (isOnFoot) { when (bikes) { 0 -> iconRed in 1..4 -> iconOrange in 5..9 -> iconYellow else -> iconGreen } } else { when (spots) { 0 -> iconRed in 1..4 -> iconOrange in 5..9 -> iconYellow else -> iconGreen } } } private fun getMarkerVisibility(isOnFoot: Boolean, bikes: Int, spots: Int): Boolean { var visibility: Boolean? = true if (isOnFoot && bikes == 0) { visibility = false } else if (spots == 0) { visibility = false } return visibility!! } private fun getMarkerSnippet(bikes: Int, spots: Int, lastUpdate: String): String { if (isApplicationReady) { val showLastUpdatedInfo = userSettings.getBoolean("lastUpdated", true) // Add number of available bikes/stands var snippet: String = getString(R.string.spots) + " " + spots + " - " + getString(R.string.bikes) + " " + bikes // Add last updated time if user has checked that option if (showLastUpdatedInfo) { snippet += getLastUpdatedInfo(lastUpdate) } // If data has not been updated for more than 1 hour if (millisecondsFrom(lastUpdate) > 3600000) { snippet += warningMessage } return snippet } return "" } private fun millisecondsFrom(event: String): Long { val eventTime = java.lang.Long.parseLong(event) val date = GregorianCalendar() val currentTime = date.timeInMillis return currentTime - eventTime } private fun getLastUpdatedInfo(lastUpdate: String): String { if (isApplicationReady) { val snippet: String val apiTime = java.lang.Long.parseLong(lastUpdate) val date = GregorianCalendar() // Set API time date.timeInMillis = apiTime // Format time as HH:mm:ss val sbu = StringBuilder() val fmt = Formatter(sbu) fmt.format("%tT", date.time) // Add to pointStyle snippet = "\n" + getString(R.string.last_updated) + " " + sbu return snippet } return "" } private fun getMarkerAlpha(currentStationIsFav: Boolean): Float { // Apply full opacity only to favourite stations return when (currentStationIsFav) { true -> 1.0f else -> 0.5f } } private fun setListeners() { setButtonListeners() setMapListeners() } private fun setInitialButtonState() { val stationsOn = ContextCompat.getDrawable(requireContext(), R.drawable.icon_map_marker) val stationsOff = ContextCompat.getDrawable(requireContext(), R.drawable.icon_map_marker_off) val bike = ContextCompat.getDrawable(requireContext(), R.drawable.icon_on_bike) val walk = ContextCompat.getDrawable(requireContext(), R.drawable.icon_walk) val bikeLanesOn = ContextCompat.getDrawable(requireContext(), R.drawable.icon_road) val bikeLanesOff = ContextCompat.getDrawable(requireContext(), R.drawable.icon_road_off) val parkingOn = ContextCompat.getDrawable(requireContext(), R.drawable.icon_parking) val parkingOff = ContextCompat.getDrawable(requireContext(), R.drawable.icon_parking_off) val showStationsLayer = settings.getBoolean("showStationsLayer", true) if (showStationsLayer) { binding.btnStationsToggle.icon = stationsOn } else { binding.btnStationsToggle.icon = stationsOff } val isCarrilLayerAdded = settings.getBoolean("isCarrilLayerAdded", false) if (isCarrilLayerAdded) { binding.btnLanesToggle.icon = bikeLanesOn } else { binding.btnLanesToggle.icon = bikeLanesOff } val isOnFoot = settings.getBoolean("isOnFoot", false) if (isOnFoot) { binding.btnOnFootToggle.icon = walk } else { binding.btnOnFootToggle.icon = bike } val isParkingLayerAdded = settings.getBoolean("isParkingLayerAdded", false) if (isParkingLayerAdded) { binding.btnParkingToggle.icon = parkingOn } else { binding.btnParkingToggle.icon = parkingOff } } private fun setButtonBackground() { binding.btnLanesToggle.background = ContextCompat.getDrawable(requireContext(), R.drawable.mapbutton_background) binding.btnStationsToggle.background = ContextCompat.getDrawable(requireContext(), R.drawable.mapbutton_background) binding.btnOnFootToggle.background = ContextCompat.getDrawable(requireContext(), R.drawable.mapbutton_background) binding.btnRefresh.background = ContextCompat.getDrawable(requireContext(), R.drawable.mapbutton_background) binding.btnParkingToggle.background = ContextCompat.getDrawable(requireContext(), R.drawable.mapbutton_background) } private fun setButtonListeners() { val bikeLanesOn = ContextCompat.getDrawable(requireContext(), R.drawable.icon_road) val bikeLanesOff = ContextCompat.getDrawable(requireContext(), R.drawable.icon_road_off) val parkingOn = ContextCompat.getDrawable(requireContext(), R.drawable.icon_parking) val parkingOff = ContextCompat.getDrawable(requireContext(), R.drawable.icon_parking_off) val bike = ContextCompat.getDrawable(requireContext(), R.drawable.icon_on_bike) val walk = ContextCompat.getDrawable(requireContext(), R.drawable.icon_walk) val stationsOn = ContextCompat.getDrawable(requireContext(), R.drawable.icon_map_marker) val stationsOff = ContextCompat.getDrawable(requireContext(), R.drawable.icon_map_marker_off) // Toggle bike lanes binding.btnLanesToggle.setOnClickListener { removeButtonListeners() if (!settings.getBoolean("isCarrilLayerAdded", false)) { binding.btnLanesToggle.icon = bikeLanesOn getLanes() } else { binding.btnLanesToggle.icon = bikeLanesOff lanes?.removeLayerFromMap() settings.edit().putBoolean("isCarrilLayerAdded", false).apply() setButtonListeners() } } // Toggle parking binding.btnParkingToggle.setOnClickListener { removeButtonListeners() if (!settings.getBoolean("isParkingLayerAdded", false)) { binding.btnParkingToggle.icon = parkingOn getParkings() } else { binding.btnParkingToggle.icon = parkingOff parking?.removeLayerFromMap() settings.edit().putBoolean("isParkingLayerAdded", false).apply() setButtonListeners() } } // Toggle stations binding.btnStationsToggle.setOnClickListener { removeButtonListeners() resetStationsLayer() if (settings.getBoolean("showStationsLayer", true)) { binding.btnStationsToggle.icon = stationsOff settings.edit().putBoolean("showStationsLayer", false).apply() setButtonListeners() } else { getStations() binding.btnStationsToggle.icon = stationsOn } } // Toggle onFoot/onBike binding.btnOnFootToggle.setOnClickListener { // If stations are visible, recalculate layer if (settings.getBoolean("showStationsLayer", true)) { removeButtonListeners() resetStationsLayer() if (settings.getBoolean("isOnFoot", false)) { settings.edit().putBoolean("isOnFoot", false).apply() binding.btnOnFootToggle.icon = bike getStations() } else { settings.edit().putBoolean("isOnFoot", true).apply() binding.btnOnFootToggle.icon = walk getStations() } // Else just change the button icon and the setting } else { if (settings.getBoolean("isOnFoot", false)) { settings.edit().putBoolean("isOnFoot", false).apply() binding.btnOnFootToggle.icon = bike } else { settings.edit().putBoolean("isOnFoot", true).apply() binding.btnOnFootToggle.icon = walk } } } // Reload bike station data binding.btnRefresh.setOnClickListener { removeButtonListeners() binding.btnStationsToggle.icon = stationsOn if (settings.getBoolean("showStationsLayer", true)) { resetStationsLayer() } getStations() } } private fun removeButtonListeners() { binding.btnLanesToggle.setOnClickListener(null) binding.btnOnFootToggle.setOnClickListener(null) binding.btnParkingToggle.setOnClickListener(null) binding.btnRefresh.setOnClickListener(null) binding.btnStationsToggle.setOnClickListener(null) } private fun setMapListeners() { val isClusteringActivated = userSettings.getBoolean("isClusteringActivated", true) requireActivity().runOnUiThread { if (isClusteringActivated) { setClusteredInfoWindow() mMap!!.apply { setOnMarkerClickListener(clusterManager) setOnInfoWindowClickListener(clusterManager) setInfoWindowAdapter(clusterManager.markerManager) setOnCameraIdleListener(clusterManager) } clusterManager.setOnClusterClickListener { cluster -> val zoom = mMap!!.cameraPosition.zoom val position = cluster.position mMap!!.animateCamera( CameraUpdateFactory.newLatLngZoom(position, zoom + 1.0.toFloat()), 250, null ) true } } else { setNormalInfoWindow() } } } @SuppressLint("PotentialBehaviorOverride") private fun setNormalInfoWindow() { mMap!!.setInfoWindowAdapter(object : GoogleMap.InfoWindowAdapter { // Use default InfoWindow frame override fun getInfoWindow(marker: Marker): View { return getInfoWindowCommonInfo(marker) } // Defines the contents of the InfoWindow override fun getInfoContents(marker: Marker): View? { return null } }) mMap!!.setOnInfoWindowClickListener { clickedMarker -> val currentStationIsFav = settings.getBoolean(clickedMarker.title, false) val showFavorites = userSettings.getBoolean("showFavorites", false) if (currentStationIsFav) { clickedMarker.alpha = 0.5f if (showFavorites) { clickedMarker.isVisible = false } settings.edit().putBoolean(clickedMarker.title, false).apply() } else { clickedMarker.alpha = 1f settings.edit().putBoolean(clickedMarker.title, true).apply() } clickedMarker.showInfoWindow() } } private fun setClusteredInfoWindow() { val markerCollection = clusterManager.markerCollection val infoWindowAdapter = object : GoogleMap.InfoWindowAdapter { // Use default InfoWindow frame override fun getInfoWindow(marker: Marker): View { // Getting view from the layout file info_window_layout return getInfoWindowCommonInfo(marker) } // Defines the contents of the InfoWindow override fun getInfoContents(marker: Marker): View? { return null } } markerCollection.setInfoWindowAdapter(infoWindowAdapter) markerCollection.setOnInfoWindowClickListener { clickedMarker -> val currentStationIsFav = settings.getBoolean(clickedMarker.title, false) val showFavorites = userSettings.getBoolean("showFavorites", false) if (currentStationIsFav) { clickedMarker.alpha = 0.5f if (showFavorites) { clickedMarker.isVisible = false } settings.edit().putBoolean(clickedMarker.title, false).apply() } else { clickedMarker.alpha = 1f settings.edit().putBoolean(clickedMarker.title, true).apply() } clickedMarker.showInfoWindow() } } private fun getBackgroundColor(): Int { var color = R.color.white when ((resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK)) { Configuration.UI_MODE_NIGHT_NO -> { color = R.color.white } Configuration.UI_MODE_NIGHT_YES -> { color = R.color.black } } return color } @SuppressLint("InflateParams") private fun getInfoWindowCommonInfo(marker: Marker): View { val starIconOff = ContextCompat.getDrawable(requireContext(), R.drawable.icon_star_outline) val startIconOn = ContextCompat.getDrawable(requireContext(), R.drawable.icon_star) // Getting view from the layout file info_window_layout val popup = requireActivity().layoutInflater.inflate(R.layout.marker_popup, null) popup.setBackgroundColor(ContextCompat.getColor(requireContext(), getBackgroundColor())) // Getting reference to the ImageView/title/snippet val title = popup.findViewById<TextView>(R.id.title) val snippet = popup.findViewById<TextView>(R.id.snippet) val btnStar = popup.findViewById<ImageView>(R.id.btn_star) if (marker.snippet!!.contains("\n\n")) { snippet.setTextColor(ContextCompat.getColor(requireContext(), R.color.red)) snippet.setTypeface(null, Typeface.BOLD) snippet.text = marker.snippet } else { snippet.text = marker.snippet } title.text = marker.title // Checking if current station is favorite val currentStationIsFav = settings.getBoolean(marker.title, false) // Setting correspondent icon if (currentStationIsFav) { btnStar.setImageDrawable(startIconOn) } else { btnStar.setImageDrawable(starIconOff) } return popup } private fun safeSnackBar(stringReference: Int) { binding.mainView.let { val snack = Snackbar.make(binding.mainView, stringReference, Snackbar.LENGTH_SHORT) // Necessary to display snackbar over bottom navigation bar val params = snack.view.layoutParams as CoordinatorLayout.LayoutParams params.anchorId = R.id.bottom_navigation_view params.anchorGravity = Gravity.TOP params.gravity = Gravity.TOP snack.view.layoutParams = params snack.show() } } private fun getLanes() { safeSnackBar(R.string.load_lanes) launch { getLanesAsync() // Has to run on the main thread lanes?.addLayerToMap() settings.edit().putBoolean("isCarrilLayerAdded", true).apply() setListeners() } } private suspend fun getLanesAsync() { try { withContext(Dispatchers.IO) { lanes = GeoJsonLayer(mMap, R.raw.bike_lanes, context) for (feature in lanes!!.features) { val stringStyle = GeoJsonLineStringStyle() stringStyle.width = 5f if (userSettings.getBoolean("cicloCalles", true)) { stringStyle.color = getLaneColor(feature) } feature.lineStringStyle = stringStyle } } } catch (e: IOException) { Log.e(LOG_TAG, "GeoJSON file could not be read") } catch (e: JSONException) { Log.e(LOG_TAG, "GeoJSON file could not be converted to a JSONObject") } } private fun getLaneColor(feature: GeoJsonFeature): Int { var color = Color.BLACK if(resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES){ color = Color.WHITE } return when (feature.getProperty("estado")) { // Normal bike lane "1" -> color // Ciclocalle "2" -> Color.BLUE // Weird fragments "3" -> Color.BLUE // River "4" -> color else -> Color.RED } } private fun getParkings() { safeSnackBar(R.string.load_parking) launch { getParkingsAsync() // Has to run on the main thread parking?.addLayerToMap() settings.edit().putBoolean("isParkingLayerAdded", true).apply() setListeners() } } private suspend fun getParkingsAsync() { val showFavorites = userSettings.getBoolean("showFavorites", false) var bitmap = BitmapFactory.decodeResource(resources, R.drawable.ic_map_marker_circle) bitmap = Bitmap.createScaledBitmap(bitmap, 50, 50, false) val iconParking = BitmapDescriptorFactory.fromBitmap(bitmap) if (isApplicationReady) { try { withContext(Dispatchers.IO) { parking = GeoJsonLayer(mMap, R.raw.aparcabicis, context) for (feature in parking!!.features) { val pointStyle = GeoJsonPointStyle() pointStyle.title = getString(R.string.parking) + " " + feature.getProperty("id") pointStyle.snippet = getString(R.string.plazas) + " " + feature.getProperty("plazas") pointStyle.alpha = 0.5f pointStyle.icon = iconParking val currentStationIsFav = settings.getBoolean(pointStyle.title, false) // Apply full opacity to fav stations if (currentStationIsFav) { pointStyle.alpha = 1f } // If favorites are selected, hide the rest if (showFavorites) { if (!currentStationIsFav) { pointStyle.isVisible = false } } feature.pointStyle = pointStyle } } } catch (e: IOException) { Log.e(LOG_TAG, "GeoJSON file could not be read") } catch (e: JSONException) { Log.e(LOG_TAG, "GeoJSON file could not be converted to a JSONObject") } } } override fun onPause() { super.onPause() if (isApplicationReady && mMap != null) { // Disable location to avoid battery drain setLocationButtonEnabled(false) } } override fun onDestroy() { super.onDestroy() if (isApplicationReady && mMap != null) { // Disable location to avoid battery drain setLocationButtonEnabled(false) } } override fun onResume() { super.onResume() if (isApplicationReady && isLocationPermissionGranted && mMap != null) { // Re-enable location setLocationButtonEnabled(true) } } }
gpl-3.0
fa94ef67c38884e2ecea7e201e61e5e8
35.92155
124
0.59852
5.133789
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/chatchannel/format/part/ChannelPart.kt
1
2881
/* * Copyright 2022 Ren Binden * * 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.rpkit.chat.bukkit.chatchannel.format.part import com.rpkit.chat.bukkit.RPKChatBukkit import com.rpkit.chat.bukkit.chatchannel.format.click.ClickAction import com.rpkit.chat.bukkit.chatchannel.format.hover.HoverAction import com.rpkit.chat.bukkit.context.DirectedPreFormatMessageContext import org.bukkit.Bukkit import org.bukkit.configuration.serialization.ConfigurationSerializable import org.bukkit.configuration.serialization.SerializableAs import java.util.concurrent.CompletableFuture.completedFuture @SerializableAs("ChannelPart") class ChannelPart( plugin: RPKChatBukkit, font: String? = null, color: String? = null, isBold: Boolean? = null, isItalic: Boolean? = null, isUnderlined: Boolean? = null, isStrikethrough: Boolean? = null, isObfuscated: Boolean? = null, insertion: String? = null, hover: HoverAction? = null, click: ClickAction? = null ) : GenericTextPart( plugin, font, color, isBold, isItalic, isUnderlined, isStrikethrough, isObfuscated, insertion, hover, click ), ConfigurationSerializable { override fun getText(context: DirectedPreFormatMessageContext) = completedFuture(context.chatChannel.name.value) override fun serialize() = mutableMapOf( "font" to font, "color" to color, "bold" to isBold, "italic" to isItalic, "underlined" to isUnderlined, "strikethrough" to isStrikethrough, "obfuscated" to isObfuscated, "insertion" to insertion, "hover" to hover, "click" to click ) companion object { @JvmStatic fun deserialize(serialized: Map<String, Any>) = ChannelPart( Bukkit.getPluginManager().getPlugin("rpk-chat-bukkit") as RPKChatBukkit, serialized["font"] as? String, serialized["color"] as? String, serialized["bold"] as? Boolean, serialized["italic"] as? Boolean, serialized["underlined"] as? Boolean, serialized["strikethrough"] as? Boolean, serialized["obfuscated"] as? Boolean, serialized["insertion"] as? String, serialized["hover"] as? HoverAction, serialized["click"] as? ClickAction ) } }
apache-2.0
db5d4db8b44bd463186ae5a260fd92c3
32.511628
116
0.685873
4.508607
false
false
false
false
cketti/k-9
app/k9mail/src/main/java/com/fsck/k9/widget/unread/UnreadWidgetConfigurationFragment.kt
1
9141
package com.fsck.k9.widget.unread import android.app.Activity import android.appwidget.AppWidgetManager import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.widget.Toast import androidx.core.os.bundleOf import androidx.preference.CheckBoxPreference import androidx.preference.Preference import com.fsck.k9.Preferences import com.fsck.k9.R import com.fsck.k9.activity.ChooseAccount import com.fsck.k9.search.SearchAccount import com.fsck.k9.ui.choosefolder.ChooseFolderActivity import com.takisoft.preferencex.PreferenceFragmentCompat import org.koin.android.ext.android.inject import com.fsck.k9.ui.R as UiR class UnreadWidgetConfigurationFragment : PreferenceFragmentCompat() { private val preferences: Preferences by inject() private val repository: UnreadWidgetRepository by inject() private val unreadWidgetUpdater: UnreadWidgetUpdater by inject() private var appWidgetId: Int = AppWidgetManager.INVALID_APPWIDGET_ID private lateinit var unreadAccount: Preference private lateinit var unreadFolderEnabled: CheckBoxPreference private lateinit var unreadFolder: Preference private var selectedAccountUuid: String? = null private var selectedFolderId: Long? = null private var selectedFolderDisplayName: String? = null override fun onCreatePreferencesFix(savedInstanceState: Bundle?, rootKey: String?) { setHasOptionsMenu(true) setPreferencesFromResource(R.xml.unread_widget_configuration, rootKey) appWidgetId = arguments?.getInt(ARGUMENT_APP_WIDGET_ID) ?: error("Missing argument '$ARGUMENT_APP_WIDGET_ID'") unreadAccount = findPreference(PREFERENCE_UNREAD_ACCOUNT)!! unreadAccount.onPreferenceClickListener = Preference.OnPreferenceClickListener { val intent = Intent(requireContext(), ChooseAccount::class.java) startActivityForResult(intent, REQUEST_CHOOSE_ACCOUNT) false } unreadFolderEnabled = findPreference(PREFERENCE_UNREAD_FOLDER_ENABLED)!! unreadFolderEnabled.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, _ -> unreadFolder.summary = getString(UiR.string.unread_widget_folder_summary) selectedFolderId = null selectedFolderDisplayName = null true } unreadFolder = findPreference(PREFERENCE_UNREAD_FOLDER)!! unreadFolder.onPreferenceClickListener = Preference.OnPreferenceClickListener { val intent = ChooseFolderActivity.buildLaunchIntent( context = requireContext(), action = ChooseFolderActivity.Action.CHOOSE, accountUuid = selectedAccountUuid!!, showDisplayableOnly = true ) startActivityForResult(intent, REQUEST_CHOOSE_FOLDER) false } if (savedInstanceState != null) { restoreInstanceState(savedInstanceState) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(STATE_SELECTED_ACCOUNT_UUID, selectedAccountUuid) outState.putLongIfPresent(STATE_SELECTED_FOLDER_ID, selectedFolderId) outState.putString(STATE_SELECTED_FOLDER_DISPLAY_NAME, selectedFolderDisplayName) } private fun restoreInstanceState(savedInstanceState: Bundle) { val accountUuid = savedInstanceState.getString(STATE_SELECTED_ACCOUNT_UUID) if (accountUuid != null) { handleChooseAccount(accountUuid) val folderId = savedInstanceState.getLongOrNull(STATE_SELECTED_FOLDER_ID) val folderSummary = savedInstanceState.getString(STATE_SELECTED_FOLDER_DISPLAY_NAME) if (folderId != null && folderSummary != null) { handleChooseFolder(folderId, folderSummary) } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode == Activity.RESULT_OK && data != null) { when (requestCode) { REQUEST_CHOOSE_ACCOUNT -> { val accountUuid = data.getStringExtra(ChooseAccount.EXTRA_ACCOUNT_UUID)!! handleChooseAccount(accountUuid) } REQUEST_CHOOSE_FOLDER -> { val folderId = data.getLongExtra(ChooseFolderActivity.RESULT_SELECTED_FOLDER_ID, -1L) val folderDisplayName = data.getStringExtra(ChooseFolderActivity.RESULT_FOLDER_DISPLAY_NAME)!! handleChooseFolder(folderId, folderDisplayName) } } } super.onActivityResult(requestCode, resultCode, data) } private fun handleChooseAccount(accountUuid: String) { val userSelectedSameAccount = accountUuid == selectedAccountUuid if (userSelectedSameAccount) { return } selectedAccountUuid = accountUuid selectedFolderId = null selectedFolderDisplayName = null unreadFolder.summary = getString(UiR.string.unread_widget_folder_summary) if (SearchAccount.UNIFIED_INBOX == selectedAccountUuid) { handleSearchAccount() } else { handleRegularAccount() } } private fun handleSearchAccount() { if (SearchAccount.UNIFIED_INBOX == selectedAccountUuid) { unreadAccount.setSummary(UiR.string.unread_widget_unified_inbox_account_summary) } unreadFolderEnabled.isEnabled = false unreadFolderEnabled.isChecked = false unreadFolder.isEnabled = false selectedFolderId = null selectedFolderDisplayName = null } private fun handleRegularAccount() { val selectedAccount = preferences.getAccount(selectedAccountUuid!!) ?: error("Account $selectedAccountUuid not found") unreadAccount.summary = selectedAccount.displayName unreadFolderEnabled.isEnabled = true unreadFolder.isEnabled = true } private fun handleChooseFolder(folderId: Long, folderDisplayName: String) { selectedFolderId = folderId selectedFolderDisplayName = folderDisplayName unreadFolder.summary = folderDisplayName } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.unread_widget_option, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.done -> { if (validateWidget()) { updateWidgetAndExit() } true } else -> super.onOptionsItemSelected(item) } } private fun validateWidget(): Boolean { if (selectedAccountUuid == null) { Toast.makeText(requireContext(), UiR.string.unread_widget_account_not_selected, Toast.LENGTH_LONG).show() return false } else if (unreadFolderEnabled.isChecked && selectedFolderId == null) { Toast.makeText(requireContext(), UiR.string.unread_widget_folder_not_selected, Toast.LENGTH_LONG).show() return false } return true } private fun updateWidgetAndExit() { val configuration = UnreadWidgetConfiguration(appWidgetId, selectedAccountUuid!!, selectedFolderId) repository.saveWidgetConfiguration(configuration) unreadWidgetUpdater.update(appWidgetId) // Let the caller know that the configuration was successful val resultValue = Intent() resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) val activity = requireActivity() activity.setResult(Activity.RESULT_OK, resultValue) activity.finish() } private fun Bundle.putLongIfPresent(key: String, value: Long?) { if (value != null) { putLong(key, value) } } private fun Bundle.getLongOrNull(key: String): Long? { return if (containsKey(key)) getLong(key) else null } companion object { private const val ARGUMENT_APP_WIDGET_ID = "app_widget_id" private const val PREFERENCE_UNREAD_ACCOUNT = "unread_account" private const val PREFERENCE_UNREAD_FOLDER_ENABLED = "unread_folder_enabled" private const val PREFERENCE_UNREAD_FOLDER = "unread_folder" private const val REQUEST_CHOOSE_ACCOUNT = 1 private const val REQUEST_CHOOSE_FOLDER = 2 private const val STATE_SELECTED_ACCOUNT_UUID = "com.fsck.k9.widget.unread.selectedAccountUuid" private const val STATE_SELECTED_FOLDER_ID = "com.fsck.k9.widget.unread.selectedFolderId" private const val STATE_SELECTED_FOLDER_DISPLAY_NAME = "com.fsck.k9.widget.unread.selectedFolderDisplayName" fun create(appWidgetId: Int): UnreadWidgetConfigurationFragment { return UnreadWidgetConfigurationFragment().apply { arguments = bundleOf(ARGUMENT_APP_WIDGET_ID to appWidgetId) } } } }
apache-2.0
9459ea7773877ca2c7cbef7c941a6cba
39.446903
118
0.682201
5.37074
false
false
false
false
nickthecoder/tickle
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/util/ImageParameter.kt
1
2394
/* Tickle Copyright (C) 2017 Nick Robinson 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 uk.co.nickthecoder.tickle.editor.util import javafx.geometry.Rectangle2D import javafx.scene.Node import javafx.scene.image.Image import javafx.scene.image.ImageView import uk.co.nickthecoder.paratask.parameters.AbstractParameter import uk.co.nickthecoder.paratask.parameters.ParameterEvent import uk.co.nickthecoder.paratask.parameters.ParameterEventType import uk.co.nickthecoder.paratask.parameters.ParameterListener import uk.co.nickthecoder.paratask.parameters.fields.ParameterField import uk.co.nickthecoder.paratask.util.uncamel class ImageParameter( name: String, label: String = name.uncamel(), description: String = "", val image: Image, val fieldFactory: (ImageParameter) -> ParameterField = { ImageParameterField(it) }) : AbstractParameter(name, label, description) { var viewPort: Rectangle2D? = null set(v) { field = v parameterListeners.fireStructureChanged(this) } override fun isStretchy() = false override fun errorMessage() = null override fun createField() = fieldFactory(this).build() override fun copy() = ImageParameter(name, label, description, image) } open class ImageParameterField(val imageParameter: ImageParameter) : ParameterField(imageParameter), ParameterListener { val imageView = ImageView(imageParameter.image) open override fun createControl(): Node { imageView.viewportProperty().set(imageParameter.viewPort) return imageView } open override fun parameterChanged(event: ParameterEvent) { if (event.type == ParameterEventType.STRUCTURAL) { imageView.viewportProperty().set(imageParameter.viewPort) } } }
gpl-3.0
a646b32c88b02161579bfe5e52f9a59f
32.25
91
0.745196
4.449814
false
false
false
false
luhaoaimama1/AndroidZone
JavaTest_Zone/src/kt/Test.kt
1
7278
package kt import kotlin.properties.Delegates import kotlin.reflect.KProperty /** * Created by fuzhipeng on 2018/7/9. */ fun main(args: Array<String>) { for (i in 0..1) { println("ga:$i") } // loop() // other() // whenStudy() // 解构() // mapLoop() // delege范例() // 方法引用(numbers) // 扩展方法() // list常用方法() // val list = listOf("args:", args) // println(list) // var list = ArrayList<Int>() // list.add(1) // list.add(2) // list.add(3) // var list2 = list // list.clear() // println(list2) // if(null is String) // print("heieh") // else // print("222") // listOf<Float>(-251F,-242F,-119F,-35F,23F,27F,23F,9.6F,0F).forEach { // print("${MathUtils.linearMap(it ,-251F,0F,-1080F,0F)},") // } } object MathUtils { // t, tMin, tMax, value1, value2 fun linearMap(srcNow: Float, src1: Float, src2: Float, dst1: Float, dst2: Float): Float { return (srcNow - src1) * (dst2 - dst1) / (src2 - src1) + dst1 } fun linearMap(srcNow: Double, src1: Double, src2: Double, dst1: Double, dst2: Double): Double { return (srcNow - src1) * (dst2 - dst1) / (src2 - src1) + dst1 } } private fun list常用方法() { val numbers = listOf<Int>(100, -1, 2, 3, 4); //过滤 println(numbers.filter { it > 0 }.toString()) val isTrue: (Int) -> Boolean = { it > 0 } //整体判定 println("any ||的意思->" + numbers.any(isTrue).toString()) println("all &&的意思->" + numbers.all(isTrue).toString()) //find println("find 返回的是元素 而不是index->" + numbers.find(isTrue).toString()) println("count 个数->" + numbers.count(isTrue).toString()) //大小 listOf(1, 42, 4).max() == 42 listOf("a", "ab").minBy { it.length } == "a" //统计 和 listOf(1, 5, 3).sum() == 9 listOf("a", "b", "cc").sumBy { it.length } == 4 //排序 listOf("bbb", "a", "cc").sorted() == listOf("a", "bbb", "cc") listOf("bbb", "a", "cc").sortedBy { it.length } == listOf("a", "cc", "bbb") //转化 println("flatMap 分裂 后合并->" + listOf("abc", "12").flatMap { it.toList() }) //分组 listOf("a", "b", "ba", "ccc", "ad").groupBy { it.length } //分裂 val numbers4 = listOf(1, 3, -4, 2, -11) val (positive, negative) = numbers4.partition { it > 0 } positive == listOf(1, 3, 2) negative == listOf(-4, -11) } private fun 扩展方法() { println(Pair(1, 3).sum_()) } fun Int.sum_():Boolean=this % 2 == 0 fun Int.sum_2():Boolean{ return this % 2 == 0 } val sum2: Int.() -> Boolean = { this % 2 == 0 } fun Pair<Int, Int>.sum_(): Int = first + second private fun 方法引用(numbers: List<Int>) { numbers.filter(::isOdd) numbers.filter(fun(x: Int): Boolean = x % 2 == 1) numbers.filter { x -> x % 2 == 1 } numbers.filter { x -> x % 2 == 1 } val compose = compose(::length, ::isOdd) println("zone:" + compose("zone")) } fun isOdd(value: Int) = value % 2 == 1; fun length(s: String) = s.length fun <A, B, C> compose(g: (A) -> B, f: (B) -> C): (A) -> C { return { x -> f(g(x)) } } private fun delege范例() { var example = Example() println(example.name) example.name = "哈哈" var lazyObj = LazyExample() println("------------") println(lazyObj.name) println(lazyObj.name) var observeObj = ObserveExample() println("------------") observeObj.name = "wakaka" observeObj.name = "安静" val user = User() // user.name //-> IllegalStateException user.init("Carl") println(user.name) var userMap = UserMap(mapOf( "name" to "zone", "skill" to 222, "skill2" to "大大大2" )); println(userMap) println("name :${userMap.name} \t skill :${userMap.skill}") } data class UserMap(val map: Map<String, Any?>) { val name: String by map val skill: Int by map } class User { var name: String by Delegates.notNull() fun init(name: String) { this.name = name } } class ObserveExample { var name by Delegates.observable("what?") { property, oldValue, newValue -> println("${property.toString()} - $oldValue - $newValue") } } class LazyExample { val name by lazy { println("懒加载初始化中") "zone" } } class Example { var name: String by Delegate() } class Delegate { operator fun getValue(thisRef: Any?, prop: KProperty<*>): String { return "$thisRef, thank you for delegating '${prop.name}' to me!" } operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: String) { println("$value has been assigned to ${prop.name} in $thisRef") } } private fun mapLoop() { var map = hashMapOf<String, String>() map.put("haha", "gaga") map.put("?", "_") // for (mutableEntry in map) // mutableEntry可以解构 for ((key, value) in map) { println("{key=$key,value=$value}") } } private fun 解构() { val (name, skills) = Animal("鸭子", "嗑瓜子") val (name2, skills2) = Animal2("鸭子", "嗑瓜子") print("name:$name \t name2:$name2") print("skills:$skills \t skills2:$skills2") println(Animal("鸭子", "嗑瓜子")) var ani = Animal("鸭子", "嗑瓜子") var ani2 = ani.copy(skills = "嗑瓜子2") println("真的相等吗:${ani === ani2} ani skills=${ani.skills} \t copy skills=${ani2.skills}") var ani3 = ani.copy() println("copy 不改名字 equal?${ani3.equals(ani)}") } private fun other() { println(MB::name.get()) Student("Lucky").showName() println(Utils.max(1, 2)) println("空吗->${Utils.parseInt("干啥?")}") println("空吗2->${Utils.getStringLength("Lucky")}") } private fun loop() { var args2 = listOf<String>("1", "2"); println("Hello:${args2[0]}") for (s in args2) { println("嘿嘿:$s!") } for (s in args2.indices) { print("\t ${args2[s]}") } println() for (i in 1 until 10) { print("\t $i") } println() val array = arrayListOf<String>() array.add("1") array.add("2") if (10 in 1..10) print("10在区间内吗") } private fun whenStudy() { Utils.case(1) Utils.case(4) Utils.case("abc") Utils.case(Student("Lucky")) } class Student(val name: String) { fun showName() = print("我的名字:$name") } object Utils { fun max(a: Int, b: Int) = if (a > b) a else b fun parseInt(str: String): Int? { try { return str.toInt() } catch(e: Exception) { return null; } } fun getStringLength(obj: Any): Int? { if (obj is String) return obj.length return null } fun case(obj: Any) { when (obj) { 1 -> println("1") in 3..5 -> println("在3-5里") is String -> println("是字符串") else -> println("是其他类型") } } } data class Animal(val name: String, val skills: String) class Animal2(val name: String, val skills: String) { operator fun component1() = name operator fun component2() = skills }
epl-1.0
79e3f1a1e363cf663c3f59a93a2cac3e
21.271565
99
0.545337
3.030435
false
false
false
false
kittinunf/ReactiveAndroid
reactiveandroid-ui/src/main/kotlin/com/github/kittinunf/reactiveandroid/view/ViewGroupEvent.kt
1
4349
package com.github.kittinunf.reactiveandroid.view import android.view.View import android.view.ViewGroup import android.view.animation.Animation import com.github.kittinunf.reactiveandroid.ExtensionFieldDelegate import com.github.kittinunf.reactiveandroid.subscription.AndroidMainThreadSubscription import io.reactivex.Observable //================================================================================ // Events //================================================================================ fun ViewGroup.rx_animationRepeat(): Observable<Animation> { return Observable.create { subscriber -> _layout_animation.onAnimationRepeat { if (it != null) subscriber.onNext(it) } subscriber.setDisposable(AndroidMainThreadSubscription { layoutAnimationListener = null }) } } fun ViewGroup.rx_animationEnd(): Observable<Animation> { return Observable.create { subscriber -> _layout_animation.onAnimationEnd { if (it != null) subscriber.onNext(it) } subscriber.setDisposable(AndroidMainThreadSubscription { layoutAnimationListener = null }) } } fun ViewGroup.rx_animationStart(): Observable<Animation> { return Observable.create { subscriber -> _layout_animation.onAnimationStart { if (it != null) subscriber.onNext(it) } subscriber.setDisposable(AndroidMainThreadSubscription { layoutAnimationListener = null }) } } data class HierarchyChangeListener(val parent: View?, val child: View?) fun ViewGroup.rx_childViewRemoved(): Observable<HierarchyChangeListener> { return Observable.create { subscriber -> _hierarchyChange.onChildViewRemoved { parent, child -> subscriber.onNext(HierarchyChangeListener(parent, child)) } subscriber.setDisposable(AndroidMainThreadSubscription { setOnHierarchyChangeListener(null) }) } } fun ViewGroup.rx_childViewAdded(): Observable<HierarchyChangeListener> { return Observable.create { subscriber -> _hierarchyChange.onChildViewAdded { parent, child -> subscriber.onNext(HierarchyChangeListener(parent, child)) } subscriber.setDisposable(AndroidMainThreadSubscription { setOnHierarchyChangeListener(null) }) } } private val ViewGroup._hierarchyChange: _ViewGroup_OnHierarchyChangeListener by ExtensionFieldDelegate({ _ViewGroup_OnHierarchyChangeListener() }, { setOnHierarchyChangeListener(it) }) internal class _ViewGroup_OnHierarchyChangeListener : ViewGroup.OnHierarchyChangeListener { private var onChildViewRemoved: ((View?, View?) -> Unit)? = null private var onChildViewAdded: ((View?, View?) -> Unit)? = null fun onChildViewRemoved(listener: (View?, View?) -> Unit) { onChildViewRemoved = listener } fun onChildViewAdded(listener: (View?, View?) -> Unit) { onChildViewAdded = listener } override fun onChildViewRemoved(parent: View?, child: View?) { onChildViewRemoved?.invoke(parent, child) } override fun onChildViewAdded(parent: View?, child: View?) { onChildViewAdded?.invoke(parent, child) } } private val ViewGroup._layout_animation: _ViewGroup_AnimationListener by ExtensionFieldDelegate({ _ViewGroup_AnimationListener() }, { layoutAnimationListener = it }) internal class _ViewGroup_AnimationListener : Animation.AnimationListener { private var onAnimationRepeat: ((Animation?) -> Unit)? = null private var onAnimationEnd: ((Animation?) -> Unit)? = null private var onAnimationStart: ((Animation?) -> Unit)? = null fun onAnimationRepeat(listener: (Animation?) -> Unit) { onAnimationRepeat = listener } fun onAnimationEnd(listener: (Animation?) -> Unit) { onAnimationEnd = listener } fun onAnimationStart(listener: (Animation?) -> Unit) { onAnimationStart = listener } override fun onAnimationRepeat(animation: Animation?) { onAnimationRepeat?.invoke(animation) } override fun onAnimationEnd(animation: Animation?) { onAnimationEnd?.invoke(animation) } override fun onAnimationStart(animation: Animation?) { onAnimationStart?.invoke(animation) } }
mit
b5b2e1e4a9c8158af9a9780e0c9fa9e2
30.514493
115
0.66705
5.519036
false
false
false
false
luxons/seven-wonders
sw-common-model/src/commonMain/kotlin/org/luxons/sevenwonders/model/cards/Cards.kt
1
2996
package org.luxons.sevenwonders.model.cards import kotlinx.serialization.Serializable import org.luxons.sevenwonders.model.boards.Requirements import org.luxons.sevenwonders.model.resources.ResourceTransactionOptions import org.luxons.sevenwonders.model.resources.singleOptionNoTransactionNeeded interface Card { val name: String val color: Color val requirements: Requirements val chainParent: String? val chainChildren: List<String> val image: String val back: CardBack } @Serializable data class TableCard( override val name: String, override val color: Color, override val requirements: Requirements, override val chainParent: String?, override val chainChildren: List<String>, override val image: String, override val back: CardBack, val playedDuringLastMove: Boolean, ) : Card /** * A card with contextual information relative to the hand it is sitting in. The extra information is especially useful * because it frees the client from a painful business logic implementation. */ @Serializable data class HandCard( override val name: String, override val color: Color, override val requirements: Requirements, override val chainParent: String?, override val chainChildren: List<String>, override val image: String, override val back: CardBack, val playability: CardPlayability, ) : Card @Serializable data class PreparedCard( val username: String, val cardBack: CardBack?, ) @Serializable data class CardBack(val image: String) enum class PlayabilityLevel(val message: String) { CHAINABLE("free because of a card on the board"), NO_REQUIREMENTS("free"), SPECIAL_FREE("free because of a special ability"), ENOUGH_RESOURCES("free"), ENOUGH_GOLD("enough gold"), ENOUGH_GOLD_AND_RES("enough gold and resources"), REQUIRES_HELP("requires buying resources"), MISSING_REQUIRED_GOLD("not enough gold"), MISSING_GOLD_FOR_RES("not enough gold to buy resources"), UNAVAILABLE_RESOURCES("missing resources that even neighbours don't have"), ALREADY_PLAYED("card already played"), WONDER_FULLY_BUILT("all wonder levels are already built"), } enum class Color(val isResource: Boolean) { BROWN(true), GREY(true), YELLOW(false), BLUE(false), GREEN(false), RED(false), PURPLE(false), } @Serializable data class CardPlayability( val isPlayable: Boolean, val isChainable: Boolean = false, val minPrice: Int = Int.MAX_VALUE, val transactionOptions: ResourceTransactionOptions = singleOptionNoTransactionNeeded(), val playabilityLevel: PlayabilityLevel, ) { val isFree: Boolean = minPrice == 0 companion object { val SPECIAL_FREE = CardPlayability( isPlayable = true, isChainable = false, minPrice = 0, transactionOptions = singleOptionNoTransactionNeeded(), playabilityLevel = PlayabilityLevel.SPECIAL_FREE, ) } }
mit
e653bb7e3044665c33fcaeb6d0936ca1
29.262626
119
0.718291
4.243626
false
false
false
false
LorittaBot/Loritta
web/dashboard/spicy-frontend/src/jsMain/kotlin/net/perfectdreams/loritta/cinnamon/dashboard/frontend/components/LocalizedText.kt
1
3236
package net.perfectdreams.loritta.cinnamon.dashboard.frontend.components import androidx.compose.runtime.Composable import net.perfectdreams.i18nhelper.core.I18nContext import net.perfectdreams.i18nhelper.core.keydata.StringI18nData import net.perfectdreams.loritta.cinnamon.dashboard.frontend.utils.GlobalState import net.perfectdreams.loritta.cinnamon.dashboard.frontend.utils.State import org.jetbrains.compose.web.dom.Div import org.jetbrains.compose.web.dom.H1 import org.jetbrains.compose.web.dom.H2 import org.jetbrains.compose.web.dom.Label import org.jetbrains.compose.web.dom.Text @Composable fun LocalizedText(i18nContext: I18nContext, keyData: StringI18nData) { Text(i18nContext.get(keyData)) } @Composable fun LocalizedText(globalState: GlobalState, keyData: StringI18nData) { val state = globalState.i18nContext when (state) { is State.Failure -> Text(keyData.key.key) is State.Loading -> Text("...") is State.Success -> LocalizedText(state.value, keyData) } } @Composable fun LocalizedFieldLabel(i18nContext: I18nContext, keyData: StringI18nData, forId: String) { Div(attrs = { classes("field-title") }) { Label(forId) { Text(i18nContext.get(keyData)) } } } @Composable fun TextReplaceControls( text: String, onText: @Composable (String) -> (Unit), onControl: @Composable (String) -> (ControlResult) ) { val builder = StringBuilder() val control = StringBuilder() var controlCharCount = 0 for (ch in text) { if (controlCharCount != 0) { if (ch == '{') { controlCharCount++ } if (ch == '}') { controlCharCount-- if (controlCharCount == 0) { val controlStr = control.toString() when (val result = onControl.invoke(controlStr)) { is ComposableFunctionResult -> result.block.invoke(controlStr) AppendControlAsIsResult -> builder.append("{$control}") DoNothingResult -> {} } control.clear() continue } } control.append(ch) continue } if (ch == '{') { onText.invoke(builder.toString()) builder.clear() controlCharCount++ continue } builder.append(ch) } onText.invoke(builder.toString()) } @Composable fun appendAsFormattedText(i18nContext: I18nContext, map: Map<String, Any?>): @Composable (String) -> (Unit) = { Text( i18nContext.formatter.format( it, map ) ) } sealed class ControlResult class ComposableFunctionResult(val block: @Composable (String) -> (Unit)) : ControlResult() object DoNothingResult : ControlResult() object AppendControlAsIsResult : ControlResult() @Composable fun LocalizedH1(i18nContext: I18nContext, keyData: StringI18nData) { H1 { LocalizedText(i18nContext, keyData) } } @Composable fun LocalizedH2(i18nContext: I18nContext, keyData: StringI18nData) { H2 { LocalizedText(i18nContext, keyData) } }
agpl-3.0
8aee427dbf23b211078a7789549e91be
27.646018
111
0.630099
4.170103
false
false
false
false
kohesive/keplin
keplin-util/src/main/kotlin/uy/kohesive/keplin/util/IoCapture.kt
1
6534
package uy.kohesive.keplin.util import org.jetbrains.kotlin.cli.common.repl.InvokeWrapper import java.io.InputStream import java.io.OutputStream import java.io.PrintStream import java.util.* // TODO: We trap the thread before it does an action need I/O captured, but if that thread spawns other, the new threads // do not have their IO trapped. // // It is possible to trap them as well using AspectJ around Thread.start(), but that brings in a dependency. // // It is also possible to assign I/O intercept to a thread group since all new threads start in the same group as their // parent. So in the thread local initializer, we would do a lookup on the thread group to get the I/O trap, and // then it would cache into the thread local. object InOutTrapper { val originalSystemIn = System.`in` val originalSystemOut = System.out val originalSystemErr = System.err init { System.setIn(ThreadAwareInputStreamForker(System.`in`)) System.setOut(ThreadAwarePrintStreamForker(System.out)) System.setErr(ThreadAwarePrintStreamForker(System.err)) } fun trapAllSystemInOutForThread(input: InputStream, output: PrintStream, errOutput: PrintStream) { (System.`in` as? ThreadAwareInputStreamForker)?.pushThread(input) (System.out as? ThreadAwarePrintStreamForker)?.pushThread(output) (System.err as? ThreadAwarePrintStreamForker)?.pushThread(errOutput) } fun removeAllSystemInOutForThread() { (System.`in` as? ThreadAwareInputStreamForker)?.popThread() (System.out as? ThreadAwarePrintStreamForker)?.popThread() (System.err as? ThreadAwarePrintStreamForker)?.popThread() } fun trapSystemOutForThread(output: PrintStream) { (System.out as? ThreadAwarePrintStreamForker)?.pushThread(output) } fun trapSystemErrForThread(errOutput: PrintStream) { (System.err as? ThreadAwarePrintStreamForker)?.pushThread(errOutput) } fun trapSystemInForThread(input: InputStream) { (System.`in` as? ThreadAwareInputStreamForker)?.pushThread(input) } fun removeSystemOutForThread() { (System.out as? ThreadAwarePrintStreamForker)?.popThread() } fun removeSystemErrForThread() { (System.err as? ThreadAwarePrintStreamForker)?.popThread() } fun removeSystemInForThread() { (System.`in` as? ThreadAwareInputStreamForker)?.popThread() } @Suppress("NOTHING_TO_INLINE") inline fun ensureInitialized() { NO_ACTION() } } fun NO_ACTION() {} open class RerouteScriptIoInvoker(val input: InputStream, val output: PrintStream, val errorOutput: PrintStream) : InvokeWrapper { override fun <T> invoke(body: () -> T): T { InOutTrapper.trapAllSystemInOutForThread(input, output, errorOutput) try { return body() } finally { InOutTrapper.removeAllSystemInOutForThread() } } } interface ThreadIoTrap<T : Any> { val fallback: T val traps: ThreadLocal<T> fun mine(): T = traps.get() ?: fallback fun pushThread(redirect: T) { traps.set(redirect) } fun popThread() { traps.remove() } } class IoTrapManager<T : Any>(override val fallback: T, override val traps: ThreadLocal<T> = ThreadLocal<T>()) : ThreadIoTrap<T> class ThreadAwareInputStreamForker(fallbackInputStream: InputStream) : InputStream(), ThreadIoTrap<InputStream> by IoTrapManager(fallbackInputStream) { override fun read(): Int { return mine().read() } } class ThreadAwareOutputStreamForker(fallbackOutputStream: OutputStream) : OutputStream(), ThreadIoTrap<OutputStream> by IoTrapManager(fallbackOutputStream) { override fun write(b: Int) { mine().write(b) } } class ThreadAwarePrintStreamForker(fallbackPrintStream: PrintStream) : PrintStream(fallbackPrintStream), ThreadIoTrap<PrintStream> by IoTrapManager(fallbackPrintStream) { override fun flush() { mine().flush() } override fun checkError(): Boolean { return mine().checkError() } override fun write(b: Int) { mine().write(b) } override fun print(b: Boolean) { mine().print(b) } override fun print(c: Char) { mine().print(c) } override fun print(i: Int) { mine().print(i) } override fun print(l: Long) { mine().print(l) } override fun print(f: Float) { mine().print(f) } override fun print(d: Double) { mine().print(d) } override fun print(s: CharArray) { mine().print(s) } override fun print(s: String?) { mine().print(s) } override fun print(obj: Any?) { mine().print(obj) } override fun println() { mine().println() } override fun println(x: Boolean) { mine().println(x) } override fun println(x: Char) { mine().println(x) } override fun println(x: Int) { mine().println(x) } override fun println(x: Long) { mine().println(x) } override fun println(x: Float) { mine().println(x) } override fun println(x: Double) { mine().println(x) } override fun println(x: CharArray) { mine().println(x) } override fun println(x: String?) { mine().println(x) } override fun println(x: Any?) { mine().println(x) } override fun append(csq: CharSequence?): PrintStream { return mine().append(csq) } override fun append(csq: CharSequence?, start: Int, end: Int): PrintStream { return mine().append(csq, start, end) } override fun append(c: Char): PrintStream { return mine().append(c) } override fun format(format: String, vararg args: Any?): PrintStream { return mine().format(format, *args) } override fun format(l: Locale?, format: String, vararg args: Any?): PrintStream { return mine().format(l, format, *args) } override fun printf(format: String, vararg args: Any?): PrintStream { return mine().printf(format, *args) } override fun printf(l: Locale?, format: String, vararg args: Any?): PrintStream { return mine().printf(l, format, *args) } override fun close() { throw UnsupportedOperationException("close() not allowed") } override fun write(buf: ByteArray, off: Int, len: Int) { mine().write(buf, off, len) } }
mit
382cd4d50b5beecbfa99522ed34957c4
26
130
0.643404
3.989011
false
false
false
false
Nagarajj/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/MessageHandlerSpec.kt
1
2517
/* * Copyright 2017 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.orca.q import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.throws import com.netflix.spinnaker.orca.pipeline.model.Pipeline import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.reset import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyZeroInteractions import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.subject.SubjectSpek object MessageHandlerSpec : SubjectSpek<MessageHandler<*>>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() val handleCallback: (Message) -> Unit = mock() subject { object : MessageHandler<ConfigurationError> { override val queue get() = queue override val repository get() = repository override val messageType = ConfigurationError::class.java override fun handle(message: ConfigurationError) { handleCallback.invoke(message) } } } fun resetMocks() = reset(queue, handleCallback) describe("when the handler is passed the wrong type of message") { val message = CompleteExecution(Pipeline::class.java, "1", "foo") afterGroup(::resetMocks) action("the handler receives a message") { assertThat( { subject.invoke(message) }, throws<IllegalArgumentException>() ) } it("does not invoke the handler") { verifyZeroInteractions(handleCallback) } } describe("when the handler is passed a sub-type of message") { val message = InvalidExecutionId(Pipeline::class.java, "1", "foo") afterGroup(::resetMocks) action("the handler receives a message") { subject.invoke(message) } it("does invoke the handler") { verify(handleCallback).invoke(message) } } })
apache-2.0
134bcee816071876310f088055b143f9
28.611765
75
0.719905
4.354671
false
false
false
false
r-artworks/game-seed
core/src/com/rartworks/engine/drawables/ComplexDrawable.kt
1
1349
package com.rartworks.engine.drawables import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.math.Vector2 import com.rartworks.engine.rendering.Drawable import com.rartworks.engine.rendering.IComplexDrawable import com.rartworks.engine.utils.fastMaxBy import com.rartworks.engine.utils.fastMinBy /** * Implementation of [IComplexDrawable] with a mutable list of childs of type [T]. */ open class ComplexDrawableOf<T : Drawable> : IComplexDrawable<T> { override val position = Vector2() override val color = Color().set(Color.WHITE) override var scale = 1f override var rotation = 0f override val origin = Vector2(0.5f, 0.5f) override val childs: MutableList<T> = arrayListOf() override val width: Float get() { if (this.childs.isEmpty()) return 0f val min = this.childs.fastMinBy { it.position.x } val max = this.childs.fastMaxBy { it.position.x + it.width } return (max.position.x + max.width) - (min.position.x) } override val height: Float get() { if (this.childs.isEmpty()) return 0f val min = this.childs.fastMinBy({ it.position.y }) val max = this.childs.fastMaxBy({ it.position.y + it.height }) return (max.position.y + max.height) - (min.position.y) } } /** * A normal [Drawable], but it can have other [Drawable]s as [childs]. */ open class ComplexDrawable : ComplexDrawableOf<Drawable>() { }
mit
98cc6559efb1598c80d80b0ff31f2df6
31.119048
82
0.73017
3.21957
false
false
false
false
mcxiaoke/kotlin-koi
samples/src/main/kotlin/com/mcxiaoke/koi/samples/ContextSample.kt
1
6263
package com.mcxiaoke.koi.samples import android.app.Activity import android.app.Fragment import android.app.IntentService import android.app.Service import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.IBinder import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.TextView import com.mcxiaoke.koi.KoiConfig import com.mcxiaoke.koi.samples.app.MainActivity import com.mcxiaoke.koi.ext.* import com.mcxiaoke.koi.log.* import java.io.File /** * Author: mcxiaoke * Date: 2016/2/2 20:38 */ class ActivityExtensionSample : Activity() { // available for Activity fun activityExtensions() { val act = getActivity() // Activity act.restart() // restart Activity val app = act.getApp() // Application val app2 = act.application // Application val textView = act.find<TextView>(android.R.id.text1) } // available for Context fun toastExtensions() { // available in Activity/Fragment/Service/Context toast(R.string.app_name) toast("this is a toast") longToast(R.string.app_name) longToast("this is a long toast") } } class FragmentExtensionSample : Fragment() { // available for Fragment fun fragmentExtensions() { val act = activity // Activity val app = getApp() // Application val textView = find<TextView>(android.R.id.text1) // view.findViewById val imageView = find<TextView>(android.R.id.icon1) // view.findViewById } } class ContextExtensionSample : Activity() { // available for Context fun inflateLayout() { val view1 = inflate(R.layout.activity_main) val viewGroup = view1 as ViewGroup val view2 = inflate(android.R.layout.activity_list_item, viewGroup, false) } // available for Context fun miscExtensions() { val hasCamera = hasCamera() mediaScan(Uri.parse("file:///sdcard/Pictures/koi/cat.png")) addToMediaStore(File("/sdcard/Pictures/koi/cat.png")) val batteryStatusIntent = getBatteryStatus() val colorValue = getResourceValue(android.R.color.darker_gray) } // available for Context fun intentExtensions() { val extras = Bundle { putString("key", "value") } val intent1 = newIntent<MainActivity>() val intent2 = newIntent<MainActivity>(Intent.FLAG_ACTIVITY_NEW_TASK, extras) } // available for Activity fun startActivityExtensions() { startActivity<MainActivity>() // equal to startActivity(Intent(this, MainActivity::class.java)) startActivity<MainActivity>(Intent.FLAG_ACTIVITY_SINGLE_TOP, Bundle()) startActivity<MainActivity>(Bundle()) startActivityForResult<MainActivity>(100) startActivityForResult<MainActivity>(Bundle(), 100) startActivityForResult<MainActivity>(200, Intent.FLAG_ACTIVITY_CLEAR_TOP) } // available for Context fun startServiceExtensions() { startService<BackgroundService>() startService<BackgroundService>(Bundle()) } // available for Context fun networkExtensions() { val name = networkTypeName() val operator = networkOperator() val type = networkType() val wifi = isWifi() val mobile = isMobile() val connected = isConnected() } // available for Context fun notificationExtensions() { // easy way using Notification.Builder val notification = newNotification() { this.setColor(0x0099cc) .setAutoCancel(true) .setContentTitle("Notification Title") .setContentText("Notification Message Text") .setDefaults(0) .setGroup("koi") .setVibrate(longArrayOf(1, 0, 0, 1)) .setSubText("this is a sub title") .setSmallIcon(android.R.drawable.ic_dialog_info) .setLargeIcon(null) } } // available for Context fun packageExtensions() { val isYoutubeInstalled = isAppInstalled("com.google.android.youtube") val isMainProcess = isMainProcess() val disabled = isComponentDisabled(MainActivity::class.java) enableComponent(MainActivity::class.java) val sig = getPackageSignature() val sigString = getSignature() println(dumpSignature()) } // available for Context // easy way to get system service, no cast fun systemServices() { val wm = getWindowService() val tm = getTelephonyManager() val nm = getNotificationManager() val cm = getConnectivityManager() val am = getAccountManager() val acm = getActivityManager() val alm = getAlarmManager() val imm = getInputMethodManager() val inflater = getLayoutService() val lm = getLocationManager() val wifi = getWifiManager() } // available for Context fun logExtensions() { KoiConfig.logEnabled = true //default is false // true == Log.VERBOSE // false == Log.ASSERT // optional KoiConfig.logLevel = Log.VERBOSE // default is Log.ASSERT // logv("log functions available in Context") //Log.v logd("log functions available in Context") //Log.d logi("log functions available in Context") //Log.i logw("log functions available in Context") //Log.w loge("log functions available in Context") //Log.e logf("log functions available in Context") //Log.wtf // support lazy evaluated message logv { "lazy eval message lambda" } //Log.v logd { "lazy eval message lambda" } //Log.d logi { "lazy eval message lambda" } //Log.i logw { "lazy eval message lambda" } //Log.w loge { "lazy eval message lambda" } //Log.e logf { "lazy eval message lambda" } //Log.wtf } } // sample service class BackgroundService : IntentService("background") { override fun onHandleIntent(intent: Intent?) { throw UnsupportedOperationException() } }
apache-2.0
76acca6a8aa00bc3bb6daab32e8d8731
30.631313
84
0.637394
4.541697
false
false
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/test/kotlin/org/jitsi/test_utils/Pcap.kt
1
7279
/* * 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.test_utils import org.jitsi.nlj.format.OpusPayloadType import org.jitsi.nlj.format.PayloadType import org.jitsi.nlj.format.RtxPayloadType import org.jitsi.nlj.format.Vp8PayloadType import org.jitsi.nlj.rtp.RtpExtension import org.jitsi.nlj.rtp.RtpExtensionType import org.jitsi.nlj.rtp.SsrcAssociationType import org.jitsi.nlj.srtp.SrtpProfileInformation import org.jitsi.nlj.srtp.TlsRole import org.jitsi.rtp.util.byteBufferOf data class SrtpData( var srtpProfileInformation: SrtpProfileInformation, var keyingMaterial: ByteArray, var tlsRole: TlsRole ) data class SourceAssociation( var primarySsrc: Long, var secondarySsrc: Long, var associationType: SsrcAssociationType ) data class PcapInformation( var filePath: String, var srtpData: SrtpData, var payloadTypes: List<PayloadType>, var headerExtensions: List<RtpExtension>, var ssrcAssociations: List<SourceAssociation> ) private val DEFAULT_HEADER_EXTENSIONS = listOf( RtpExtension(1, RtpExtensionType.SSRC_AUDIO_LEVEL), RtpExtension(3, RtpExtensionType.ABS_SEND_TIME), RtpExtension(4, RtpExtensionType.RTP_STREAM_ID), RtpExtension(5, RtpExtensionType.TRANSPORT_CC) ) object Pcaps { object Incoming { val ONE_PARTICIPANT_RTP_RTCP_SIM_RTX = PcapInformation( filePath = javaClass.classLoader.getResource( "pcaps/1_incoming_participant_rtp_rtcp_sim_rtx.pcap" ).path, srtpData = SrtpData( srtpProfileInformation = SrtpProfileInformation( cipherKeyLength = 16, cipherSaltLength = 14, cipherName = 1, authFunctionName = 1, authKeyLength = 20, rtcpAuthTagLength = 10, rtpAuthTagLength = 10 ), keyingMaterial = byteBufferOf( 0x70, 0xD5, 0x56, 0xB1, 0xC5, 0xB3, 0xC7, 0x7E, 0xE6, 0x31, 0xC3, 0xA2, 0xC2, 0x93, 0x4E, 0xAD, 0xBE, 0x53, 0xDD, 0x22, 0xB5, 0x6E, 0xF2, 0xD9, 0xB6, 0x67, 0xE9, 0xEF, 0xD5, 0xB2, 0x88, 0x6F, 0x6C, 0x6F, 0x16, 0xAC, 0xA2, 0x13, 0xDF, 0x1D, 0x63, 0x60, 0x39, 0x1F, 0x23, 0x74, 0xBA, 0x0C, 0x5B, 0x0B, 0x14, 0x3E, 0x2E, 0x3E, 0x6D, 0x30, 0xFF, 0x6F, 0x54, 0x5B ).array(), tlsRole = TlsRole.CLIENT ), payloadTypes = listOf( RtxPayloadType(96, parameters = mapOf("apt" to "100")), Vp8PayloadType(100, rtcpFeedbackSet = setOf("nack pli", "ccm fir")), OpusPayloadType(111) ), headerExtensions = DEFAULT_HEADER_EXTENSIONS, ssrcAssociations = listOf( SourceAssociation(1632300152, 1929115835, SsrcAssociationType.RTX), SourceAssociation(3232245189, 3407277242, SsrcAssociationType.RTX), SourceAssociation(1465075899, 3483093671, SsrcAssociationType.RTX) ) ) val ONE_PARTICIPANT_RTP_RTCP = PcapInformation( filePath = javaClass.classLoader.getResource( "pcaps/capture_1_incoming_participant_1_rtp_and_rtcp.pcap" ).path, srtpData = SrtpData( srtpProfileInformation = SrtpProfileInformation( cipherKeyLength = 16, cipherSaltLength = 14, cipherName = 1, authFunctionName = 1, authKeyLength = 20, rtcpAuthTagLength = 10, rtpAuthTagLength = 10 ), keyingMaterial = byteBufferOf( 0x2D, 0x6C, 0x37, 0xC7, 0xA3, 0x49, 0x25, 0x82, 0x1F, 0x3B, 0x62, 0x0D, 0x05, 0x8A, 0x29, 0x64, 0x6F, 0x49, 0xD6, 0x04, 0xE6, 0xD6, 0x48, 0xE0, 0x67, 0x43, 0xF3, 0x1F, 0x6D, 0x2F, 0x4B, 0x33, 0x6A, 0x61, 0xD8, 0x84, 0x00, 0x32, 0x1A, 0x84, 0x00, 0x8C, 0xC5, 0xC3, 0xCB, 0x18, 0xCE, 0x8D, 0x34, 0x3C, 0x2C, 0x70, 0x62, 0x26, 0x39, 0x05, 0x7D, 0x5A, 0xF9, 0xC7 ).array(), tlsRole = TlsRole.CLIENT ), payloadTypes = listOf( Vp8PayloadType(100), OpusPayloadType(111) ), headerExtensions = DEFAULT_HEADER_EXTENSIONS, ssrcAssociations = listOf() ) } object Outgoing { val ONE_PARITICPANT_RTP_AND_RTCP_DECRYPTED = PcapInformation( filePath = javaClass.classLoader.getResource( "pcaps/capture_1_incoming_participant_1_rtp_and_rtcp_decrypted_2.pcap" ).path, srtpData = SrtpData( srtpProfileInformation = SrtpProfileInformation( cipherKeyLength = 16, cipherSaltLength = 14, cipherName = 1, authFunctionName = 1, authKeyLength = 20, rtcpAuthTagLength = 10, rtpAuthTagLength = 10 ), keyingMaterial = byteBufferOf( 0x2D, 0x6C, 0x37, 0xC7, 0xA3, 0x49, 0x25, 0x82, 0x1F, 0x3B, 0x62, 0x0D, 0x05, 0x8A, 0x29, 0x64, 0x6F, 0x49, 0xD6, 0x04, 0xE6, 0xD6, 0x48, 0xE0, 0x67, 0x43, 0xF3, 0x1F, 0x6D, 0x2F, 0x4B, 0x33, 0x6A, 0x61, 0xD8, 0x84, 0x00, 0x32, 0x1A, 0x84, 0x00, 0x8C, 0xC5, 0xC3, 0xCB, 0x18, 0xCE, 0x8D, 0x34, 0x3C, 0x2C, 0x70, 0x62, 0x26, 0x39, 0x05, 0x7D, 0x5A, 0xF9, 0xC7 ).array(), tlsRole = TlsRole.CLIENT ), payloadTypes = listOf( Vp8PayloadType(100), OpusPayloadType(111), RtxPayloadType(96, parameters = mapOf("apt" to "100")) ), headerExtensions = DEFAULT_HEADER_EXTENSIONS, ssrcAssociations = listOf() ) } }
apache-2.0
8f6ca092de8f6a8ba5681866de1ac23a
37.718085
86
0.532353
3.652283
false
false
false
false
danielrs/botellier
src/test/kotlin/org/botellier/store/StoreTransaction.kt
1
1562
package org.botellier.store import org.botellier.value.IntValue import org.botellier.value.NilValue import org.junit.Test import org.junit.Assert class StoreTransactionTest { @Test fun cachingDuringTransaction() { val store = Store() val transaction = store.transaction() transaction.begin { set("one", IntValue(1)) Assert.assertEquals(IntValue(1), get("one")) Assert.assertEquals(NilValue(), store.get("one")) } Assert.assertEquals(IntValue(1), store.get("one")) } @Test fun updatingExistingValues() { val store = Store() val transaction = store.transaction() transaction.begin { set("one", IntValue(1)) set("two", IntValue(2)) set("three", IntValue(3)) } transaction.begin { update<IntValue>("one") { IntValue(it.unwrap() * 10) } update<IntValue>("two") { IntValue(it.unwrap() * 10) } update<IntValue>("three") { IntValue(it.unwrap() * 10) } } Assert.assertEquals(IntValue(10), store.get("one")) Assert.assertEquals(IntValue(20), store.get("two")) Assert.assertEquals(IntValue(30), store.get("three")) } @Test fun updatingUnexistingValues() { val store = Store() val transaction = store.transaction() transaction.begin { mupdate<IntValue>("one") { IntValue((it?.unwrap() ?: 9) * 10) } } Assert.assertEquals(IntValue(90), store.get("one")) } }
mit
a236e7114126d7176ca41fff16230097
27.925926
75
0.579385
4.233062
false
true
false
false
ValCanBuild/Subspace
app/src/main/kotlin/com/rockspin/subspace/network/SubApi.kt
1
1822
package com.rockspin.subspace.network import com.rockspin.subspace.util.hexValue import retrofit2.Retrofit import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import rx.Single import java.io.BufferedReader import java.io.File import java.io.FileInputStream import java.io.InputStreamReader import java.security.MessageDigest /** * Created by valentin.hinov on 19/01/2017. */ class SubApi { private val subInterface: SubtitleWebInterface by lazy { Retrofit.Builder().apply { baseUrl("http://api.thesubdb.com") addCallAdapterFactory(RxJavaCallAdapterFactory.create()) }.build().create(SubtitleWebInterface::class.java) } fun downloadSubtitleForMovieFile(file: File): Single<String> { return Single.defer { Single.just(calculateHash(file)) .flatMap { subInterface.downloadSubtitleForHash(it).toSingle() } .map { responseBody -> val readerIn = BufferedReader(InputStreamReader(responseBody.byteStream())) val sb = StringBuilder() readerIn.lines().forEach { sb.append(it) sb.appendln() } readerIn.close() sb.toString() } } } private fun calculateHash(file: File): String { val fs = FileInputStream(file) val first64Bytes = ByteArray(65536) fs.read(first64Bytes, 0, 65536) val last64Bytes = ByteArray(65536) fs.skip(file.length() - 131072) fs.read(last64Bytes) val combined = first64Bytes + last64Bytes val digest = MessageDigest.getInstance("MD5") val hashValue = digest.digest(combined).hexValue return hashValue } }
mit
44661d915796c5d40ddc39884361c136
27.484375
95
0.6191
4.577889
false
false
false
false
Ph1b/MaterialAudiobookPlayer
common/src/main/kotlin/de/ph1b/audiobook/common/comparator/IntelliJStringComparator.kt
1
3064
package de.ph1b.audiobook.common.comparator import java.util.Comparator /** * Simple copy of IntelliJs-Community naturalCompare. * Licensed as Apache v2. */ class IntelliJStringComparator : Comparator<String> { private fun isDecimalDigit(c: Char) = c in '0'..'9' override fun compare(lhs: String?, rhs: String?) = naturalCompare(lhs, rhs, false) private fun naturalCompare(lhs: String?, rhs: String?, caseSensitive: Boolean): Int { if (lhs === rhs) { return 0 } if (lhs == null) { return -1 } if (rhs == null) { return 1 } val string1Length = lhs.length val string2Length = rhs.length var i = 0 var j = 0 while (i < string1Length && j < string2Length) { var ch1 = lhs[i] var ch2 = rhs[j] if ((isDecimalDigit(ch1) || ch1 == ' ') && (isDecimalDigit(ch2) || ch2 == ' ')) { var startNum1 = i while (ch1 == ' ' || ch1 == '0') { // skip leading spaces and zeros startNum1++ if (startNum1 >= string1Length) break ch1 = lhs[startNum1] } var startNum2 = j while (ch2 == ' ' || ch2 == '0') { // skip leading spaces and zeros startNum2++ if (startNum2 >= string2Length) break ch2 = rhs[startNum2] } i = startNum1 j = startNum2 // find end index of number while (i < string1Length && isDecimalDigit(lhs[i])) i++ while (j < string2Length && isDecimalDigit(rhs[j])) j++ val lengthDiff = i - startNum1 - (j - startNum2) if (lengthDiff != 0) { // numbers with more digits are always greater than shorter numbers return lengthDiff } while (startNum1 < i) { // compare numbers with equal digit count val diff = lhs[startNum1] - rhs[startNum2] if (diff != 0) { return diff } startNum1++ startNum2++ } i-- j-- } else { if (caseSensitive) { return ch1 - ch2 } else { // similar logic to charsMatch() below if (ch1 != ch2) { val diff1 = ch1.uppercaseChar() - ch2.uppercaseChar() if (diff1 != 0) { val diff2 = ch1.lowercaseChar() - ch2.lowercaseChar() if (diff2 != 0) { return diff2 } } } } } i++ j++ } // After the loop the end of one of the strings might not have been reached, if the other // string ends with a number and the strings are equal until the end of that number. When // there are more characters in the string, then it is greater. if (i < string1Length) { return 1 } if (j < string2Length) { return -1 } if (!caseSensitive && string1Length == string2Length) { // do case sensitive compare if case insensitive strings are equal return naturalCompare(lhs, rhs, true) } return string1Length - string2Length } }
lgpl-3.0
4a16dc7d2c36c48a45a0797c570af420
28.747573
93
0.540144
3.938303
false
false
false
false
tom-kita/kktAPK
app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/behavior/AvatarImageBehavior.kt
3
5453
package com.bl_lia.kirakiratter.presentation.behavior import android.content.Context import android.support.design.widget.CoordinatorLayout import android.util.AttributeSet import android.view.View import android.widget.ImageView import android.widget.Toolbar import com.bl_lia.kirakiratter.R class AvatarImageBehavior(private val mContext: Context, attrs: AttributeSet?) : CoordinatorLayout.Behavior<ImageView>() { private var mCustomFinalYPosition: Float = 0.toFloat() private var mCustomStartXPosition: Float = 0.toFloat() private var mCustomStartToolbarPosition: Float = 0.toFloat() private var mCustomStartHeight: Float = 0.toFloat() private var mCustomFinalHeight: Float = 0.toFloat() private var mAvatarMaxSize: Float = 0.toFloat() private val mFinalLeftAvatarPadding: Float private val mStartPosition: Float = 0.toFloat() private var mStartXPosition: Int = 0 private var mStartToolbarPosition: Float = 0.toFloat() private var mStartYPosition: Int = 0 private var mFinalYPosition: Int = 0 private var mStartHeight: Int = 0 private var mFinalXPosition: Int = 0 private var mChangeBehaviorPoint: Float = 0.toFloat() init { if (attrs != null) { val a = mContext.obtainStyledAttributes(attrs, R.styleable.AvatarImageBehavior) mCustomFinalYPosition = a.getDimension(R.styleable.AvatarImageBehavior_finalYPosition, 0f) mCustomStartXPosition = a.getDimension(R.styleable.AvatarImageBehavior_startXPosition, 0f) mCustomStartToolbarPosition = a.getDimension(R.styleable.AvatarImageBehavior_startToolbarPosition, 0f) mCustomStartHeight = a.getDimension(R.styleable.AvatarImageBehavior_startHeight, 0f) mCustomFinalHeight = a.getDimension(R.styleable.AvatarImageBehavior_finalHeight, 0f) a.recycle() } init() mFinalLeftAvatarPadding = mContext.resources.getDimension( R.dimen.spacing_normal) } private fun init() { bindDimensions() } private fun bindDimensions() { mAvatarMaxSize = mContext.resources.getDimension(R.dimen.image_width) } override fun layoutDependsOn(parent: CoordinatorLayout?, child: ImageView?, dependency: View?): Boolean { return dependency is Toolbar } override fun onDependentViewChanged(parent: CoordinatorLayout?, child: ImageView?, dependency: View?): Boolean { if (child != null && dependency != null) { maybeInitProperties(child, dependency) } val maxScrollDistance = mStartToolbarPosition.toInt() val expandedPercentageFactor = dependency!!.y / maxScrollDistance if (expandedPercentageFactor < mChangeBehaviorPoint) { val heightFactor = (mChangeBehaviorPoint - expandedPercentageFactor) / mChangeBehaviorPoint val distanceXToSubtract = (mStartXPosition - mFinalXPosition) * heightFactor + child!!.height / 2 val distanceYToSubtract = (mStartYPosition - mFinalYPosition) * (1f - expandedPercentageFactor) + child.height / 2 child.x = mStartXPosition - distanceXToSubtract child.y = mStartYPosition - distanceYToSubtract val heightToSubtract = (mStartHeight - mCustomFinalHeight) * heightFactor val lp = child.layoutParams as CoordinatorLayout.LayoutParams lp.width = (mStartHeight - heightToSubtract).toInt() lp.height = (mStartHeight - heightToSubtract).toInt() child.layoutParams = lp } else { val distanceYToSubtract = (mStartYPosition - mFinalYPosition) * (1f - expandedPercentageFactor) + mStartHeight / 2 child!!.x = (mStartXPosition - child.width / 2).toFloat() child.y = mStartYPosition - distanceYToSubtract val lp = child.layoutParams as CoordinatorLayout.LayoutParams lp.width = mStartHeight.toInt() lp.height = mStartHeight.toInt() child.layoutParams = lp } return true } private fun maybeInitProperties(child: ImageView, dependency: View) { if (mStartYPosition == 0) mStartYPosition = dependency.y.toInt() if (mFinalYPosition == 0) mFinalYPosition = dependency.height / 2 if (mStartHeight == 0) mStartHeight = child.height if (mStartXPosition == 0) mStartXPosition = (child.x + child.width / 2).toInt() if (mFinalXPosition == 0) mFinalXPosition = mContext.resources.getDimensionPixelOffset(R.dimen.abc_action_bar_content_inset_material) + mCustomFinalHeight.toInt() / 2 if (mStartToolbarPosition == 0f) mStartToolbarPosition = dependency.y if (mChangeBehaviorPoint == 0f) { mChangeBehaviorPoint = (child.height - mCustomFinalHeight) / (2f * (mStartYPosition - mFinalYPosition)) } } val statusBarHeight: Int get() { var result = 0 val resourceId = mContext.resources.getIdentifier("status_bar_height", "dimen", "android") if (resourceId > 0) { result = mContext.resources.getDimensionPixelSize(resourceId) } return result } companion object { private val MIN_AVATAR_PERCENTAGE_SIZE = 0.3f private val EXTRA_FINAL_AVATAR_PADDING = 80 private val TAG = "behavior" } }
mit
47754331b3dd796355d64740a802babb
37.957143
152
0.673574
4.540383
false
false
false
false
JayNewstrom/ScreenSwitcher
sample-core/src/main/java/screenswitchersample/core/activity/ScreenSwitcherActivity.kt
1
2937
package screenswitchersample.core.activity import android.app.Activity import android.os.Bundle import android.view.MotionEvent import android.view.ViewGroup import com.jaynewstrom.concrete.Concrete import com.jaynewstrom.screenswitcher.ScreenSwitcher import com.jaynewstrom.screenswitcher.ScreenSwitcherFactory import com.jaynewstrom.screenswitcher.ScreenSwitcherFinishHandler import com.jaynewstrom.screenswitcher.ScreenSwitcherState import com.jaynewstrom.screenswitcher.dialogmanager.DialogManager import screenswitchersample.core.R import screenswitchersample.core.screen.SystemBackPressed import javax.inject.Inject class ScreenSwitcherActivity : Activity(), ScreenSwitcherFinishHandler { private val concreteHelper = ActivityConcreteHelper() @Inject internal lateinit var screenSwitcherState: ScreenSwitcherState @Inject internal lateinit var dialogManager: DialogManager private lateinit var screenSwitcher: ScreenSwitcher private var finishCompleteHandler: ScreenSwitcherFinishHandler.FinishCompleteHandler? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) concreteHelper.onActivityCreated(this, savedInstanceState) concreteHelper.activityWall?.component?.inject(this) setContentView(R.layout.screen_switcher_activity) val screenHost = findViewById<ViewGroup>(R.id.screen_host) screenSwitcher = ScreenSwitcherFactory.viewScreenSwitcher(screenHost, screenSwitcherState, this) dialogManager.attachActivity(this) dialogManager.restoreState() screenHost.isSaveFromParentEnabled = false } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) concreteHelper.onActivitySaveInstanceState(outState) screenSwitcher.saveViewHierarchyStateToScreenSwitcherState() } override fun onDestroy() { super.onDestroy() dialogManager.dropActivity(this) finishCompleteHandler?.finishComplete() finishCompleteHandler = null if (!isFinishing) { dialogManager.saveState() } concreteHelper.onActivityDestroyed(this) } override fun dispatchTouchEvent(ev: MotionEvent): Boolean { return screenSwitcher.isTransitioning || super.dispatchTouchEvent(ev) } override fun onBackPressed() { if (!screenSwitcher.isTransitioning && !isFinishing) { screenSwitcher.pop(1, SystemBackPressed) } } override fun getSystemService(name: String): Any? { return if (Concrete.isService(name)) { concreteHelper.activityWall } else { super.getSystemService(name) } } override fun onScreenSwitcherFinished(finishCompleteHandler: ScreenSwitcherFinishHandler.FinishCompleteHandler) { this.finishCompleteHandler = finishCompleteHandler finish() } }
apache-2.0
f3dbdacac865fd98c4f4577764a2a9bf
36.177215
117
0.755192
5.531073
false
false
false
false
facebook/litho
sample/src/main/java/com/facebook/samples/litho/kotlin/mountables/SimpleImageViewExampleComponent.kt
1
1457
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.samples.litho.kotlin.mountables import com.facebook.litho.Column import com.facebook.litho.Component import com.facebook.litho.ComponentScope import com.facebook.litho.KComponent import com.facebook.litho.Style import com.facebook.litho.core.height import com.facebook.litho.core.margin import com.facebook.litho.core.padding import com.facebook.litho.core.width import com.facebook.litho.dp import com.facebook.litho.kotlin.widget.Text class SimpleImageViewExampleComponent : KComponent() { override fun ComponentScope.render(): Component { return Column(style = Style.padding(all = 20.dp)) { child( SimpleImageViewComponent(style = Style.width(100.dp).height(100.dp).margin(all = 50.dp))) child(Text("Litho logo rendered using a Mountable Component", textSize = 16f.dp)) } } }
apache-2.0
c465d286357e6b7151592c276574d5bb
35.425
99
0.757035
3.916667
false
false
false
false
diyaakanakry/Diyaa
Array.kt
1
557
fun main(args:Array<String>){ var arrayInt= Array<Int>(5){0} arrayInt[3]=55 println("Array[3]="+ arrayInt[3]) println("Al element by object") for (element in arrayInt){ println(element) } println("Al element by index") for( index in 0..4){ println(arrayInt[index]) } var arrayStr=Array<String>(4){""} for (index in 0..3){ print("arrayStr[ $index ]=") arrayStr[index]= readLine()!! } for (index in 0..3){ println("arrayStr[ $index ]="+ arrayStr[index]) } }
unlicense
1ec0e1e8475b8ef95b1477de98db58bb
19.666667
55
0.552962
3.355422
false
false
false
false
xfournet/intellij-community
plugins/git4idea/tests/git4idea/index/GitIndexTest.kt
2
3866
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.index import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.Executor.* import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.vcsUtil.VcsUtil import git4idea.repo.GitRepository import git4idea.test.GitPlatformTest import git4idea.test.git import org.junit.Assume class GitIndexTest : GitPlatformTest() { private val FILE = "file.txt" private lateinit var repository: GitRepository public override fun setUp() { super.setUp() repository = createRepository(projectPath) cd(projectPath) touch(FILE, "initial") git("add .") git("commit -m initial") } fun `test read staged file`() { assertEquals("initial", readFileContent(FILE)) overwrite(FILE, "modified") assertEquals("initial", readFileContent(FILE)) git("add .") assertEquals("modified", readFileContent(FILE)) overwrite(FILE, "modi\nfied") git("add .") assertEquals("modi\nfied", readFileContent(FILE)) } fun `test write staged file`() { assertEquals("initial", readFileContent(FILE)) writeFileContent(FILE, "modified") assertEquals("modified", readFileContent(FILE)) overwrite(FILE, "modi\nfied") assertEquals("modified", readFileContent(FILE)) } fun `test read permissions1`() { Assume.assumeFalse(SystemInfo.isWindows) // Can't set executable flag on windows assertEquals(false, readFilePermissions()) FileUtil.setExecutableAttribute(FILE.path.path, true) git("add .") assertEquals(true, readFilePermissions()) FileUtil.setExecutableAttribute(FILE.path.path, false) assertEquals(true, readFilePermissions()) git("add .") assertEquals(false, readFilePermissions()) } fun `test read permissions2`() { assertEquals(false, readFilePermissions()) setExecutableFlagInIndex(FILE, true) assertEquals(true, readFilePermissions()) setExecutableFlagInIndex(FILE, false) assertEquals(false, readFilePermissions()) } fun `test write permissions`() { assertEquals(false, readFilePermissions()) writeFileContent(FILE, "modified", true) assertEquals(true, readFilePermissions()) writeFileContent(FILE, "modified", false) assertEquals(false, readFilePermissions()) setExecutableFlagInIndex(FILE, true) assertEquals(true, readFilePermissions()) } private fun readFileContent(path: String): String { val stagedFile = GitIndexUtil.list(repository, path.path) val bytes = GitIndexUtil.read(repository, stagedFile!!.blobHash) return String(bytes, CharsetToolkit.UTF8_CHARSET) } private fun writeFileContent(path: String, content: String, executable: Boolean = false) { val bytes = content.toByteArray(CharsetToolkit.UTF8_CHARSET) GitIndexUtil.write(repository, path.path, bytes, executable) } private fun readFilePermissions() = GitIndexUtil.list(repository, FILE.path)!!.isExecutable private val String.path: FilePath get() = VcsUtil.getFilePath(repository.root, this) private fun setExecutableFlagInIndex(path: String, executable: Boolean) { val mode = if (executable) "+x" else "-x" git("update-index --chmod=$mode '$path'") } }
apache-2.0
1e7e3fb30f090b5bcd2abe4e84a58bcc
29.203125
93
0.730471
4.39818
false
true
false
false
Kotlin/dokka
runners/gradle-plugin/src/test/kotlin/org/jetbrains/dokka/gradle/KotlinSourceSetGistTest.kt
1
8809
package org.jetbrains.dokka.gradle import org.gradle.api.artifacts.FileCollectionDependency import org.gradle.kotlin.dsl.get import org.gradle.testfixtures.ProjectBuilder import org.jetbrains.dokka.gradle.kotlin.gistOf import org.jetbrains.kotlin.gradle.dsl.KotlinJvmProjectExtension import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType import java.io.File import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue class KotlinSourceSetGistTest { @Test fun `main source set with kotlin jvm`() { val project = ProjectBuilder.builder().build() project.plugins.apply("org.jetbrains.kotlin.jvm") val kotlin = project.kotlin as KotlinJvmProjectExtension val mainSourceSet = kotlin.sourceSets.getByName("main") val mainSourceSetGist = project.gistOf(mainSourceSet) assertEquals( "main", mainSourceSetGist.name, "Expected correct source set name" ) assertEquals( KotlinPlatformType.jvm, mainSourceSetGist.platform.getSafe(), "Expected correct platform" ) assertTrue( mainSourceSetGist.isMain.getSafe(), "Expected main sources to be marked as 'isMain'" ) assertEquals( emptySet(), mainSourceSetGist.dependentSourceSetNames.get(), "Expected no dependent source sets" ) } @Test fun `test source set with kotlin jvm`() { val project = ProjectBuilder.builder().build() project.plugins.apply("org.jetbrains.kotlin.jvm") val kotlin = project.kotlin as KotlinJvmProjectExtension val testSourceSet = kotlin.sourceSets.getByName("test") val testSourceSetGist = project.gistOf(testSourceSet) assertFalse( testSourceSetGist.isMain.getSafe(), "Expected test source set not being marked as 'isMain'" ) assertEquals( emptySet(), testSourceSetGist.dependentSourceSetNames.get(), "Expected no dependent source sets" ) } @Test fun `sourceRoots of main source set with kotlin jvm`() { val project = ProjectBuilder.builder().build() project.plugins.apply("org.jetbrains.kotlin.jvm") val kotlin = project.kotlin as KotlinJvmProjectExtension val mainSourceSet = kotlin.sourceSets.getByName("main") val mainSourceSetGist = project.gistOf(mainSourceSet) assertEquals( emptySet(), mainSourceSetGist.sourceRoots.files, "Expected no sourceRoots, because default source root does not exist on filesystem yet" ) // Create default source root on filesystem val defaultSourceRoot = project.file("src/main/kotlin") defaultSourceRoot.mkdirs() assertEquals( setOf(defaultSourceRoot), mainSourceSetGist.sourceRoots.files, "Expected default source root in source roots, since it is present on the filesystem" ) // Create custom source set (and make sure it exists on filesystem) val customSourceRoot = project.file("src/main/custom").also(File::mkdirs) mainSourceSet.kotlin.srcDir(customSourceRoot) assertEquals( setOf(defaultSourceRoot, customSourceRoot), mainSourceSetGist.sourceRoots.files, "Expected recently registered custom source root to be present" ) // removing default source root mainSourceSet.kotlin.setSrcDirs(listOf(customSourceRoot)) assertEquals( setOf(customSourceRoot), mainSourceSetGist.sourceRoots.files, "Expected only custom source root being present in source roots" ) } @Suppress("UnstableApiUsage") @Test fun `classpath of main source set with kotlin jvm`() { val project = ProjectBuilder.builder().build() project.plugins.apply("org.jetbrains.kotlin.jvm") val kotlin = project.kotlin as KotlinJvmProjectExtension val mainSourceSet = kotlin.sourceSets.getByName("main") val mainSourceSetGist = project.gistOf(mainSourceSet) /* Only work with file dependencies */ project.configurations.forEach { configuration -> configuration.withDependencies { dependencies -> dependencies.removeIf { dependency -> dependency !is FileCollectionDependency } } } val implementationJar = project.file("implementation.jar") val compileOnlyJar = project.file("compileOnly.jar") val apiJar = project.file("api.jar") val runtimeOnlyJar = project.file("runtimeOnly.jar") mainSourceSet.dependencies { implementation(project.files(implementationJar)) compileOnly(project.files(compileOnlyJar)) api(project.files(apiJar)) runtimeOnly(project.files(runtimeOnlyJar)) } assertEquals( emptySet(), mainSourceSetGist.classpath.getSafe().files, "Expected no files on the classpath, since no file exists" ) /* Creating dependency files */ check(implementationJar.createNewFile()) check(compileOnlyJar.createNewFile()) check(apiJar.createNewFile()) check(runtimeOnlyJar.createNewFile()) assertEquals( setOf(implementationJar, compileOnlyJar, apiJar), mainSourceSetGist.classpath.getSafe().files, "Expected implementation, compileOnly and api dependencies on classpath" ) } @Test fun `common, jvm and macos source sets with kotlin multiplatform`() { val project = ProjectBuilder.builder().build() project.plugins.apply("org.jetbrains.kotlin.multiplatform") val kotlin = project.kotlin as KotlinMultiplatformExtension kotlin.jvm() kotlin.macosX64("macos") val commonMainSourceSet = kotlin.sourceSets.getByName("commonMain") val commonMainSourceSetGist = project.gistOf(commonMainSourceSet) val jvmMainSourceSet = kotlin.sourceSets.getByName("jvmMain") val jvmMainSourceSetGist = project.gistOf(jvmMainSourceSet) val macosMainSourceSet = kotlin.sourceSets.getByName("macosMain") val macosMainSourceSetGist = project.gistOf(macosMainSourceSet) assertEquals( "commonMain", commonMainSourceSetGist.name, "Expected correct source set name" ) assertEquals( "jvmMain", jvmMainSourceSetGist.name, "Expected correct source set name" ) assertEquals( "macosMain", macosMainSourceSetGist.name, "Expected correct source set name" ) assertEquals( KotlinPlatformType.common, commonMainSourceSetGist.platform.getSafe(), "Expected common platform for commonMain source set" ) assertEquals( KotlinPlatformType.jvm, jvmMainSourceSetGist.platform.getSafe(), "Expected jvm platform for jvmMain source set" ) assertEquals( KotlinPlatformType.native, macosMainSourceSetGist.platform.getSafe(), "Expected native platform for macosMain source set" ) assertTrue( commonMainSourceSetGist.isMain.getSafe(), "Expected commonMain to be marked with 'isMain'" ) assertTrue( jvmMainSourceSetGist.isMain.getSafe(), "Expected jvmMain to be marked with 'isMain'" ) assertTrue( macosMainSourceSetGist.isMain.getSafe(), "Expected macosMain to be marked with 'isMain'" ) assertFalse( project.gistOf(kotlin.sourceSets["commonTest"]).isMain.getSafe(), "Expected commonTest not being marked with 'isMain'" ) assertFalse( project.gistOf(kotlin.sourceSets["jvmTest"]).isMain.getSafe(), "Expected jvmTest not being marked with 'isMain'" ) assertFalse( project.gistOf(kotlin.sourceSets["macosTest"]).isMain.getSafe(), "Expected macosTest not being marked with 'isMain'" ) assertEquals( setOf("commonMain"), jvmMainSourceSetGist.dependentSourceSetNames.get(), "Expected jvmMain to depend on commonMain by default" ) /* Why not? */ jvmMainSourceSet.dependsOn(macosMainSourceSet) assertEquals( setOf("commonMain", "macosMain"), jvmMainSourceSetGist.dependentSourceSetNames.get(), "Expected dependent source set changes to be reflected in gist" ) } }
apache-2.0
6cb748f0be27967ba03703a4da168689
34.663968
106
0.65399
5.13046
false
true
false
false
AllanWang/Frost-for-Facebook
app/src/main/kotlin/com/pitchedapps/frost/web/FrostRequestInterceptor.kt
1
2951
/* * Copyright 2018 Allan Wang * * 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.pitchedapps.frost.web import android.webkit.WebResourceRequest import android.webkit.WebResourceResponse import android.webkit.WebView import com.pitchedapps.frost.utils.FrostPglAdBlock import com.pitchedapps.frost.utils.L import java.io.ByteArrayInputStream import okhttp3.HttpUrl.Companion.toHttpUrlOrNull /** * Created by Allan Wang on 2017-07-13. * * Handler to decide when a request should be done by us This is the crux of Frost's optimizations * for the web browser */ private val blankResource: WebResourceResponse = WebResourceResponse("text/plain", "utf-8", ByteArrayInputStream("".toByteArray())) fun WebView.shouldFrostInterceptRequest(request: WebResourceRequest): WebResourceResponse? { val requestUrl = request.url?.toString() ?: return null val httpUrl = requestUrl.toHttpUrlOrNull() ?: return null val host = httpUrl.host val url = httpUrl.toString() if (host.contains("facebook") || host.contains("fbcdn")) return null if (FrostPglAdBlock.isAd(host)) return blankResource // if (!shouldLoadImages && !Prefs.loadMediaOnMeteredNetwork && request.isMedia) return // blankResource L.v { "Intercept Request: $host $url" } return null } /** Wrapper to ensure that null exceptions are not reached */ fun WebResourceRequest.query(action: (url: String) -> Boolean): Boolean { return action(url?.path ?: return false) } val WebResourceRequest.isImage: Boolean get() = query { it.contains(".jpg") || it.contains(".png") } val WebResourceRequest.isMedia: Boolean get() = query { it.contains(".jpg") || it.contains(".png") || it.contains("video") } /** * Generic filter passthrough If Resource is already nonnull, pass it, otherwise check if filter is * met and override the response accordingly */ fun WebResourceResponse?.filter(request: WebResourceRequest, filter: (url: String) -> Boolean) = filter(request.query { filter(it) }) fun WebResourceResponse?.filter(filter: Boolean): WebResourceResponse? = this ?: if (filter) blankResource else null fun WebResourceResponse?.filterCss(request: WebResourceRequest): WebResourceResponse? = filter(request) { it.endsWith(".css") } fun WebResourceResponse?.filterImage(request: WebResourceRequest): WebResourceResponse? = filter(request.isImage)
gpl-3.0
009e4d30434de504ce99483de39a01ea
38.878378
99
0.753304
4.191761
false
false
false
false
mrkirby153/KirBot
src/main/kotlin/me/mrkirby153/KirBot/command/control/CommandBackfill.kt
1
3144
package me.mrkirby153.KirBot.command.control import me.mrkirby153.KirBot.backfill.BackfillJob import me.mrkirby153.KirBot.backfill.BackfillManager import me.mrkirby153.KirBot.command.CommandException import me.mrkirby153.KirBot.command.annotations.AdminCommand import me.mrkirby153.KirBot.command.annotations.Command import me.mrkirby153.KirBot.command.args.CommandContext import me.mrkirby153.KirBot.utils.Context import me.mrkirby153.kcutils.Time class CommandBackfill { @AdminCommand @Command(name = "backfill", arguments = ["<type:string>", "<id:snowflake>"]) fun execute(context: Context, cmdContext: CommandContext) { val type = cmdContext.getNotNull<String>("type") val id = cmdContext.getNotNull<String>("id") val backfillType = when (type.toLowerCase()) { "guild" -> BackfillJob.JobType.GUILD "channel" -> BackfillJob.JobType.CHANNEL "message" -> BackfillJob.JobType.MESSAGE else -> throw CommandException("Type not found") } val start = System.currentTimeMillis() val job = BackfillManager.backfill(context.guild, id, backfillType, onComplete = { context.channel.sendMessage( "Backfill ${backfillType.name.toLowerCase().capitalize()} $id finished in ${Time.format( 1, System.currentTimeMillis() - start)}").queue() }) context.channel.sendMessage( "Starting backfill of ${backfillType.name.toLowerCase().capitalize()} $id -- ${job.jobId}").queue() } @AdminCommand @Command(name = "cancel", arguments = ["<job:string>"], parent="backfill") fun cancel(context: Context, cmdContext: CommandContext) { val job = cmdContext.getNotNull<String>("job") BackfillManager.cancel(job) context.send().success("Sent interrupt to $job").queue() } @AdminCommand @Command(name = "status", parent="backfill") fun status(context: Context, cmdContext: CommandContext) { val jobs = BackfillManager.getRunningJobs() context.channel.sendMessage(buildString { appendln("**${jobs.size}** jobs are running") if (jobs.isNotEmpty()) { append("```") jobs.forEach { appendln(" - ${it.jobId}: ${it.jobType} ${it.guild.id} ${it.id}") } append("```") } }).queue() } @AdminCommand @Command(name = "logs", arguments = ["<job:string>"], parent="backfill") fun logs(context: Context, cmdContext: CommandContext) { val job = cmdContext.getNotNull<String>("job") val backfillJob = BackfillManager.getJob(job) ?: throw CommandException( "Job is not running") var msg = "" backfillJob.getLogMessages().forEach { m -> if (msg.length + m.length + 1 >= 1990) { context.channel.sendMessage(msg).queue() msg = "$m\n" } else { msg += "$m\n" } } context.channel.sendMessage(msg).queue() } }
mit
a0a8c965306e6644d9b3d03f18bc7682
38.3125
115
0.60687
4.318681
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/psi/element/MdMacroImpl.kt
1
4135
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.psi.element import com.intellij.lang.ASTNode import com.intellij.navigation.ItemPresentation import com.intellij.psi.PsiElement import com.intellij.psi.tree.IElementType import com.vladsch.md.nav.MdBundle import com.vladsch.md.nav.actions.handlers.util.PsiEditContext import com.vladsch.md.nav.parser.MdFactoryContext import com.vladsch.md.nav.psi.util.MdPsiBundle import com.vladsch.md.nav.psi.util.MdPsiImplUtil import com.vladsch.md.nav.psi.util.MdTypes import com.vladsch.md.nav.settings.MdApplicationSettings import com.vladsch.plugin.util.maxLimit import icons.MdIcons import javax.swing.Icon class MdMacroImpl(node: ASTNode) : MdReferenceElementImpl(node), MdMacro, MdStructureViewPresentableItem { override fun getMacroTextElement(): MdMacroText? { return MdPsiImplUtil.findChildByType(this, MdTypes.MACRO_TEXT) as MdMacroText? } override fun getMacroText(): String { val macroText = macroTextElement return if (macroText == null) "" else macroText.text } override fun getReferenceDisplayName(): String { return REFERENCE_DISPLAY_NAME } override fun getReferenceType(): IElementType { return REFERENCE_TYPE } override fun getReferenceIdentifier(): MdMacroId? { val id = MdPsiImplUtil.findChildByType(this, MdTypes.MACRO_ID) as MdMacroId? return id } override fun isReferenceFor(refElement: MdReferencingElement?): Boolean { return refElement is MdMacroRef && isReferenceFor(refElement.referenceId) } override fun getIcon(flags: Int): Icon? { return MdIcons.Element.MACRO } override fun normalizeReferenceId(referenceId: String?): String { return normalizeReferenceText(referenceId) } override fun getReferencingElementText(): String? { return "<<<$referenceId>>>" } private fun continuationIndent(firstLineIndent: Int, parentIndent: Int, editContext: PsiEditContext): Int { return MdIndentingCompositeImpl.continuationIndent(firstLineIndent, parentIndent, editContext) } override fun getStructureViewPresentation(): ItemPresentation { return MdElementItemPresentation(this) } override fun getLocationString(): String? { return null } override fun getPresentableText(): String { val textElement = MdPsiImplUtil.findChildTextBlock(this) ?: return "$referenceId:" val text = MdPsiImplUtil.getNodeText(textElement, true, false) val length = text.length.maxLimit(100) val eolPos = text.indexOf('\n') val result = text.substring(0, if (eolPos < 0) length else eolPos.maxLimit(length)) return "$referenceId: $result" } override fun getBreadcrumbInfo(): String { val settings = MdApplicationSettings.instance.documentSettings if (settings.showBreadcrumbText && !node.text.isEmpty()) { val truncateStringForDisplay = MdPsiImplUtil.truncateStringForDisplay(node.text, settings.maxBreadcrumbText, false, true, true) if (!truncateStringForDisplay.isEmpty()) return truncateStringForDisplay } return MdPsiBundle.message("macro") } override fun getBreadcrumbTooltip(): String? { return node.text } override fun getBreadcrumbTextElement(): PsiElement? { val textBlock = MdPsiImplUtil.findChildTextBlock(this) return textBlock } companion object { val REFERENCE_DISPLAY_NAME: String = MdBundle.message("reference.type.macro") val REFERENCE_TYPE = MdTypes.MACRO!! @JvmStatic @Suppress("UNUSED_PARAMETER") fun getElementText(factoryContext: MdFactoryContext, referenceId: String, text: String): String { return ">>>$referenceId\n$text\n<<<\n" } @JvmStatic fun normalizeReferenceText(referenceId: String?): String { return referenceId ?: "" } } }
apache-2.0
18d7ae15c3cae73d2a0b26121c2350f5
35.27193
177
0.710278
4.640853
false
false
false
false
canou/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/views/MyDialogViewPager.kt
1
1436
package com.simplemobiletools.commons.views import android.content.Context import android.support.v4.view.ViewPager import android.util.AttributeSet import android.view.MotionEvent import android.view.View class MyDialogViewPager : ViewPager { var allowSwiping = true constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) // disable manual swiping of viewpager at the dialog by swiping over the pattern override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { return false } override fun onTouchEvent(ev: MotionEvent): Boolean { if (!allowSwiping) return false try { return super.onTouchEvent(ev) } catch (ignored: Exception) { } return false } // https://stackoverflow.com/a/20784791/1967672 override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { var height = 0 for (i in 0..childCount - 1) { val child = getChildAt(i) child.measure(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)) val h = child.measuredHeight if (h > height) height = h } val newHeightMeasureSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY) super.onMeasure(widthMeasureSpec, newHeightMeasureSpec) } }
apache-2.0
49f52ce70aa64120e37fd038ea5fd485
30.217391
110
0.681755
4.723684
false
false
false
false
ac-opensource/Matchmaking-App
app/src/main/java/com/youniversals/playupgo/newmatch/step/SetDateAndTimeStepFragment.kt
1
3228
package com.youniversals.playupgo.newmatch.step import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.Toast import com.stepstone.stepper.Step import com.stepstone.stepper.VerificationError import com.youniversals.playupgo.PlayUpApplication import com.youniversals.playupgo.R import com.youniversals.playupgo.flux.action.MatchActionCreator import com.youniversals.playupgo.flux.store.MatchStore import kotlinx.android.synthetic.main.fragment_set_date_and_time_step.* import java.util.* import javax.inject.Inject /** * A simple [Fragment] subclass. */ class SetDateAndTimeStepFragment : Fragment(), Step { @Inject lateinit var matchActionCreator: MatchActionCreator @Inject lateinit var matchStore: MatchStore override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) PlayUpApplication.fluxComponent.inject(this) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment return inflater!!.inflate(R.layout.fragment_set_date_and_time_step, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) { timePicker.hour = 17 timePicker.minute = 0 } else { timePicker.currentHour = 17 timePicker.currentMinute = 0 } } override fun verifyStep(): VerificationError? { val newMatch = matchStore.newMatch ?: return VerificationError("No sport selected!") val gameDate = Calendar.getInstance() gameDate.set(Calendar.DAY_OF_MONTH, datePicker.dayOfMonth) gameDate.set(Calendar.MONTH, datePicker.month) gameDate.set(Calendar.YEAR, datePicker.year) var hour = 17 var min = 0 if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) { hour = timePicker.hour min = timePicker.minute } else { hour = timePicker.currentHour min = timePicker.currentMinute } gameDate.set(Calendar.HOUR_OF_DAY, hour) gameDate.set(Calendar.MINUTE, min) matchActionCreator.updateNewMatch(newMatch.copy(date = gameDate.timeInMillis)) //return null if the user can go to the next step, create a new VerificationError instance otherwise return null } override fun onSelected() { //update UI when selected (activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow(view?.windowToken, 0) } override fun onError(error: VerificationError) { //handle error inside of the fragment, e.g. show error on EditText Toast.makeText(context, error.errorMessage, Toast.LENGTH_SHORT).show() } }
agpl-3.0
ad5c1f0cca4c15dccdbb1b5b5896dbfa
34.472527
108
0.702912
4.495822
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/cargo/runconfig/command/RunClippyAction.kt
2
909
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.runconfig.command import com.intellij.openapi.actionSystem.AnActionEvent import org.rust.cargo.icons.CargoIcons import org.rust.cargo.project.settings.toolchain import org.rust.cargo.toolchain.RustChannel import java.nio.file.Paths class RunClippyAction : RunCargoCommandActionBase(CargoIcons.CLIPPY) { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val toolchain = project.toolchain ?: return val module = getAppropriateModule(e) ?: return val moduleDirectory = Paths.get(module.moduleFilePath).parent!! val channel = if (toolchain.isRustupAvailable) RustChannel.NIGHTLY else RustChannel.DEFAULT runCommand(module, toolchain.cargo(moduleDirectory).clippyCommandLine(channel)) } }
mit
df8bc0833013e124944742204062494b
33.961538
99
0.755776
4.247664
false
false
false
false
asymmetric-team/secure-messenger-android
conversation-view/src/main/java/com/safechat/conversation/ConversationActivity.kt
1
3044
package com.safechat.conversation import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.TextView import com.safechat.message.Message class ConversationActivity : AppCompatActivity(), ConversationView { val controller by lazy { conversationControllerProvider(this) } val adapter = ConversationAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.conversation) val otherPublicKey = intent.getStringExtra(OTHER_PUBLIC_KEY) initToolbar(otherPublicKey) initMessageInput(otherPublicKey) initMessageContainer() controller.onCreated(otherPublicKey) } private fun initMessageContainer() { val recyclerView = findViewById(R.id.conversation_messages) as RecyclerView recyclerView.layoutManager = LinearLayoutManager(this) recyclerView.adapter = adapter } private fun initMessageInput(otherPublicKey: String) { (findViewById(R.id.conversation_message) as TextView).setOnEditorActionListener { textView, i, keyEvent -> controller.onNewMessage(otherPublicKey, Message(textView.text.toString().trim(), true, false, System.currentTimeMillis())) textView.text = "" true } } private fun initToolbar(otherPublicKey: String?) { setSupportActionBar(findViewById(R.id.toolbar) as Toolbar) supportActionBar!!.title = otherPublicKey supportActionBar!!.setDisplayHomeAsUpEnabled(true) } override fun showMessages(messages: List<com.safechat.message.Message>) { adapter.add(messages.map { ConversationAdapter.MessageItemAdapter(it) }) } override fun showError() { (findViewById(R.id.conversation_error) as TextView).apply { visibility = View.VISIBLE text = "Error" } } override fun close() { finish() } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { controller.onBackArrowClick() return true } return super.onOptionsItemSelected(item) } companion object { private val OTHER_PUBLIC_KEY = "otherPublicKey" lateinit var conversationControllerProvider: (ConversationActivity) -> ConversationController val start: (Context, String) -> Unit = { context: Context, otherPublicKey: String -> context.startActivity(activityIntent(context, otherPublicKey)) } fun activityIntent(context: Context, otherPublicKey: String) = Intent(context, ConversationActivity::class.java).apply { putExtra(OTHER_PUBLIC_KEY, otherPublicKey) } } }
apache-2.0
6ca4eefefd99f07a97994760214eb05c
34.406977
173
0.708607
4.990164
false
false
false
false
jcgay/gradle-notifier
src/main/kotlin/fr/jcgay/gradle/notifier/GradleNotifierPlugin.kt
1
2776
package fr.jcgay.gradle.notifier import fr.jcgay.gradle.notifier.extension.Configuration import fr.jcgay.notification.Application import fr.jcgay.notification.Icon import fr.jcgay.notification.Notifier import fr.jcgay.notification.SendNotification import fr.jcgay.notification.SendNotificationException import fr.jcgay.notification.notifier.DoNothingNotifier import org.gradle.api.Plugin import org.gradle.api.Project import org.slf4j.LoggerFactory import java.util.Date import java.util.Properties import java.util.concurrent.TimeUnit.MILLISECONDS import javax.inject.Inject class GradleNotifierPlugin constructor(private val sendNotification: SendNotification): Plugin<Project> { private val logger = LoggerFactory.getLogger(this.javaClass) private val startTime = Clock(Date().time) @Inject constructor() : this(SendNotification()) override fun apply(project: Project) { project.extensions.create("notifier", Configuration::class.java) project.afterEvaluate { if (shouldNotifiy(it)) { val config = it.extensions.getByType(Configuration::class.java) val notifier: Notifier = createNotifier(config) it.gradle.addBuildListener(NotifierListener(notifier, startTime, config.threshold)) } } } fun createNotifier(config: Configuration): Notifier { val application = Application.builder("application/x-vnd-gradle-inc.gradle", "Gradle", GRADLE_ICON) val userTimeout = config.timeout userTimeout.time?.let {time -> userTimeout.unit?.let { unit -> application.timeout(MILLISECONDS.convert(time, unit)) } } return try { sendNotification.setApplication(application.build()) .addConfigurationProperties(mergeProperties(config)) .initNotifier() } catch (e: SendNotificationException) { logger.warn("Cannot initialize a notifier.", e) DoNothingNotifier.doNothing() } } private fun shouldNotifiy(project: Project): Boolean = when { project.gradle.rootProject.name == "buildSrc" -> false project.gradle.startParameter.isContinuous -> project.extensions.getByType(Configuration::class.java).continuousNotify else -> true } companion object { val GRADLE_ICON: Icon = Icon.create(GradleNotifierPlugin::class.java.getResource("/GradleLogoReg.png"), "gradle") @JvmStatic fun mergeProperties(config: Configuration): Properties { val result = Properties(config.asProperties()) result.putAll(System.getProperties().filter { it.key.toString().startsWith("notifier") }) return result } } }
mit
2f74b1d3e7b21a2da5daede4d86d4729
37.027397
126
0.690562
4.745299
false
true
false
false
vsch/PluginDevelopersToolbox
src/com/vladsch/pluginDevelopersToolbox/Helpers.kt
1
10933
/* * Copyright (c) 2015-2015 Vladimir Schneider <[email protected]> * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.vladsch.pluginDevelopersToolbox import java.io.UnsupportedEncodingException import java.net.URLDecoder import java.net.URLEncoder fun String?.ifNullOr(condition: Boolean, altValue: String): String { return if (this == null || condition) altValue else this } fun String?.ifNullOrNot(condition: Boolean, altValue: String): String { return if (this == null || !condition) altValue else this } inline fun String?.ifNullOr(condition: (String) -> Boolean, altValue: String): String { return if (this == null || condition(this)) altValue else this } inline fun String?.ifNullOrNot(condition: (String) -> Boolean, altValue: String): String { return if (this == null || !condition(this)) altValue else this } fun String?.ifNullOrEmpty(altValue: String): String { return if (this == null || this.isEmpty()) altValue else this } fun String?.ifNullOrBlank(altValue: String): String { return if (this == null || this.isBlank()) altValue else this } fun String?.wrapWith(prefixSuffix: Char): String { return wrapWith(prefixSuffix, prefixSuffix) } fun String?.wrapWith(prefixSuffix: Char, ignoreCase: Boolean): String { return wrapWith(prefixSuffix, prefixSuffix, ignoreCase) } fun String?.wrapWith(prefix: Char, suffix: Char): String { return prefixWith(prefix, false).suffixWith(suffix, false) } fun String?.wrapWith(prefix: Char, suffix: Char, ignoreCase: Boolean): String { return prefixWith(prefix, ignoreCase).suffixWith(suffix, ignoreCase) } fun String?.wrapWith(prefixSuffix: String): String { return wrapWith(prefixSuffix, prefixSuffix) } fun String?.wrapWith(prefixSuffix: String, ignoreCase: Boolean): String { return wrapWith(prefixSuffix, prefixSuffix, ignoreCase) } fun String?.wrapWith(prefix: String, suffix: String): String { return prefixWith(prefix, false).suffixWith(suffix, false) } fun String?.wrapWith(prefix: String, suffix: String, ignoreCase: Boolean): String { return prefixWith(prefix, ignoreCase).suffixWith(suffix, ignoreCase) } fun String?.suffixWith(suffix: Char): String { return suffixWith(suffix, false) } fun String?.suffixWith(suffix: Char, ignoreCase: Boolean): String { if (this != null && !isEmpty() && !endsWith(suffix, ignoreCase)) return plus(suffix) return orEmpty() } fun String?.suffixWith(suffix: String): String { return suffixWith(suffix, false) } fun String?.suffixWith(suffix: String, ignoreCase: Boolean): String { if (this != null && !isEmpty() && suffix.isNotEmpty() && !endsWith(suffix, ignoreCase)) return plus(suffix) return orEmpty() } fun String?.prefixWith(prefix: Char): String { return prefixWith(prefix, false) } fun String?.prefixWith(prefix: Char, ignoreCase: Boolean): String { if (this != null && !isEmpty() && !startsWith(prefix, ignoreCase)) return prefix.plus(this) return orEmpty() } fun String?.prefixWith(prefix: String): String { return prefixWith(prefix, false) } fun String?.prefixWith(prefix: String, ignoreCase: Boolean): String { if (this != null && !isEmpty() && prefix.isNotEmpty() && !startsWith(prefix, ignoreCase)) return prefix.plus(this) return orEmpty() } fun String?.endsWith(vararg needles: String): Boolean { return endsWith(false, *needles) } fun String?.endsWith(ignoreCase: Boolean, vararg needles: String): Boolean { if (this == null) return false for (needle in needles) { if (endsWith(needle, ignoreCase)) { return true } } return false } fun String?.startsWith(vararg needles: String): Boolean { return startsWith(false, *needles) } fun String?.startsWith(ignoreCase: Boolean, vararg needles: String): Boolean { if (this == null) return false for (needle in needles) { if (startsWith(needle, ignoreCase)) { return true } } return false } fun String?.count(char: Char, startIndex: Int = 0, endIndex: Int = Int.MAX_VALUE): Int { if (this == null) return 0 var count = 0 var pos = startIndex val lastIndex = Math.min(length, endIndex) while (pos >= 0 && pos <= lastIndex) { pos = indexOf(char, pos) if (pos < 0) break count++ pos++ } return count } fun String?.count(char: String, startIndex: Int = 0, endIndex: Int = Int.MAX_VALUE): Int { if (this == null) return 0 var count = 0 var pos = startIndex val lastIndex = Math.min(length, endIndex) while (pos >= 0 && pos <= lastIndex) { pos = indexOf(char, pos) if (pos < 0) break count++ pos++ } return count } fun String?.urlDecode(charSet: String? = null): String { try { return URLDecoder.decode(this, charSet ?: "UTF-8") } catch (e: UnsupportedEncodingException) { //e.printStackTrace() return orEmpty() } } fun String?.urlEncode(charSet: String? = null): String { try { return URLEncoder.encode(this, charSet ?: "UTF-8") } catch (e: UnsupportedEncodingException) { //e.printStackTrace() return orEmpty() } } fun String?.ifEmpty(arg: String): String { if (this != null && !this.isEmpty()) return this return arg } fun String?.ifEmpty(ifEmptyArg: String, ifNotEmptyArg: String): String { return if (this == null || this.isEmpty()) ifEmptyArg else ifNotEmptyArg } fun String?.ifEmptyNulls(ifEmptyArg: String?, ifNotEmptyArg: String?): String? { return if (this == null || this.isEmpty()) ifEmptyArg else ifNotEmptyArg } fun String?.ifEmpty(arg: () -> String): String { if (this != null && !this.isEmpty()) return this return arg() } fun String?.ifEmpty(ifEmptyArg: () -> String?, ifNotEmptyArg: () -> String?): String? { return if (this == null || this.isEmpty()) ifEmptyArg() else ifNotEmptyArg() } fun String?.removeStart(prefix: Char): String { if (this != null) { return removePrefix(prefix.toString()) } return "" } fun String?.removeStart(prefix: String): String { if (this != null) { return removePrefix(prefix) } return "" } fun String?.removeEnd(prefix: Char): String { if (this != null) { return removeSuffix(prefix.toString()) } return "" } fun String?.removeEnd(prefix: String): String { if (this != null) { return removeSuffix(prefix) } return "" } fun String?.regexGroup(): String { return "(?:" + this.orEmpty() + ")" } fun splicer(delimiter: String): (accum: String, elem: String) -> String { return { accum, elem -> accum + delimiter + elem } } fun skipEmptySplicer(delimiter: String): (accum: String, elem: String) -> String { return { accum, elem -> if (elem.isEmpty()) accum else accum + delimiter + elem } } fun StringBuilder.regionMatches(thisOffset:Int, other:String, otherOffset:Int, length:Int, ignoreCase: Boolean = false) : Boolean { for (i in 0..length-1) { if (!this.get(i+thisOffset).equals(other.get(i+otherOffset), ignoreCase)) return false } return true } fun StringBuilder.endsWith(suffix: String, ignoreCase: Boolean = false): Boolean { return this.length >= suffix.length && this.regionMatches(this.length - suffix.length, suffix, 0, suffix.length, ignoreCase) } fun StringBuilder.startsWith(prefix: String, ignoreCase: Boolean = false): Boolean { return this.length >= prefix.length && this.regionMatches(0, prefix, 0, prefix.length, ignoreCase) } fun Array<String>.splice(delimiter: String): String { val result = StringBuilder(this.size * (delimiter.length + 10)) var first = true; for (elem in this) { if (!elem.isEmpty()) { if (!first && !elem.startsWith(delimiter) && !result.endsWith(delimiter)) result.append(delimiter) else first = false result.append(elem.orEmpty()) } } return result.toString() } fun List<String?>.splice(delimiter: String, skipNullOrEmpty: Boolean = true): String { val result = StringBuilder(this.size * (delimiter.length + 10)) var first = true; for (elem in this) { if (elem != null && !elem.isEmpty() || !skipNullOrEmpty) { if (!first && (!skipNullOrEmpty || !elem.startsWith(delimiter) && !result.endsWith(delimiter))) result.append(delimiter) else first = false result.append(elem.orEmpty()) } } return result.toString() } fun Collection<String?>.splice(delimiter: String, skipNullOrEmpty: Boolean = true): String { val result = StringBuilder(this.size * (delimiter.length + 10)) var first = true; for (elem in this) { if (elem != null && !elem.isEmpty() || !skipNullOrEmpty) { if (!first && (!skipNullOrEmpty || !elem.startsWith(delimiter) && !result.endsWith(delimiter))) result.append(delimiter) else first = false result.append(elem.orEmpty()) } } return result.toString() } fun Iterator<String>.splice(delimiter: String, skipEmpty: Boolean = true): String { val result = StringBuilder(10 * (delimiter.length + 10)) var first = true; for (elem in this) { if (!elem.isEmpty() || !skipEmpty) { if (!first && (!skipEmpty || !elem.startsWith(delimiter) && !result.endsWith(delimiter))) result.append(delimiter) else first = false result.append(elem.orEmpty()) } } return result.toString() } fun String?.appendDelim(delimiter: String, vararg args: String): String { return arrayListOf<String?>(this.orEmpty(), *args).splice(delimiter, true) } fun <T:Any> Any?.ifNotNull(eval: () -> T?):T? = if (this == null) null else eval() fun <T:Any?> T.nullIf(nullIfValue:T) :T? = if (this == null || this == nullIfValue) null else this fun <T:Any?> Boolean.ifElse(ifTrue:T, ifFalse:T) :T = if (this) ifTrue else ifFalse operator fun <T:Any> StringBuilder.plusAssign(text:T):Unit { this.append(text) } fun repeatChar(char: Char, count:Int):String { var result = "" for (i in 1..count) { result += char } return result }
apache-2.0
b6829449d7245583ef7f148cfe50b665
30.059659
132
0.663404
3.814724
false
false
false
false
czyzby/gdx-setup
src/main/kotlin/com/github/czyzby/setup/views/extensions.kt
2
2457
package com.github.czyzby.setup.views import com.badlogic.gdx.scenes.scene2d.ui.Button import com.badlogic.gdx.utils.ObjectMap import com.github.czyzby.autumn.annotation.Processor import com.github.czyzby.autumn.context.Context import com.github.czyzby.autumn.context.ContextDestroyer import com.github.czyzby.autumn.context.ContextInitializer import com.github.czyzby.autumn.processor.AbstractAnnotationProcessor import com.github.czyzby.lml.annotation.LmlActor import com.github.czyzby.lml.parser.LmlParser import com.github.czyzby.setup.data.libs.Library import com.kotcrab.vis.ui.widget.VisTextField /** * Holds data about official and third-party extensions. * @author MJ */ @Processor class ExtensionsData : AbstractAnnotationProcessor<Extension>() { val official = mutableListOf<Library>() val thirdParty = mutableListOf<Library>() @LmlActor("\$officialExtensions") private lateinit var officialButtons: ObjectMap<String, Button> @LmlActor("\$thirdPartyExtensions") private lateinit var thirdPartyButtons: ObjectMap<String, Button> private val thirdPartyVersions = ObjectMap<String, VisTextField>() fun assignVersions(parser: LmlParser) { thirdParty.forEach { thirdPartyVersions.put(it.id, parser.actorsMappedByIds.get(it.id + "Version") as VisTextField) } } fun getVersion(libraryId: String): String = thirdPartyVersions.get(libraryId).text fun getSelectedOfficialExtensions(): Array<Library> = official.filter { officialButtons.get(it.id).isChecked }.toTypedArray() fun getSelectedThirdPartyExtensions(): Array<Library> = thirdParty.filter { thirdPartyButtons.get(it.id).isChecked }.toTypedArray() // Automatic scanning of extensions: override fun getSupportedAnnotationType(): Class<Extension> = Extension::class.java override fun isSupportingTypes(): Boolean = true override fun processType(type: Class<*>, annotation: Extension, component: Any, context: Context, initializer: ContextInitializer, contextDestroyer: ContextDestroyer) { if (annotation.official) { official.add(component as Library) } else { thirdParty.add(component as Library) } } } /** * Should annotate all third-party extensions. * @author MJ */ @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) annotation class Extension(val official: Boolean = false)
unlicense
f176ba6c734c5806fd7b87c2a52b9330
39.278689
135
0.746032
4.451087
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/AnkiDroidApp.kt
1
22232
/**************************************************************************************** * Copyright (c) 2009 Edu Zamora <[email protected]> * * Copyright (c) 2009 Casey Link <[email protected]> * * Copyright (c) 2014 Timothy Rae <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.anki import android.annotation.SuppressLint import android.app.Application import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.res.Configuration import android.content.res.Resources import android.net.Uri import android.os.Build import android.os.Environment import android.os.LocaleList import android.system.Os import android.util.Log import android.webkit.CookieManager import androidx.annotation.VisibleForTesting import androidx.core.content.edit import androidx.lifecycle.MutableLiveData import com.ichi2.anki.CrashReportService.sendExceptionReport import com.ichi2.anki.UIUtils.showThemedToast import com.ichi2.anki.analytics.UsageAnalytics import com.ichi2.anki.contextmenu.AnkiCardContextMenu import com.ichi2.anki.contextmenu.CardBrowserContextMenu import com.ichi2.anki.exception.StorageAccessException import com.ichi2.anki.services.BootService import com.ichi2.anki.services.NotificationService import com.ichi2.compat.CompatHelper import com.ichi2.themes.Themes import com.ichi2.utils.* import com.ichi2.utils.LanguageUtil.getCurrentLanguage import com.ichi2.utils.LanguageUtil.getLanguage import net.ankiweb.rsdroid.BackendFactory import timber.log.Timber import timber.log.Timber.DebugTree import java.io.InputStream import java.util.* import java.util.regex.Pattern /** * Application class. */ @KotlinCleanup("lots to do") @KotlinCleanup("IDE Lint") open class AnkiDroidApp : Application() { /** An exception if the WebView subsystem fails to load */ private var mWebViewError: Throwable? = null private val mNotifications = MutableLiveData<Void?>() @KotlinCleanup("can move analytics here now") override fun attachBaseContext(base: Context) { // update base context with preferred app language before attach // possible since API 17, only supported way since API 25 // for API < 17 we update the configuration directly super.attachBaseContext(updateContextWithLanguage(base)) // DO NOT INIT A WEBVIEW HERE (Moving Analytics to this method) // Crashes only on a Physical API 19 Device - #7135 // After we move past API 19, we're good to go. } /** * On application creation. */ override fun onCreate() { BackendFactory.defaultLegacySchema = BuildConfig.LEGACY_SCHEMA try { // enable debug logging of sync actions if (BuildConfig.DEBUG) { Os.setenv("RUST_LOG", "info,anki::sync=debug,anki::media=debug", false) } } catch (_: Exception) { } // Uncomment the following lines to see a log of all SQL statements // executed by the backend. The log may be delayed by 100ms, so you should not // assume than a given SQL statement has run after a Timber.* line just // because the SQL statement appeared later. // Os.setenv("TRACESQL", "1", false); super.onCreate() if (isInitialized) { Timber.i("onCreate() called multiple times") // 5887 - fix crash. if (instance.resources == null) { Timber.w("Skipping re-initialisation - no resources. Maybe uninstalling app?") return } } instance = this // Get preferences val preferences = getSharedPrefs(this) // TODO remove the following if-block once AnkiDroid uses the new schema by default if (BuildConfig.LEGACY_SCHEMA) { val isNewSchemaEnabledByPref = preferences.getBoolean(getString(R.string.pref_rust_backend_key), false) if (isNewSchemaEnabledByPref) { Timber.i("New schema enabled by preference") BackendFactory.defaultLegacySchema = false } } CrashReportService.initialize(this) if (BuildConfig.DEBUG) { // Enable verbose error logging and do method tracing to put the Class name as log tag Timber.plant(DebugTree()) LeakCanaryConfiguration.setInitialConfigFor(this) } else { Timber.plant(ProductionCrashReportingTree()) LeakCanaryConfiguration.disable() } Timber.tag(TAG) Timber.d("Startup - Application Start") // analytics after ACRA, they both install UncaughtExceptionHandlers but Analytics chains while ACRA does not UsageAnalytics.initialize(this) if (BuildConfig.DEBUG) { UsageAnalytics.setDryRun(true) } // Stop after analytics and logging are initialised. if (CrashReportService.isProperServiceProcess()) { Timber.d("Skipping AnkiDroidApp.onCreate from ACRA sender process") return } if (AdaptionUtil.isUserATestClient) { showThemedToast(this.applicationContext, getString(R.string.user_is_a_robot), false) } // make default HTML / JS debugging true for debug build and disable for unit/android tests if (BuildConfig.DEBUG && !AdaptionUtil.isRunningAsUnitTest) { preferences.edit { putBoolean("html_javascript_debugging", true) } } CardBrowserContextMenu.ensureConsistentStateWithPreferenceStatus( this, preferences.getBoolean( getString(R.string.card_browser_external_context_menu_key), false ) ) AnkiCardContextMenu.ensureConsistentStateWithPreferenceStatus( this, preferences.getBoolean(getString(R.string.anki_card_external_context_menu_key), true) ) CompatHelper.compat.setupNotificationChannel(applicationContext) // Configure WebView to allow file scheme pages to access cookies. if (!acceptFileSchemeCookies()) { return } // Forget the last deck that was used in the CardBrowser CardBrowser.clearLastDeckId() LanguageUtil.setDefaultBackendLanguages() // Create the AnkiDroid directory if missing. Send exception report if inaccessible. if (Permissions.hasStorageAccessPermission(this)) { try { val dir = CollectionHelper.getCurrentAnkiDroidDirectory(this) CollectionHelper.initializeAnkiDroidDirectory(dir) } catch (e: StorageAccessException) { Timber.e(e, "Could not initialize AnkiDroid directory") val defaultDir = CollectionHelper.getDefaultAnkiDroidDirectory(this) if (isSdCardMounted && CollectionHelper.getCurrentAnkiDroidDirectory(this) == defaultDir) { // Don't send report if the user is using a custom directory as SD cards trip up here a lot sendExceptionReport(e, "AnkiDroidApp.onCreate") } } } Timber.i("AnkiDroidApp: Starting Services") BootService().onReceive(this, Intent(this, BootService::class.java)) // Register for notifications mNotifications.observeForever { NotificationService.triggerNotificationFor(this) } Themes.systemIsInNightMode = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES Themes.updateCurrentTheme() } fun scheduleNotification() { mNotifications.postValue(null) } @Suppress("deprecation") // 7109: setAcceptFileSchemeCookies protected fun acceptFileSchemeCookies(): Boolean { return try { CookieManager.setAcceptFileSchemeCookies(true) true } catch (e: Throwable) { // 5794: Errors occur if the WebView fails to load // android.webkit.WebViewFactory.MissingWebViewPackageException.MissingWebViewPackageException // Error may be excessive, but I expect a UnsatisfiedLinkError to be possible here. mWebViewError = e sendExceptionReport(e, "setAcceptFileSchemeCookies") Timber.e(e, "setAcceptFileSchemeCookies") false } } /** * A tree which logs necessary data for crash reporting. * * Requirements: * 1) ignore verbose and debug log levels * 2) use the fixed AnkiDroidApp.TAG log tag (ACRA filters logcat for it when reporting errors) * 3) dynamically discover the class name and prepend it to the message for warn and error */ @SuppressLint("LogNotTimber") class ProductionCrashReportingTree : Timber.Tree() { /** * Extract the tag which should be used for the message from the `element`. By default * this will use the class name without any anonymous class suffixes (e.g., `Foo$1` * becomes `Foo`). * * * Note: This will not be called if an API with a manual tag was called with a non-null tag */ fun createStackElementTag(element: StackTraceElement): String { val m = ANONYMOUS_CLASS.matcher(element.className) val tag = if (m.find()) m.replaceAll("") else element.className return tag.substring(tag.lastIndexOf('.') + 1) } // --- this is not present in the Timber.DebugTree copy/paste --- // We are in production and should not crash the app for a logging failure // throw new IllegalStateException( // "Synthetic stacktrace didn't have enough elements: are you using proguard?"); // --- end of alteration from upstream Timber.DebugTree.getTag --- // DO NOT switch this to Thread.getCurrentThread().getStackTrace(). The test will pass // because Robolectric runs them on the JVM but on Android the elements are different. val tag: String get() { // DO NOT switch this to Thread.getCurrentThread().getStackTrace(). The test will pass // because Robolectric runs them on the JVM but on Android the elements are different. val stackTrace = Throwable().stackTrace return if (stackTrace.size <= CALL_STACK_INDEX) { // --- this is not present in the Timber.DebugTree copy/paste --- // We are in production and should not crash the app for a logging failure "$TAG unknown class" // throw new IllegalStateException( // "Synthetic stacktrace didn't have enough elements: are you using proguard?"); // --- end of alteration from upstream Timber.DebugTree.getTag --- } else createStackElementTag(stackTrace[CALL_STACK_INDEX]) } // ---- END copied from Timber.DebugTree because DebugTree.getTag() is package private ---- override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { when (priority) { Log.VERBOSE, Log.DEBUG -> {} Log.INFO -> Log.i(TAG, message, t) Log.WARN -> Log.w(TAG, "${this.tag}/ $message", t) Log.ERROR, Log.ASSERT -> Log.e(TAG, "${this.tag}/ $message", t) } } companion object { // ---- BEGIN copied from Timber.DebugTree because DebugTree.getTag() is package private ---- private const val CALL_STACK_INDEX = 6 private val ANONYMOUS_CLASS = Pattern.compile("(\\$\\d+)+$") } } companion object { /** Running under instrumentation. a "/androidTest" directory will be created which contains a test collection */ var INSTRUMENTATION_TESTING = false /** * Toggles Scoped Storage functionality introduced in later commits * * * Can be set to true or false only by altering the declaration itself. * This restriction ensures that this flag will only be used by developers for testing * * * Set to false by default, so won't migrate data or use new scoped dirs * * * If true, enables data migration & use of scoped dirs in later commits * * * Should be set to true for testing Scoped Storage * * * TODO: Should be removed once app is fully functional under Scoped Storage */ var TESTING_SCOPED_STORAGE = false const val XML_CUSTOM_NAMESPACE = "http://arbitrary.app.namespace/com.ichi2.anki" const val ANDROID_NAMESPACE = "http://schemas.android.com/apk/res/android" // Tag for logging messages. const val TAG = "AnkiDroid" /** Singleton instance of this class. * Note: this may not be initialized if AnkiDroid is run via BackupManager */ lateinit var instance: AnkiDroidApp private set /** * The latest package version number that included important changes to the database integrity check routine. All * collections being upgraded to (or after) this version must run an integrity check as it will contain fixes that * all collections should have. */ const val CHECK_DB_AT_VERSION = 21000172 /** HACK: Whether an exception report has been thrown - TODO: Rewrite an ACRA Listener to do this */ @VisibleForTesting var sentExceptionReportHack = false fun getResourceAsStream(name: String): InputStream { return instance.applicationContext.classLoader.getResourceAsStream(name) } @get:JvmName("isInitialized") val isInitialized: Boolean get() = this::instance.isInitialized @VisibleForTesting(otherwise = VisibleForTesting.NONE) fun simulateRestoreFromBackup() { val field = AnkiDroidApp::class.java.getDeclaredField("instance") with(field) { isAccessible = true set(field, null) } } @VisibleForTesting(otherwise = VisibleForTesting.NONE) fun internalSetInstanceValue(value: AnkiDroidApp) { val field = AnkiDroidApp::class.java.getDeclaredField("instance") with(field) { isAccessible = true set(field, value) } } /** * Convenience method for accessing Shared preferences * * @param context Context to get preferences for. * @return A SharedPreferences object for this instance of the app. */ @Suppress("deprecation") // TODO Tracked in https://github.com/ankidroid/Anki-Android/issues/5019 fun getSharedPrefs(context: Context?): SharedPreferences { return android.preference.PreferenceManager.getDefaultSharedPreferences(context) } val cacheStorageDirectory: String get() = instance.cacheDir.absolutePath val appResources: Resources get() = instance.resources val isSdCardMounted: Boolean get() = Environment.MEDIA_MOUNTED == Environment.getExternalStorageState() /** * Returns a Context with the correct, saved language, to be attached using attachBase(). * For old APIs directly sets language using deprecated functions * * @param remoteContext The base context offered by attachBase() to be passed to super.attachBase(). * Can be modified here to set correct GUI language. */ fun updateContextWithLanguage(remoteContext: Context): Context { return try { // sInstance (returned by getInstance() ) set during application OnCreate() // if getInstance() is null, the method is called during applications attachBaseContext() // and preferences need mBase directly (is provided by remoteContext during attachBaseContext()) val preferences = if (isInitialized) { getSharedPrefs(instance.baseContext) } else { getSharedPrefs(remoteContext) } val langConfig = getLanguageConfig(remoteContext.resources.configuration, preferences) remoteContext.createConfigurationContext(langConfig) } catch (e: Exception) { Timber.e(e, "failed to update context with new language") // during AnkiDroidApp.attachBaseContext() ACRA is not initialized, so the exception report will not be sent sendExceptionReport(e, "AnkiDroidApp.updateContextWithLanguage") remoteContext } } /** * Creates and returns a new configuration with the chosen GUI language that is saved in the preferences * * @param remoteConfig The configuration of the remote context to set the language for * @param prefs */ private fun getLanguageConfig( remoteConfig: Configuration, prefs: SharedPreferences ): Configuration { val newConfig = Configuration(remoteConfig) val newLocale = LanguageUtil.getLocale(prefs.getLanguage(), prefs) Timber.d("AnkiDroidApp::getLanguageConfig - setting locale to %s", newLocale) // API level >=24 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // Build list of locale strings, separated by commas: newLocale as first element var strLocaleList = newLocale.toLanguageTag() // if Anki locale from settings is no equal to system default, add system default as second item // LocaleList must not contain language tags twice, will crash otherwise! if (!strLocaleList.contains(Locale.getDefault().toLanguageTag())) { strLocaleList = strLocaleList + "," + Locale.getDefault().toLanguageTag() } val newLocaleList = LocaleList.forLanguageTags(strLocaleList) // first element of setLocales() is automatically setLocal() newConfig.setLocales(newLocaleList) } else { // API level >=17 but <24 newConfig.setLocale(newLocale) } return newConfig } fun getMarketIntent(context: Context): Intent { val uri = context.getString(if (CompatHelper.isKindle) R.string.link_market_kindle else R.string.link_market) val parsed = Uri.parse(uri) return Intent(Intent.ACTION_VIEW, parsed) } // TODO actually this can be done by translating "link_help" string for each language when the App is // properly translated /** * Get the url for the feedback page * @return */ val feedbackUrl: String get() = // TODO actually this can be done by translating "link_help" string for each language when the App is // properly translated when (getSharedPrefs(instance).getCurrentLanguage()) { "ja" -> appResources.getString(R.string.link_help_ja) "zh" -> appResources.getString(R.string.link_help_zh) "ar" -> appResources.getString(R.string.link_help_ar) else -> appResources.getString(R.string.link_help) } // TODO actually this can be done by translating "link_manual" string for each language when the App is // properly translated /** * Get the url for the manual * @return */ val manualUrl: String get() = // TODO actually this can be done by translating "link_manual" string for each language when the App is // properly translated when (getSharedPrefs(instance).getCurrentLanguage()) { "ja" -> appResources.getString(R.string.link_manual_ja) "zh" -> appResources.getString(R.string.link_manual_zh) "ar" -> appResources.getString(R.string.link_manual_ar) else -> appResources.getString(R.string.link_manual) } fun webViewFailedToLoad(): Boolean { return instance.mWebViewError != null } val webViewErrorMessage: String? get() { val error = instance.mWebViewError if (error == null) { Timber.w("getWebViewExceptionMessage called without webViewFailedToLoad check") return null } return ExceptionUtil.getExceptionMessage(error) } } }
gpl-3.0
ff7a0514780deb68da810d6cfee27e78
45.413361
124
0.612945
5.198036
false
true
false
false
fan123199/V2ex-simple
app/src/main/java/im/fdx/v2ex/ui/LoginActivity.kt
1
10739
package im.fdx.v2ex.ui import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View.GONE import android.view.View.VISIBLE import android.widget.EditText import androidx.appcompat.app.AlertDialog import androidx.core.os.bundleOf import com.bumptech.glide.load.model.GlideUrl import com.bumptech.glide.load.model.LazyHeaders import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade import com.elvishew.xlog.XLog import im.fdx.v2ex.GlideApp import im.fdx.v2ex.R import im.fdx.v2ex.databinding.ActivityLoginBinding import im.fdx.v2ex.network.* import im.fdx.v2ex.network.NetManager.HTTPS_V2EX_BASE import im.fdx.v2ex.network.NetManager.SIGN_IN_URL import im.fdx.v2ex.pref import im.fdx.v2ex.setLogin import im.fdx.v2ex.utils.Keys import im.fdx.v2ex.utils.extensions.logd import im.fdx.v2ex.utils.extensions.loge import im.fdx.v2ex.utils.extensions.setStatusBarColor import im.fdx.v2ex.utils.extensions.setUpToolbar import im.fdx.v2ex.view.CustomChrome import okhttp3.* import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import org.jetbrains.anko.longToast import org.jetbrains.anko.toast import org.jsoup.Jsoup import java.io.IOException class LoginActivity : BaseActivity() { /** * 不一定是用户名,可能是邮箱 */ private var loginName: String? = null private var password: String? = null var onceCode: String? = null var passwordKey: String? = null var nameKey: String? = null var imageCodeKey: String? = null private lateinit var binding: ActivityLoginBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLoginBinding.inflate(layoutInflater) setContentView(binding.root) setUpToolbar() setStatusBarColor(R.color.bg_login) val usernamePref = pref.getString(Keys.KEY_USERNAME, "") binding.btnLogin.setOnClickListener { if (!isValidated()) return@setOnClickListener loginName = binding.inputUsername.text.toString() password = binding.inputPassword.text.toString() binding.pbLogin.visibility = VISIBLE binding.btnLogin.visibility = GONE postLogin(nameKey ?: "", passwordKey ?: "", onceCode = onceCode ?: "", imageCodeKey = imageCodeKey ?: "") } binding.linkSignUp.setOnClickListener { CustomChrome(this@LoginActivity).load(NetManager.SIGN_UP_URL) } binding.ivCode.setOnClickListener { getLoginElement() } binding.tvGoogleLogin.setOnClickListener{ if(onceCode == null) { toast("请稍后") } else { val intent = Intent(this, WebViewActivity::class.java).apply { putExtras(bundleOf( "url" to "https://www.v2ex.com/auth/google?once=$onceCode")) } startActivityForResult(intent, 144 ) } } if (!usernamePref.isNullOrEmpty()) { binding.inputUsername.setText(usernamePref) binding.inputPassword.requestFocus() } getLoginElement() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == 144 && resultCode == RESULT_OK) { finish() } } private fun getLoginElement() { val requestToGetOnce = Request.Builder() .url(SIGN_IN_URL) .build() HttpHelper.OK_CLIENT.newCall(requestToGetOnce).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { loge("error in get login page") } @Throws(IOException::class) override fun onResponse(call: Call, response0: Response) { val htmlString = response0.body?.string() val body = Jsoup.parse(htmlString).body() nameKey = body.getElementsByAttributeValue("placeholder", "用户名或电子邮箱地址").attr("name") passwordKey = body.getElementsByAttributeValue("type", "password").attr("name") onceCode = body.getElementsByAttributeValue("name", "once").attr("value") imageCodeKey = body.getElementsByAttributeValue("placeholder", "请输入上图中的验证码").attr("name") runOnUiThread { val str = "https://www.v2ex.com/_captcha?once=$onceCode" val headers: LazyHeaders = LazyHeaders.Builder() .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") .addHeader("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7") .addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6") .addHeader("Host", "www.v2ex.com") .addHeader("Cache-Control", "max-age=0") // .addHeader("X-Requested-With", "com.android.browser") // .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3013.3 Mobile Safari/537.36"); .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" + " (KHTML, like Gecko) Chrome/58.0.3013.3 Safari/537.36") .addHeader("cookie", HttpHelper.myCookieJar.loadForRequest(str.toHttpUrlOrNull()!!).joinToString(separator = ";")) .build() val url = GlideUrl(str, headers) if ([email protected]) { GlideApp.with(binding.ivCode) .load(url) .transition(withCrossFade()) .centerCrop().into(binding.ivCode) } } XLog.tag("LoginActivity").d("$nameKey|$passwordKey|$onceCode|$imageCodeKey") } }) } private fun postLogin(nameKey: String, passwordKey: String, onceCode: String, imageCodeKey: String) { val requestBody = FormBody.Builder() .add(nameKey, binding.inputUsername.text.toString()) .add(passwordKey, binding.inputPassword.text.toString()) .add(imageCodeKey, binding.etInputCode.text.toString()) .add("once", onceCode) .build() val request = Request.Builder() .url(SIGN_IN_URL) .header("Origin", HTTPS_V2EX_BASE) .header("Referer", SIGN_IN_URL) .header("Content-Type", "application/x-www-form-urlencoded") .post(requestBody) .build() HttpHelper.OK_CLIENT.newCall(request).start(object : Callback { override fun onFailure(call: Call, e: IOException) { Log.e("LoginActivity", "error in Post Login") } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val httpcode = response.code val errorMsg = Parser(response.body!!.string()).getErrorMsg() logd("http code: ${response.code}") logd("errorMsg: $errorMsg") when (httpcode) { 302 -> { vCall(HTTPS_V2EX_BASE).start(object : Callback { override fun onFailure(call: Call, e: IOException) { e.printStackTrace() } @Throws(IOException::class) override fun onResponse(call: Call, response2: Response) { if (response2.code == 302) { if (("/2fa" == response2.header("Location"))) { runOnUiThread { binding.pbLogin.visibility = GONE binding.btnLogin.visibility = VISIBLE showTwoStepDialog(this@LoginActivity) } } } else { setLogin(true) runOnUiThread { toast("登录成功") finish() } } } }) } 200 -> runOnUiThread { longToast("登录失败:\n $errorMsg") binding.pbLogin.visibility = GONE binding.btnLogin.visibility = VISIBLE } } } }) } private fun isValidated(): Boolean { val username = binding.inputUsername.text.toString() val password = binding.inputPassword.text.toString() if (username.isEmpty()) { binding.inputUsername.error = "名字不能为空" binding.inputUsername.requestFocus() return false } if (password.isEmpty()) { binding.inputPassword.error = "密码不能为空" binding.inputPassword.requestFocus() return false } if (binding.etInputCode.text.isNullOrEmpty()) { binding.etInputCode.error = "验证码不能为空" binding.etInputCode.requestFocus() return false } return true } /** * 两步验证,对话框 */ @SuppressLint("InflateParams") fun showTwoStepDialog(activity: Activity) { val dialogEt = LayoutInflater.from(activity).inflate(R.layout.dialog_et, null) val etCode = dialogEt.findViewById<EditText>(R.id.et_two_step_code) AlertDialog.Builder(activity, R.style.AppTheme_Simple) .setTitle("您需要进行两步验证") .setPositiveButton("验证") { _, _ -> finishLogin(etCode.text.toString(), activity) } .setNegativeButton("暂不登录") { _, _ -> HttpHelper.myCookieJar.clear() setLogin(false) } .setView(dialogEt).show() } /** * 两步验证,完成登录 */ private fun finishLogin(code: String, activity: Activity) { val twoStepUrl = "https://www.v2ex.com/2fa" vCall(twoStepUrl).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { NetManager.dealError(activity) } override fun onResponse(call: Call, response: Response) { if (response.code == 200) { val bodyStr = response.body?.string()!! val once = Parser(bodyStr).getOnceNum() val body: RequestBody = FormBody.Builder() .add("code", code) .add("once", once).build() HttpHelper.OK_CLIENT.newCall(Request.Builder() .post(body) .url(twoStepUrl) .build()) .enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { NetManager.dealError(activity) } override fun onResponse(call: Call, response: Response) { activity.runOnUiThread { if (response?.code == 302) { activity.toast("登录成功") setLogin(true) } else { activity.toast("登录失败") } } } }) } } }) } }
apache-2.0
3a3bf59a816feab2a4f73b0236999dbd
33.993355
180
0.618247
4.087311
false
false
false
false
vovagrechka/k2php
k2php/src/k2php/php-ast.kt
1
12565
package k2php import com.intellij.util.SmartList import org.jetbrains.kotlin.js.backend.ast.* import org.jetbrains.kotlin.js.common.Symbol import org.jetbrains.kotlin.js.translate.context.StaticContext import org.jetbrains.kotlin.js.util.AstUtil import kotlin.properties.Delegates.notNull import photlin.* fun phpThisRef(): JsExpression { return JsNameRef("this")-{o-> o.kind = PHPNameRefKind.VAR } } fun phpName(s: String): JsName { return StaticContext.current.program.scope.declareName(s) } fun phpNameRef(s: String): JsNameRef { return JsNameRef(s) } fun newPHPVar(name: JsName, expr: JsExpression?): JsVars { return JsVars(JsVars.JsVar(name, expr)) } //class PHPVars @JvmOverloads constructor(private val vars: MutableList<PHPVar> = SmartList<PHPVar>(), val isMultiline: Boolean = false) : SourceInfoAwareJsNode(), JsStatement, Iterable<PHPVar> { // // constructor(multiline: Boolean) : this(SmartList<PHPVar>(), multiline) {} // // constructor(`var`: PHPVar) : this(SmartList(`var`), false) {} // // constructor(vararg vars: PHPVar) : this(SmartList(*vars), false) {} // // // fun add(`var`: PHPVar) { // vars.add(`var`) // } // // fun addAll(vars: Collection<PHPVar>) { // this.vars.addAll(vars) // } // // fun addAll(otherVars: PHPVars) { // this.vars.addAll(otherVars.vars) // } // // val isEmpty: Boolean // get() = vars.isEmpty() // // override fun iterator(): Iterator<PHPVar> { // return vars.iterator() // } // // fun getVars(): List<PHPVar> { // return vars // } // // override fun accept(v: JsVisitor) { // v.visitPHPVars(this) // } // // override fun acceptChildren(visitor: JsVisitor) { // visitor.acceptWithInsertRemove(vars) // } // // override fun traverse(v: JsVisitorWithContext, ctx: JsContext<*>) { // if (v.visit(this, ctx)) { // v.acceptList(vars) // } // v.endVisit(this, ctx) // } // // override fun deepCopy(): PHPVars { // return PHPVars(AstUtil.deepCopy(vars), isMultiline).withMetadataFrom(this) // } //} //class PHPVar(val name: JsName, var initExpression: JsExpression? = null, val visibility: String? = null) : SourceInfoAwareJsNode() { // init { // constructed() // } // // private fun constructed() { // val fuck = "break on me" // } // // override fun accept(v: JsVisitor) { // v.visit(this) // } // // override fun acceptChildren(visitor: JsVisitor) { // val initExpression = this.initExpression // if (initExpression != null) { // visitor.accept<JsExpression>(initExpression) // } // } // // override fun traverse(v: JsVisitorWithContext, ctx: JsContext<*>) { // if (v.visit(this, ctx)) { // if (initExpression != null) { // initExpression = v.accept<JsExpression>(initExpression) // } // } // v.endVisit(this, ctx) // } // // override fun deepCopy(): PHPVar { // val initExpression = this.initExpression // if (initExpression == null) return PHPVar(name) // // return PHPVar(name, initExpression.deepCopy()).withMetadataFrom(this) // } //} //class PHPFieldRef(var receiver: JsExpression, val fieldName: JsName) : JsExpression() { // init { // } // // override fun accept(v: JsVisitor) { // v.visitPHPFieldRef(this) // } // // override fun acceptChildren(visitor: JsVisitor) { // visitor.accept(receiver) // } // // override fun traverse(v: JsVisitorWithContext, ctx: JsContext<*>) { // if (v.visit(this, ctx)) { // receiver = v.accept(receiver) // } // v.endVisit(this, ctx) // } // // override fun deepCopy(): PHPFieldRef { // val receiverCopy = AstUtil.deepCopy(receiver) // return PHPFieldRef(receiverCopy!!, fieldName).withMetadataFrom(this) // } //} //class PHPVarRef : JsExpression, HasName { // // private var ident: String? = null // private var name: JsName? = null //// var qualifier: JsExpression? = null // // constructor(name: JsName) { // this.name = name // constructed() // } // // constructor(ident: String) { // this.ident = ident // constructed() // } // // private fun constructed() { // initDebugTag() // } // // fun getIdent(): String { // return if (name == null) ident!! else name!!.ident // } // // override fun getName(): JsName? { // return name // } // // override fun setName(name: JsName) { // this.name = name // } // // override fun getSymbol(): Symbol? { // return name // } // // override fun isLeaf(): Boolean { // return true //// return qualifier == null // } // // fun resolve(name: JsName) { // this.name = name // ident = null // } // // override fun accept(v: JsVisitor) { // v.visitPHPVarRef(this) // } // // override fun acceptChildren(visitor: JsVisitor) { //// if (qualifier != null) { //// visitor.accept<JsExpression>(qualifier) //// } // } // // override fun traverse(v: JsVisitorWithContext, ctx: JsContext<*>) { // if (v.visit(this, ctx)) { //// if (qualifier != null) { //// qualifier = v.accept<JsExpression>(qualifier) //// } // } // v.endVisit(this, ctx) // } // // override fun deepCopy(): PHPVarRef { //// val qualifierCopy = AstUtil.deepCopy(qualifier) // // val res = if (name != null) { // PHPVarRef(name!!).withMetadataFrom(this) // } else { // return PHPVarRef(ident!!).withMetadataFrom(this) // } // return res // } //} class PHPGlobalVarRef : JsExpression, HasName { private var ident: String? = null private var name: JsName? = null // var qualifier: JsExpression? = null constructor(name: JsName) { this.name = name constructed() } constructor(ident: String) { this.ident = ident constructed() } private fun constructed() { initDebugTag() } fun getIdent(): String { return if (name == null) ident!! else name!!.ident } override fun getName(): JsName? { return name } override fun setName(name: JsName) { this.name = name } override fun getSymbol(): Symbol? { return name } override fun isLeaf(): Boolean { return true // return qualifier == null } fun resolve(name: JsName) { this.name = name ident = null } override fun accept(v: JsVisitor) { v.visitPHPGlobalVarRef(this) } override fun acceptChildren(visitor: JsVisitor) { // if (qualifier != null) { // visitor.accept<JsExpression>(qualifier) // } } override fun traverse(v: JsVisitorWithContext, ctx: JsContext<*>) { if (v.visit(this, ctx)) { // if (qualifier != null) { // qualifier = v.accept<JsExpression>(qualifier) // } } v.endVisit(this, ctx) } override fun deepCopy(): PHPGlobalVarRef { // val qualifierCopy = AstUtil.deepCopy(qualifier) val res = if (name != null) { PHPGlobalVarRef(name!!).withMetadataFrom(this) } else { return PHPGlobalVarRef(ident!!).withMetadataFrom(this) } return res } } //sealed class PHPInvocationCallee { // class NamedFunction(val name: JsName) : PHPInvocationCallee() //// class VarArrowMethod(val varName: String, val methodName: String) : PHPInvocationCallee() //} //class PHPInvocation(var callee: JsExpression, arguments: List<JsExpression>) : JsExpression.JsExpressionHasArguments(SmartList(arguments)) { // // init { // constructed() // } // // private fun constructed() { // val fuck = "break on me" // } // // override fun getArguments(): List<JsExpression> { // return arguments // } // // override fun accept(v: JsVisitor) { // v.visitPHPInvocation(this) // } // // override fun acceptChildren(visitor: JsVisitor) { // visitor.accept(callee) // visitor.acceptList(arguments) // } // // override fun traverse(v: JsVisitorWithContext, ctx: JsContext<*>) { // if (v.visit(this, ctx)) { // callee = v.accept(callee) // v.acceptList(arguments) // } // v.endVisit(this, ctx) // } // // override fun deepCopy(): PHPInvocation { // val calleeCopy = AstUtil.deepCopy(callee) // val argumentsCopy = AstUtil.deepCopy(arguments) // return PHPInvocation(calleeCopy!!, argumentsCopy).withMetadataFrom(this) // } //} class PHPMethodCall(val receiver: JsExpression, val methodName: String, arguments: List<JsExpression>) : JsExpression.JsExpressionHasArguments(SmartList(arguments)) { init { initDebugTag() } override fun getArguments(): List<JsExpression> { return arguments } override fun accept(v: JsVisitor) { v.visitPHPMethodCall(this) } override fun acceptChildren(visitor: JsVisitor) { visitor.acceptList(arguments) } override fun traverse(v: JsVisitorWithContext, ctx: JsContext<*>) { if (v.visit(this, ctx)) { // callee = v.accept(callee) v.acceptList(arguments) } v.endVisit(this, ctx) } override fun deepCopy(): PHPMethodCall { // val qualifierCopy = AstUtil.deepCopy(qualifier) val argumentsCopy = AstUtil.deepCopy(arguments) return PHPMethodCall(receiver, methodName, argumentsCopy).withMetadataFrom(this) } } class PHPStaticMethodCall(val className: String, val methodName: String, arguments: List<JsExpression>) : JsExpression.JsExpressionHasArguments(SmartList(arguments)) { init { initDebugTag() } override fun getArguments(): List<JsExpression> { return arguments } override fun accept(v: JsVisitor) { v.visitPHPStaticMethodCall(this) } override fun acceptChildren(visitor: JsVisitor) { // visitor.accept(qualifier) visitor.acceptList(arguments) } override fun traverse(v: JsVisitorWithContext, ctx: JsContext<*>) { if (v.visit(this, ctx)) { // callee = v.accept(callee) v.acceptList(arguments) } v.endVisit(this, ctx) } override fun deepCopy(): PHPStaticMethodCall { val argumentsCopy = AstUtil.deepCopy(arguments) return PHPStaticMethodCall(className, methodName, argumentsCopy).withMetadataFrom(this) } } class PHPClass @JvmOverloads constructor(val className: JsName, val statements: MutableList<JsStatement> = mutableListOf()) : SourceInfoAwareJsNode(), JsStatement { var constructorFunction by notNull<JsFunction>() init { initDebugTag() } val isEmpty: Boolean get() = statements.isEmpty() override fun accept(v: JsVisitor) { v.visitPHPClass(this) } override fun acceptChildren(visitor: JsVisitor) { visitor.acceptWithInsertRemove(statements) } override fun traverse(v: JsVisitorWithContext, ctx: JsContext<*>) { if (v.visit(this, ctx)) { v.acceptStatementList(statements) } v.endVisit(this, ctx) } override fun deepCopy(): PHPClass { return PHPClass(className, AstUtil.deepCopy(statements)).withMetadataFrom(this) } } class JsSingleLineComment(val text: String) : SourceInfoAwareJsNode(), JsStatement { init { initDebugTag() } override fun accept(v: JsVisitor) { v.visitSingleLineComment(this) } override fun traverse(v: JsVisitorWithContext, ctx: JsContext<*>) { v.visit(this, ctx) v.endVisit(this, ctx) } override fun deepCopy(): JsSingleLineComment { return this } } class PHPPlainCodeExpression(val spewCode: () -> String) : JsExpression() { init { initDebugTag() } override fun accept(visitor: JsVisitor) { visitor.visitPHPPlainCodeExpression(this) } override fun traverse(visitor: JsVisitorWithContext, ctx: JsContext<*>) { } override fun deepCopy(): PHPPlainCodeExpression { return this } } enum class PHPNameRefKind { DUNNO, VAR, GLOBAL_VAR, FIELD, STATIC, LAMBDA, LAMBDA_CREATOR, STRING_LITERAL }
apache-2.0
26a847e84a05d930ef24d4d35c7706bf
24.02988
195
0.598567
3.761976
false
false
false
false
BrianLusina/MovieReel
app/src/main/kotlin/com/moviereel/ui/entertain/base/EntertainPageBaseAdapter.kt
1
1772
package com.moviereel.ui.entertain.base import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.moviereel.R import com.moviereel.ui.base.BaseRecyclerAdapter import com.moviereel.ui.base.BaseViewHolder /** * @author lusinabrian on 13/09/17. * @Notes base adapter for entertainment */ abstract class EntertainPageBaseAdapter<E>(objectList: ArrayList<E>) : BaseRecyclerAdapter<E>(objectList) { val VIEW_TYPE_LOADING = 0 val VIEW_TYPE_NORMAL = 1 lateinit var mCallback: Callback fun setCallback(callback: Callback) { mCallback = callback } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): EntertainPageBaseViewHolder<E> { return when (viewType) { VIEW_TYPE_LOADING -> { val v = LayoutInflater.from(parent?.context).inflate(R.layout.progress_dialog, parent, false) LoadingViewHolder(v) } else -> { val v = LayoutInflater.from(parent?.context).inflate(R.layout.item_empty_view, parent, false) EmptyViewHolder(v) } } } override fun getItemViewType(position: Int): Int { return if (objectList.size > 0) { VIEW_TYPE_NORMAL } else { VIEW_TYPE_LOADING } } override fun getItemCount() = objectList.size interface Callback { fun onViewEmptyViewRetryClick() } inner class EmptyViewHolder(itemView: View) : EntertainPageBaseViewHolder<E>(itemView) { fun onRetryClick() { // btn_retry mCallback.onViewEmptyViewRetryClick() } } inner class LoadingViewHolder(itemView: View) : EntertainPageBaseViewHolder<E>(itemView) }
mit
afb2dab23e49d0414a02dab3e8185384
28.065574
109
0.650677
4.463476
false
false
false
false
tfcbandgeek/SmartReminders-android
app/src/main/java/jgappsandgames/smartreminderslite/adapter/TagAdapter.kt
1
3368
package jgappsandgames.smartreminderslite.adapter // Android OS import android.app.Activity // Views import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView // Anko import org.jetbrains.anko.sdk25.coroutines.onClick // App import jgappsandgames.smartreminderslite.R // Save import jgappsandgames.smartreminderssave.tags.TagManager /** * TagAdapter */ class TagAdapter(private var activity: Activity, private var switcher: TagSwitcher, _tags: ArrayList<String>, private var selected: Boolean = false, search: String = ""): BaseAdapter() { // Data ---------------------------------------------------------------------------------------- private var tags: ArrayList<String> = ArrayList() // Initializer --------------------------------------------------------------------------------- init { if (selected) for (tag in _tags) { if (tag.toLowerCase().contains(search.toLowerCase())) { if (TagManager.tags.contains(tag)) tags.add(tag) } } else { for (t in TagManager.tags) { if (t.toLowerCase().contains(search.toLowerCase())) { if (!_tags.contains(t)) tags.add(t) } } } } // List Methods -------------------------------------------------------------------------------- override fun getCount(): Int = tags.size override fun getViewTypeCount(): Int = 1 override fun hasStableIds(): Boolean = false // Item Methods -------------------------------------------------------------------------------- override fun getItem(position: Int): String = tags[position] override fun getItemViewType(position: Int): Int = 0 override fun getItemId(position: Int): Long = position.toLong() override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { return if (convertView == null) { val view = LayoutInflater.from(activity).inflate(R.layout.list_tag, parent, false) view.tag = TagHolder(getItem(position), selected, switcher, view) view } else { (convertView.tag as TagHolder).updateView(getItem(position), selected) convertView } } // Interfaces ---------------------------------------------------------------------------------- interface TagSwitcher { fun moveTag(tag: String, selected: Boolean) } // Internal Classes ---------------------------------------------------------------------------- class TagHolder(private var tagText: String, private var tagSelected: Boolean, private val switcher: TagSwitcher, view: View) { private val textView: TextView = view.findViewById(R.id.tag) // Initializer ----------------------------------------------------------------------------- init { textView.text = tagText textView.onClick { switcher.moveTag(tagText, !tagSelected) } } // Management Methods ---------------------------------------------------------------------- fun updateView(tag: String, selected: Boolean) { this.tagSelected = selected this.tagText = tag textView.text = tagText } } }
apache-2.0
f1ad3c481df0605cd487ce6a72fa3810
35.225806
131
0.509204
5.530378
false
false
false
false
shkschneider/android_Skeleton
core/src/main/kotlin/me/shkschneider/skeleton/ui/transforms/BaseTransformer.kt
1
1614
package me.shkschneider.skeleton.ui.transforms import android.view.View import androidx.viewpager.widget.ViewPager // <https://github.com/ToxicBakery/ViewPagerTransforms> abstract class BaseTransformer : ViewPager.PageTransformer { protected abstract fun onTransform(page: View, position: Float) open fun isPagingEnabled(): Boolean { return false } override fun transformPage(page: View, position: Float) { onPreTransform(page, position) onTransform(page, position) onPostTransform(page, position) } private fun hideOffscreenPages(): Boolean { return true } private fun onPreTransform(page: View, position: Float) { val width = page.width.toFloat() page.rotationX = 1.toFloat() page.rotationY = 1.toFloat() page.rotation = 1.toFloat() page.scaleX = 1.toFloat() page.scaleY = 1.toFloat() page.pivotX = 1.toFloat() page.pivotY = 1.toFloat() page.translationY = 1.toFloat() page.translationX = if (isPagingEnabled()) 1.toFloat() else -width * position if (hideOffscreenPages()) { page.alpha = if (position <= (-1).toFloat() || position >= 1.toFloat()) 1.toFloat() else 1.toFloat() } else { page.alpha = 1.toFloat() } } @Suppress("UNUSED_PARAMETER") private fun onPostTransform(page: View, position: Float) { // Empty } protected fun min(value: Float, min: Float): Float { return if (value < min) min else value } }
apache-2.0
4625cce2a9c3377dc7a396a47493693b
29.038462
112
0.609046
4.315508
false
false
false
false
sabi0/intellij-community
java/java-tests/testSrc/com/intellij/java/testFramework/fixtures/MultiModuleJava9ProjectDescriptor.kt
1
5136
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.testFramework.fixtures import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.* import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.ex.temp.TempFileSystem import com.intellij.pom.java.LanguageLevel import com.intellij.testFramework.IdeaTestUtil import com.intellij.testFramework.LightPlatformTestCase import com.intellij.testFramework.fixtures.DefaultLightProjectDescriptor import org.jetbrains.jps.model.java.JavaSourceRootType /** * Dependencies: 'main' -> 'm2', 'main' -> 'm4', 'main' -> 'm5', 'main' -> 'm6' => 'm7', 'm6' -> 'm8' */ object MultiModuleJava9ProjectDescriptor : DefaultLightProjectDescriptor() { enum class ModuleDescriptor(internal val moduleName: String, internal val rootName: String) { MAIN(TEST_MODULE_NAME, "/not_used/"), M2("${TEST_MODULE_NAME}_m2", "src_m2"), M3("${TEST_MODULE_NAME}_m3", "src_m3"), M4("${TEST_MODULE_NAME}_m4", "src_m4"), M5("${TEST_MODULE_NAME}_m5", "src_m5"), M6("${TEST_MODULE_NAME}_m6", "src_m6"), M7("${TEST_MODULE_NAME}_m7", "src_m7"), M8("${TEST_MODULE_NAME}_m8", "src_m8"); fun root(): VirtualFile = if (this == MAIN) LightPlatformTestCase.getSourceRoot() else TempFileSystem.getInstance().findFileByPath("/$rootName")!! fun testRoot(): VirtualFile? = if (this == MAIN) TempFileSystem.getInstance().findFileByPath("/test_src")!! else null } override fun getSdk(): Sdk = IdeaTestUtil.getMockJdk9() override fun setUpProject(project: Project, handler: SetupHandler) { super.setUpProject(project, handler) runWriteAction { val main = ModuleManager.getInstance(project).findModuleByName(TEST_MODULE_NAME)!! val m2 = makeModule(project, ModuleDescriptor.M2) ModuleRootModificationUtil.addDependency(main, m2) makeModule(project, ModuleDescriptor.M3) val m4 = makeModule(project, ModuleDescriptor.M4) ModuleRootModificationUtil.addDependency(main, m4) val m5 = makeModule(project, ModuleDescriptor.M5) ModuleRootModificationUtil.addDependency(main, m5) val m6 = makeModule(project, ModuleDescriptor.M6) ModuleRootModificationUtil.addDependency(main, m6) val m7 = makeModule(project, ModuleDescriptor.M7) ModuleRootModificationUtil.addDependency(m6, m7, DependencyScope.COMPILE, true) val m8 = makeModule(project, ModuleDescriptor.M8) ModuleRootModificationUtil.addDependency(m6, m8) val libDir = "jar://${PathManagerEx.getTestDataPath()}/codeInsight/jigsaw" ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-named-1.0.jar!/") ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-with-claimed-name.jar!/") ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-auto-1.0.jar!/") ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-auto-2.0.jar!/") ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-multi-release.jar!/") ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib_invalid_1_2.jar!/") ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-xml-bind.jar!/") ModuleRootModificationUtil.addModuleLibrary(main, "${libDir}/lib-xml-ws.jar!/") ModuleRootModificationUtil.updateModel(main) { val entries = it.orderEntries.toMutableList() entries.add(0, entries.last()) // places an upgrade module before the JDK entries.removeAt(entries.size - 1) it.rearrangeOrderEntries(entries.toTypedArray()) } } } private fun makeModule(project: Project, descriptor: ModuleDescriptor): Module { val path = FileUtil.join(FileUtil.getTempDirectory(), "${descriptor.moduleName}.iml") val module = createModule(project, path) val sourceRoot = createSourceRoot(module, descriptor.rootName) createContentEntry(module, sourceRoot) return module } override fun configureModule(module: Module, model: ModifiableRootModel, contentEntry: ContentEntry) { model.getModuleExtension(LanguageLevelModuleExtension::class.java).languageLevel = LanguageLevel.JDK_1_9 if (module.name == TEST_MODULE_NAME) { val testRoot = createSourceRoot(module, "test_src") registerSourceRoot(module.project, testRoot) model.addContentEntry(testRoot).addSourceFolder(testRoot, JavaSourceRootType.TEST_SOURCE) } } fun cleanupSourceRoots() = runWriteAction { ModuleDescriptor.values().asSequence() .filter { it != ModuleDescriptor.MAIN } .flatMap { it.root().children.asSequence() } .plus(ModuleDescriptor.MAIN.testRoot()!!.children.asSequence()) .forEach { it.delete(this) } } }
apache-2.0
891875d12d87b9a2df2d4c7be632266d
44.866071
140
0.732671
4.305113
false
true
false
false
RoverPlatform/rover-android
experiences/src/main/kotlin/io/rover/sdk/experiences/events/contextproviders/ConversionsContextProvider.kt
1
3666
package io.rover.sdk.experiences.events.contextproviders import io.rover.sdk.core.data.domain.DeviceContext import io.rover.sdk.core.events.ContextProvider import io.rover.sdk.core.logging.log import io.rover.sdk.core.platform.LocalStorage import io.rover.sdk.core.streams.subscribe import io.rover.sdk.experiences.data.events.RoverEvent import io.rover.sdk.experiences.services.EventEmitter import org.json.JSONObject import java.util.Date import java.util.Locale class ConversionsContextProvider( localStorage: LocalStorage ) : ContextProvider { fun startListening(emitter: EventEmitter) { emitter.trackedEvents.subscribe { event -> getConversion(event)?.let { (tag, expires) -> currentConversions = currentConversions.add(tag, Date(Date().time + expires * 1000)) } } } override fun captureContext(deviceContext: DeviceContext): DeviceContext { return deviceContext.copy(conversions = currentConversions.values()) } private val store = localStorage.getKeyValueStorageFor(STORAGE_CONTEXT_IDENTIFIER) private var currentConversions: TagSet = try { when (val data = store[CONVERSIONS_KEY]) { null -> TagSet.empty() else -> TagSet.decodeJson(data) } } catch (throwable: Throwable) { log.w("Corrupted conversion tags, ignoring and starting fresh. Cause ${throwable.message}") TagSet.empty() } get() { return field.filterActiveTags() } set(value) { field = value.filterActiveTags() store[CONVERSIONS_KEY] = field.encodeJson() } private fun getConversion(event: RoverEvent): Pair<String, Long>? = when (event) { is RoverEvent.BlockTapped -> event.block.conversion?.let { Pair( it.tag, it.expires.seconds ) } is RoverEvent.ScreenPresented -> event.screen.conversion?.let { Pair( it.tag, it.expires.seconds ) } // NOTE: We always append the poll's option to the tag is RoverEvent.PollAnswered -> event.block.conversion?.let { val pollTag = event.option.text.replace(" ", "_").toLowerCase(Locale.ROOT) Pair("${it.tag}_${pollTag}", it.expires.seconds) } else -> null } companion object { private const val STORAGE_CONTEXT_IDENTIFIER = "conversions" private const val CONVERSIONS_KEY = "conversions" } } private data class TagSet( private val data: Map<String, Date> ) { fun add(tag: String, expires: Date): TagSet { val mutableData = data.toMutableMap() mutableData[tag] = expires return TagSet(data = mutableData) } fun values(): List<String> = data.keys.toList() fun filterActiveTags() = TagSet(data = data.filter { Date().before(it.value) }) fun encodeJson(): String { return JSONObject(data.map { Pair(it.key, it.value.time) }.associate { it }).toString() } companion object { fun decodeJson(input: String): TagSet { val json = JSONObject(input) val data = json.keys().asSequence().map { val value = json.get(it) val expires = if (value is Long) Date(value) else Date() Pair(it, expires) }.associate { it } return TagSet(data = data) } fun empty(): TagSet = TagSet(data = emptyMap()) } }
apache-2.0
cfb36559d42bf0f11e935b85bcc5c101
32.027027
99
0.596017
4.40096
false
false
false
false
SimonVT/cathode
cathode-sync/src/main/java/net/simonvt/cathode/actions/ActionManager.kt
1
1856
package net.simonvt.cathode.actions import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.launch import timber.log.Timber suspend fun <T> Action<T>.invokeSync(params: T) { ActionManager.invokeSync(this, params) } suspend fun <T> Action<T>.invokeAsync(params: T): Deferred<*> = ActionManager.invokeAsync(this, params) object ActionManager { private val job = SupervisorJob() private val scope = CoroutineScope(Dispatchers.IO + job) private val inFlight = mutableMapOf<String, Deferred<*>>() suspend fun <P> invokeSync(action: Action<P>, params: P) { val deferred = invokeAsync(action, params) deferred.await() } suspend fun <P> invokeAsync(action: Action<P>, params: P): Deferred<*> { val key = action.key(params) var deferred: Deferred<Unit>? synchronized(inFlight) { Timber.d("Invoking action: $key") if (inFlight.containsKey(key)) { Timber.d("Existing action found: $key") return inFlight[key]!! } Timber.d("Creating action: $key") deferred = scope.async(Dispatchers.IO) { try { action(params) } catch (e: ActionFailedException) { Timber.d(e, "Action failed: $key") } catch (t: Throwable) { Timber.e(t, "Action failed: $key") } } inFlight[key] = deferred!! } scope.launch(Dispatchers.IO) { try { Timber.d("Awaiting action: $key") deferred!!.await() } catch (t: Throwable) { // Handled above } synchronized(inFlight) { Timber.d("Removing action: $key") inFlight.remove(key) } } Timber.d("Returning deferred: $key") return deferred!! } }
apache-2.0
35613ac16048ee46a63f170a7e1bf9c9
25.514286
74
0.64278
3.957356
false
false
false
false
Geobert/radis
app/src/main/kotlin/fr/geobert/radis/tools/Tools.kt
1
13176
package fr.geobert.radis.tools import android.app.Activity import android.app.AlertDialog import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.content.Intent import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import android.content.pm.PackageManager.NameNotFoundException import android.graphics.Rect import android.graphics.drawable.Drawable import android.os.Build import android.os.Bundle import android.os.Handler import android.support.v4.app.DialogFragment import android.view.Gravity import android.view.MenuItem import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.AutoCompleteTextView import android.widget.EditText import android.widget.Toast import fr.geobert.radis.BaseActivity import fr.geobert.radis.MainActivity import fr.geobert.radis.R import fr.geobert.radis.db.DbContentProvider import fr.geobert.radis.db.DbHelper import fr.geobert.radis.service.InstallRadisServiceReceiver import fr.geobert.radis.service.RadisService import fr.geobert.radis.ui.OperationListFragment import fr.geobert.radis.ui.adapter.InfoAdapter import java.util.* public object Tools { // Intents actions public val INTENT_RADIS_STARTED: String = "fr.geobert.radis.STARTED" public val INTENT_REFRESH_NEEDED: String = "fr.geobert.radis.REFRESH_NEEDED" public val INTENT_REFRESH_STAT: String = "fr.geobert.radis.REFRESH_STAT" public val DEBUG_DIALOG: Int = 9876 // debug mode stuff public var DEBUG_MODE: Boolean = true // public static int SCREEN_HEIGHT; private var mActivity: Activity? = null public fun checkDebugMode(ctx: Activity) { // See if we're a debug or a release build try { val packageInfo = ctx.packageManager.getPackageInfo(ctx.packageName, PackageManager.GET_CONFIGURATIONS) val flags = packageInfo.applicationInfo.flags DEBUG_MODE = (flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0 } catch (e1: NameNotFoundException) { e1.printStackTrace() } } public fun setViewBg(v: View, drawable: Drawable?) { if (Build.VERSION.SDK_INT >= 16) { v.background = drawable } else { //noinspection deprecation v.setBackgroundDrawable(drawable) } } // public fun createRestartClickListener(ctx: Context): DialogInterface.OnClickListener { // return object : DialogInterface.OnClickListener { // override fun onClick(dialog: DialogInterface, which: Int) { // Tools.restartApp(ctx) // } // } // } public fun popMessage(ctx: Context, msg: String, titleStrId: Int, btnText: String, onClick: ((d: DialogInterface, i: Int) -> Unit)?) { val alertDialog = AlertDialog.Builder(ctx).create() alertDialog.setTitle(titleStrId) alertDialog.setMessage(msg) alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, btnText, onClick) alertDialog.show() } public fun popError(ctx: Context, msg: String, onClick: ((d: DialogInterface, i: Int) -> Unit)?) { Tools.popMessage(ctx, msg, R.string.error, ctx.getString(R.string.ok), onClick) } public fun setTextWithoutComplete(v: AutoCompleteTextView, text: String) { val adapter = v.adapter as InfoAdapter v.setAdapter(null) v.setText(text) v.setAdapter(adapter) } public fun createDeleteConfirmationDialog(ctx: Context, onClick: ((d: DialogInterface, i: Int) -> Unit)?): Dialog { return Tools.createDeleteConfirmationDialog(ctx, ctx.getString(R.string.delete_confirmation), ctx.getString(R.string.delete), onClick) } public fun createDeleteConfirmationDialog(ctx: Context, msg: String, title: String, onClick: ((d: DialogInterface, i: Int) -> Unit)?): Dialog { val builder = AlertDialog.Builder(ctx) builder.setMessage(msg).setTitle(title) .setCancelable(false) .setPositiveButton(R.string.yes, onClick) .setNegativeButton(R.string.cancel, { d, i -> d.cancel() }) return builder.create() } public fun onDefaultOptionItemSelected(ctx: MainActivity, item: MenuItem): Boolean { mActivity = ctx when (item.itemId) { R.id.debug -> { Tools.showDebugDialog(ctx) return true } } return false } public class AdvancedDialog : DialogFragment() { private var mId: Int = 0 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val args = arguments this.mId = args.getInt("id") val ctx = activity val listener: DialogInterface.OnClickListener? = when (mId) { MainActivity.SAVE_ACCOUNT -> createRestoreOrBackupClickListener(R.string.backup_success, R.string.backup_failed, { -> DbHelper.backupDatabase() }) MainActivity.RESTORE_ACCOUNT -> createRestoreOrBackupClickListener(R.string.restore_success, R.string.restore_failed, { -> DbHelper.restoreDatabase(ctx) }) MainActivity.PROCESS_SCH -> DialogInterface.OnClickListener { dialog: DialogInterface, which: Int -> RadisService.acquireStaticLock(ctx) ctx.startService(Intent(ctx, RadisService::class.java)) } else -> { null } } return Tools.getAdvancedDialog(activity, mId, listener!!) } companion object { public fun newInstance(id: Int, ctx: Context): AdvancedDialog { mActivity = ctx as Activity val frag = AdvancedDialog() val args = Bundle() args.putInt("id", id) frag.arguments = args return frag } } } public fun getAdvancedDialog(ctx: Activity, id: Int, onClick: DialogInterface.OnClickListener): Dialog { var msgId = -1 when (id) { MainActivity.RESTORE_ACCOUNT -> msgId = R.string.restore_confirm MainActivity.SAVE_ACCOUNT -> msgId = R.string.backup_confirm MainActivity.PROCESS_SCH -> msgId = R.string.process_scheduled_transactions else -> { } } val builder = AlertDialog.Builder(ctx) builder.setMessage(msgId).setCancelable(false).setPositiveButton(R.string.to_continue, onClick) .setNegativeButton(R.string.cancel, { d, i -> d.cancel() }) return builder.create() } public class ErrorDialog : DialogFragment() { private var mId: Int = 0 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val args = arguments this.mId = args.getInt("id") return Tools.createFailAndRestartDialog(activity, mId) } companion object { public fun newInstance(id: Int): ErrorDialog { val frag = ErrorDialog() val args = Bundle() args.putInt("id", id) frag.arguments = args return frag } } } private fun createFailAndRestartDialog(ctx: Activity, id: Int): Dialog { val builder = AlertDialog.Builder(ctx) val msg = StringBuilder() msg.append(ctx.getString(id)).append('\n').append(ctx.getString(R.string.will_restart)) builder.setMessage(msg).setCancelable(false).setPositiveButton(R.string.ok, { d, i -> Tools.restartApp(ctx) }) return builder.create() } private fun createRestoreOrBackupClickListener(successTextId: Int, failureTextId: Int, action: () -> Boolean): DialogInterface.OnClickListener { return DialogInterface.OnClickListener { dialog: DialogInterface, id: Int -> val ctx = mActivity if (action() && ctx != null) { val msg = StringBuilder() msg.append(ctx.getString(successTextId)).append('\n').append(ctx.getString(R.string.restarting)) Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show() Handler().postDelayed({ Tools.restartApp(ctx) }, 2000) } else { ErrorDialog.newInstance(failureTextId).show((ctx as BaseActivity).supportFragmentManager, "") } } } public fun createClearedCalendar(): GregorianCalendar { val cal = GregorianCalendar() clearTimeOfCalendar(cal) return cal } public fun clearTimeOfCalendar(c: Calendar) { c.set(Calendar.HOUR_OF_DAY, 0) c.set(Calendar.MINUTE, 0) c.set(Calendar.SECOND, 0) c.set(Calendar.MILLISECOND, 0) } // ------------------------------------------------------ // DEBUG TOOLS // ------------------------------------------------------ public fun restartApp(ctx: Context) { OperationListFragment.restart(ctx) } public fun showDebugDialog(activity: Context) { DebugDialog.newInstance().show((activity as BaseActivity).supportFragmentManager, "debug") } public class DebugDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val context = activity val items = arrayOf<CharSequence>("Trash DB", "Restart", "Install RadisService", "Trash Prefs") val builder = AlertDialog.Builder(context) builder.setNegativeButton("Cancel", object : DialogInterface.OnClickListener { override fun onClick(dialog: DialogInterface, id: Int) { dialog.cancel() } }) builder.setItems(items, object : DialogInterface.OnClickListener { override fun onClick(dialog: DialogInterface, item: Int) { when (item) { 0 -> { val client = context.contentResolver.acquireContentProviderClient("fr.geobert.radis.db") val provider = client.localContentProvider as DbContentProvider provider.deleteDatabase(context) client.release() Tools.restartApp(context) } 1 -> Tools.restartApp(context) 2 -> { val i = Intent(context, InstallRadisServiceReceiver::class.java) i.setAction(Tools.INTENT_RADIS_STARTED) context.sendBroadcast(i) } 3 -> DBPrefsManager.getInstance(context).resetAll() } } }) builder.setTitle("Debug menu") return builder.create() } companion object { public fun newInstance(): DebugDialog { val frag = DebugDialog() return frag } } } public fun setSumTextGravity(sumText: EditText) { val gravity: Int if (sumText.length() > 0) { gravity = Gravity.CENTER_VERTICAL or Gravity.RIGHT } else { gravity = Gravity.CENTER_VERTICAL or Gravity.LEFT } sumText.gravity = gravity } public fun getDateStr(date: Long): String { return date.formatDate() } public fun getDateStr(cal: Calendar): String { return getDateStr(cal.timeInMillis) } public fun createTooltip(stringId: Int): View.OnLongClickListener { return object : View.OnLongClickListener { override fun onLongClick(v: View): Boolean { val ctx = v.context val t = Toast.makeText(ctx, ctx.getString(stringId), Toast.LENGTH_SHORT) val screenPos = IntArray(2) val displayFrame = Rect() val screenWidth = ctx.resources.displayMetrics.widthPixels v.getWindowVisibleDisplayFrame(displayFrame) v.getLocationInWindow(screenPos) t.setGravity(Gravity.RIGHT or Gravity.TOP, screenWidth - screenPos[0], screenPos[1] - v.height - v.height / 2) t.show() return true } } } public fun hideKeyboard(ctx: Activity) { val inputManager = ctx.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputManager.hideSoftInputFromWindow(ctx.currentFocus!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS) } public fun showKeyboard(ctx: Activity) { val inputManager = ctx.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputManager.showSoftInput(ctx.currentFocus, InputMethodManager.SHOW_IMPLICIT) } }
gpl-2.0
0c00eb9f88cef00c761840f2e4ff7ead
37.982249
119
0.601093
4.945946
false
false
false
false
ihmc/dspcap
src/main/kotlin/us/ihmc/aci/dspro/pcap/dspro/Metadata.kt
1
2056
package us.ihmc.aci.dspro.pcap.dspro import com.beust.klaxon.JsonObject import com.beust.klaxon.Parser import io.pkts.buffer.Buffer import org.slf4j.LoggerFactory import us.ihmc.aci.dspro.pcap.Body import us.ihmc.aci.dspro.pcap.zdecompress import java.util.* /** * Created by gbenincasa on 10/31/17. */ data class Metadata(private val buf: Buffer) : Body { val metadata: JsonObject companion object { val LOGGER = LoggerFactory.getLogger(javaClass) } init { val uncompressedStringLength = buf.readUnsignedInt() val sMetadata = zdecompress(buf.readBytes(buf.readableBytes), uncompressedStringLength.toInt()) metadata = Parser().parse(StringBuilder(sMetadata)) as JsonObject if(metadata["Application_Metadata_Format"].toString().toLowerCase().endsWith("base64")) { try { val sAppMetadata = String(Base64.getDecoder() .decode(metadata["Application_Metadata"].toString()), Charsets.UTF_8) metadata["Application_Metadata"] = Parser().parse(StringBuilder(sAppMetadata)) as JsonObject } catch(e: Exception) { LOGGER.warn("${e.message} ${metadata["Application_Metadata"].toString()}") } } } override fun toString() = metadata.toJsonString(prettyPrint = true) } enum class MetadataElement { Application_Metadata, Application_Metadata_Format, Message_ID, Refers_To, Referred_Data_Object_Id, Referred_Data_Instance_Id, External_Referred_Cached_Data_URL, ComputedVOI, Prev_Msg_ID, Node_Type, Data_Content, Classification, Data_Format, Left_Upper_Latitude, Right_Lower_Latitude, Left_Upper_Longitude, Right_Lower_Longitude, Description, Pedigree, Importance, Location, Receiver_Time_Stamp, Source, Source_Reliability, Source_Time_Stamp, Expiration_Time, Relevant_Missions, Target_ID, Target_Role, Target_Team, Track_ID, Track_Action }
mit
e9d7e8c1a903a3408c2f05d4074dd747
25.025316
108
0.659533
4.007797
false
false
false
false
FHannes/intellij-community
plugins/git4idea/tests/git4idea/test/GitSingleRepoTest.kt
6
3127
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.test import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.Executor.cd import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vcs.VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY import com.intellij.openapi.vcs.VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY import com.intellij.openapi.vcs.VcsTestUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.vcs.AbstractVcsTestCase import git4idea.GitUtil import git4idea.GitVcs import git4idea.repo.GitRepository import java.nio.file.Files import java.nio.file.Paths abstract class GitSingleRepoTest : GitPlatformTest() { protected lateinit var myRepo: GitRepository @Throws(Exception::class) override fun setUp() { super.setUp() myRepo = createRepository(myProject, myProjectPath, makeInitialCommit()) cd(myProjectPath) } protected open fun makeInitialCommit(): Boolean { return true } protected fun VcsConfiguration.StandardConfirmation.doSilently() = AbstractVcsTestCase.setStandardConfirmation(myProject, GitVcs.NAME, this, DO_ACTION_SILENTLY) protected fun VcsConfiguration.StandardConfirmation.doNothing() = AbstractVcsTestCase.setStandardConfirmation(myProject, GitVcs.NAME, this, DO_NOTHING_SILENTLY) protected fun prepareUnversionedFile(filePath: String): VirtualFile { val path = Paths.get(myProjectPath, filePath) Files.createDirectories(path.parent) Files.createFile(path) FileUtil.writeToFile(path.toFile(), "initial\ncontent\n") val file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(path.toFile())!! updateChangeListManager() assertUnversioned(file) return file } protected fun VirtualFile.createDir(dir: String) = VcsTestUtil.findOrCreateDir(myProject, this, dir)!! protected fun VirtualFile.createFile(fileName: String, content: String = Math.random().toString()) = VcsTestUtil.createFile(myProject, this, fileName, content)!! protected fun renameFile(file: VirtualFile, newName: String) { VcsTestUtil.renameFileInCommand(myProject, file, newName) updateChangeListManager() } protected fun build(f: RepoBuilder.() -> Unit) { build(myRepo, f) } protected fun assertUnversioned(file: VirtualFile) { assertTrue("File should be unversioned! All changes: " + GitUtil.getLogString(myProjectPath, changeListManager.allChanges), changeListManager.isUnversioned(file)) } }
apache-2.0
3dc5b369a38582cfc8a2662d77022547
35.788235
127
0.774224
4.48637
false
true
false
false
danrien/projectBlueWater
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/stored/library/sync/GivenAnInternalStoragePreference/WhenLookingUpTheSyncDrive.kt
2
1875
package com.lasthopesoftware.bluewater.client.stored.library.sync.GivenAnInternalStoragePreference import com.lasthopesoftware.bluewater.client.browsing.library.access.FakeLibraryProvider import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId import com.lasthopesoftware.bluewater.client.stored.library.sync.SyncDirectoryLookup import com.lasthopesoftware.bluewater.shared.promises.extensions.FuturePromise import com.lasthopesoftware.storage.directories.FakePrivateDirectoryLookup import com.lasthopesoftware.storage.directories.FakePublicDirectoryLookup import org.assertj.core.api.AssertionsForClassTypes.assertThat import org.junit.BeforeClass import org.junit.Test import java.io.File class WhenLookingUpTheSyncDrive { @Test fun thenTheDriveIsTheOneWithTheMostSpace() { assertThat(file!!.path).isEqualTo("/storage/0/my-private-sd-card/1") } companion object { private var file: File? = null @BeforeClass @JvmStatic fun before() { val fakePrivateDirectoryLookup = FakePrivateDirectoryLookup() fakePrivateDirectoryLookup.addDirectory("", 1) fakePrivateDirectoryLookup.addDirectory("", 2) fakePrivateDirectoryLookup.addDirectory("", 3) fakePrivateDirectoryLookup.addDirectory("/storage/0/my-private-sd-card", 10) val publicDrives = FakePublicDirectoryLookup() publicDrives.addDirectory("fake-private-path", 12) publicDrives.addDirectory("/fake-private-path", 5) val syncDirectoryLookup = SyncDirectoryLookup( FakeLibraryProvider( Library() .setId(1) .setSyncedFileLocation(Library.SyncedFileLocation.INTERNAL) ), publicDrives, fakePrivateDirectoryLookup, fakePrivateDirectoryLookup ) file = FuturePromise(syncDirectoryLookup.promiseSyncDirectory(LibraryId(1))).get() } } }
lgpl-3.0
c5bf951e3f4af8f989bedfeac4528ead
38.0625
98
0.8112
4.076087
false
false
false
false
Tapadoo/sputnik
sputnik/src/main/kotlin/com/tapadoo/sputnik/utils/GitUtils.kt
1
1573
package com.tapadoo.sputnik.utils import java.io.BufferedReader import java.io.InputStreamReader /** * @author Elliot Tormey * @since 07/11/2016 */ internal object GitUtils { fun getCommitHash(): String { val command = arrayOf("git", "rev-parse", "--short", "HEAD").execute() val hash = command if (hash.isEmpty()) { return "no_commits" } else { return hash } } /** * This method will search through the git commit history of the project and find any commits matching * the grep command below and return the latest pull request number. If none are found it will return * the baseValue. */ fun getPullRequestNumber(baseValue: Int): Int { val command = arrayOf("sh", "-c", """git --no-pager log --oneline --grep 'pull request #' | head -1""").execute() val pr = command.substring(command.indexOf("#") + 1, command.indexOf(")")) if (pr.isEmpty()) { return baseValue } else { return Integer.parseInt(pr) } } private fun Array<String>.execute(): String { val process = Runtime.getRuntime().exec(this) val reader = BufferedReader(InputStreamReader(process.inputStream)) val builder = StringBuilder(100) var line: String? = reader.readLine() while (line != null) { builder.append(line) builder.append(System.getProperty("line.separator")) line = reader.readLine() } return builder.toString().trim() } }
mit
5e2c12d6bc48b831452cb2423477d748
29.862745
121
0.596313
4.333333
false
false
false
false
yotkaz/thimman
thimman-backend/src/main/kotlin/yotkaz/thimman/backend/model/User.kt
1
1938
package yotkaz.thimman.backend.model import com.fasterxml.jackson.annotation.JsonIgnore import yotkaz.thimman.backend.app.JPA_EMPTY_CONSTRUCTOR import java.time.LocalDateTime import java.util.* import javax.persistence.* @Entity open class User( @Id @GeneratedValue(strategy = GenerationType.TABLE) var id: Long? = null, @Column(unique = true) var name: String, @JsonIgnore var password: String, var registrationDate: LocalDateTime, @Enumerated(EnumType.STRING) @ElementCollection(fetch = FetchType.EAGER) var roles: Set<@JvmSuppressWildcards UserRole>, @OneToOne var person: Person? ) { override fun equals(other: Any?): Boolean{ if (this === other) return true if (other !is User) return false if (id != other.id) return false if (name != other.name) return false if (password != other.password) return false if (registrationDate != other.registrationDate) return false if (roles != other.roles) return false if (person != other.person) return false return true } override fun hashCode(): Int{ var result = id?.hashCode() ?: 0 result = 31 * result + name.hashCode() result = 31 * result + password.hashCode() result = 31 * result + registrationDate.hashCode() result = 31 * result + roles.hashCode() result = 31 * result + (person?.hashCode() ?: 0) return result } override fun toString(): String{ return "User(id=$id, name='$name', password='$password', registrationDate=$registrationDate, roles=$roles, person=$person)" } @Deprecated(JPA_EMPTY_CONSTRUCTOR) constructor() : this( name = "", password = "", registrationDate = LocalDateTime.now(), roles = HashSet(), person = null ) }
apache-2.0
733022777ffdeb6b05d81c6827fd7b16
26.309859
131
0.609391
4.538642
false
false
false
false
TeamAmaze/AmazeFileManager
app/src/main/java/com/amaze/filemanager/filesystem/ExternalSdCardOperation.kt
1
6973
/* * Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager 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.amaze.filemanager.filesystem import android.annotation.TargetApi import android.content.Context import android.net.Uri import android.os.Build import androidx.documentfile.provider.DocumentFile import androidx.preference.PreferenceManager import com.amaze.filemanager.database.UtilsHandler import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.File import java.io.IOException import java.util.* object ExternalSdCardOperation { private val log: Logger = LoggerFactory.getLogger(UtilsHandler::class.java) /** * Get a DocumentFile corresponding to the given file (for writing on ExtSdCard on Android 5). If * the file is not existing, it is created. * * @param file The file. * @param isDirectory flag indicating if the file should be a directory. * @return The DocumentFile */ @JvmStatic fun getDocumentFile( file: File, isDirectory: Boolean, context: Context ): DocumentFile? { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) return DocumentFile.fromFile(file) val baseFolder = getExtSdCardFolder(file, context) var originalDirectory = false if (baseFolder == null) { return null } var relativePath: String? = null try { val fullPath = file.canonicalPath if (baseFolder != fullPath) { relativePath = fullPath.substring(baseFolder.length + 1) } else { originalDirectory = true } } catch (e: IOException) { return null } val preferenceUri = PreferenceManager.getDefaultSharedPreferences(context) .getString(PreferencesConstants.PREFERENCE_URI, null) var treeUri: Uri? = null if (preferenceUri != null) { treeUri = Uri.parse(preferenceUri) } if (treeUri == null) { return null } // start with root of SD card and then parse through document tree. var document = DocumentFile.fromTreeUri(context, treeUri) if (originalDirectory || relativePath == null) { return document } val parts = relativePath.split("/").toTypedArray() for (i in parts.indices) { if (document == null) { return null } var nextDocument = document.findFile(parts[i]) if (nextDocument == null) { nextDocument = if (i < parts.size - 1 || isDirectory) { document.createDirectory(parts[i]) } else { document.createFile("image", parts[i]) } } document = nextDocument } return document } /** * Get a list of external SD card paths. (Kitkat or higher.) * * @return A list of external SD card paths. */ @JvmStatic @TargetApi(Build.VERSION_CODES.KITKAT) private fun getExtSdCardPaths(context: Context): Array<String> { val paths: MutableList<String> = ArrayList() for (file in context.getExternalFilesDirs("external")) { if (file != null && file != context.getExternalFilesDir("external")) { val index = file.absolutePath.lastIndexOf("/Android/data") if (index < 0) { log.warn("Unexpected external file dir: " + file.absolutePath) } else { var path = file.absolutePath.substring(0, index) try { path = File(path).canonicalPath } catch (e: IOException) { // Keep non-canonical path. } paths.add(path) } } } if (paths.isEmpty()) paths.add("/storage/sdcard1") return paths.toTypedArray() } @JvmStatic @TargetApi(Build.VERSION_CODES.KITKAT) fun getExtSdCardPathsForActivity(context: Context): Array<String> { val paths: MutableList<String> = ArrayList() for (file in context.getExternalFilesDirs("external")) { if (file != null) { val index = file.absolutePath.lastIndexOf("/Android/data") if (index < 0) { log.warn("Unexpected external file dir: " + file.absolutePath) } else { var path = file.absolutePath.substring(0, index) try { path = File(path).canonicalPath } catch (e: IOException) { // Keep non-canonical path. } paths.add(path) } } } if (paths.isEmpty()) paths.add("/storage/sdcard1") return paths.toTypedArray() } /** * Determine the main folder of the external SD card containing the given file. * * @param file the file. * @return The main folder of the external SD card containing this file, if the file is on an SD * card. Otherwise, null is returned. */ @JvmStatic @TargetApi(Build.VERSION_CODES.KITKAT) public fun getExtSdCardFolder(file: File, context: Context): String? { val extSdPaths = getExtSdCardPaths(context) try { for (i in extSdPaths.indices) { if (file.canonicalPath.startsWith(extSdPaths[i])) { return extSdPaths[i] } } } catch (e: IOException) { return null } return null } /** * Determine if a file is on external sd card. (Kitkat or higher.) * * @param file The file. * @return true if on external sd card. */ @JvmStatic @TargetApi(Build.VERSION_CODES.KITKAT) fun isOnExtSdCard(file: File, c: Context): Boolean { return getExtSdCardFolder(file, c) != null } }
gpl-3.0
2a561ee7811882f2e232fc15bf4695eb
34.758974
107
0.592428
4.676727
false
false
false
false
ylegall/BrainSaver
src/main/java/org/ygl/InterpreterOptions.kt
1
1494
package org.ygl import org.apache.commons.cli.Option import org.apache.commons.cli.Options class InterpreterOptions ( val wrap: Boolean = false, val optimize: Boolean = true, val debug: Boolean = false, val predefinedInput: String = "", val memorySize: Int = 30000 ) val DEFAULT_INTERPRETER_OPTIONS = InterpreterOptions() fun configureInterpreterOptions(): Options { val options = Options() val noOptimization = Option.builder() .longOpt("no-opt") .desc("disable optimizations") .build() val wrapping = Option.builder("w") .longOpt("wrap") .desc("generate code for wrapping interpreters") .build() val debug = Option.builder("d") .longOpt("debug") .desc("enable debug mode interpreter output") .build() val size = Option.builder("m") .longOpt("memory") .desc("specify memory size") .hasArg(true) .build() val version = Option.builder() .longOpt("version") .desc("prints the version") .build() val help = Option.builder("h") .longOpt("help") .desc("print this message") .build() with (options) { addOption(noOptimization) addOption(wrapping) addOption(debug) addOption(size) addOption(version) addOption(help) } return options }
gpl-3.0
c039950c82d777d426f2958d27c4c471
23.916667
60
0.562249
4.513595
false
false
false
false
nemerosa/ontrack
ontrack-extension-jenkins/src/main/java/net/nemerosa/ontrack/extension/jenkins/indicator/JenkinsPipelineLibraryIndicatorSettingsCasc.kt
1
2243
package net.nemerosa.ontrack.extension.jenkins.indicator import com.fasterxml.jackson.databind.JsonNode import net.nemerosa.ontrack.extension.casc.context.AbstractCascContext import net.nemerosa.ontrack.extension.casc.context.settings.SubSettingsContext import net.nemerosa.ontrack.extension.casc.schema.CascType import net.nemerosa.ontrack.extension.casc.schema.cascArray import net.nemerosa.ontrack.extension.casc.schema.cascObject import net.nemerosa.ontrack.json.JsonParseException import net.nemerosa.ontrack.json.asJson import net.nemerosa.ontrack.json.parse import net.nemerosa.ontrack.model.settings.CachedSettingsService import net.nemerosa.ontrack.model.settings.SettingsManagerService import org.springframework.stereotype.Component @Component class JenkinsPipelineLibraryIndicatorSettingsCasc( private val cachedSettingsService: CachedSettingsService, private val settingsManagerService: SettingsManagerService, ) : AbstractCascContext(), SubSettingsContext { override val field: String = "jenkins-pipeline-library-indicator" override val type: CascType = cascArray( description = "List of library versions requirements", type = cascObject(JenkinsPipelineLibraryIndicatorLibrarySettings::class) ) override fun run(node: JsonNode, paths: List<String>) { val items = node.mapIndexed { index, child -> try { child.parse<JenkinsPipelineLibraryIndicatorLibrarySettings>() } catch (ex: JsonParseException) { throw IllegalStateException( "Cannot parse into ${JenkinsPipelineLibraryIndicatorLibrarySettings::class.qualifiedName}: ${ path( paths + index.toString() ) }", ex ) } } settingsManagerService.saveSettings( JenkinsPipelineLibraryIndicatorSettings( libraryVersions = items ) ) } override fun render(): JsonNode { val settings = cachedSettingsService.getCachedSettings(JenkinsPipelineLibraryIndicatorSettings::class.java) return settings.libraryVersions.asJson() } }
mit
ed312a108e0222f5e4bf93bdd9e66cb5
39.8
115
0.705751
5.315166
false
false
false
false
Sportner/CBLMapper
cblmapper/src/main/java/io/sportner/cblmapper/mappers/ObjectDefaultTypeAdapter.kt
1
2296
package io.sportner.cblmapper.mappers import io.sportner.cblmapper.annotations.DocumentField import java.util.* import kotlin.reflect.KClass import kotlin.reflect.KMutableProperty1 import kotlin.reflect.KProperty import kotlin.reflect.KTypeProjection import kotlin.reflect.full.createInstance import kotlin.reflect.full.findAnnotation import kotlin.reflect.full.memberProperties import kotlin.reflect.jvm.jvmErasure class ObjectDefaultTypeAdapter : CBLMTypeAdapter<Any> { override fun decode(value: Any?, typeOfT: KClass<Any>, typesParameter: List<KTypeProjection>?, context: CBLMapperDecoderContext): Any? { return if (value == null) null else { val map = value as Map<String, Any?> val instanceOfT = typeOfT.createInstance() for (property in typeOfT.memberProperties) { if (property.findAnnotation<Transient>() != null) { continue } (property as? KMutableProperty1<Any, Any>)?.let { mutableProperty -> context.decode(map[getPropertySerializedName(property)], property.returnType.jvmErasure, property.returnType.arguments)?.let { propertyValue -> mutableProperty.set(instanceOfT, propertyValue) } } property.returnType.arguments } instanceOfT } } override fun encode(value: Any, typeOfT: KClass<Any>, typesParameter: List<KTypeProjection>?, context: CBLMapperEncoderContext): Any? { val map = HashMap<String, Any>() for (property in value.javaClass.kotlin.memberProperties) { if (property.findAnnotation<Transient>() != null) { continue } context.encode(property.get(value), property.returnType.jvmErasure, property.returnType.arguments)?.let { map[getPropertySerializedName(property)] = it } } return map } private fun getPropertySerializedName(property: KProperty<*>): String { val documentFieldAnnotation = property.findAnnotation<DocumentField>() return if (documentFieldAnnotation != null && documentFieldAnnotation.value.isNotBlank()) documentFieldAnnotation.value else property.name } }
apache-2.0
afb996a5a5c7eb94b1b3e3a25ba01d44
40
163
0.665505
5.102222
false
false
false
false
SrirangaDigital/shankara-android
app/src/main/java/co/ideaportal/srirangadigital/shankaraandroid/home/bindings/MainAdapter.kt
1
1753
package co.ideaportal.srirangadigital.shankaraandroid.home.bindings import android.content.Context import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter import co.ideaportal.srirangadigital.shankaraandroid.books.BookmarkFragment import co.ideaportal.srirangadigital.shankaraandroid.home.BookNavFragment import co.ideaportal.srirangadigital.shankaraandroid.home.HomeFragment import co.ideaportal.srirangadigital.shankaraandroid.search.SearchFragment import android.view.ViewGroup class MainAdapter(fm:FragmentManager, context : Context) : FragmentPagerAdapter(fm) { lateinit var homeFragment : HomeFragment lateinit var bookNavFragment : BookNavFragment lateinit var bookmarkFragment : BookmarkFragment var searchFragment : SearchFragment? = null override fun getItem(position: Int): Fragment { return when(position){ 0 -> HomeFragment() 1-> BookNavFragment() 2-> BookmarkFragment() 3-> SearchFragment() else -> HomeFragment() } } override fun getCount(): Int { return 4 } override fun instantiateItem(container: ViewGroup, position: Int): Any { val createdFragment = super.instantiateItem(container, position) as Fragment when (position) { 0 -> homeFragment = createdFragment as HomeFragment 1 -> bookNavFragment = createdFragment as BookNavFragment 2 -> bookmarkFragment = createdFragment as BookmarkFragment 3 -> searchFragment = createdFragment as SearchFragment } return createdFragment } fun clearSearch(){ searchFragment?.clearSearch() } }
gpl-2.0
a03c1069297c0b4487292818363bea86
34.08
85
0.72162
5.410494
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/template/postfix/utils.kt
1
2537
package org.rust.ide.template.postfix import com.intellij.codeInsight.template.postfix.templates.PostfixTemplateExpressionSelector import com.intellij.codeInsight.template.postfix.templates.PostfixTemplatePsiInfo import com.intellij.openapi.editor.Document import com.intellij.psi.PsiElement import com.intellij.util.Function import org.rust.lang.core.psi.RsBlock import org.rust.lang.core.psi.RsExpr import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.psi.ext.ancestors import org.rust.lang.core.types.type import org.rust.lang.core.types.ty.TyBool import org.rust.lang.utils.negate internal object RsPostfixTemplatePsiInfo : PostfixTemplatePsiInfo() { override fun getNegatedExpression(element: PsiElement): PsiElement = element.negate() override fun createExpression(context: PsiElement, prefix: String, suffix: String): PsiElement = RsPsiFactory(context.project).createExpression("$prefix${context.text}$suffix") } abstract class RsExprParentsSelectorBase(val pred: (RsExpr) -> Boolean) : PostfixTemplateExpressionSelector { override fun getRenderer(): Function<PsiElement, String> = Function { it.text } abstract override fun getExpressions(context: PsiElement, document: Document, offset: Int): List<PsiElement> } class RsTopMostInScopeSelector(pred: (RsExpr) -> Boolean) : RsExprParentsSelectorBase(pred) { override fun getExpressions(context: PsiElement, document: Document, offset: Int): List<PsiElement> = context .ancestors .takeWhile { it !is RsBlock && it.textRange.endOffset == context.textRange.endOffset } .filter { it is RsExpr && pred(it) } .toList() override fun hasExpression(context: PsiElement, copyDocument: Document, newOffset: Int): Boolean = context .ancestors .takeWhile { it !is RsBlock } .any { it is RsExpr && pred(it) } } class RsAllParentsSelector(pred: (RsExpr) -> Boolean) : RsExprParentsSelectorBase(pred) { override fun getExpressions(context: PsiElement, document: Document, offset: Int): List<PsiElement> = context .ancestors .takeWhile { it !is RsBlock } .filter { it is RsExpr && pred(it) } .toList() override fun hasExpression(context: PsiElement, copyDocument: Document, newOffset: Int): Boolean = context .ancestors .takeWhile { it !is RsBlock } .any { it is RsExpr && pred(it) } } fun RsExpr.isBool() = type == TyBool
mit
b2bc22297cb4c8132afaf63df403f653
41.283333
112
0.710682
4.329352
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mixin/insight/MixinImplicitUsageProvider.kt
1
1140
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.insight import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.SHADOW import com.intellij.codeInsight.daemon.ImplicitUsageProvider import com.intellij.psi.PsiElement import com.intellij.psi.PsiField import com.intellij.psi.PsiMethod import com.intellij.psi.PsiParameter class MixinImplicitUsageProvider : ImplicitUsageProvider { private fun isShadowField(element: PsiElement) = element is PsiField && element.hasAnnotation(SHADOW) private fun isParameterInShadow(element: PsiElement): Boolean { if (element !is PsiParameter) { return false } val method = element.declarationScope as? PsiMethod ?: return false return method.hasAnnotation(SHADOW) } override fun isImplicitUsage(element: PsiElement) = isParameterInShadow(element) override fun isImplicitRead(element: PsiElement) = isShadowField(element) override fun isImplicitWrite(element: PsiElement) = isShadowField(element) }
mit
c7054999035379ec1c3e4ab07e373fed
30.666667
105
0.760526
4.418605
false
false
false
false
is00hcw/anko
dsl/static/src/common/RelativeLayoutLayoutParamsHelpers.kt
2
3217
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE") @file:JvmMultifileClass @file:JvmName("RelativeLayoutLayoutParamsHelpersKt") package org.jetbrains.anko import android.view.View import android.widget.RelativeLayout.* public inline fun LayoutParams.topOf(v: View): Unit = addRule(ABOVE, v.id) public inline fun LayoutParams.above(v: View): Unit = addRule(ABOVE, v.id) public inline fun LayoutParams.below(v: View): Unit = addRule(BELOW, v.id) public inline fun LayoutParams.bottomOf(v: View): Unit = addRule(BELOW, v.id) public inline fun LayoutParams.leftOf(v: View): Unit = addRule(LEFT_OF, v.id) public inline fun LayoutParams.rightOf(v: View): Unit = addRule(RIGHT_OF, v.id) public inline fun LayoutParams.sameLeft(v: View): Unit = addRule(ALIGN_LEFT, v.id) public inline fun LayoutParams.sameTop(v: View): Unit = addRule(ALIGN_TOP, v.id) public inline fun LayoutParams.sameRight(v: View): Unit = addRule(ALIGN_RIGHT, v.id) public inline fun LayoutParams.sameBottom(v: View): Unit = addRule(ALIGN_BOTTOM, v.id) public inline fun LayoutParams.topOf(id: Int): Unit = addRule(ABOVE, id) public inline fun LayoutParams.above(id: Int): Unit = addRule(ABOVE, id) public inline fun LayoutParams.below(id: Int): Unit = addRule(BELOW, id) public inline fun LayoutParams.bottomOf(id: Int): Unit = addRule(BELOW, id) public inline fun LayoutParams.leftOf(id: Int): Unit = addRule(LEFT_OF, id) public inline fun LayoutParams.rightOf(id: Int): Unit = addRule(RIGHT_OF, id) public inline fun LayoutParams.sameLeft(id: Int): Unit = addRule(ALIGN_LEFT, id) public inline fun LayoutParams.sameTop(id: Int): Unit = addRule(ALIGN_TOP, id) public inline fun LayoutParams.sameRight(id: Int): Unit = addRule(ALIGN_RIGHT, id) public inline fun LayoutParams.sameBottom(id: Int): Unit = addRule(ALIGN_BOTTOM, id) public inline fun LayoutParams.alignParentTop(): Unit = addRule(ALIGN_PARENT_TOP) public inline fun LayoutParams.alignParentLeft(): Unit = addRule(ALIGN_PARENT_LEFT) public inline fun LayoutParams.alignParentBottom(): Unit = addRule(ALIGN_PARENT_BOTTOM) public inline fun LayoutParams.alignParentRight(): Unit = addRule(ALIGN_PARENT_RIGHT) public inline fun LayoutParams.centerHorizontally(): Unit = addRule(CENTER_HORIZONTAL) public inline fun LayoutParams.centerVertically(): Unit = addRule(CENTER_VERTICAL) public inline fun LayoutParams.centerInParent(): Unit = addRule(CENTER_IN_PARENT) // Unavailable in older versions of SDK public inline fun LayoutParams.alignParentStart(): Unit = addRule(20) // ALIGN_PARENT_START public inline fun LayoutParams.alignParentEnd(): Unit = addRule(21) // ALIGN_PARENT_END
apache-2.0
6fdb505ed2950fb3af5f14e28c219030
38.231707
91
0.763755
3.693456
false
false
false
false
Kotlin/kotlin-coroutines
examples/sequence/fibonacci.kt
1
372
package sequence // inferred type is Sequence<Int> val fibonacci = sequence { yield(1) // first Fibonacci number var cur = 1 var next = 1 while (true) { yield(next) // next Fibonacci number val tmp = cur + next cur = next next = tmp } } fun main(args: Array<String>) { println(fibonacci.take(10).joinToString()) }
apache-2.0
e7dc83884d573e3dbda5a29effa253cc
19.666667
46
0.594086
3.835052
false
false
false
false
is00hcw/anko
dsl/testData/robolectric/FindViewTest.kt
3
1624
package test import android.app.* import android.widget.* import android.os.Bundle import org.jetbrains.anko.* import org.jetbrains.anko.custom.* import org.junit.runner.RunWith import org.robolectric.annotation.Config import org.robolectric.* import org.junit.Test import org.junit.Assert.* public open class TestActivity() : Activity() { public override fun onCreate(savedInstanceState: Bundle?): Unit { super.onCreate(savedInstanceState) verticalLayout { id = 1 relativeLayout { id = 2 customView<Button> { text = "Button text" id = 3 } } val text = textView { id = 4 } } } } @RunWith(RobolectricTestRunner::class) public class RobolectricTest() { @Test public fun test() { val activity = Robolectric.buildActivity(javaClass<TestActivity>()).create().get() val verticalLayout = activity.findViewById(1) as? LinearLayout val relativeLayout = activity.findViewById(2) as? RelativeLayout assertNotNull(verticalLayout) assertNotNull(relativeLayout) val button = relativeLayout!!.findViewById(3) as? Button val textView = verticalLayout!!.findViewById(4) as? TextView assertNotNull(button) assertNotNull(textView) assertEquals("Button text", button!!.getText().toString()) assertEquals(2, verticalLayout!!.getChildCount()) assertEquals(1, relativeLayout!!.getChildCount()) println("[COMPLETE]") } }
apache-2.0
f275cf96df6b5ef86ecd98a2cb216ac8
24.390625
90
0.623768
5.155556
false
true
false
false
Ztiany/Repository
Kotlin/Kotlin-Android-V1.3/app/src/main/java/com/ztiany/kotlin/coroutines/ex/CoroutinesEx.kt
2
1283
package com.ztiany.kotlin.coroutines.ex import io.reactivex.schedulers.Schedulers import kotlinx.coroutines.* import java.util.concurrent.Executor /** * - DeferredCoroutine 任务创建后会立即启动 * - LazyDeferredCoroutine 任务创建后new的状态,要等用户调用 start() or join() or await()去启动他 * *@author Ztiany * Email: [email protected] * Date : 2017-07-21 00:37 */ fun <T> launch(dispatcher: CoroutineDispatcher = Dispatchers.Default, block: suspend CoroutineScope.() -> T, uiBlock: suspend (T) -> Unit): Deferred<T> { val deferred = GlobalScope.async(context = dispatcher, block = block) GlobalScope.launch(Dispatchers.Main) { uiBlock(deferred.await()) } return deferred } fun launchUI(start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> Unit) = GlobalScope.launch(Dispatchers.Main, start, block) private val rxIoExecutor = Executor { command -> command?.let { Schedulers.io().scheduleDirect(it) } } private val rxComputationExecutor = Executor { command -> command?.let { Schedulers.computation().scheduleDirect(it) } } val Io = rxIoExecutor.asCoroutineDispatcher() val Computation = rxComputationExecutor.asCoroutineDispatcher()
apache-2.0
bb6e2e702f1f77f42a672dfaec9081a6
27.511628
153
0.716735
3.990228
false
false
false
false
pennlabs/penn-mobile-android
PennMobile/src/main/java/com/pennapps/labs/pennmobile/HomeFragment.kt
1
16438
package com.pennapps.labs.pennmobile import android.content.* import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Build import android.os.Bundle import android.os.Handler import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.annotation.RequiresApi import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.fragment.app.Fragment import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.preference.PreferenceManager import androidx.recyclerview.widget.LinearLayoutManager import com.google.firebase.analytics.FirebaseAnalytics import com.pennapps.labs.pennmobile.adapters.HomeAdapter import com.pennapps.labs.pennmobile.api.OAuth2NetworkManager import com.pennapps.labs.pennmobile.classes.DiningHallPreference import com.pennapps.labs.pennmobile.classes.HomeCell import com.pennapps.labs.pennmobile.classes.HomeCellInfo import com.pennapps.labs.pennmobile.components.collapsingtoolbar.ToolbarBehavior import com.pennapps.labs.pennmobile.utils.Utils import kotlinx.android.synthetic.main.fragment_home.* import kotlinx.android.synthetic.main.fragment_home.view.* import kotlinx.android.synthetic.main.include_main.* import kotlinx.android.synthetic.main.loading_panel.* import java.util.* import kotlin.collections.ArrayList class HomeFragment : Fragment() { private lateinit var mActivity: MainActivity private lateinit var sharedPreferences: SharedPreferences override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mActivity = activity as MainActivity sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mActivity) LocalBroadcastManager .getInstance(mActivity) .registerReceiver(broadcastReceiver, IntentFilter("refresh")) val bundle = Bundle() bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "11") bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "Home") bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "App Feature") FirebaseAnalytics.getInstance(mActivity).logEvent(FirebaseAnalytics.Event.VIEW_ITEM, bundle) } @RequiresApi(Build.VERSION_CODES.M) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_home, container, false) view.home_cells_rv.layoutManager = LinearLayoutManager( context, LinearLayoutManager.VERTICAL, false) view.home_refresh_layout .setColorSchemeResources(R.color.color_accent, R.color.color_primary) view.home_refresh_layout .setOnRefreshListener { getHomePage() } initAppBar(view) return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) getHomePage() } @RequiresApi(Build.VERSION_CODES.M) private fun getHomePage() { // get session id from shared preferences val sp = sharedPreferences val sessionID = sp.getString(getString(R.string.huntsmanGSR_SessionID), "") val accountID = sp.getString(getString(R.string.accountID), "") val deviceID = OAuth2NetworkManager(mActivity).getDeviceId() OAuth2NetworkManager(mActivity).getAccessToken() val bearerToken = "Bearer " + sp.getString(getString(R.string.access_token), "").toString() Log.i("HomeFragment", bearerToken) //displays banner if not connected if (!isOnline(context)) { internetConnectionHome?.setBackgroundColor(resources.getColor(R.color.darkRedBackground)) internetConnection_message?.text = getString(R.string.internet_error) home_cells_rv?.setPadding(0, 90, 0, 0) internetConnectionHome?.visibility = View.VISIBLE home_refresh_layout?.isRefreshing = false loadingPanel?.visibility = View.GONE return } else { internetConnectionHome?.visibility = View.GONE home_cells_rv?.setPadding(0, 0, 0, 0) } // get API data val homepageCells = mutableListOf<HomeCell>() for (i in 1..6) { homepageCells.add(HomeCell()) } val studentLife = MainActivity.studentLifeInstance if (bearerToken != "Bearer ") { studentLife.getNews().subscribe({ article -> mActivity.runOnUiThread { val newsCell = HomeCell() newsCell.info = HomeCellInfo() newsCell.info?.article = article newsCell.type = "news" homepageCells.set(2, newsCell) home_cells_rv?.adapter = HomeAdapter(ArrayList(homepageCells)) loadingPanel?.visibility = View.GONE home_refresh_layout?.isRefreshing = false } }, { throwable -> mActivity.runOnUiThread { Log.e("Home", "Could not load news", throwable) throwable.printStackTrace() loadingPanel?.visibility = View.GONE home_refresh_layout?.isRefreshing = false } }) studentLife.getDiningPreferences(bearerToken).subscribe({ preferences -> mActivity.runOnUiThread { val list = preferences.preferences val venues = mutableListOf<Int>() val diningCell = HomeCell() diningCell.type = "dining" val diningCellInfo = HomeCellInfo() if(list?.isEmpty() == true ) { venues.add(593) venues.add(1442) venues.add(636) } else { list?.forEach({ it?.id?.let { it1 -> venues.add(it1) } }) } diningCellInfo.venues = venues diningCell.info = diningCellInfo homepageCells.set(3, diningCell) home_cells_rv?.adapter = HomeAdapter(ArrayList(homepageCells)) loadingPanel?.visibility = View.GONE internetConnectionHome?.visibility = View.GONE home_refresh_layout?.isRefreshing = false } }, { throwable -> mActivity.runOnUiThread { Log.e("Home", "Could not load Dining", throwable) throwable.printStackTrace() loadingPanel?.visibility = View.GONE home_refresh_layout?.isRefreshing = false } }) studentLife.getCalendar().subscribe({ events -> mActivity.runOnUiThread { val calendar = HomeCell() calendar.type = "calendar" calendar.events = events homepageCells.set(0, calendar) val gsrBookingCell = HomeCell() gsrBookingCell.type = "gsr_booking" gsrBookingCell.buildings = arrayListOf("Huntsman Hall", "Weigle") homepageCells.set(4, gsrBookingCell) home_cells_rv?.adapter = HomeAdapter(ArrayList(homepageCells)) loadingPanel?.visibility = View.GONE home_refresh_layout?.isRefreshing = false } }, { throwable -> mActivity.runOnUiThread { Log.e("Home", "Could not load calendar", throwable) throwable.printStackTrace() loadingPanel?.visibility = View.GONE home_refresh_layout?.isRefreshing = false } }) studentLife.getLaundryPref(bearerToken).subscribe({ preferences -> mActivity.runOnUiThread { val venues = mutableListOf<Int>() val laundryCell = HomeCell() laundryCell.type = "laundry" val laundryCellInfo = HomeCellInfo() if(preferences?.isEmpty() == false ) { laundryCellInfo.roomId = preferences[0] } laundryCell.info = laundryCellInfo homepageCells.set(5, laundryCell) home_cells_rv?.adapter = HomeAdapter(ArrayList(homepageCells)) loadingPanel?.visibility = View.GONE internetConnectionHome?.visibility = View.GONE home_refresh_layout?.isRefreshing = false } }, { throwable -> mActivity.runOnUiThread { Log.e("Home", "Could not load laundry", throwable) throwable.printStackTrace() loadingPanel?.visibility = View.GONE home_refresh_layout?.isRefreshing = false } }) studentLife.validPostsList(bearerToken).subscribe ({ post -> if (post.size >= 1) { //there exists a post mActivity.runOnUiThread { var postCell = HomeCell() postCell.info = HomeCellInfo() postCell.type = "post" postCell.info?.post = post[0] homepageCells.set(1, postCell) home_cells_rv?.adapter = HomeAdapter(ArrayList(homepageCells)) loadingPanel?.visibility = View.GONE home_refresh_layout?.isRefreshing = false } } }, {throwable -> mActivity.runOnUiThread { Log.e("Home", "Could not load posts", throwable) throwable.printStackTrace() loadingPanel?.visibility = View.GONE home_refresh_layout?.isRefreshing = false } }) /*studentLife.getHomePage(bearerToken).subscribe({ cells -> mActivity.runOnUiThread { val gsrBookingCell = HomeCell() gsrBookingCell.type = "gsr_booking" gsrBookingCell.buildings = arrayListOf("Huntsman Hall", "Weigle") cells?.add(cells.size - 1, gsrBookingCell) homepageCells.addAll(homepageCells.size, cells) home_cells_rv?.adapter = HomeAdapter(ArrayList(homepageCells)) //(home_cells_rv?.adapter as HomeAdapter).notifyDataSetChanged() loadingPanel?.visibility = View.GONE home_refresh_layout?.isRefreshing = false } }, { throwable -> mActivity.runOnUiThread { Log.e("Home", "Could not load Home page", throwable) throwable.printStackTrace() Toast.makeText(mActivity, "Could not load Home page", Toast.LENGTH_LONG).show() loadingPanel?.visibility = View.GONE internetConnectionHome?.setBackgroundColor(resources.getColor(R.color.darkRedBackground)) internetConnection_message?.text = getString(R.string.internet_error) internetConnectionHome?.visibility = View.VISIBLE home_refresh_layout?.isRefreshing = false } }) */ } else { studentLife.getCalendar().subscribe({ events -> mActivity.runOnUiThread { val calendar = HomeCell() calendar.type = "calendar" calendar.events = events homepageCells.add(0, calendar) home_cells_rv?.adapter = HomeAdapter(ArrayList(homepageCells)) loadingPanel?.visibility = View.GONE home_refresh_layout?.isRefreshing = false } }, { throwable -> mActivity.runOnUiThread { Log.e("Home", "Could not load Home page", throwable) throwable.printStackTrace() loadingPanel?.visibility = View.GONE home_refresh_layout?.isRefreshing = false } }) studentLife.getNews().subscribe({ article -> mActivity.runOnUiThread { val newsCell = HomeCell() newsCell.info = HomeCellInfo() newsCell.info?.article = article newsCell.type = "news" homepageCells.add(homepageCells.size, newsCell) val gsrBookingCell = HomeCell() gsrBookingCell.type = "gsr_booking" gsrBookingCell.buildings = arrayListOf("Huntsman Hall", "Weigle") homepageCells.add(homepageCells.size, gsrBookingCell) home_cells_rv?.adapter = HomeAdapter(ArrayList(homepageCells)) loadingPanel?.visibility = View.GONE home_refresh_layout?.isRefreshing = false } }, { throwable -> mActivity.runOnUiThread { Log.e("Home", "Could not load Home page", throwable) throwable.printStackTrace() loadingPanel?.visibility = View.GONE home_refresh_layout?.isRefreshing = false } }) } } private val broadcastReceiver = object : BroadcastReceiver() { @RequiresApi(Build.VERSION_CODES.M) override fun onReceive(context: Context?, intent: Intent?) { getHomePage() } } override fun onResume() { super.onResume() mActivity.removeTabs() this.setTitle(getString(R.string.home)) mActivity.toolbar.visibility = View.GONE val initials = sharedPreferences.getString(getString(R.string.initials), null) if (initials != null && initials.isNotEmpty()) { this.initials.text = initials } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { this.profile_background.setImageDrawable( resources.getDrawable (R.drawable.ic_guest_avatar, context?.theme)) } else { @Suppress("DEPRECATION") this.profile_background.setImageDrawable( resources.getDrawable (R.drawable.ic_guest_avatar)) } } if (Build.VERSION.SDK_INT > 17) { mActivity.setSelectedTab(MainActivity.HOME) } mActivity.showBottomBar() } private fun setTitle(title: CharSequence) { title_view.text = title } private fun initAppBar(view: View) { val firstName = sharedPreferences.getString(getString(R.string.first_name), null) firstName?.let { view.date_view.text = "Welcome, $it!".toUpperCase(Locale.getDefault()) Handler().postDelayed( { view.date_view.text = Utils.getCurrentSystemTime() }, 4000 ) } ?: run { view.date_view.text = Utils.getCurrentSystemTime() } if (Build.VERSION.SDK_INT > 16) { (view.appbar_home.layoutParams as CoordinatorLayout.LayoutParams).behavior = ToolbarBehavior() } view.profile.setOnClickListener { //TODO: Account Settings } } /** * Show a SnackBar message right below the app bar */ @Suppress("DEPRECATION") private fun displaySnack(view: View, text: String) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { (view as ViewGroup).showSneakerToast(message = text, doOnRetry = { }, sneakerColor = R.color.sneakerBlurColorOverlay) } } }
mit
93fd35634953fcb66b1f0600fd7d9678
41.478036
129
0.569534
5.25008
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/cardstack/tools/RxAdapterUpDownStackAnimator.kt
1
2725
package com.tamsiree.rxui.view.cardstack.tools import android.animation.ObjectAnimator import android.view.View import com.tamsiree.rxui.view.cardstack.RxCardStackView /** * @author tamsiree * @date 2018/6/11 11:36:40 整合修改 */ class RxAdapterUpDownStackAnimator(rxCardStackView: RxCardStackView) : RxAdapterAnimator(rxCardStackView) { override fun itemExpandAnimatorSet(viewHolder: RxCardStackView.ViewHolder, position: Int) { val itemView = viewHolder.itemView itemView.clearAnimation() val oa = ObjectAnimator.ofFloat(itemView, View.Y, itemView.y, mRxCardStackView.getChildAt(0).y) mSet!!.play(oa) var collapseShowItemCount = 0 for (i in 0 until mRxCardStackView.childCount) { var childTop: Int if (i == mRxCardStackView.selectPosition) { continue } val child = mRxCardStackView.getChildAt(i) child.clearAnimation() if (i > mRxCardStackView.selectPosition && collapseShowItemCount < mRxCardStackView.numBottomShow) { childTop = mRxCardStackView.showHeight - getCollapseStartTop(collapseShowItemCount) val oAnim = ObjectAnimator.ofFloat(child, View.Y, child.y, childTop.toFloat()) mSet!!.play(oAnim) collapseShowItemCount++ } else if (i < mRxCardStackView.selectPosition) { val oAnim = ObjectAnimator.ofFloat(child, View.Y, child.y, mRxCardStackView.getChildAt(0).y) mSet!!.play(oAnim) } else { val oAnim = ObjectAnimator.ofFloat(child, View.Y, child.y, mRxCardStackView.showHeight.toFloat()) mSet!!.play(oAnim) } } } override fun itemCollapseAnimatorSet(viewHolder: RxCardStackView.ViewHolder) { var childTop = mRxCardStackView.paddingTop for (i in 0 until mRxCardStackView.childCount) { val child = mRxCardStackView.getChildAt(i) child.clearAnimation() val lp = child.layoutParams as RxCardStackView.LayoutParams childTop += lp.topMargin if (i != 0) { childTop -= mRxCardStackView.overlapGaps * 2 } val temp = if (childTop - mRxCardStackView.rxScrollDelegate?.viewScrollY!! < mRxCardStackView.getChildAt(0).y) { mRxCardStackView.getChildAt(0).y } else { (childTop - mRxCardStackView.rxScrollDelegate?.viewScrollY!!).toFloat() } val oAnim: ObjectAnimator = ObjectAnimator.ofFloat<View>(child, View.Y, child.y, temp) mSet!!.play(oAnim) childTop += lp.mHeaderHeight } } }
apache-2.0
4eca6d383c1b124506cb96cfd2ce3def
43.557377
124
0.633419
4.225505
false
false
false
false
Ribesg/anko
dsl/testData/functional/sdk19/LayoutsTest.kt
2
40152
private val defaultInit: Any.() -> Unit = {} open class _AppWidgetHostView(ctx: Context): android.appwidget.AppWidgetHostView(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.widget.FrameLayout.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _WebView(ctx: Context): android.webkit.WebView(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.view.ViewGroup.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.view.ViewGroup.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.view.ViewGroup.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.view.ViewGroup.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.view.ViewGroup.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.view.ViewGroup.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _AbsoluteLayout(ctx: Context): android.widget.AbsoluteLayout(ctx) { fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, x: Int, y: Int, init: android.widget.AbsoluteLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.AbsoluteLayout.LayoutParams(width, height, x, y) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.AbsoluteLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.AbsoluteLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.widget.AbsoluteLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.AbsoluteLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _FrameLayout(ctx: Context): android.widget.FrameLayout(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.widget.FrameLayout.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _Gallery(ctx: Context): android.widget.Gallery(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.Gallery.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.Gallery.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.Gallery.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.Gallery.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.widget.Gallery.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.Gallery.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _GridLayout(ctx: Context): android.widget.GridLayout(ctx) { fun <T: View> T.lparams( rowSpec: android.widget.GridLayout.Spec?, columnSpec: android.widget.GridLayout.Spec?, init: android.widget.GridLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.GridLayout.LayoutParams(rowSpec!!, columnSpec!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( init: android.widget.GridLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.GridLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( params: android.view.ViewGroup.LayoutParams?, init: android.widget.GridLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( params: android.view.ViewGroup.MarginLayoutParams?, init: android.widget.GridLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.widget.GridLayout.LayoutParams?, init: android.widget.GridLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.GridLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( context: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.GridLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.GridLayout.LayoutParams(context!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } } open class _GridView(ctx: Context): android.widget.GridView(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.AbsListView.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.AbsListView.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.AbsListView.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.AbsListView.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, viewType: Int, init: android.widget.AbsListView.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.AbsListView.LayoutParams(width, height, viewType) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.widget.AbsListView.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.AbsListView.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _HorizontalScrollView(ctx: Context): android.widget.HorizontalScrollView(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.widget.FrameLayout.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _ImageSwitcher(ctx: Context): android.widget.ImageSwitcher(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.widget.FrameLayout.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _LinearLayout(ctx: Context): android.widget.LinearLayout(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.LinearLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.LinearLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.LinearLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.LinearLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float, init: android.widget.LinearLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.LinearLayout.LayoutParams(width, height, weight) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( p: android.view.ViewGroup.LayoutParams?, init: android.widget.LinearLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.LinearLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.widget.LinearLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.widget.LinearLayout.LayoutParams?, init: android.widget.LinearLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _RadioGroup(ctx: Context): android.widget.RadioGroup(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.RadioGroup.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.RadioGroup.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.RadioGroup.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.RadioGroup.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: android.widget.RadioGroup.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.RadioGroup.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( p: android.view.ViewGroup.LayoutParams?, init: android.widget.RadioGroup.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.RadioGroup.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.widget.RadioGroup.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.RadioGroup.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _RelativeLayout(ctx: Context): android.widget.RelativeLayout(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.RelativeLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.RelativeLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.RelativeLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.RelativeLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.widget.RelativeLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.widget.RelativeLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.widget.RelativeLayout.LayoutParams?, init: android.widget.RelativeLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _ScrollView(ctx: Context): android.widget.ScrollView(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.widget.FrameLayout.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _TableLayout(ctx: Context): android.widget.TableLayout(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.TableLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.TableLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.TableLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.TableLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: android.widget.TableLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.TableLayout.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( init: android.widget.TableLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.TableLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( p: android.view.ViewGroup.LayoutParams?, init: android.widget.TableLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.TableLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.widget.TableLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.TableLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _TableRow(ctx: Context): android.widget.TableRow(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.TableRow.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.TableRow.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.TableRow.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.TableRow.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: android.widget.TableRow.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.TableRow.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( init: android.widget.TableRow.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.TableRow.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( column: Int, init: android.widget.TableRow.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.TableRow.LayoutParams(column) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( p: android.view.ViewGroup.LayoutParams?, init: android.widget.TableRow.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.TableRow.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.widget.TableRow.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.TableRow.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _TextSwitcher(ctx: Context): android.widget.TextSwitcher(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.widget.FrameLayout.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _ViewAnimator(ctx: Context): android.widget.ViewAnimator(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.widget.FrameLayout.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } } open class _ViewSwitcher(ctx: Context): android.widget.ViewSwitcher(ctx) { fun <T: View> T.lparams( c: android.content.Context?, attrs: android.util.AttributeSet?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.view.ViewGroup.MarginLayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } fun <T: View> T.lparams( source: android.widget.FrameLayout.LayoutParams?, init: android.widget.FrameLayout.LayoutParams.() -> Unit = defaultInit ): T { val layoutParams = android.widget.FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } }
apache-2.0
4920eb86c0ff96b76a7c872ea9e3a953
36.316914
93
0.634389
4.715997
false
false
false
false
Popalay/Cardme
presentation/src/main/kotlin/com/popalay/cardme/utils/transitions/GravityArcMotion.kt
1
5117
/* * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.popalay.cardme.utils.transitions import android.graphics.Path import android.transition.ArcMotion /** * A tweak to [ArcMotion] which slightly alters the path calculation. In the real world * gravity slows upward motion and accelerates downward motion. This class emulates this behavior * to make motion paths appear more natural. * * See https://www.google.com/design/spec/motion/movement.html#movement-movement-within-screen-bounds */ class GravityArcMotion : ArcMotion() { companion object { private val DEFAULT_MAX_ANGLE_DEGREES = 70f private val DEFAULT_MAX_TANGENT = Math.tan(Math.toRadians((DEFAULT_MAX_ANGLE_DEGREES / 2).toDouble())).toFloat() private fun toTangent(arcInDegrees: Float): Float { if (arcInDegrees < 0 || arcInDegrees > 90) throw IllegalArgumentException("Arc must be between 0 and 90 degrees") return Math.tan(Math.toRadians((arcInDegrees / 2).toDouble())).toFloat() } } private var minimumHorizontalAngle = 0f private var minimumVerticalAngle = 0f private var maximumAngle = DEFAULT_MAX_ANGLE_DEGREES private var minimumHorizontalTangent = 0f private var minimumVerticalTangent = 0f private var maximumTangent = DEFAULT_MAX_TANGENT override fun setMinimumHorizontalAngle(angleInDegrees: Float) { minimumHorizontalAngle = angleInDegrees minimumHorizontalTangent = toTangent(angleInDegrees) } override fun getMinimumHorizontalAngle(): Float { return minimumHorizontalAngle } override fun setMinimumVerticalAngle(angleInDegrees: Float) { minimumVerticalAngle = angleInDegrees minimumVerticalTangent = toTangent(angleInDegrees) } override fun getMinimumVerticalAngle(): Float { return minimumVerticalAngle } override fun setMaximumAngle(angleInDegrees: Float) { maximumAngle = angleInDegrees maximumTangent = toTangent(angleInDegrees) } override fun getMaximumAngle(): Float { return maximumAngle } override fun getPath(startX: Float, startY: Float, endX: Float, endY: Float): Path { val path = Path() path.moveTo(startX, startY) var ex: Float var ey: Float if (startY == endY) { ex = (startX + endX) / 2 ey = startY + minimumHorizontalTangent * Math.abs(endX - startX) / 2 } else if (startX == endX) { ex = startX + minimumVerticalTangent * Math.abs(endY - startY) / 2 ey = (startY + endY) / 2 } else { val deltaX = endX - startX val deltaY: Float if (endY < startY) { deltaY = startY - endY } else { deltaY = endY - startY } val h2 = deltaX * deltaX + deltaY * deltaY val dx = (startX + endX) / 2 val dy = (startY + endY) / 2 val midDist2 = h2 * 0.25f val minimumArcDist2: Float if (Math.abs(deltaX) < Math.abs(deltaY)) { val eDistY = h2 / (2 * deltaY) ey = endY + eDistY ex = endX minimumArcDist2 = midDist2 * minimumVerticalTangent * minimumVerticalTangent } else { val eDistX = h2 / (2 * deltaX) ex = endX + eDistX ey = endY minimumArcDist2 = midDist2 * minimumHorizontalTangent * minimumHorizontalTangent } val arcDistX = dx - ex val arcDistY = dy - ey val arcDist2 = arcDistX * arcDistX + arcDistY * arcDistY val maximumArcDist2 = midDist2 * maximumTangent * maximumTangent var newArcDistance2 = 0f if (arcDist2 < minimumArcDist2) { newArcDistance2 = minimumArcDist2 } else if (arcDist2 > maximumArcDist2) { newArcDistance2 = maximumArcDist2 } if (newArcDistance2 != 0f) { val ratio2 = newArcDistance2 / arcDist2 val ratio = Math.sqrt(ratio2.toDouble()).toFloat() ex = dx + ratio * (ex - dx) ey = dy + ratio * (ey - dy) } } val controlX1 = (startX + ex) / 2 val controlY1 = (startY + ey) / 2 val controlX2 = (ex + endX) / 2 val controlY2 = (ey + endY) / 2 path.cubicTo(controlX1, controlY1, controlX2, controlY2, endX, endY) return path } }
apache-2.0
392692cffa463417bc445c863a7c6981
33.574324
125
0.614227
4.392275
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/service/AccountAuthenticatorService.kt
1
4425
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.service import android.accounts.AbstractAccountAuthenticator import android.accounts.Account import android.accounts.AccountAuthenticatorResponse import android.accounts.AccountManager import android.app.Service import android.content.Context import android.content.Intent import android.os.Bundle import android.os.IBinder import org.mariotaku.ktextension.set import de.vanita5.twittnuker.activity.SignInActivity class AccountAuthenticatorService : BaseService() { private lateinit var authenticator: TwidereAccountAuthenticator override fun onCreate() { super.onCreate() authenticator = TwidereAccountAuthenticator(this) } override fun onBind(intent: Intent): IBinder { return authenticator.iBinder } internal class TwidereAccountAuthenticator(val context: Context) : AbstractAccountAuthenticator(context) { override fun addAccount(response: AccountAuthenticatorResponse, accountType: String, authTokenType: String?, requiredFeatures: Array<String>?, options: Bundle?): Bundle { val intent = Intent(context, SignInActivity::class.java) intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response) val result = Bundle() result[AccountManager.KEY_INTENT] = intent return result } override fun getAuthToken(response: AccountAuthenticatorResponse, account: Account, authTokenType: String, options: Bundle?): Bundle { val am = AccountManager.get(context) val authToken = am.peekAuthToken(account, authTokenType) if (authToken.isNullOrEmpty()) { val intent = Intent(context, SignInActivity::class.java) intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response) val result = Bundle() result[AccountManager.KEY_INTENT] = intent return result } val result = Bundle() result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name) result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type) result.putString(AccountManager.KEY_AUTHTOKEN, authToken) return result } override fun confirmCredentials(response: AccountAuthenticatorResponse, account: Account, options: Bundle?): Bundle { val result = Bundle() result[AccountManager.KEY_BOOLEAN_RESULT] = true return result } override fun editProperties(response: AccountAuthenticatorResponse, accountType: String): Bundle { val result = Bundle() result[AccountManager.KEY_BOOLEAN_RESULT] = true return result } override fun getAuthTokenLabel(authTokenType: String): String { return authTokenType } override fun hasFeatures(response: AccountAuthenticatorResponse, account: Account, features: Array<String>): Bundle { val result = Bundle() result[AccountManager.KEY_BOOLEAN_RESULT] = true return result } override fun updateCredentials(response: AccountAuthenticatorResponse, account: Account, authTokenType: String, options: Bundle?): Bundle { val result = Bundle() result[AccountManager.KEY_BOOLEAN_RESULT] = true return result } } }
gpl-3.0
cce8456ed8bf6b395195c1e510c579ca
39.236364
142
0.67661
5.181499
false
false
false
false
AromaTech/banana-data-operations
src/main/java/tech/aroma/data/sql/SQLFollowerRepository.kt
3
3681
/* * Copyright 2017 RedRoma, 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 tech.aroma.data.sql import org.springframework.jdbc.core.JdbcOperations import tech.aroma.data.FollowerRepository import tech.aroma.data.sql.SQLStatements.* import tech.aroma.thrift.Application import tech.aroma.thrift.User import tech.aroma.thrift.exceptions.InvalidArgumentException import javax.inject.Inject /** * * @author SirWellington */ internal class SQLFollowerRepository @Inject constructor(val database: JdbcOperations, val appSerializer: DatabaseSerializer<Application>, val userSerializer: DatabaseSerializer<User>) : FollowerRepository { override fun saveFollowing(user: User, application: Application) { checkUserId(user.userId) checkAppId(application.applicationId) val userId = user.userId?.toUUID() ?: throw InvalidArgumentException("Invalid userId: $user") val appId = application.applicationId?.toUUID() ?: throw InvalidArgumentException("Invalid appId: $application") val sql = Inserts.FOLLOWING try { database.update(sql, appId, userId) } catch (ex: Exception) { failWithMessage("Could not save following for User[$userId] and App[$appId]", ex) } } override fun deleteFollowing(userId: String, applicationId: String) { checkUserId(userId) checkAppId(applicationId) val sql = Deletes.FOLLOWING try { database.update(sql, applicationId.toUUID(), userId.toUUID()) } catch (ex: Exception) { failWithMessage("Could not delete following for User[$userId] and App[$applicationId", ex) } } override fun followingExists(userId: String, applicationId: String): Boolean { checkUserId(userId) checkAppId(applicationId) val sql = Queries.CHECK_FOLLOWING_EXISTS return try { database.queryForObject(sql, Boolean::class.java, applicationId.toUUID(), userId.toUUID()) } catch (ex: Exception) { failWithMessage("Could not check if user [$userId] follows App[$applicationId]", ex) } } override fun getApplicationsFollowedBy(userId: String): MutableList<Application> { checkUserId(userId) val sql = Queries.SELECT_APPS_FOLLOWING return try { database.query(sql, appSerializer, userId.toUUID()) ?: mutableListOf() } catch (ex: Exception) { failWithMessage("Could not determine apps being followed by User[$userId]", ex) } } override fun getApplicationFollowers(applicationId: String): MutableList<User> { checkAppId(applicationId) val sql = Queries.SELECT_APP_FOLLOWERS return try { database.query(sql, userSerializer, applicationId.toUUID()) ?: mutableListOf() } catch (ex: Exception) { failWithMessage("Could not determine who follows App [$applicationId]", ex) } } }
apache-2.0
7da5756e395ff27f799635743ec9ba5e
28.934959
120
0.651997
4.799218
false
false
false
false
visiolink-android-dev/visiolink-app-plugin
src/main/kotlin/com/visiolink/app/Extensions.kt
1
961
package com.visiolink.app import groovy.lang.Closure import java.io.File import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit internal fun String.execute(dir: File? = null): String { val cmdArgs = split(" ") val process = ProcessBuilder(cmdArgs) .directory(dir) .redirectOutput(ProcessBuilder.Redirect.PIPE) .redirectError(ProcessBuilder.Redirect.PIPE) .start() return with(process) { waitFor(10, TimeUnit.SECONDS) inputStream.bufferedReader().readText() } } internal fun String.print() = apply { println(this) } fun dateFormat( pattern: String, locale: Locale = Locale.getDefault(), block: SimpleDateFormat.() -> Unit = {} ) = SimpleDateFormat(pattern, locale).apply(block) fun <T> closure(block: () -> T) = object : Closure<T>(null) { fun doCall(vararg args: Any?): T { return block.invoke() } }
apache-2.0
e0a32a3ff5d249a022f1d22a2505dd30
25.722222
61
0.650364
4.054852
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/imagemanipulator/arguments/SaveOptions.kt
2
930
package abi43_0_0.expo.modules.imagemanipulator.arguments import abi43_0_0.expo.modules.core.arguments.ReadableArguments import android.graphics.Bitmap.CompressFormat private const val KEY_BASE64 = "base64" private const val KEY_COMPRESS = "compress" private const val KEY_FORMAT = "format" data class SaveOptions( val base64: Boolean, val compress: Double, val format: CompressFormat ) { companion object { fun fromArguments(arguments: ReadableArguments): SaveOptions { val base64 = arguments.getBoolean(KEY_BASE64, false) val compress = arguments.getDouble(KEY_COMPRESS, 1.0) val format = toCompressFormat(arguments.getString(KEY_FORMAT, "jpeg")) return SaveOptions(base64, compress, format) } } } fun toCompressFormat(format: String): CompressFormat { return when (format) { "jpeg" -> CompressFormat.JPEG "png" -> CompressFormat.PNG else -> CompressFormat.JPEG } }
bsd-3-clause
11b9732cd71a736127e39d6913e6cd5c
29
76
0.736559
3.940678
false
false
false
false
ioc1778/incubator
incubator-events/src/main/java/com/riaektiv/events/TradeEvent.kt
2
1363
package com.riaektiv.events import java.nio.ByteBuffer /** * Coding With Passion Since 1991 * Created: 10/22/2016, 7:18 PM Eastern Time * @author Sergey Chuykov */ class TradeEvent { var ts: Long = 0 var symbol = ByteArray(3) var exchange = ByteArray(3) var price = 0.0 var qty = 0 fun symbol(symbol: String) { this.symbol = symbol.toByteArray() } fun exchange(exchange: String) { this.exchange = exchange.toByteArray() } companion object { val TS_POS = 0 val PRICE_POS = 8 val QTY_POS = 16 val SYMBOL_POS = 20 val EXCHANGE_POS = 23 fun getByteBuffer(ts: Long, symbol: ByteArray, exchange: ByteArray, price: Double, qty: Int): ByteBuffer { val data = ByteBuffer.allocateDirect(32) data.putLong(TS_POS, ts) data.putDouble(PRICE_POS, price) data.putInt(TradeEvent.QTY_POS, qty) data.position(SYMBOL_POS) data.put(symbol) data.position(EXCHANGE_POS) data.put(exchange) return data } } fun getByteBuffer(): ByteBuffer { return getByteBuffer(ts, symbol, exchange, price, qty) } override fun toString(): String { return String.format("[$ts %s %s $price $qty]", String(symbol), String(exchange)) } }
bsd-3-clause
05559bcf61cf9b856b0d506bc35f128f
23.8
114
0.590609
3.98538
false
false
false
false
stoyicker/dinger
app/src/main/kotlin/app/home/seen/SeenRecommendationViewHolder.kt
1
891
package app.home.seen import android.support.v7.widget.RecyclerView import android.view.View import domain.recommendation.DomainRecommendationUser import kotlinx.android.synthetic.main.item_view_recommendation.view.name import kotlinx.android.synthetic.main.item_view_recommendation.view.picture import kotlinx.android.synthetic.main.item_view_recommendation.view.teaser import org.stoyicker.dinger.R class SeenRecommendationViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bindTo(item: DomainRecommendationUser) { itemView.name.text = item.name itemView.teaser.apply { val desc = item.teaser.description if (desc.isEmpty()) { visibility = View.GONE } else { visibility = View.VISIBLE text = desc } } item.photos.firstOrNull()?.url?.let { itemView.picture.loadImage(it, R.drawable.ic_no_profile) } } }
mit
54b5aa4728f5a5c0d8bf2102b8b91add
34.68
100
0.749719
3.942478
false
false
false
false