repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
tensorflow/examples
lite/examples/pose_estimation/android/app/src/main/java/org/tensorflow/lite/examples/poseestimation/ml/PoseDetector.kt
1
958
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================================================================== */ package org.tensorflow.lite.examples.poseestimation.ml import android.graphics.Bitmap import org.tensorflow.lite.examples.poseestimation.data.Person interface PoseDetector : AutoCloseable { fun estimatePoses(bitmap: Bitmap): List<Person> fun lastInferenceTimeNanos(): Long }
apache-2.0
f144a624632537f96b465adb81370f0f
34.481481
78
0.727557
4.742574
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/gltf/GltfTexture.kt
1
1559
package de.fabmax.kool.modules.gltf import de.fabmax.kool.pipeline.Texture2d import de.fabmax.kool.pipeline.TextureProps import kotlinx.serialization.Serializable import kotlinx.serialization.Transient /** * A texture and its sampler. * * @param sampler The index of the sampler used by this texture. When undefined, a sampler with repeat wrapping and * auto filtering should be used. * @param source The index of the image used by this texture. When undefined, it is expected that an extension or * other mechanism will supply an alternate texture source, otherwise behavior is undefined. * @param name The user-defined name of this object. */ @Serializable data class GltfTexture( val sampler: Int = -1, val source: Int = 0, val name: String? = null ) { @Transient lateinit var imageRef: GltfImage @Transient private var createdTex: Texture2d? = null fun makeTexture(): Texture2d { if (createdTex == null) { val uri = imageRef.uri val name = if (uri != null && !uri.startsWith("data:", true)) { uri } else { "gltf_tex_$source" } createdTex = Texture2d(TextureProps(), name) { assetMgr -> if (uri != null) { assetMgr.loadTextureData(uri) } else { assetMgr.createTextureData(imageRef.bufferViewRef!!.getData(), imageRef.mimeType!!) } } } return createdTex!! } }
apache-2.0
da3f7ba214c4be2a63398e5531b4f5f3
32.191489
115
0.610006
4.428977
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/core/model/object/ObjectCube.kt
1
5725
package com.cout970.modeler.core.model.`object` import com.cout970.modeler.api.model.ITransformation import com.cout970.modeler.api.model.`object`.IObject import com.cout970.modeler.api.model.`object`.IObjectCube import com.cout970.modeler.api.model.material.IMaterialRef import com.cout970.modeler.api.model.mesh.IMesh import com.cout970.modeler.core.model.TRSTransformation import com.cout970.modeler.core.model.TRTSTransformation import com.cout970.modeler.core.model.material.MaterialRefNone import com.cout970.modeler.core.model.mesh.FaceIndex import com.cout970.modeler.core.model.mesh.Mesh import com.cout970.modeler.core.model.mesh.MeshFactory import com.cout970.vector.api.IVector2 import com.cout970.vector.api.IVector3 import com.cout970.vector.extensions.* import java.util.* /** * Created by cout970 on 2017/05/14. */ data class ObjectCube( override val name: String, override val transformation: ITransformation, override val material: IMaterialRef = MaterialRefNone, override val textureOffset: IVector2 = Vector2.ORIGIN, override val textureSize: IVector2 = vec2Of(64), override val visible: Boolean = true, val mirrored: Boolean = false, override val id: UUID = UUID.randomUUID() ) : IObjectCube { override val mesh: IMesh by lazy { generateMesh() } val trs get() = when (transformation) { is TRSTransformation -> transformation.toTRTS() is TRTSTransformation -> transformation else -> error("Invalid type: $transformation") } val size: IVector3 get() = trs.scale val pos: IVector3 get() = trs.translation fun generateMesh(): IMesh { val cube = MeshFactory.createCube(Vector3.ONE, Vector3.ORIGIN) return updateTextures(cube, size, textureOffset, textureSize) } fun updateTextures(mesh: IMesh, size: IVector3, offset: IVector2, textureSize: IVector2): IMesh { val uvs = generateUVs(size, offset, textureSize) val newFaces = mesh.faces.mapIndexed { index, face -> val faceIndex = face as FaceIndex FaceIndex.from(faceIndex.pos, faceIndex.tex.mapIndexed { vertexIndex, _ -> index * 4 + vertexIndex }) } return Mesh(mesh.pos, uvs, newFaces) } private fun generateUVs(size: IVector3, offset: IVector2, textureSize: IVector2): List<IVector2> { val width = size.xd val height = size.yd val length = size.zd val offsetX = offset.xd val offsetY = offset.yd val texelSize = vec2Of(1) / textureSize return listOf( //-y vec2Of(offsetX + length + width + width, offsetY + length) * texelSize, vec2Of(offsetX + length + width + width, offsetY) * texelSize, vec2Of(offsetX + length + width, offsetY) * texelSize, vec2Of(offsetX + length + width, offsetY + length) * texelSize, //+y vec2Of(offsetX + length, offsetY + length) * texelSize, vec2Of(offsetX + length + width, offsetY + length) * texelSize, vec2Of(offsetX + length + width, offsetY) * texelSize, vec2Of(offsetX + length, offsetY) * texelSize, //-z vec2Of(offsetX + length + width + length + width, offsetY + length) * texelSize, vec2Of(offsetX + length + width + length, offsetY + length) * texelSize, vec2Of(offsetX + length + width + length, offsetY + length + height) * texelSize, vec2Of(offsetX + length + width + length + width, offsetY + length + height) * texelSize, //+z vec2Of(offsetX + length + width, offsetY + length + height) * texelSize, vec2Of(offsetX + length + width, offsetY + length) * texelSize, vec2Of(offsetX + length, offsetY + length) * texelSize, vec2Of(offsetX + length, offsetY + length + height) * texelSize, //-x vec2Of(offsetX + length, offsetY + length + height) * texelSize, vec2Of(offsetX + length, offsetY + length) * texelSize, vec2Of(offsetX, offsetY + length) * texelSize, vec2Of(offsetX, offsetY + length + height) * texelSize, //+x vec2Of(offsetX + length + width + length, offsetY + length) * texelSize, vec2Of(offsetX + length + width, offsetY + length) * texelSize, vec2Of(offsetX + length + width, offsetY + length + height) * texelSize, vec2Of(offsetX + length + width + length, offsetY + length + height) * texelSize ) } override fun withVisibility(visible: Boolean): IObject = copy(visible = visible) override fun withSize(size: IVector3): IObjectCube = copy(transformation = trs.copy(scale = size)) override fun withPos(pos: IVector3): IObjectCube = copy(transformation = trs.copy(translation = pos)) override fun withTransformation(transform: ITransformation): IObjectCube = copy(transformation = transform) override fun withTextureOffset(tex: IVector2): IObjectCube = copy(textureOffset = tex) override fun withTextureSize(size: IVector2): IObjectCube = copy(textureSize = size) override fun withMesh(newMesh: IMesh): IObject = Object(name, newMesh, material, transformation, visible, id) override fun withMaterial(materialRef: IMaterialRef): IObject = copy(material = materialRef) override fun withName(name: String): IObject = copy(name = name) override fun withId(id: UUID): IObject = copy(id = id) override fun makeCopy(): IObjectCube = copy(id = UUID.randomUUID()) }
gpl-3.0
b8020fbcdb1349e94b578c7f068ecc6a
44.444444
113
0.648734
4.243884
false
false
false
false
DanielGrech/anko
preview/robowrapper/src/org/jetbrains/kotlin/android/robowrapper/androidUtils/Gravity.kt
6
2166
/* * 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. */ package org.jetbrains.kotlin.android.robowrapper import android.view.Gravity private val gravity = listOf( Gravity.START to "start", Gravity.END to "end", Gravity.LEFT to "left", Gravity.TOP to "top", Gravity.RIGHT to "right", Gravity.BOTTOM to "bottom", Gravity.CENTER_VERTICAL to "center_vertical", Gravity.CENTER_HORIZONTAL to "center_horizontal", Gravity.CLIP_HORIZONTAL to "clip_horizontal", Gravity.CLIP_VERTICAL to "clip_vertical" ) //convert Int gravity to a string representation fun resolveGravity(g: Int): String? { if (g == -1 || g == 0) return null val ret = arrayListOf<String>() val present = hashSetOf<String>() for (it in gravity) { if ((it.first and g) == it.first) { if (it.second == "left" && "start" in present) continue if (it.second == "right" && "end" in present) continue if (it.second == "center_horizontal" && "start" in present) continue if (it.second == "center_horizontal" && "end" in present) continue if (it.second == "center_horizontal" && "left" in present) continue if (it.second == "center_horizontal" && "right" in present) continue if (it.second == "center_vertical" && "top" in present) continue if (it.second == "center_vertical" && "bottom" in present) continue present.add(it.second) ret.add(it.second) } } return if (present.isEmpty()) null else ret.joinToString("|") }
apache-2.0
cc5fb59ce9641dcbb9fc04948130251d
36.362069
80
0.636196
3.98895
false
false
false
false
leafclick/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHPRSubmittableTextField.kt
1
9952
// 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.ui import com.intellij.icons.AllIcons import com.intellij.ide.BrowserUtil import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonShortcuts import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.fileTypes.FileTypes import com.intellij.openapi.project.DumbAwareAction import com.intellij.ui.EditorTextField import com.intellij.ui.ListFocusTraversalPolicy import com.intellij.ui.components.labels.LinkLabel import com.intellij.util.EventDispatcher import com.intellij.util.ui.JBInsets import com.intellij.util.ui.JBUI import com.intellij.util.ui.UI import com.intellij.util.ui.UIUtil import icons.GithubIcons import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import org.jetbrains.annotations.Nls import org.jetbrains.plugins.github.api.data.GHUser import org.jetbrains.plugins.github.pullrequest.avatars.GHAvatarIconsProvider import org.jetbrains.plugins.github.pullrequest.ui.SimpleEventListener import org.jetbrains.plugins.github.ui.InlineIconButton import org.jetbrains.plugins.github.util.handleOnEdt import java.awt.Dimension import java.awt.event.* import java.util.concurrent.CompletableFuture import javax.swing.JComponent import javax.swing.JLayeredPane import javax.swing.JPanel import javax.swing.border.EmptyBorder import kotlin.properties.Delegates object GHPRSubmittableTextField { private val SUBMIT_SHORTCUT_SET = CommonShortcuts.CTRL_ENTER private val CANCEL_SHORTCUT_SET = CommonShortcuts.ESCAPE fun create(model: Model, @Nls(capitalization = Nls.Capitalization.Title) actionName: String = "Comment", onCancel: (() -> Unit)? = null): JComponent { val textField = createTextField(model.document, actionName) val submitButton = createSubmitButton(actionName) val cancelButton = createCancelButton() return create(model, textField, submitButton, cancelButton, null, onCancel) } fun create(model: Model, avatarIconsProvider: GHAvatarIconsProvider, author: GHUser, @Nls(capitalization = Nls.Capitalization.Title) actionName: String = "Comment", onCancel: (() -> Unit)? = null): JComponent { val textField = createTextField(model.document, actionName) val submitButton = createSubmitButton(actionName) val cancelButton = createCancelButton() val authorLabel = LinkLabel.create("") { BrowserUtil.browse(author.url) }.apply { icon = avatarIconsProvider.getIcon(author.avatarUrl) isFocusable = true border = JBUI.Borders.empty(getEditorTextFieldVerticalOffset() - 2, 0) putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) } return create(model, textField, submitButton, cancelButton, authorLabel, onCancel) } private fun create(model: Model, textField: EditorTextField, submitButton: InlineIconButton, cancelButton: InlineIconButton, authorLabel: LinkLabel<out Any>? = null, onCancel: (() -> Unit)? = null): JPanel { val panel = JPanel(null) Controller(model, panel, textField, submitButton, cancelButton, onCancel) val textFieldWithSubmitButton = createTextFieldWithInlinedButton(textField, submitButton) return panel.apply { isOpaque = false layout = MigLayout(LC().gridGap("0", "0") .insets("0", "0", "0", "0") .fillX()) if (authorLabel != null) { isFocusCycleRoot = true isFocusTraversalPolicyProvider = true focusTraversalPolicy = ListFocusTraversalPolicy(listOf(textField, authorLabel)) add(authorLabel, CC().alignY("top").gapRight("${UI.scale(6)}")) } add(textFieldWithSubmitButton, CC().grow().pushX()) add(cancelButton, CC().alignY("top").hideMode(3)) } } private fun createTextField(document: Document, placeHolder: String): EditorTextField { return object : EditorTextField(document, null, FileTypes.PLAIN_TEXT) { //always paint pretty border override fun updateBorder(editor: EditorEx) = setupBorder(editor) override fun createEditor(): EditorEx { // otherwise border background is painted from multiple places return super.createEditor().apply { //TODO: fix in editor //com.intellij.openapi.editor.impl.EditorImpl.getComponent() == non-opaque JPanel // which uses default panel color component.isOpaque = false //com.intellij.ide.ui.laf.darcula.ui.DarculaEditorTextFieldBorder.paintBorder scrollPane.isOpaque = false } } }.apply { putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) setOneLineMode(false) setPlaceholder(placeHolder) addSettingsProvider { it.colorsScheme.lineSpacing = 1f } selectAll() } } private fun createSubmitButton(actionName: String) = InlineIconButton(GithubIcons.Send, GithubIcons.SendHovered, tooltip = actionName, shortcut = SUBMIT_SHORTCUT_SET).apply { putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) } private fun createCancelButton() = InlineIconButton(AllIcons.Actions.Close, AllIcons.Actions.CloseHovered, tooltip = "Cancel", shortcut = CANCEL_SHORTCUT_SET).apply { border = JBUI.Borders.empty(getEditorTextFieldVerticalOffset(), 0) putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) } private fun getEditorTextFieldVerticalOffset() = if (UIUtil.isUnderDarcula() || UIUtil.isUnderIntelliJLaF()) 6 else 4 private fun createTextFieldWithInlinedButton(textField: EditorTextField, button: JComponent): JComponent { val bordersListener = object : ComponentAdapter(), HierarchyListener { override fun componentResized(e: ComponentEvent?) { val scrollPane = (textField.editor as? EditorEx)?.scrollPane ?: return val buttonSize = button.size JBInsets.removeFrom(buttonSize, button.insets) scrollPane.viewportBorder = JBUI.Borders.emptyRight(buttonSize.width) scrollPane.viewport.revalidate() } override fun hierarchyChanged(e: HierarchyEvent?) { val scrollPane = (textField.editor as? EditorEx)?.scrollPane ?: return button.border = EmptyBorder(scrollPane.border.getBorderInsets(scrollPane)) componentResized(null) } } textField.addHierarchyListener(bordersListener) button.addComponentListener(bordersListener) val layeredPane = object : JLayeredPane() { override fun getPreferredSize(): Dimension { return textField.preferredSize } override fun doLayout() { super.doLayout() textField.setBounds(0, 0, width, height) val preferredButtonSize = button.preferredSize button.setBounds(width - preferredButtonSize.width, height - preferredButtonSize.height, preferredButtonSize.width, preferredButtonSize.height) } } layeredPane.add(textField, JLayeredPane.DEFAULT_LAYER, 0) layeredPane.add(button, JLayeredPane.POPUP_LAYER, 1) return layeredPane } class Model(private val submitter: (String) -> CompletableFuture<*>) { val document = EditorFactory.getInstance().createDocument("") var isSubmitting by Delegates.observable(false) { _, _, _ -> stateEventDispatcher.multicaster.eventOccurred() } private set private val stateEventDispatcher = EventDispatcher.create(SimpleEventListener::class.java) fun submit() { if (isSubmitting) return isSubmitting = true submitter(document.text).handleOnEdt { _, _ -> runWriteAction { document.setText("") } isSubmitting = false } } fun addStateListener(listener: () -> Unit) = stateEventDispatcher.addListener(object : SimpleEventListener { override fun eventOccurred() = listener() }) } private class Controller(private val model: Model, private val panel: JPanel, private val textField: EditorTextField, private val submitButton: InlineIconButton, cancelButton: InlineIconButton, onCancel: (() -> Unit)?) { init { textField.addDocumentListener(object : DocumentListener { override fun documentChanged(event: DocumentEvent) { updateSubmittionState() panel.revalidate() } }) submitButton.actionListener = ActionListener { model.submit() } object : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) = model.submit() }.registerCustomShortcutSet(SUBMIT_SHORTCUT_SET, textField) cancelButton.isVisible = onCancel != null if (onCancel != null) { cancelButton.actionListener = ActionListener { onCancel() } object : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { onCancel() } }.registerCustomShortcutSet(CANCEL_SHORTCUT_SET, textField) } model.addStateListener { updateSubmittionState() } updateSubmittionState() } private fun updateSubmittionState() { textField.isEnabled = !model.isSubmitting submitButton.isEnabled = !model.isSubmitting && textField.text.isNotBlank() } } }
apache-2.0
af6a78fdae6a903ea7f2e854ee2ca942
37.727626
140
0.701768
4.973513
false
false
false
false
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/test/kotlin/com/vrem/wifianalyzer/wifi/predicate/AnyPredicateTest.kt
1
1601
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.wifianalyzer.wifi.predicate import com.vrem.wifianalyzer.wifi.model.WiFiDetail import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test class AmyPredicateTest { @Test fun testAnyPredicateIsTrue() { // setup val wiFiDetail = WiFiDetail.EMPTY val fixture = listOf(falsePredicate, truePredicate, falsePredicate).anyPredicate() // execute val actual = fixture(wiFiDetail) // validate assertTrue(actual) } @Test fun testAnyPredicateIsFalse() { // setup val wiFiDetail = WiFiDetail.EMPTY val fixture = listOf(falsePredicate, falsePredicate, falsePredicate).anyPredicate() // execute val actual = fixture(wiFiDetail) // validate assertFalse(actual) } }
gpl-3.0
2f8927d0dc4803c9033abbabe0878625
31.693878
91
0.707058
4.434903
false
true
false
false
siosio/intellij-community
plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleBuildIssuesMiscImportingTest.kt
1
2471
// 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.plugins.gradle.importing import org.assertj.core.api.Assertions.assertThat import org.junit.Test class GradleBuildIssuesMiscImportingTest : BuildViewMessagesImportingTestCase() { var lastImportErrorMessage: String? = null override fun handleImportFailure(errorMessage: String, errorDetails: String?) { // do not fail tests with failed builds and save the import error message lastImportErrorMessage = errorMessage } @Test fun `test out of memory build failures`() { createProjectSubFile("gradle.properties", "org.gradle.jvmargs=-Xmx100m") importProject(""" List list = new ArrayList() while (true) { list.add(new Object()) } """.trimIndent()) val buildScript = myProjectConfig.toNioPath().toString() val oomMessage = if (lastImportErrorMessage!!.contains("Java heap space")) "Java heap space" else "GC overhead limit exceeded" assertSyncViewTreeEquals { treeTestPresentation -> assertThat(treeTestPresentation).satisfiesAnyOf( { assertThat(it).isEqualTo("-\n" + " -failed\n" + " -build.gradle\n" + " $oomMessage") }, { assertThat(it).isEqualTo("-\n" + " -failed\n" + " $oomMessage") } ) } assertSyncViewSelectedNode(oomMessage, true) { text -> assertThat(text).satisfiesAnyOf( { assertThat(it).startsWith(""" * Where: Build file '$buildScript' line: 10 * What went wrong: Out of memory. $oomMessage Possible solution: - Check the JVM memory arguments defined for the gradle process in: gradle.properties in project root directory """.trimIndent()) }, { assertThat(it).startsWith(""" * What went wrong: Out of memory. $oomMessage Possible solution: - Check the JVM memory arguments defined for the gradle process in: gradle.properties in project root directory """.trimIndent()) } ) } } }
apache-2.0
908fffe394828d193bb04789a2cc0d56
31.513158
140
0.571024
5.180294
false
true
false
false
siosio/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/tree/elements.kt
1
9248
// 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.tree import org.jetbrains.kotlin.nj2k.symbols.JKClassSymbol import org.jetbrains.kotlin.nj2k.tree.visitors.JKVisitor import org.jetbrains.kotlin.nj2k.types.JKType class JKTreeRoot(element: JKTreeElement) : JKTreeElement() { var element by child(element) override fun accept(visitor: JKVisitor) = visitor.visitTreeRoot(this) } class JKFile( packageDeclaration: JKPackageDeclaration, importList: JKImportList, declarationList: List<JKDeclaration> ) : JKTreeElement(), PsiOwner by PsiOwnerImpl() { override fun accept(visitor: JKVisitor) = visitor.visitFile(this) var packageDeclaration: JKPackageDeclaration by child(packageDeclaration) var importList: JKImportList by child(importList) var declarationList by children(declarationList) } class JKTypeElement(var type: JKType, annotationList: JKAnnotationList = JKAnnotationList()) : JKTreeElement(), JKAnnotationListOwner { override fun accept(visitor: JKVisitor) = visitor.visitTypeElement(this) override var annotationList: JKAnnotationList by child(annotationList) } abstract class JKBlock : JKTreeElement() { abstract var statements: List<JKStatement> val leftBrace = JKTokenElementImpl("{") val rightBrace = JKTokenElementImpl("}") } object JKBodyStub : JKBlock() { override val trailingComments: MutableList<JKComment> = mutableListOf() override val leadingComments: MutableList<JKComment> = mutableListOf() override var hasTrailingLineBreak = false override var hasLeadingLineBreak = false override fun copy(): JKTreeElement = this override var statements: List<JKStatement> get() = emptyList() set(_) {} override fun acceptChildren(visitor: JKVisitor) {} override var parent: JKElement? get() = null set(_) {} override fun detach(from: JKElement) {} override fun attach(to: JKElement) {} override fun accept(visitor: JKVisitor) = Unit } class JKInheritanceInfo( extends: List<JKTypeElement>, implements: List<JKTypeElement> ) : JKTreeElement() { var extends: List<JKTypeElement> by children(extends) var implements: List<JKTypeElement> by children(implements) override fun accept(visitor: JKVisitor) = visitor.visitInheritanceInfo(this) } class JKPackageDeclaration(name: JKNameIdentifier) : JKDeclaration() { override var name: JKNameIdentifier by child(name) override fun accept(visitor: JKVisitor) = visitor.visitPackageDeclaration(this) } abstract class JKLabel : JKTreeElement() class JKLabelEmpty : JKLabel() { override fun accept(visitor: JKVisitor) = visitor.visitLabelEmpty(this) } class JKLabelText(label: JKNameIdentifier) : JKLabel() { val label: JKNameIdentifier by child(label) override fun accept(visitor: JKVisitor) = visitor.visitLabelText(this) } class JKImportStatement(name: JKNameIdentifier) : JKTreeElement() { val name: JKNameIdentifier by child(name) override fun accept(visitor: JKVisitor) = visitor.visitImportStatement(this) } class JKImportList(imports: List<JKImportStatement>) : JKTreeElement() { var imports by children(imports) override fun accept(visitor: JKVisitor) = visitor.visitImportList(this) } abstract class JKAnnotationParameter : JKTreeElement() { abstract var value: JKAnnotationMemberValue } class JKAnnotationParameterImpl(value: JKAnnotationMemberValue) : JKAnnotationParameter() { override var value: JKAnnotationMemberValue by child(value) override fun accept(visitor: JKVisitor) = visitor.visitAnnotationParameter(this) } class JKAnnotationNameParameter( value: JKAnnotationMemberValue, name: JKNameIdentifier ) : JKAnnotationParameter() { override var value: JKAnnotationMemberValue by child(value) val name: JKNameIdentifier by child(name) override fun accept(visitor: JKVisitor) = visitor.visitAnnotationNameParameter(this) } abstract class JKArgument : JKTreeElement() { abstract var value: JKExpression } class JKNamedArgument( value: JKExpression, name: JKNameIdentifier ) : JKArgument() { override var value by child(value) val name by child(name) override fun accept(visitor: JKVisitor) = visitor.visitNamedArgument(this) } class JKArgumentImpl(value: JKExpression) : JKArgument() { override var value by child(value) override fun accept(visitor: JKVisitor) = visitor.visitArgument(this) } class JKArgumentList(arguments: List<JKArgument> = emptyList()) : JKTreeElement() { constructor(vararg arguments: JKArgument) : this(arguments.toList()) constructor(vararg values: JKExpression) : this(values.map { JKArgumentImpl(it) }) var arguments by children(arguments) override fun accept(visitor: JKVisitor) = visitor.visitArgumentList(this) } class JKTypeParameterList(typeParameters: List<JKTypeParameter> = emptyList()) : JKTreeElement() { var typeParameters by children(typeParameters) override fun accept(visitor: JKVisitor) = visitor.visitTypeParameterList(this) } class JKAnnotationList(annotations: List<JKAnnotation> = emptyList()) : JKTreeElement() { var annotations: List<JKAnnotation> by children(annotations) override fun accept(visitor: JKVisitor) = visitor.visitAnnotationList(this) } class JKAnnotation( var classSymbol: JKClassSymbol, arguments: List<JKAnnotationParameter> = emptyList() ) : JKAnnotationMemberValue() { var arguments: List<JKAnnotationParameter> by children(arguments) override fun accept(visitor: JKVisitor) = visitor.visitAnnotation(this) } class JKTypeArgumentList(typeArguments: List<JKTypeElement> = emptyList()) : JKTreeElement(), PsiOwner by PsiOwnerImpl() { var typeArguments: List<JKTypeElement> by children(typeArguments) override fun accept(visitor: JKVisitor) = visitor.visitTypeArgumentList(this) } class JKNameIdentifier(val value: String) : JKTreeElement() { override fun accept(visitor: JKVisitor) = visitor.visitNameIdentifier(this) } interface JKAnnotationListOwner : JKFormattingOwner { var annotationList: JKAnnotationList } class JKBlockImpl(statements: List<JKStatement> = emptyList()) : JKBlock() { constructor(vararg statements: JKStatement) : this(statements.toList()) override var statements by children(statements) override fun accept(visitor: JKVisitor) = visitor.visitBlock(this) } class JKKtWhenCase(labels: List<JKKtWhenLabel>, statement: JKStatement) : JKTreeElement() { var labels: List<JKKtWhenLabel> by children(labels) var statement: JKStatement by child(statement) override fun accept(visitor: JKVisitor) = visitor.visitKtWhenCase(this) } abstract class JKKtWhenLabel : JKTreeElement() class JKKtElseWhenLabel : JKKtWhenLabel() { override fun accept(visitor: JKVisitor) = visitor.visitKtElseWhenLabel(this) } class JKKtValueWhenLabel(expression: JKExpression) : JKKtWhenLabel() { var expression: JKExpression by child(expression) override fun accept(visitor: JKVisitor) = visitor.visitKtValueWhenLabel(this) } class JKClassBody(declarations: List<JKDeclaration> = emptyList()) : JKTreeElement() { var declarations: List<JKDeclaration> by children(declarations) override fun accept(visitor: JKVisitor) = visitor.visitClassBody(this) val leftBrace = JKTokenElementImpl("{") val rightBrace = JKTokenElementImpl("}") } class JKJavaTryCatchSection( parameter: JKParameter, block: JKBlock ) : JKStatement() { var parameter: JKParameter by child(parameter) var block: JKBlock by child(block) override fun accept(visitor: JKVisitor) = visitor.visitJavaTryCatchSection(this) } abstract class JKJavaSwitchCase : JKTreeElement() { abstract fun isDefault(): Boolean abstract var statements: List<JKStatement> } class JKJavaDefaultSwitchCase(statements: List<JKStatement>) : JKJavaSwitchCase(), PsiOwner by PsiOwnerImpl() { override var statements: List<JKStatement> by children(statements) override fun isDefault(): Boolean = true override fun accept(visitor: JKVisitor) = visitor.visitJavaDefaultSwitchCase(this) } class JKJavaLabelSwitchCase( label: JKExpression, statements: List<JKStatement> ) : JKJavaSwitchCase(), PsiOwner by PsiOwnerImpl() { override var statements: List<JKStatement> by children(statements) var label: JKExpression by child(label) override fun isDefault(): Boolean = false override fun accept(visitor: JKVisitor) = visitor.visitJavaLabelSwitchCase(this) } class JKKtTryCatchSection( parameter: JKParameter, block: JKBlock ) : JKTreeElement() { var parameter: JKParameter by child(parameter) var block: JKBlock by child(block) override fun accept(visitor: JKVisitor) = visitor.visitKtTryCatchSection(this) } sealed class JKJavaResourceElement : JKTreeElement(), PsiOwner by PsiOwnerImpl() class JKJavaResourceExpression(expression: JKExpression) : JKJavaResourceElement() { var expression by child(expression) } class JKJavaResourceDeclaration(declaration: JKLocalVariable) : JKJavaResourceElement() { var declaration by child(declaration) }
apache-2.0
fb449d71a35b2416fb1ffb0edae72563
34.569231
158
0.761246
4.809152
false
false
false
false
siosio/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/gradle/GradleProjectModuleOperationProvider.kt
1
2975
package com.jetbrains.packagesearch.intellij.plugin.gradle import com.intellij.buildsystem.model.OperationFailure import com.intellij.buildsystem.model.OperationItem import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.extensibility.AbstractProjectModuleOperationProvider import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyOperationMetadata import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleType import com.jetbrains.packagesearch.intellij.plugin.gradle.configuration.packageSearchGradleConfigurationForProject private const val EXTENSION_GRADLE = "gradle" private const val FILENAME_GRADLE_PROPERTIES = "gradle.properties" private const val FILENAME_GRADLE_WRAPPER_PROPERTIES = "gradle-wrapper.properties" internal open class GradleProjectModuleOperationProvider : AbstractProjectModuleOperationProvider() { override fun hasSupportFor(project: Project, psiFile: PsiFile?): Boolean { // Logic based on com.android.tools.idea.gradle.project.sync.GradleFiles.isGradleFile() val file = psiFile?.virtualFile ?: return false return EXTENSION_GRADLE.equals(file.extension, ignoreCase = true) || FILENAME_GRADLE_PROPERTIES.equals(file.name, ignoreCase = true) || FILENAME_GRADLE_WRAPPER_PROPERTIES.equals(file.name, ignoreCase = true) } override fun hasSupportFor(projectModuleType: ProjectModuleType): Boolean = projectModuleType is GradleProjectModuleType override fun addDependencyToModule( operationMetadata: DependencyOperationMetadata, module: ProjectModule ): List<OperationFailure<out OperationItem>> { requireNotNull(operationMetadata.newScope) { PackageSearchBundle.getMessage("packagesearch.packageoperation.error.gradle.missing.configuration") } saveAdditionalScopeToConfigurationIfNeeded(module.nativeModule.project, operationMetadata.newScope) return super.addDependencyToModule(operationMetadata, module) } override fun removeDependencyFromModule( operationMetadata: DependencyOperationMetadata, module: ProjectModule ): List<OperationFailure<out OperationItem>> { requireNotNull(operationMetadata.currentScope) { PackageSearchBundle.getMessage("packagesearch.packageoperation.error.gradle.missing.configuration") } return super.removeDependencyFromModule(operationMetadata, module) } private fun saveAdditionalScopeToConfigurationIfNeeded(project: Project, scopeName: String) { val configuration = packageSearchGradleConfigurationForProject(project) if (!configuration.updateScopesOnUsage) return configuration.addGradleScope(scopeName) } }
apache-2.0
bcf117f60fd16eeab094271d55b17333
46.983871
114
0.791261
5.688337
false
true
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/internal/ui/uiDslShowcase/DemoComponents.kt
3
3443
// 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.internal.ui.uiDslShowcase import com.intellij.icons.AllIcons import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.util.Disposer import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.dsl.gridLayout.VerticalAlign @Suppress("DialogTitleCapitalization") @Demo(title = "Components", description = "There are many different components supported by UI DSL. Here are some of them.", scrollbar = true) fun demoComponents(parentDisposable: Disposable): DialogPanel { val panel = panel { row { checkBox("checkBox") } var radioButtonValue = 2 buttonsGroup { row("radioButton") { radioButton("Value 1", 1) radioButton("Value 2", 2) } }.bind({ radioButtonValue }, { radioButtonValue = it }) row { button("button") {} } row("actionButton:") { val action = object : DumbAwareAction("Action text", "Action description", AllIcons.Actions.QuickfixOffBulb) { override fun actionPerformed(e: AnActionEvent) { } } actionButton(action) } row("actionsButton:") { actionsButton(object : DumbAwareAction("Action one") { override fun actionPerformed(e: AnActionEvent) { } }, object : DumbAwareAction("Action two") { override fun actionPerformed(e: AnActionEvent) { } }) } row("segmentedButton:") { segmentedButton(listOf("Button 1", "Button 2", "Button Last")) { it } } row("tabbedPaneHeader:") { tabbedPaneHeader(listOf("Tab 1", "Tab 2", "Last Tab")) } row("label:") { label("Some label") } row("text:") { text("text supports max line width and can contain links, try <a href='https://www.jetbrains.com'>jetbrains.com</a>") } row("link:") { link("Focusable link") {} } row("browserLink:") { browserLink("jetbrains.com", "https://www.jetbrains.com") } row("dropDownLink:") { dropDownLink("Item 1", listOf("Item 1", "Item 2", "Item 3")) } row("icon:") { icon(AllIcons.Actions.QuickfixOffBulb) } row("contextHelp:") { contextHelp("contextHelp description", "contextHelp title") } row("textField:") { textField() } row("textFieldWithBrowseButton:") { textFieldWithBrowseButton() } row("expandableTextField:") { expandableTextField() } row("intTextField(0..100):") { intTextField(0..100) } row("spinner(0..100):") { spinner(0..100) } row("spinner(0.0..100.0, 0.01):") { spinner(0.0..100.0, 0.01) } row { label("textArea:") .verticalAlign(VerticalAlign.TOP) .gap(RightGap.SMALL) textArea() .rows(5) .horizontalAlign(HorizontalAlign.FILL) }.layout(RowLayout.PARENT_GRID) row("comboBox:") { comboBox(listOf("Item 1", "Item 2")) } } val disposable = Disposer.newDisposable() panel.registerValidators(disposable) Disposer.register(parentDisposable, disposable) return panel }
apache-2.0
25fdeaeae1fd831b86936697caef518b
24.69403
158
0.633169
4.22973
false
false
false
false
dkrivoruchko/ScreenStream
app/src/firebase/kotlin/info/dvkr/screenstream/ui/activity/AppUpdateActivity.kt
1
5011
package info.dvkr.screenstream.ui.activity import android.content.Intent import android.os.Bundle import androidx.annotation.LayoutRes import androidx.lifecycle.lifecycleScope import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.callbacks.onDismiss import com.afollestad.materialdialogs.lifecycle.lifecycleOwner import com.elvishew.xlog.XLog import com.google.android.play.core.appupdate.AppUpdateManagerFactory import com.google.android.play.core.ktx.AppUpdateResult import com.google.android.play.core.ktx.isFlexibleUpdateAllowed import com.google.android.play.core.ktx.requestUpdateFlow import info.dvkr.screenstream.R import info.dvkr.screenstream.common.getLog import info.dvkr.screenstream.common.settings.AppSettings import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import org.koin.android.ext.android.inject abstract class AppUpdateActivity(@LayoutRes contentLayoutId: Int) : BaseActivity(contentLayoutId) { companion object { private const val APP_UPDATE_FLEXIBLE_REQUEST_CODE = 15 private const val APP_UPDATE_REQUEST_TIMEOUT = 8 * 60 * 60 * 1000L // 8 hours. Don't need exact time frame } protected val appSettings: AppSettings by inject() private var appUpdateConfirmationDialog: MaterialDialog? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AppUpdateManagerFactory.create(this).requestUpdateFlow().onEach { appUpdateResult -> when (appUpdateResult) { AppUpdateResult.NotAvailable -> { XLog.v([email protected]("AppUpdateResult.NotAvailable")) } is AppUpdateResult.Available -> { XLog.d([email protected]("AppUpdateResult.Available")) if (appUpdateResult.updateInfo.isFlexibleUpdateAllowed) { XLog.d([email protected]("AppUpdateResult.Available", "FlexibleUpdateAllowed")) val lastRequestMillisPassed = System.currentTimeMillis() - appSettings.lastUpdateRequestMillisFlow.first() if (lastRequestMillisPassed >= APP_UPDATE_REQUEST_TIMEOUT) { XLog.d([email protected]("AppUpdateResult.Available", "startFlexibleUpdate")) appSettings.setLastUpdateRequestMillis(System.currentTimeMillis()) appUpdateResult.startFlexibleUpdate(this, APP_UPDATE_FLEXIBLE_REQUEST_CODE) } } } is AppUpdateResult.InProgress -> { XLog.v([email protected]("AppUpdateResult.InProgress", appUpdateResult.installState.toString())) } is AppUpdateResult.Downloaded -> { XLog.d([email protected]("AppUpdateResult.Downloaded")) showUpdateConfirmationDialog(appUpdateResult) } } } .catch { cause -> XLog.e([email protected]("AppUpdateManager.requestUpdateFlow.catch: $cause")) } .launchIn(lifecycleScope) } @Suppress("DEPRECATION") @Deprecated("Deprecated in Java") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { requestCode != APP_UPDATE_FLEXIBLE_REQUEST_CODE || return super.onActivityResult(requestCode, resultCode, data) } private fun showUpdateConfirmationDialog(appUpdateResult: AppUpdateResult.Downloaded) { XLog.d(getLog("showUpdateConfirmationDialog")) appUpdateConfirmationDialog?.dismiss() appUpdateConfirmationDialog = MaterialDialog(this).show { lifecycleOwner(this@AppUpdateActivity) icon(R.drawable.ic_permission_dialog_24dp) title(R.string.app_update_activity_dialog_title) message(R.string.app_update_activity_dialog_message) positiveButton(R.string.app_update_activity_dialog_restart) { dismiss() onUpdateConfirmationDialogClick(appUpdateResult, true) } negativeButton(android.R.string.cancel) { dismiss() onUpdateConfirmationDialogClick(appUpdateResult, false) } cancelable(false) cancelOnTouchOutside(false) noAutoDismiss() onDismiss { appUpdateConfirmationDialog = null } } } private fun onUpdateConfirmationDialogClick(appUpdateResult: AppUpdateResult.Downloaded, isPositive: Boolean) { lifecycleScope.launchWhenStarted { XLog.d([email protected]("onUpdateConfirmationDialogClick", "isPositive: $isPositive")) if (isPositive) appUpdateResult.completeUpdate() } } }
mit
503c080db9637e49973775cd6f51573c
46.283019
128
0.679705
5.376609
false
false
false
false
androidx/androidx
core/uwb/uwb/src/main/java/androidx/core/uwb/impl/UwbControllerSessionScopeImpl.kt
3
3025
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.uwb.impl import androidx.core.uwb.RangingCapabilities import androidx.core.uwb.RangingParameters import androidx.core.uwb.RangingResult import androidx.core.uwb.UwbAddress import androidx.core.uwb.UwbComplexChannel import androidx.core.uwb.UwbControllerSessionScope import androidx.core.uwb.exceptions.UwbSystemCallbackException import com.google.android.gms.common.api.ApiException import com.google.android.gms.nearby.uwb.UwbClient import com.google.android.gms.nearby.uwb.UwbStatusCodes import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.tasks.await internal class UwbControllerSessionScopeImpl( private val uwbClient: UwbClient, override val rangingCapabilities: RangingCapabilities, override val localAddress: UwbAddress, override val uwbComplexChannel: UwbComplexChannel ) : UwbControllerSessionScope { private val uwbClientSessionScope = UwbClientSessionScopeImpl(uwbClient, rangingCapabilities, localAddress) override suspend fun addControlee(address: UwbAddress) { val uwbAddress = com.google.android.gms.nearby.uwb.UwbAddress(address.address) try { uwbClient.addControlee(uwbAddress).await() } catch (e: ApiException) { if (e.statusCode == UwbStatusCodes.INVALID_API_CALL) { throw IllegalStateException("Please check that the ranging is active and the" + "ranging profile supports multi-device ranging.") } } } override suspend fun removeControlee(address: UwbAddress) { val uwbAddress = com.google.android.gms.nearby.uwb.UwbAddress(address.address) try { uwbClient.removeControlee(uwbAddress).await() } catch (e: ApiException) { when (e.statusCode) { UwbStatusCodes.INVALID_API_CALL -> throw IllegalStateException("Please check that the ranging is active and the" + "ranging profile supports multi-device ranging.") UwbStatusCodes.UWB_SYSTEM_CALLBACK_FAILURE -> throw UwbSystemCallbackException("The operation failed due to hardware or " + "firmware issues.") } } } override fun prepareSession(parameters: RangingParameters): Flow<RangingResult> { return uwbClientSessionScope.prepareSession(parameters) } }
apache-2.0
21cd757a2a98fa7bc32ee542cba8ef55
41.027778
99
0.713719
4.886914
false
false
false
false
GunoH/intellij-community
jvm/jvm-analysis-java-tests/testSrc/com/intellij/codeInspection/tests/java/test/junit/JavaJUnit5ConverterInspectionTest.kt
8
4101
package com.intellij.codeInspection.tests.java.test.junit import com.intellij.codeInspection.tests.ULanguage import com.intellij.codeInspection.tests.test.junit.JUnit5ConverterInspectionTestBase class JavaJUnit5ConverterInspectionTest : JUnit5ConverterInspectionTestBase() { fun `test qualified conversion`() { myFixture.testQuickFix(ULanguage.JAVA, """ import org.junit.Test; import org.junit.Before; import org.junit.Assert; import java.util.*; public class Qual<caret>ified { @Before public void setUp() {} @Test public void testMethodCall() throws Exception { Assert.assertArrayEquals(new Object[] {}, null); Assert.assertArrayEquals("message", new Object[] {}, null); Assert.assertEquals("Expected", "actual"); Assert.assertEquals("message", "Expected", "actual"); Assert.fail(); Assert.fail(""); } @Test public void testMethodRef() { List<Boolean> booleanList = new ArrayList<>(); booleanList.add(true); booleanList.forEach(Assert::assertTrue); } } """.trimIndent(), """ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeEach; import java.util.*; public class Qualified { @BeforeEach public void setUp() {} @Test public void testMethodCall() throws Exception { Assertions.assertArrayEquals(new Object[] {}, null); Assertions.assertArrayEquals(new Object[] {}, null, "message"); Assertions.assertEquals("Expected", "actual"); Assertions.assertEquals("Expected", "actual", "message"); Assertions.fail(); Assertions.fail(""); } @Test public void testMethodRef() { List<Boolean> booleanList = new ArrayList<>(); booleanList.add(true); booleanList.forEach(Assertions::assertTrue); } } """.trimIndent(), "Migrate to JUnit 5") } fun `test unqualified conversion`() { myFixture.testQuickFix(ULanguage.JAVA, """ import org.junit.Test; import static org.junit.Assert.*; import org.junit.Assert; import java.util.*; public class UnQual<caret>ified { @Test public void testMethodCall() throws Exception { assertArrayEquals(new Object[] {}, null); assertArrayEquals("message", new Object[] {}, null); assertEquals("Expected", "actual"); assertEquals("message", "Expected", "actual"); fail(); fail(""); } @Test public void testMethodRef() { List<Boolean> booleanList = new ArrayList<>(); booleanList.add(true); booleanList.forEach(Assert::assertTrue); } } """.trimIndent(), """ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.*; public class UnQualified { @Test public void testMethodCall() throws Exception { Assertions.assertArrayEquals(new Object[] {}, null); Assertions.assertArrayEquals(new Object[] {}, null, "message"); Assertions.assertEquals("Expected", "actual"); Assertions.assertEquals("Expected", "actual", "message"); Assertions.fail(); Assertions.fail(""); } @Test public void testMethodRef() { List<Boolean> booleanList = new ArrayList<>(); booleanList.add(true); booleanList.forEach(Assertions::assertTrue); } } """.trimIndent(), "Migrate to JUnit 5") } fun `test expected on test annotation`() { myFixture.testQuickFixUnavailable(ULanguage.JAVA, """ import org.junit.Test; import static org.junit.Assert.*; public class Simp<caret>le { @Test(expected = Exception.class) public void testFirst() throws Exception { } } """.trimIndent()) } }
apache-2.0
ff44cc0eb001314766b951453ab176ae
30.312977
85
0.596928
5.025735
false
true
false
false
klaplume/lesseract
src/main/kotlin/integrator/SamplerIntegrator.kt
1
3385
package integrator import math.Bounds2i import math.Point2i import sampler.Sampler import kotlinx.coroutines.experimental.* import main.* abstract class SamplerIntegrator(val cam: Camera, val sampler: Sampler) : Integrator { var scene: Scene? = null override fun render(scene: Scene) { preprocess(scene, this.sampler) this.scene = scene val tiles = computeNbTiles(cam.film.getSampleBounds(), cam.film.tileSize) runBlocking { val jobs = mutableListOf<Job>() for (y in 0..tiles.y-1) { for (x in 0..tiles.x-1) { val tile = Point2i(x, y) val job = launch(CommonPool) { renderTile(tile, tiles) } jobs.add(job) } } jobs.forEach({ it.join() }) } cam.film.writeImage() } private suspend fun renderTile(tile: Point2i, tiles: Point2i) { println("Rendering tile (${tile.x}, ${tile.y})") val seed = tile.y * tiles.x + tile.x val tileSampler = sampler.clone(seed) val tileBounds = cam.film.computeTileBounds(tile, cam.film.getSampleBounds()) //println("tile (${tile.x}; ${tile.y}) bounds x=(${tileBounds.xMin}; ${tileBounds.xMax}) y=(${tileBounds.yMin}; ${tileBounds.yMax})") val frac = seed.toFloat() / (tiles.x * tiles.y) val filmTile = cam.film.getFilmTile(tileBounds, frac) for(i in 0..filmTile.pixels.size-1){ val pixel = filmTile.pixels[i] pixel.x = i % cam.film.tileSize + tileBounds.xMin pixel.y = i / cam.film.tileSize + tileBounds.yMin tileSampler.startPixel(pixel) while(tileSampler.hasNextSample()){ tileSampler.nextSample() val cameraSample = tileSampler.getCameraSample(pixel) //Generate ray val rayDiffData: RayDifferentialData = cam.generateRayDifferential(cameraSample) val ray: RayDifferential = rayDiffData.ray val rayWeight: Float = rayDiffData.rayWeight ray.scaleDifferentials(1 / Math.sqrt(tileSampler.samplesPerPixel.toDouble())) //Evaluate radiance along ray var L: Spectrum = Spectrum() if(scene != null){ //TODO possible to avoid this? if(rayWeight > 0) { L = Li(ray, scene!!, tileSampler) checkLValue(L) } } //Add contribution to image filmTile.addSample(cameraSample.posFilm, L, rayWeight) //Free data structures } } cam.film.mergeFilmTile(filmTile) } private fun checkLValue(l: Spectrum) { //TODO check for valid values } private fun computeNbTiles(sampleBounds: Bounds2i, tileSize: Int): Point2i { //TODO compute var p = Point2i(Math.ceil(((sampleBounds.xMax+1-sampleBounds.xMin).toDouble() / tileSize)).toInt(), Math.ceil(((sampleBounds.yMax+1-sampleBounds.yMin).toDouble() / tileSize)).toInt()) return p } fun preprocess(scene: Scene, sampler: Sampler) { } abstract fun Li(ray: RayDifferential, scene: Scene, tileSampler: Sampler, depth: Int = 0): Spectrum }
apache-2.0
0baf004066c4eee202ac303f71be9285
36.197802
141
0.568981
4.290241
false
false
false
false
GunoH/intellij-community
jvm/jvm-analysis-kotlin-tests/testSrc/com/intellij/codeInspection/tests/kotlin/KotlinDependencyInspectionTest.kt
8
3277
package com.intellij.codeInspection.tests.kotlin import com.intellij.codeInspection.tests.DependencyInspectionTestBase class KotlinDependencyInspectionTest0 : DependencyInspectionTestBase() { fun `test illegal imported dependency Java API`() = dependencyViolationTest(javaFooFile, "ImportClientJava.kt", """ package pkg.client import <error descr="Dependency rule 'Deny usages of scope 'JavaFoo' in scope 'ImportClientJava'.' is violated">pkg.api.JavaFoo</error> fun main() { <error descr="Dependency rule 'Deny usages of scope 'JavaFoo' in scope 'ImportClientJava'.' is violated">JavaFoo()</error> } """.trimIndent()) fun `test illegal imported dependency Kotlin API`() = dependencyViolationTest(kotlinFooFile, "ImportClientKotlin.kt", """ package pkg.client import <error descr="Dependency rule 'Deny usages of scope 'KotlinFoo' in scope 'ImportClientKotlin'.' is violated">pkg.api.KotlinFoo</error> fun main() { <error descr="Dependency rule 'Deny usages of scope 'KotlinFoo' in scope 'ImportClientKotlin'.' is violated">KotlinFoo()</error> } """.trimIndent()) fun `test illegal imported dependency skip imports`() = dependencyViolationTest(kotlinFooFile, "ImportClientKotlin.kt", """ package pkg.client import pkg.api.KotlinFoo fun main() { <error descr="Dependency rule 'Deny usages of scope 'KotlinFoo' in scope 'ImportClientKotlin'.' is violated">KotlinFoo()</error> } """.trimIndent(), skipImports = true) fun `test illegal imported dependency Kotlin API in Java`() = dependencyViolationTest(kotlinFooFile, "ImportClientKotlin.java", """ package pkg.client; import <error descr="Dependency rule 'Deny usages of scope 'KotlinFoo' in scope 'ImportClientKotlin'.' is violated">pkg.api.KotlinFoo</error>; class Client { public static void main(String[] args) { new <error descr="Dependency rule 'Deny usages of scope 'KotlinFoo' in scope 'ImportClientKotlin'.' is violated">KotlinFoo</error>(); } } """.trimIndent()) fun `test illegal fully qualified dependency Java API`() = dependencyViolationTest(javaFooFile, "FqClientJava.kt", """ package pkg.client fun main() { <error descr="Dependency rule 'Deny usages of scope 'JavaFoo' in scope 'FqClientJava'.' is violated">pkg.api.JavaFoo()</error> } """.trimIndent()) fun `test illegal fully qualified dependency Kotlin API`() = dependencyViolationTest(kotlinFooFile, "FqClientKotlin.kt", """ package pkg.client fun main() { <error descr="Dependency rule 'Deny usages of scope 'KotlinFoo' in scope 'FqClientKotlin'.' is violated">pkg.api.KotlinFoo()</error> } """.trimIndent()) fun `test illegal fully qualified dependency Kotlin API in Java`() = dependencyViolationTest(kotlinFooFile, "FqClientKotlin.java", """ package pkg.client; class Client { public static void main(String[] args) { new <error descr="Dependency rule 'Deny usages of scope 'KotlinFoo' in scope 'FqClientKotlin'.' is violated">pkg.api.KotlinFoo</error>(); } } """.trimIndent()) }
apache-2.0
905c5b539caac5b04ad2bf925347e6c9
43.90411
148
0.676533
5.026074
false
true
false
false
gjuillot/testng
kobalt/src/Build.kt
1
3119
import com.beust.kobalt.TaskResult import com.beust.kobalt.api.Project import com.beust.kobalt.api.annotation.Task import com.beust.kobalt.buildScript import com.beust.kobalt.plugin.java.javaCompiler import com.beust.kobalt.plugin.packaging.assemble import com.beust.kobalt.plugin.publish.bintray import com.beust.kobalt.project import com.beust.kobalt.test import org.apache.maven.model.Developer import org.apache.maven.model.License import org.apache.maven.model.Model import org.apache.maven.model.Scm import java.io.File val VERSION = "6.11.1-SNAPSHOT" val bs = buildScript { repos("https://dl.bintray.com/cbeust/maven") } //val pl = plugins("com.beust:kobalt-groovy:0.4") // file(homeDir("kotlin/kobalt-groovy/kobaltBuild/libs/kobalt-groovy-0.1.jar"))) val p = project { name = "testng" group = "org.testng" artifactId = name url = "http://testng.org" version = VERSION pom = Model().apply { name = project.name description = "A testing framework for the JVM" url = "http://testng.org" licenses = listOf(License().apply { name = "Apache 2.0" url = "http://www.apache.org/licenses/LICENSE-2.0" }) scm = Scm().apply { url = "http://github.com/cbeust/testng" connection = "https://github.com/cbeust/testng.git" developerConnection = "[email protected]:cbeust/testng.git" } developers = listOf(Developer().apply { name = "Cedric Beust" email = "[email protected]" }) } sourceDirectories { path("src/generated/java", "src/main/groovy") } sourceDirectoriesTest { path("src/test/groovy") } dependencies { compile("com.beust:jcommander:1.64", "org.yaml:snakeyaml:1.17") provided("com.google.inject:guice:4.1.0") compileOptional("junit:junit:4.12", "org.apache.ant:ant:1.9.7", "org.apache-extras.beanshell:bsh:2.0b6") } dependenciesTest { compile("org.assertj:assertj-core:3.5.2", "org.testng:testng:6.9.13.7", "org.spockframework:spock-core:1.0-groovy-2.4") } test { jvmArgs("-Dtest.resources.dir=src/test/resources") } javaCompiler { args("-target", "1.7", "-source", "1.7") } assemble { mavenJars { } } bintray { publish = true sign = true autoGitTag = true } } @Task(name = "createVersion", reverseDependsOn = arrayOf("compile"), runAfter = arrayOf("clean"), description = "") fun taskCreateVersion(project: Project): TaskResult { val path = "org/testng/internal" with(arrayListOf<String>()) { File("src/main/resources/$path/VersionTemplateJava").forEachLine { add(it.replace("@version@", VERSION)) } File("src/generated/java/$path").apply { mkdirs() File(this, "Version.java").apply { writeText(joinToString("\n")) } } } return TaskResult() }
apache-2.0
f98930e2a28bedb08db913dc149ce2a1
27.354545
115
0.599872
3.673734
false
true
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/ToggleKotlinVariablesView.kt
4
1975
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.core import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ToggleAction import com.intellij.openapi.components.service import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.impl.XDebuggerUtilImpl import org.jetbrains.kotlin.idea.base.util.KOTLIN_FILE_EXTENSIONS class ToggleKotlinVariablesState { companion object { private const val KOTLIN_VARIABLE_VIEW = "debugger.kotlin.variable.view" fun getService(): ToggleKotlinVariablesState = service() } var kotlinVariableView = PropertiesComponent.getInstance().getBoolean(KOTLIN_VARIABLE_VIEW, true) set(newValue) { field = newValue PropertiesComponent.getInstance().setValue(KOTLIN_VARIABLE_VIEW, newValue) } } class ToggleKotlinVariablesView : ToggleAction() { private val kotlinVariableViewService = ToggleKotlinVariablesState.getService() override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { super.update(e) val session = e.getData(XDebugSession.DATA_KEY) e.presentation.isEnabledAndVisible = session != null && session.isInKotlinFile() } private fun XDebugSession.isInKotlinFile(): Boolean { val fileExtension = currentPosition?.file?.extension ?: return false return fileExtension in KOTLIN_FILE_EXTENSIONS } override fun isSelected(e: AnActionEvent) = kotlinVariableViewService.kotlinVariableView override fun setSelected(e: AnActionEvent, state: Boolean) { kotlinVariableViewService.kotlinVariableView = state XDebuggerUtilImpl.rebuildAllSessionsViews(e.project) } }
apache-2.0
0498a068e9e40f637e350134247bf3d4
38.52
120
0.762532
4.912935
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/psi/impl/MarkdownImage.kt
2
2914
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.lang.psi.impl import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.tree.IElementType import com.intellij.psi.util.elementType import com.intellij.psi.util.siblings import org.intellij.plugins.markdown.lang.MarkdownElementTypes import org.intellij.plugins.markdown.lang.MarkdownTokenTypes import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElement import org.intellij.plugins.markdown.lang.psi.util.children import org.intellij.plugins.markdown.lang.psi.util.hasType class MarkdownImage(node: ASTNode): ASTWrapperPsiElement(node), MarkdownPsiElement, MarkdownLink { val exclamationMark: PsiElement? get() = firstChild val link: MarkdownInlineLink? get() = findChildByType(MarkdownElementTypes.INLINE_LINK) override val linkText: MarkdownLinkText? get() = link?.children()?.filterIsInstance<MarkdownLinkText>()?.firstOrNull() override val linkDestination: MarkdownLinkDestination? get() = link?.children()?.filterIsInstance<MarkdownLinkDestination>()?.firstOrNull() private val linkTitle: PsiElement? get() = link?.children()?.find { it.hasType(MarkdownElementTypes.LINK_TITLE) } fun collectLinkDescriptionText(): String? { return linkText?.let { collectTextFromWrappedBlock(it, MarkdownTokenTypes.LBRACKET, MarkdownTokenTypes.RBRACKET) } } fun collectLinkTitleText(): String? { return linkTitle?.let { collectTextFromWrappedBlock(it, MarkdownTokenTypes.DOUBLE_QUOTE, MarkdownTokenTypes.DOUBLE_QUOTE) } } private fun collectTextFromWrappedBlock(element: PsiElement, prefix: IElementType? = null, suffix: IElementType? = null): String? { val children = element.firstChild?.siblings(withSelf = true)?.toList() ?: return null val left = when (children.first().elementType) { prefix -> 1 else -> 0 } val right = when (children.last().elementType) { suffix -> children.size - 1 else -> children.size } val elements = children.subList(left, right) val content = elements.joinToString(separator = "") { it.text } return content.takeIf { it.isNotEmpty() } } companion object { /** * Useful for determining if some element is an actual image by it's leaf child. */ fun getByLeadingExclamationMark(exclamationMark: PsiElement): MarkdownImage? { if (!exclamationMark.hasType(MarkdownTokenTypes.EXCLAMATION_MARK)) { return null } val image = exclamationMark.parent ?: return null if (!image.hasType(MarkdownElementTypes.IMAGE) || image.firstChild != exclamationMark) { return null } return image as? MarkdownImage } } }
apache-2.0
f4f1bb50944404645ca30adea12b76dc
38.378378
158
0.738161
4.596215
false
false
false
false
danielgindi/android-helpers
Helpers/src/main/java/com/dg/controls/EditTextEx.kt
1
3125
package com.dg.controls import android.content.Context import android.content.res.TypedArray import android.graphics.Paint import android.graphics.Typeface import android.os.Build import android.util.AttributeSet import android.view.View import android.view.ViewGroup import android.view.ViewParent import androidx.appcompat.widget.AppCompatEditText import com.dg.R import com.dg.helpers.FontHelper @Suppress("unused") class EditTextEx : AppCompatEditText { private val mCanFocusZeroSized = Build.VERSION.SDK_INT < Build.VERSION_CODES.P constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { setCustomFontFamily(context, attrs) } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { setCustomFontFamily(context, attrs) } private fun setCustomFontFamily(context: Context, attrs: AttributeSet) { if (isInEditMode) { return } val fontFamily: String? var styledAttributes: TypedArray? = null try { styledAttributes = context.obtainStyledAttributes(attrs, R.styleable.EditTextEx) fontFamily = styledAttributes!!.getString(R.styleable.EditTextEx_customFontFamily) } finally { styledAttributes?.recycle() } if (fontFamily != null && !fontFamily.isEmpty()) { paintFlags = this.paintFlags or Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG setCustomFont(fontFamily) } } @Deprecated("This version was a mistake", replaceWith = ReplaceWith("setCustomFont(fontFamily)")) fun setCustomFont(context: Context, fontFamily: String): Boolean { return setCustomFont(fontFamily) } fun setCustomFont(fontFamily: String): Boolean { val typeface: Typeface? = FontHelper.getFont(context, fontFamily) return if (typeface != null) { setTypeface(typeface) true } else { false } } /* * This is a workaround for a bug in Android where onKeyUp throws if requestFocus() returns false */ override fun focusSearch(direction: Int): View? { val view = super.focusSearch(direction) ?: return null if (view.visibility != View.VISIBLE) return null if (!view.isFocusable) return null if (!view.isEnabled) return null if (!mCanFocusZeroSized && (view.bottom <= view.top || view.right <= view.left)) return null if (view.isInTouchMode && !view.isFocusableInTouchMode) return null var ancestor = view.parent while (ancestor is ViewGroup) { val vgAncestor = ancestor if (vgAncestor.descendantFocusability == ViewGroup.FOCUS_BLOCK_DESCENDANTS) return null ancestor = vgAncestor.parent } return view } }
mit
aa6d9ae1fa8fd592b5d408ad70df4d35
27.153153
101
0.62784
4.913522
false
false
false
false
siosio/intellij-community
plugins/kotlin/common/src/org/jetbrains/kotlin/idea/util/IdeDescriptorRenderers.kt
2
4328
// 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.util import org.jetbrains.kotlin.descriptors.annotations.BuiltInAnnotationDescriptor import org.jetbrains.kotlin.renderer.AnnotationArgumentsRenderingPolicy import org.jetbrains.kotlin.renderer.ClassifierNamePolicy import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.renderer.DescriptorRenderer.Companion.FQ_NAMES_IN_TYPES import org.jetbrains.kotlin.renderer.DescriptorRendererModifier import org.jetbrains.kotlin.renderer.OverrideRenderingPolicy import org.jetbrains.kotlin.resolve.calls.inference.isCaptured import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.checker.NewCapturedTypeConstructor import org.jetbrains.kotlin.types.isDynamic import org.jetbrains.kotlin.types.typeUtil.builtIns object IdeDescriptorRenderers { @JvmField val APPROXIMATE_FLEXIBLE_TYPES: (KotlinType) -> KotlinType = { it.approximateFlexibleTypes(preferNotNull = false) } @JvmField val APPROXIMATE_FLEXIBLE_TYPES_NOT_NULL: (KotlinType) -> KotlinType = { it.approximateFlexibleTypes(preferNotNull = true) } private fun unwrapAnonymousType(type: KotlinType): KotlinType { if (type.isDynamic()) return type if (type.constructor is NewCapturedTypeConstructor) return type val classifier = type.constructor.declarationDescriptor if (classifier != null && !classifier.name.isSpecial) return type type.constructor.supertypes.singleOrNull()?.let { return it } val builtIns = type.builtIns return if (type.isMarkedNullable) builtIns.nullableAnyType else builtIns.anyType } private val BASE: DescriptorRenderer = DescriptorRenderer.withOptions { normalizedVisibilities = true withDefinedIn = false renderDefaultVisibility = false overrideRenderingPolicy = OverrideRenderingPolicy.RENDER_OVERRIDE unitReturnType = false enhancedTypes = true modifiers = DescriptorRendererModifier.ALL renderUnabbreviatedType = false annotationArgumentsRenderingPolicy = AnnotationArgumentsRenderingPolicy.UNLESS_EMPTY annotationFilter = { it.fqName?.isRedundantJvmAnnotation != true } } @JvmField val SOURCE_CODE: DescriptorRenderer = BASE.withOptions { classifierNamePolicy = ClassifierNamePolicy.SOURCE_CODE_QUALIFIED typeNormalizer = { APPROXIMATE_FLEXIBLE_TYPES(unwrapAnonymousType(it)) } } @JvmField val FQ_NAMES_IN_TYPES_WITH_NORMALIZER: DescriptorRenderer = FQ_NAMES_IN_TYPES.withOptions { classifierNamePolicy = ClassifierNamePolicy.SOURCE_CODE_QUALIFIED typeNormalizer = { APPROXIMATE_FLEXIBLE_TYPES(unwrapAnonymousType(it)) } } @JvmField val SOURCE_CODE_TYPES: DescriptorRenderer = BASE.withOptions { classifierNamePolicy = ClassifierNamePolicy.SOURCE_CODE_QUALIFIED typeNormalizer = { APPROXIMATE_FLEXIBLE_TYPES(unwrapAnonymousType(it)) } annotationFilter = { it !is BuiltInAnnotationDescriptor && it.fqName?.isRedundantJvmAnnotation != true } parameterNamesInFunctionalTypes = false } @JvmField val SOURCE_CODE_TYPES_WITH_SHORT_NAMES: DescriptorRenderer = BASE.withOptions { classifierNamePolicy = ClassifierNamePolicy.SHORT typeNormalizer = { APPROXIMATE_FLEXIBLE_TYPES(unwrapAnonymousType(it)) } modifiers -= DescriptorRendererModifier.ANNOTATIONS parameterNamesInFunctionalTypes = false } @JvmField val SOURCE_CODE_NOT_NULL_TYPE_APPROXIMATION: DescriptorRenderer = BASE.withOptions { classifierNamePolicy = ClassifierNamePolicy.SOURCE_CODE_QUALIFIED typeNormalizer = { APPROXIMATE_FLEXIBLE_TYPES_NOT_NULL(unwrapAnonymousType(it)) } presentableUnresolvedTypes = true informativeErrorType = false } @JvmField val SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS: DescriptorRenderer = BASE.withOptions { classifierNamePolicy = ClassifierNamePolicy.SHORT typeNormalizer = { APPROXIMATE_FLEXIBLE_TYPES(unwrapAnonymousType(it)) } modifiers -= DescriptorRendererModifier.ANNOTATIONS } }
apache-2.0
d104620c734717d82bf6c69d86cfd2f2
44.083333
158
0.754159
5.27162
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/Version.kt
2
2112
// 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.compiler.configuration import org.jetbrains.kotlin.config.KotlinCompilerVersion import org.jetbrains.kotlin.config.LanguageVersion fun LanguageVersion.coerceAtMostVersion(version: Version): LanguageVersion { // 1.4.30+ and 1.5.30+ have full support of next language version val languageVersion = if (version.major == 1 && (version.minor == 4 || version.minor == 5) && version.patch >= 30) { Version.lookup(version.major, version.minor + 1) } else { version.languageVersion } return this.coerceAtMost(languageVersion) } class Version(val major: Int, val minor: Int, val patch: Int) { val languageVersion: LanguageVersion get() = lookup(major, minor) private constructor(languageVersion: LanguageVersion): this(languageVersion.major, languageVersion.minor, 0) fun coerceAtMost(languageVersion: LanguageVersion): LanguageVersion { // 1.4.30+ and 1.5.30+ have full support of next language version val version = if (major == 1 && (minor == 4 || minor == 5) && patch >= 30) { lookup(major, minor + 1) } else { this.languageVersion } return languageVersion.coerceAtMost(version) } companion object { private val VERSION_REGEX = Regex("(\\d+)\\.(\\d+)(\\.(\\d+).*)?") val CURRENT_VERSION = parse(KotlinCompilerVersion.VERSION) internal fun lookup(major: Int, minor: Int) = LanguageVersion.values().firstOrNull { it.major == major && it.minor == minor } ?: LanguageVersion.LATEST_STABLE fun parse(version: String?): Version { version ?: return CURRENT_VERSION val matchEntire = VERSION_REGEX.matchEntire(version) ?: return CURRENT_VERSION val values = matchEntire.groupValues return Version(values[1].toInt(), values[2].toInt(), values[4].takeIf { it.isNotEmpty() }?.toInt() ?: 0) } } }
apache-2.0
dfb06e2cdd72084431a608fa2b973eff
43.957447
158
0.662405
4.4
false
true
false
false
smmribeiro/intellij-community
platform/statistics/devkit/src/com/intellij/internal/statistic/devkit/actions/CleanupEventsTestSchemeAction.kt
3
1808
// 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.internal.statistic.devkit.actions import com.intellij.icons.AllIcons import com.intellij.idea.ActionsBundle import com.intellij.internal.statistic.StatisticsBundle import com.intellij.internal.statistic.eventLog.validator.storage.ValidationTestRulesPersistedStorage import com.intellij.internal.statistic.utils.StatisticsRecorderUtil.isAnyTestModeEnabled import com.intellij.internal.statistic.utils.StatisticsRecorderUtil.isTestModeEnabled import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.DumbAwareAction class CleanupEventsTestSchemeAction(private val recorderId: String? = null) : DumbAwareAction(ActionsBundle.message("action.CleanupEventsTestSchemeAction.text"), ActionsBundle.message("action.CleanupEventsTestSchemeAction.description"), AllIcons.Actions.GC) { override fun update(event: AnActionEvent) { event.presentation.isEnabled = recorderId?.let { isTestModeEnabled(recorderId) } ?: isAnyTestModeEnabled() } override fun actionPerformed(e: AnActionEvent) { val project = e.project ProgressManager.getInstance().run(object : Task.Backgroundable(project, StatisticsBundle.message("stats.removing.test.scheme"), false) { override fun run(indicator: ProgressIndicator) { if (recorderId == null) { ValidationTestRulesPersistedStorage.cleanupAll() } else { ValidationTestRulesPersistedStorage.cleanupAll(listOf(recorderId)) } } }) } }
apache-2.0
79b4fa0cb85ec88bd0164b3870377247
45.384615
140
0.78042
5.050279
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateSetFunctionActionFactory.kt
2
3199
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil import org.jetbrains.kotlin.idea.inspections.isReadOnlyCollectionOrMap import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.calls.callUtil.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.ErrorUtils import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.util.OperatorNameConventions import java.util.* object CreateSetFunctionActionFactory : CreateGetSetFunctionActionFactory(isGet = false) { override fun createCallableInfo(element: KtArrayAccessExpression, diagnostic: Diagnostic): CallableInfo? { val arrayExpr = element.arrayExpression ?: return null val arrayType = TypeInfo(arrayExpr, Variance.IN_VARIANCE) val builtIns = element.builtIns val parameters = element.indexExpressions.mapTo(ArrayList<ParameterInfo>()) { ParameterInfo(TypeInfo(it, Variance.IN_VARIANCE)) } val assignmentExpr = QuickFixUtil.getParentElementOfType(diagnostic, KtOperationExpression::class.java) ?: return null if (arrayExpr.getType(arrayExpr.analyze(BodyResolveMode.PARTIAL))?.isReadOnlyCollectionOrMap(builtIns) == true) return null val valType = when (assignmentExpr) { is KtBinaryExpression -> { TypeInfo(assignmentExpr.right ?: return null, Variance.IN_VARIANCE) } is KtUnaryExpression -> { if (assignmentExpr.operationToken !in OperatorConventions.INCREMENT_OPERATIONS) return null val rhsType = assignmentExpr.resolveToCall()?.resultingDescriptor?.returnType TypeInfo(if (rhsType == null || ErrorUtils.containsErrorType(rhsType)) builtIns.anyType else rhsType, Variance.IN_VARIANCE) } else -> return null } parameters.add(ParameterInfo(valType, "value")) val returnType = TypeInfo(builtIns.unitType, Variance.OUT_VARIANCE) return FunctionInfo( OperatorNameConventions.SET.asString(), arrayType, returnType, Collections.emptyList(), parameters, modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD) ) } }
apache-2.0
550db7db04cd3e358a7897ca8e8fa7e7
51.442623
158
0.753986
4.998438
false
false
false
false
erdo/asaf-project
fore-kt-core/src/main/java/co/early/fore/kt/core/logging/TagFormatter.kt
1
1350
package co.early.fore.kt.core.logging import co.early.fore.core.utils.text.TextPadder interface TagFormatter { fun limitTagLength(tag: String): String fun padTagWithSpace(tag: String): String } class TagFormatterImpl(private val overrideMaxTagLength: Int? = null) : TagFormatter { init { if (overrideMaxTagLength != null && overrideMaxTagLength<4){ throw IllegalArgumentException("overrideMaxTagLength needs to be 4 or bigger, or not set at all") } } private val bookEndLength = (overrideMaxTagLength ?: MAX_TAG_LENGTH / 2) - 1 private var longestTagLength = 0 override fun limitTagLength(tag: String): String { return if (tag.length <= overrideMaxTagLength ?: MAX_TAG_LENGTH) { tag } else { tag.substring(0, bookEndLength) + ".." + tag.substring(tag.length - bookEndLength, tag.length) } } override fun padTagWithSpace(tag: String): String { longestTagLength = longestTagLength.coerceAtLeast(tag.length + 1) return if (longestTagLength != tag.length) { (TextPadder.padText(tag, longestTagLength, TextPadder.Pad.RIGHT, ' ') ?: tag) } else { tag } } companion object { private const val MAX_TAG_LENGTH = 30 //below API 24 is limited to 23 characters } }
apache-2.0
c871b937289b5e366205c03e16b495a0
31.142857
109
0.64963
4.21875
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/body/RequestBodyActivity.kt
1
6555
package ch.rmy.android.http_shortcuts.activities.editor.body import android.os.Bundle import android.widget.ArrayAdapter import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import ch.rmy.android.framework.extensions.bindViewModel import ch.rmy.android.framework.extensions.collectEventsWhileActive import ch.rmy.android.framework.extensions.collectViewStateWhileActive import ch.rmy.android.framework.extensions.doOnTextChanged import ch.rmy.android.framework.extensions.initialize import ch.rmy.android.framework.extensions.setTextSafely import ch.rmy.android.framework.extensions.whileLifecycleActive import ch.rmy.android.framework.ui.BaseIntentBuilder import ch.rmy.android.framework.utils.DragOrderingHelper import ch.rmy.android.framework.viewmodel.ViewModelEvent import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.activities.BaseActivity import ch.rmy.android.http_shortcuts.dagger.ApplicationComponent import ch.rmy.android.http_shortcuts.data.enums.RequestBodyType import ch.rmy.android.http_shortcuts.databinding.ActivityRequestBodyBinding import ch.rmy.android.http_shortcuts.extensions.applyTheme import kotlinx.coroutines.launch import javax.inject.Inject class RequestBodyActivity : BaseActivity() { @Inject lateinit var adapter: ParameterAdapter private val viewModel: RequestBodyViewModel by bindViewModel() private lateinit var binding: ActivityRequestBodyBinding private var isDraggingEnabled = false override fun inject(applicationComponent: ApplicationComponent) { applicationComponent.inject(this) } override fun onCreated(savedState: Bundle?) { viewModel.initialize() initViews() initUserInputBindings() initViewModelBindings() } private fun initViews() { binding = applyBinding(ActivityRequestBodyBinding.inflate(layoutInflater)) setTitle(R.string.section_request_body) binding.inputRequestBodyType.setItemsFromPairs( REQUEST_BODY_TYPES.map { it.first.type to getString(it.second) } ) val manager = LinearLayoutManager(context) binding.parameterList.layoutManager = manager binding.parameterList.setHasFixedSize(true) binding.parameterList.adapter = adapter initDragOrdering() binding.buttonAddParameter.applyTheme(themeHelper) binding.buttonAddParameter.setOnClickListener { viewModel.onAddParameterButtonClicked() } binding.variableButtonBodyContent.setOnClickListener { viewModel.onBodyContentVariableButtonClicked() } binding.inputContentType.setAdapter(ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, CONTENT_TYPE_SUGGESTIONS)) } private fun initUserInputBindings() { initDragOrdering() whileLifecycleActive { adapter.userEvents.collect { event -> when (event) { is ParameterAdapter.UserEvent.ParameterClicked -> viewModel.onParameterClicked(event.id) } } } lifecycleScope.launch { binding.inputRequestBodyType.selectionChanges.collect { requestBodyType -> viewModel.onRequestBodyTypeChanged(RequestBodyType.parse(requestBodyType)) } } binding.inputContentType.doOnTextChanged { newContentType -> viewModel.onContentTypeChanged(newContentType.toString()) } binding.inputBodyContent.doOnTextChanged { viewModel.onBodyContentChanged(binding.inputBodyContent.rawString) } binding.buttonAddParameter.setOnClickListener { viewModel.onAddParameterButtonClicked() } } private fun initDragOrdering() { val dragOrderingHelper = DragOrderingHelper( isEnabledCallback = { isDraggingEnabled }, getId = { (it as? ParameterAdapter.ParameterViewHolder)?.parameterId }, ) dragOrderingHelper.attachTo(binding.parameterList) whileLifecycleActive { dragOrderingHelper.movementSource.collect { (parameterId1, parameterId2) -> viewModel.onParameterMoved(parameterId1, parameterId2) } } } private fun initViewModelBindings() { collectViewStateWhileActive(viewModel) { viewState -> adapter.items = viewState.parameters isDraggingEnabled = viewState.isDraggingEnabled binding.inputRequestBodyType.selectedItem = viewState.requestBodyType.type binding.inputContentType.setTextSafely(viewState.contentType) binding.inputBodyContent.rawString = viewState.bodyContent binding.parameterList.isVisible = viewState.parameterListVisible binding.buttonAddParameter.isVisible = viewState.addParameterButtonVisible binding.containerInputContentType.isVisible = viewState.contentTypeVisible binding.containerInputBodyContent.isVisible = viewState.bodyContentVisible setDialogState(viewState.dialogState, viewModel) } collectEventsWhileActive(viewModel, ::handleEvent) } override fun handleEvent(event: ViewModelEvent) { when (event) { is RequestBodyEvent.InsertVariablePlaceholder -> binding.inputBodyContent.insertVariablePlaceholder(event.variablePlaceholder) else -> super.handleEvent(event) } } override fun onBackPressed() { viewModel.onBackPressed() } class IntentBuilder : BaseIntentBuilder(RequestBodyActivity::class) companion object { private val REQUEST_BODY_TYPES = listOf( RequestBodyType.CUSTOM_TEXT to R.string.request_body_option_custom_text, RequestBodyType.FORM_DATA to R.string.request_body_option_form_data, RequestBodyType.X_WWW_FORM_URLENCODE to R.string.request_body_option_x_www_form_urlencoded, RequestBodyType.FILE to R.string.request_body_option_file, RequestBodyType.IMAGE to R.string.request_body_option_image, ) private val CONTENT_TYPE_SUGGESTIONS = listOf( "application/javascript", "application/json", "application/octet-stream", "application/xml", "text/css", "text/csv", "text/plain", "text/html", "text/xml", ) } }
mit
2b6f97076774ccb94646f816bfaf6bf9
37.110465
139
0.707399
5.307692
false
false
false
false
h0tk3y/better-parse
src/commonMain/kotlin/com/github/h0tk3y/betterParse/lexer/LambdaToken.kt
1
749
package com.github.h0tk3y.betterParse.lexer public inline fun token(ignored: Boolean = false, crossinline matcher: (CharSequence, Int) -> Int): Token { return object : Token(null, ignored) { override fun match(input: CharSequence, fromIndex: Int) = matcher(input, fromIndex) override fun toString() = "${name ?: ""} {lambda}" + if (ignored) " [ignorable]" else "" } } public inline fun token(name: String, ignored: Boolean = false, crossinline matcher: (CharSequence, Int) -> Int): Token { return object : Token(name, ignored) { override fun match(input: CharSequence, fromIndex: Int) = matcher(input, fromIndex) override fun toString() = "$name {lambda}" + if (ignored) " [ignorable]" else "" } }
apache-2.0
550a566c8febd354fddcc293ebd49533
45.8125
121
0.664887
3.962963
false
false
false
false
parkee/messenger-send-api-client
src/main/kotlin/com/github/parkee/messenger/builder/request/MessengerRequestBuilder.kt
1
1616
package com.github.parkee.messenger.builder.request import com.github.parkee.messenger.model.request.* import com.github.parkee.messenger.model.request.senderaction.SenderAction /** * Created by parkee on 4/29/16. */ object MessengerRequestBuilder { fun byRecipientId(recipientId: Long, message: RequestMessage, notificationType: NotificationType = NotificationType.REGULAR): FacebookRequest { val recipient = RequestRecipient(id = recipientId) return FacebookRequest(recipient, message, notificationType) } fun byRecipientPhoneNumber(phoneNumber: String, message: RequestMessage, notificationType: NotificationType = NotificationType.REGULAR): FacebookRequest { val recipient = RequestRecipient(phoneNumber = phoneNumber) return FacebookRequest(recipient, message, notificationType) } fun byRecipientId(recipientId: Long, senderAction: SenderAction, notificationType: NotificationType = NotificationType.REGULAR): FacebookRequest { val recipient = RequestRecipient(id = recipientId) return FacebookRequest(recipient, senderAction = senderAction, notificationType = notificationType) } fun byRecipientPhoneNumber(phoneNumber: String, senderAction: SenderAction, notificationType: NotificationType = NotificationType.REGULAR): FacebookRequest { val recipient = RequestRecipient(phoneNumber = phoneNumber) return FacebookRequest(recipient, senderAction = senderAction, notificationType = notificationType) } }
mit
87051b248be86ba46f71fbe9520562b6
48
112
0.730198
5.919414
false
false
false
false
breadwallet/breadwallet-android
app/src/androidTest/java/com/breadwallet/util/Screens.kt
1
10905
package com.breadwallet.util import android.view.View import com.agoda.kakao.common.views.KView import com.agoda.kakao.edit.KEditText import com.agoda.kakao.image.KImageView import com.agoda.kakao.pager.KViewPager import com.agoda.kakao.progress.KProgressBar import com.agoda.kakao.recycler.KRecyclerItem import com.agoda.kakao.recycler.KRecyclerView import com.agoda.kakao.screen.Screen import com.agoda.kakao.switch.KSwitch import com.agoda.kakao.text.KButton import com.agoda.kakao.text.KTextView import com.breadwallet.BuildConfig import com.breadwallet.R import com.breadwallet.ui.controllers.AlertDialogController import com.breadwallet.ui.settings.SettingsController import com.breadwallet.ui.settings.fastsync.FastSyncController import com.breadwallet.uiview.KeyboardView import com.kaspersky.components.kautomator.component.common.views.UiView import com.kaspersky.components.kautomator.component.edit.UiEditText import com.kaspersky.components.kautomator.component.text.UiButton import com.kaspersky.components.kautomator.component.text.UiTextView import com.kaspersky.components.kautomator.screen.UiScreen import com.kaspersky.kaspresso.screens.KScreen import org.hamcrest.Matcher class KIntroScreen : Screen<KIntroScreen>() { init { rootView = KView { isCompletelyDisplayed() withId(R.id.intro_layout) } } val getStarted = KButton { isCompletelyDisplayed() withId(R.id.button_new_wallet) } val recover = KButton { isCompletelyDisplayed() withId(R.id.button_recover_wallet) } } class OnBoardingScreen : Screen<OnBoardingScreen>() { init { rootView = KView { isCompletelyDisplayed() withId(R.id.layoutOnboarding) } } val skip = KButton { isDisplayed() withId(R.id.button_skip) } val pager = KViewPager { isDisplayed() withId(R.id.view_pager) } val primaryText = KTextView { isVisible() isCompletelyDisplayed() withId(R.id.primary_text) } val secondaryText = KTextView { isVisible() isCompletelyDisplayed() withId(R.id.secondary_text) } val lastScreenText = KTextView { isVisible() isCompletelyDisplayed() withId(R.id.last_screen_title) } val buy = KButton { isVisible() isDisplayed() withId(R.id.button_buy) } val browse = KButton { isVisible() isDisplayed() withId(R.id.button_browse) } val loading = KView { withId(R.id.loading_view) } } class InputPinScreen : Screen<InputPinScreen>() { init { rootView = KView { isCompletelyDisplayed() withId(R.id.layoutSetPin) } } val title = KTextView { isDisplayed() withId(R.id.title) } val keyboard = KeyboardView(R.id.layoutSetPin) { isCompletelyDisplayed() withId(R.id.brkeyboard) } } class KWriteDownScreen : Screen<KWriteDownScreen>() { init { rootView = KView { withId(R.id.activity_write_down) } } val close = KButton { withId(R.id.close_button) } val writeDownKey = KButton { withId(R.id.button_write_down) } } class WebScreen : Screen<WebScreen>() { init { rootView = KView { withId(R.id.layoutWebController) } } } object ShowPaperKeyScreen : UiScreen<ShowPaperKeyScreen>() { override val packageName: String = BuildConfig.APPLICATION_ID val next = UiButton { withId([email protected], "next_button") } val word = UiView { withId([email protected], "word_button") } } object ProvePaperKeyScreen : UiScreen<ProvePaperKeyScreen>() { override val packageName: String = BuildConfig.APPLICATION_ID val firstWordLabel = UiTextView { withId([email protected], "first_word_label") } val lastWordLabel = UiTextView { withId([email protected], "last_word_label") } val firstWord = UiEditText { withId([email protected], "first_word") } val secondWord = UiEditText { withId([email protected], "second_word") } } class KHomeScreen : Screen<KHomeScreen>() { init { rootView = KView { withId(R.id.layoutHome) } } val totalAssets = KTextView { isCompletelyDisplayed() withId(R.id.total_assets_usd) } val menu = KView { isCompletelyDisplayed() withId(R.id.menu_layout) } val wallets = KRecyclerView({ withId(R.id.rv_wallet_list) }, itemTypeBuilder = { itemType(::KWalletItem) }) class KWalletItem(parent: Matcher<View>) : KRecyclerItem<KWalletItem>(parent) { val name = KTextView(parent) { withId(R.id.wallet_name) } val progress = KProgressBar(parent) { withId(R.id.sync_progress) } } } object KSettingsScreen : KScreen<KSettingsScreen>() { override val layoutId: Int = R.layout.controller_settings override val viewClass: Class<*> = SettingsController::class.java val back = KButton { isCompletelyDisplayed() withId(R.id.back_button) } val close = KButton { isCompletelyDisplayed() withId(R.id.close_button) } val recycler = KRecyclerView({ isCompletelyDisplayed() withId(R.id.settings_list) }, itemTypeBuilder = { itemType(::KSettingsItem) }) class KSettingsItem(parent: Matcher<View>) : KRecyclerItem<KSettingsItem>(parent) { val title = KTextView(parent) { withId(R.id.item_title) } val addon = KTextView(parent) { withId(R.id.item_addon) } val subHeader = KTextView(parent) { withId(R.id.item_sub_header) } val icon = KImageView(parent) { withId(R.id.setting_icon) } } } object KFastSyncScreen : KScreen<KFastSyncScreen>() { override val layoutId: Int = R.layout.controller_fast_sync override val viewClass: Class<*> = FastSyncController::class.java val switch = KSwitch { isCompletelyDisplayed() withId(R.id.switch_fast_sync) } val back = KButton { isCompletelyDisplayed() withId(R.id.back_btn) } } object KDialogScreen : KScreen<KDialogScreen>() { override val layoutId: Int = R.layout.controller_alert_dialog override val viewClass: Class<*> = AlertDialogController::class.java val positive = KButton { isCompletelyDisplayed() withId(R.id.pos_button) } val negative = KButton { isCompletelyDisplayed() withId(R.id.neg_button) } } class KWalletScreen : Screen<KWalletScreen>() { init { rootView = KView { withId(R.id.layoutWalletScreen) } } val send = KButton { isDisplayed() withId(R.id.send_button) } val receive = KButton { isDisplayed() withId(R.id.receive_button) } val transactions = KRecyclerView({ isDisplayed() withId(R.id.tx_list) }, itemTypeBuilder = { itemType(::KTransactionItem) }) class KTransactionItem(parent: Matcher<View>) : KRecyclerItem<KTransactionItem>(parent) } class KIntroRecoveryScreen : Screen<KIntroRecoveryScreen>() { init { rootView = KView { withId(R.id.layoutRecoverIntro) } } val next = KButton { isClickable() isCompletelyDisplayed() withId(R.id.send_button) } } class KRecoveryKeyScreen : Screen<KRecoveryKeyScreen>() { init { rootView = KView { withId(R.id.layoutRecoverWallet) } } val next = KButton { withId(R.id.send_button) } val loading = KView { withId(R.id.loading_view) } fun enterPhrase(phrase: String) { val words = phrase.split(" ") word1.replaceText(words[0]) word2.replaceText(words[1]) word3.replaceText(words[2]) word4.replaceText(words[3]) word5.replaceText(words[4]) word6.replaceText(words[5]) word7.replaceText(words[6]) word8.replaceText(words[7]) word9.replaceText(words[8]) word10.replaceText(words[9]) word11.replaceText(words[10]) word12.replaceText(words[11]) } val word1 = KEditText { isCompletelyDisplayed() withId(R.id.word1) } val word2 = KEditText { withId(R.id.word2) } val word3 = KEditText { withId(R.id.word3) } val word4 = KEditText { withId(R.id.word4) } val word5 = KEditText { withId(R.id.word5) } val word6 = KEditText { withId(R.id.word6) } val word7 = KEditText { withId(R.id.word7) } val word8 = KEditText { withId(R.id.word8) } val word9 = KEditText { withId(R.id.word9) } val word10 = KEditText { withId(R.id.word10) } val word11 = KEditText { withId(R.id.word11) } val word12 = KEditText { withId(R.id.word12) } } class KSendScreen : Screen<KSendScreen>() { init { rootView = KView { withId(R.id.layoutSendSheet) } } val paste = KButton { isCompletelyDisplayed() withId(R.id.buttonPaste) } val amount = KEditText { isCompletelyDisplayed() withId(R.id.textInputAmount) } val keyboard = KeyboardView(R.id.layoutSendSheet) { isCompletelyDisplayed() withId(R.id.keyboard) } val send = KButton { isCompletelyDisplayed() withId(R.id.buttonSend) } } class KSignalScreen : Screen<KSignalScreen>() { init { rootView = KView { withId(R.id.layoutSignal) } } val title = KTextView { withId(R.id.title) } } class KTxDetailsScreen : Screen<KTxDetailsScreen>() { init { rootView = KView { withId(R.id.layoutTransactionDetails) } } val action = KTextView { isDisplayed() withId(R.id.tx_action) } } class KConfirmationScreen : Screen<KConfirmationScreen>() { init { rootView = KView { withId(R.id.layoutBackground) } } val send = KTextView { isCompletelyDisplayed() withId(R.id.ok_btn) } val cancel = KTextView { isCompletelyDisplayed() withId(R.id.cancel_btn) } val amountToSend = KTextView { withId(R.id.amount_value) } } class KPinAuthScreen : Screen<KPinAuthScreen>() { init { rootView = KView { withId(R.id.activity_pin) } } val title = KTextView { withParent { withId(R.id.pin_dialog) } isDisplayed() withId(R.id.title) } val keyboard = KeyboardView(R.id.activity_pin) { withId(R.id.brkeyboard) } }
mit
db991bfa785d11d9236043540a6a2b68
23.671946
91
0.627235
4.018055
false
false
false
false
AlmasB/Zephyria
src/main/kotlin/com/almasb/zeph/events/Events.kt
1
4756
package com.almasb.zeph.events import com.almasb.fxgl.entity.Entity import com.almasb.zeph.character.CharacterEntity import com.almasb.zeph.combat.Experience import com.almasb.zeph.events.Events.ON_ARMOR_EQUIPPED import com.almasb.zeph.events.Events.ON_ATTACK import com.almasb.zeph.events.Events.ON_BEFORE_SKILL_CAST import com.almasb.zeph.events.Events.ON_BEING_KILLED import com.almasb.zeph.events.Events.ON_ITEM_PICKED_UP import com.almasb.zeph.events.Events.ON_ITEM_USED import com.almasb.zeph.events.Events.ON_LEVEL_UP import com.almasb.zeph.events.Events.ON_MAGICAL_DAMAGE_DEALT import com.almasb.zeph.events.Events.ON_MONEY_RECEIVED import com.almasb.zeph.events.Events.ON_ORDERED_MOVE import com.almasb.zeph.events.Events.ON_PHYSICAL_DAMAGE_DEALT import com.almasb.zeph.events.Events.ON_SKILL_LEARNED import com.almasb.zeph.events.Events.ON_WEAPON_EQUIPPED import com.almasb.zeph.events.Events.ON_XP_RECEIVED import com.almasb.zeph.item.Armor import com.almasb.zeph.item.Item import com.almasb.zeph.item.UsableItem import com.almasb.zeph.item.Weapon import com.almasb.zeph.skill.Skill import javafx.event.Event import javafx.event.EventType /** * Defines a generic game event. * * @author Almas Baimagambetov ([email protected]) */ sealed class GameEvent(eventType: EventType<out GameEvent>) : Event(eventType) /** * Stores all game event types. */ object Events { val ANY = EventType<GameEvent>(Event.ANY) /** * Fired after an item was picked up and added to inventory. */ val ON_ITEM_PICKED_UP = EventType<OnItemPickedUpEvent>(ANY, "ON_ITEM_PICKED_UP") /** * Fired after an item was used. */ val ON_ITEM_USED = EventType<OnItemUsedEvent>(ANY, "ON_ITEM_USED") val ON_WEAPON_EQUIPPED = EventType<OnWeaponEquippedEvent>(ANY, "ON_WEAPON_EQUIPPED") val ON_ARMOR_EQUIPPED = EventType<OnArmorEquippedEvent>(ANY, "ON_ARMOR_EQUIPPED") val ON_XP_RECEIVED = EventType<OnXPReceivedEvent>(ANY, "ON_XP_RECEIVED") val ON_MONEY_RECEIVED = EventType<OnMoneyReceivedEvent>(ANY, "ON_MONEY_RECEIVED") val ON_LEVEL_UP = EventType<OnLevelUpEvent>(ANY, "ON_LEVEL_UP") val ON_SKILL_LEARNED = EventType<OnSkillLearnedEvent>(ANY, "ON_SKILL_LEARNED") val ON_ATTACK = EventType<OnAttackEvent>(ANY, "ON_ATTACK") val ON_PHYSICAL_DAMAGE_DEALT = EventType<OnPhysicalDamageDealtEvent>(ANY, "ON_PHYSICAL_DAMAGE_DEALT") val ON_MAGICAL_DAMAGE_DEALT = EventType<OnMagicalDamageDealtEvent>(ANY, "ON_MAGICAL_DAMAGE_DEALT") val ON_BEFORE_SKILL_CAST = EventType<OnBeforeSkillCastEvent>(ANY, "ON_BEFORE_SKILL_CAST") /** * Fired just before a character is killed. */ val ON_BEING_KILLED = EventType<OnBeingKilledEvent>(ANY, "ON_BEING_KILLED") val ORDER_ANY = EventType<GameEvent>(ANY, "ORDER_ANY") val ON_ORDERED_MOVE = EventType<OnOrderedMoveEvent>(ORDER_ANY, "ON_ORDERED_MOVE") } class OnAttackEvent( val attacker: CharacterEntity, val target: CharacterEntity ) : GameEvent(ON_ATTACK) class OnBeingKilledEvent( val killer: CharacterEntity, val killedEntity: CharacterEntity ) : GameEvent(ON_BEING_KILLED) class OnItemPickedUpEvent( val user: CharacterEntity, val item: Item ) : GameEvent(ON_ITEM_PICKED_UP) class OnItemUsedEvent( val user: CharacterEntity, val item: UsableItem ) : GameEvent(ON_ITEM_USED) class OnWeaponEquippedEvent( val user: CharacterEntity, val weapon: Weapon ) : GameEvent(ON_WEAPON_EQUIPPED) class OnArmorEquippedEvent( val user: CharacterEntity, val armor: Armor ) : GameEvent(ON_ARMOR_EQUIPPED) class OnPhysicalDamageDealtEvent( val attacker: CharacterEntity, val target: CharacterEntity, val damage: Int, val isCritical: Boolean ) : GameEvent(ON_PHYSICAL_DAMAGE_DEALT) class OnMagicalDamageDealtEvent( val attacker: CharacterEntity, val target: CharacterEntity, val damage: Int, val isCritical: Boolean ) : GameEvent(ON_MAGICAL_DAMAGE_DEALT) class OnMoneyReceivedEvent( val receiver: CharacterEntity, val amount: Int ) : GameEvent(ON_MONEY_RECEIVED) class OnXPReceivedEvent( val receiver: CharacterEntity, val xp: Experience ) : GameEvent(ON_XP_RECEIVED) class OnSkillLearnedEvent( val learner: CharacterEntity, val skill: Skill ) : GameEvent(ON_SKILL_LEARNED) class OnBeforeSkillCastEvent( val caster: CharacterEntity, val skill: Skill ) : GameEvent(ON_BEFORE_SKILL_CAST) class OnOrderedMoveEvent( val char: CharacterEntity, val cellX: Int, val cellY: Int ) : GameEvent(ON_ORDERED_MOVE) class OnLevelUpEvent( val char: CharacterEntity ) : GameEvent(ON_LEVEL_UP)
gpl-2.0
f82dc689138f98f7fd29053ca9dcd6fd
30.713333
105
0.728553
3.658462
false
false
false
false
square/sqldelight
extensions/rxjava3-extensions/src/main/kotlin/com/squareup/sqldelight/runtime/rx3/RxJavaExtensions.kt
1
2570
@file:JvmName("RxQuery") package com.squareup.sqldelight.runtime.rx3 import com.squareup.sqldelight.Query import io.reactivex.rxjava3.annotations.CheckReturnValue import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.core.ObservableEmitter import io.reactivex.rxjava3.core.ObservableOnSubscribe import io.reactivex.rxjava3.core.Scheduler import io.reactivex.rxjava3.disposables.Disposable import io.reactivex.rxjava3.schedulers.Schedulers import java.util.Optional import java.util.concurrent.atomic.AtomicBoolean /** * Turns this [Query] into an [Observable] which emits whenever the underlying result set changes. * * @param scheduler By default, emissions occur on the [Schedulers.io] scheduler but can be * optionally overridden. */ @CheckReturnValue @JvmOverloads @JvmName("toObservable") fun <T : Any> Query<T>.asObservable(scheduler: Scheduler = Schedulers.io()): Observable<Query<T>> { return Observable.create(QueryOnSubscribe(this)).observeOn(scheduler) } private class QueryOnSubscribe<T : Any>( private val query: Query<T> ) : ObservableOnSubscribe<Query<T>> { override fun subscribe(emitter: ObservableEmitter<Query<T>>) { val listenerAndDisposable = QueryListenerAndDisposable(emitter, query) query.addListener(listenerAndDisposable) emitter.setDisposable(listenerAndDisposable) emitter.onNext(query) } } private class QueryListenerAndDisposable<T : Any>( private val emitter: ObservableEmitter<Query<T>>, private val query: Query<T> ) : AtomicBoolean(), Query.Listener, Disposable { override fun queryResultsChanged() { emitter.onNext(query) } override fun isDisposed() = get() override fun dispose() { if (compareAndSet(false, true)) { query.removeListener(this) } } } @CheckReturnValue fun <T : Any> Observable<Query<T>>.mapToOne(): Observable<T> { return map { it.executeAsOne() } } @CheckReturnValue fun <T : Any> Observable<Query<T>>.mapToOneOrDefault(defaultValue: T): Observable<T> { return map { it.executeAsOneOrNull() ?: defaultValue } } @CheckReturnValue fun <T : Any> Observable<Query<T>>.mapToOptional(): Observable<Optional<T>> { return map { Optional.ofNullable(it.executeAsOneOrNull()) } } @CheckReturnValue fun <T : Any> Observable<Query<T>>.mapToList(): Observable<List<T>> { return map { it.executeAsList() } } @CheckReturnValue fun <T : Any> Observable<Query<T>>.mapToOneNonNull(): Observable<T> { return flatMap { val result = it.executeAsOneOrNull() if (result == null) Observable.empty() else Observable.just(result) } }
apache-2.0
607cb0f60245377989291ea2451ca3dc
29.963855
99
0.753696
4.021909
false
false
false
false
oversecio/oversec_crypto
crypto/src/main/java/io/oversec/one/crypto/sym/OversecKeystore2.kt
1
13662
package io.oversec.one.crypto.sym import android.annotation.SuppressLint import android.content.Context import android.util.Log import com.google.protobuf.ByteString import com.google.protobuf.InvalidProtocolBufferException import io.oversec.one.crypto.proto.Kex import io.oversec.one.crypto.symbase.KeyCache import io.oversec.one.crypto.symbase.KeyUtil import io.oversec.one.crypto.symbase.OversecChacha20Poly1305 import io.oversec.one.crypto.symbase.OversecKeyCacheListener import net.rehacktive.waspdb.WaspFactory import org.spongycastle.util.encoders.Base64 import org.spongycastle.util.encoders.DecoderException import roboguice.util.Ln import java.io.IOException import java.security.NoSuchAlgorithmException import java.security.Security import java.util.* import kotlin.collections.HashMap class OversecKeystore2 private constructor(private val mCtx: Context) { private val mKeyCache = KeyCache.getInstance(mCtx) private val mDb = WaspFactory.openOrCreateDatabase(mCtx.filesDir.path, DATABASE_NAME, null) private val mSymmetricEncryptedKeys = mDb.openOrCreateHash("symmetric_keys") private val mListeners = ArrayList<KeyStoreListener>() val encryptedKeys_sorted: List<SymmetricKeyEncrypted> get() { val list: List<SymmetricKeyEncrypted>? = mSymmetricEncryptedKeys.getAllValues() return list?.sortedBy { it.name } ?: emptyList() } val isEmpty: Boolean get() { val allKeys = mSymmetricEncryptedKeys.getAllKeys<Any>() return allKeys == null || allKeys.isEmpty() } init { if (!isEmpty) { //cleanup databases of users that may have ended up with a null key in it. var allIds = mSymmetricEncryptedKeys.getAllKeys<Any>(); var zombieFound = false; for (id in allIds) { if (mSymmetricEncryptedKeys.get<SymmetricKeyEncrypted>(id)==null) { Ln.w("found a null key entry int the database id="+id) zombieFound = true; } } if (zombieFound) { Ln.w("rewriting database") var allData = HashMap(mSymmetricEncryptedKeys.getAllData<Any, SymmetricKeyEncrypted>()); mSymmetricEncryptedKeys.flush(); for (id in allData.keys) { if (allData.get(id)!=null) { mSymmetricEncryptedKeys.put(id,allData.get(id)); } } } } } fun clearAllCaches() { mKeyCache.clearAll() } @Synchronized @Throws( NoSuchAlgorithmException::class, IOException::class, OversecKeystore2.AliasNotUniqueException::class ) fun addKey__longoperation(plainKey: SymmetricKeyPlain, password: CharArray): Long? { val allKeys: List<SymmetricKeyEncrypted> = mSymmetricEncryptedKeys.getAllValues() ?: emptyList() (allKeys.firstOrNull() { it.name == plainKey.name })?.run { throw AliasNotUniqueException(plainKey.name) } val id = KeyUtil.calcKeyId( Arrays.copyOf(plainKey.raw!!, plainKey.raw!!.size), SymmetricCryptoHandler.BCRYPT_FINGERPRINT_COST ) plainKey.id = id val encKey = encryptSymmetricKey(plainKey, password) mSymmetricEncryptedKeys.put(id, encKey) mKeyCache.doCacheKey(plainKey, 0) fireChange() return id } @Synchronized fun confirmKey(id: Long?) { val k = getSymmetricKeyEncrypted(id) if (k==null) { //hard bail out, quick! This would insert a *null* key into the database throw java.lang.Exception("key to be confirmed was not found anymore.") } k?.confirmedDate = Date() mSymmetricEncryptedKeys.put(id, k) } @Synchronized fun getConfirmDate(id: Long?): Date? { return getSymmetricKeyEncrypted(id)?.confirmedDate } @Synchronized fun getCreatedDate(id: Long?): Date? { val k = mSymmetricEncryptedKeys.get<SymmetricKeyEncrypted>(id) return k?.createdDate } @Synchronized fun deleteKey(id: Long?) { mSymmetricEncryptedKeys.remove(id) fireChange() } @Synchronized fun getKeyIdByHashedKeyId(hashedKeyId: Long, salt: ByteArray, cost: Int): Long? { val allIds = mSymmetricEncryptedKeys.getAllKeys<Long>() if (allIds != null) { for (id in allIds) { val aSessionKeyId = KeyUtil.calcSessionKeyId(id!!, salt, cost) if (aSessionKeyId == hashedKeyId) { return id } } } return null } @Synchronized fun hasKey(keyId: Long?): Boolean { return mSymmetricEncryptedKeys.get<Any>(keyId) != null } @Synchronized @Throws(KeyNotCachedException::class) fun getPlainKeyAsTransferBytes(id: Long?): ByteArray { val k = mKeyCache[id] return getPlainKeyAsTransferBytes(k.raw) } @Synchronized @Throws(IOException::class, OversecChacha20Poly1305.MacMismatchException::class) fun doCacheKey__longoperation(keyId: Long?, pw: CharArray, ttl: Long) { val k = mSymmetricEncryptedKeys.get<SymmetricKeyEncrypted>(keyId) ?: throw IllegalArgumentException("invalid key id") var dec: SymmetricKeyPlain? = null //it might still/already be cached try { dec = mKeyCache[keyId] } catch (e: KeyNotCachedException) { //ignore } if (dec == null) { dec = decryptSymmetricKey(k, pw) } mKeyCache.doCacheKey(dec, ttl) } @Synchronized @Throws(KeyNotCachedException::class) fun getPlainKeyData(id: Long?): ByteArray? { val k = mKeyCache[id] return k.raw } @Synchronized @Throws(KeyNotCachedException::class) fun getPlainKey(id: Long?): SymmetricKeyPlain { return mKeyCache[id] } @Synchronized fun addKeyCacheListener(l: OversecKeyCacheListener) { mKeyCache.addKeyCacheListener(l) } @Synchronized fun removeKeyCacheListener(l: OversecKeyCacheListener) { mKeyCache.removeKeyCacheListener(l) } fun getSymmetricKeyEncrypted(id: Long?): SymmetricKeyEncrypted? { return mSymmetricEncryptedKeys.get(id) } fun hasName(name: String): Boolean { val l = mSymmetricEncryptedKeys.getAllValues<SymmetricKeyEncrypted>() l ?: return false; for (key in l) { if (key.name == name) { return true } } return false } @Throws(IOException::class) fun encryptSymmetricKey( plainKey: SymmetricKeyPlain, password: CharArray ): SymmetricKeyEncrypted { val cost = KeyUtil.DEFAULT_KEYSTORAGE_BCRYPT_COST val bcrypt_salt = KeyUtil.getRandomBytes(16) val bcryptedPassword = KeyUtil.brcryptifyPassword(password, bcrypt_salt, cost, 32) KeyUtil.erase(password) val chachaIv = KeyUtil.getRandomBytes(8) val ciphertext = OversecChacha20Poly1305.enChacha(plainKey.raw!!, bcryptedPassword, chachaIv) Ln.w("XXX encryptSymmetricKey password="+String(password)) Ln.w("XXX encryptSymmetricKey bcryptedPassword="+bytesToHex(bcryptedPassword)) Ln.w("XXX encryptSymmetricKey ciphertext="+bytesToHex(ciphertext!!)) Ln.w("XXX encryptSymmetricKey iv="+bytesToHex(chachaIv)) Ln.w("XXX encryptSymmetricKey salt="+bytesToHex(bcrypt_salt)) KeyUtil.erase(bcryptedPassword) return SymmetricKeyEncrypted( plainKey.id, plainKey.name!!, plainKey.createdDate!!, bcrypt_salt, chachaIv, cost, ciphertext ) } private val hexArray = "0123456789ABCDEF".toCharArray() fun bytesToHex(bytes: ByteArray): String { val hexChars = CharArray(bytes.size * 2) for (j in bytes.indices) { val v = bytes[j].toInt() and 0xFF hexChars[j * 2] = hexArray[v.ushr(4)] hexChars[j * 2 + 1] = hexArray[v and 0x0F] } return String(hexChars) } fun hexToBytes(s: String): ByteArray { val len = s.length val data = ByteArray(len / 2) var i = 0 while (i < len) { data[i / 2] = ((Character.digit(s[i], 16) shl 4) + Character.digit(s[i + 1], 16)).toByte() i += 2 } return data } @Throws(IOException::class, OversecChacha20Poly1305.MacMismatchException::class) fun decryptSymmetricKey(k: SymmetricKeyEncrypted, password: CharArray): SymmetricKeyPlain { Ln.w("XXX decryptSymmetricKey password="+String(password)) val bcryptedPassword = KeyUtil.brcryptifyPassword(password, k.salt!!, k.cost, 32) KeyUtil.erase(password) Ln.w("XXX decryptSymmetricKey bcryptedPassword="+bytesToHex(bcryptedPassword)) Ln.w("XXX decryptSymmetricKey ciphertext="+bytesToHex(k.ciphertext!!)) Ln.w("XXX decryptSymmetricKey iv="+bytesToHex(k.iv!!)) Ln.w("XXX decryptSymmetricKey salt="+bytesToHex(k.salt!!)) val raw = OversecChacha20Poly1305.deChacha(k.ciphertext!!, bcryptedPassword, k.iv!!) KeyUtil.erase(bcryptedPassword) return SymmetricKeyPlain( k.id, k.name!!, k.createdDate!!, raw ) } class AliasNotUniqueException(val alias: String?) : Exception() @Synchronized fun addListener(v: KeyStoreListener) { mListeners.add(v) } @Synchronized fun removeListener(v: KeyStoreListener) { mListeners.remove(v) } @Synchronized private fun fireChange() { for (v in mListeners) { v.onKeyStoreChanged() } } interface KeyStoreListener { fun onKeyStoreChanged() } class Base64DecodingException(ex: DecoderException) : Exception(ex) companion object { private const val DATABASE_NAME = "keystore" @SuppressLint("StaticFieldLeak") // note that we're storing *Application*context @Volatile private var INSTANCE: OversecKeystore2? = null init { Security.insertProviderAt(org.spongycastle.jce.provider.BouncyCastleProvider(), 1) } fun noop() { //just a dummy method we can call in order to make sure the static code get's initialized } fun getInstance(ctx: Context): OversecKeystore2 = INSTANCE ?: synchronized(this) { INSTANCE ?: OversecKeystore2(ctx.applicationContext).also { INSTANCE = it } } fun getPlainKeyAsTransferBytes(raw: ByteArray?): ByteArray { val builder = Kex.KeyTransferV0.newBuilder() val plainKeyBuilder = builder.symmetricKeyPlainV0Builder plainKeyBuilder.keydata = ByteString.copyFrom(raw!!) return builder.build().toByteArray() } fun getEncryptedKeyAsTransferBytes(key: SymmetricKeyEncrypted): ByteArray { val builder = Kex.KeyTransferV0.newBuilder() val encryptedKeyBuilder = builder.symmetricKeyEncryptedV0Builder encryptedKeyBuilder.id = key.id encryptedKeyBuilder.alias = key.name encryptedKeyBuilder.createddate = key.createdDate!!.time encryptedKeyBuilder.cost = key.cost encryptedKeyBuilder.iv = ByteString.copyFrom(key.iv!!) encryptedKeyBuilder.salt = ByteString.copyFrom(key.salt!!) encryptedKeyBuilder.ciphertext = ByteString.copyFrom(key.ciphertext!!) return builder.build().toByteArray() } @Throws(OversecKeystore2.Base64DecodingException::class) fun getEncryptedKeyFromBase64Text(text: String): SymmetricKeyEncrypted? { try { val data = Base64.decode(text) return getEncryptedKeyFromTransferBytes(data) } catch (ex: DecoderException) { throw Base64DecodingException(ex) } } fun getEncryptedKeyFromTransferBytes(data: ByteArray): SymmetricKeyEncrypted? { try { val transfer = Kex.KeyTransferV0 .parseFrom(data) if (transfer.hasSymmetricKeyEncryptedV0()) { val encryptedKeyV0 = transfer.symmetricKeyEncryptedV0 val cost = encryptedKeyV0.cost val ciphertext = encryptedKeyV0.ciphertext.toByteArray() val salt = encryptedKeyV0.salt.toByteArray() val iv = encryptedKeyV0.iv.toByteArray() val created = encryptedKeyV0.createddate val alias = encryptedKeyV0.alias val id = encryptedKeyV0.id return SymmetricKeyEncrypted( id, alias, Date(created), salt, iv, cost, ciphertext ) } else { Ln.w("data array doesn't contain secret key") return null } } catch (e: InvalidProtocolBufferException) { e.printStackTrace() return null } } @Throws(OversecKeystore2.Base64DecodingException::class) fun getPlainKeyFromBase64Text(text: String): SymmetricKeyPlain? { try { val data = Base64.decode(text) return getPlainKeyFromTransferBytes(data) } catch (ex: DecoderException) { throw Base64DecodingException(ex) } } fun getPlainKeyFromTransferBytes(data: ByteArray): SymmetricKeyPlain? { try { val transfer = Kex.KeyTransferV0 .parseFrom(data) return if (transfer.hasSymmetricKeyPlainV0()) { val plainKeyV0 = transfer.symmetricKeyPlainV0 val keyBytes = plainKeyV0.keydata.toByteArray() SymmetricKeyPlain(keyBytes) } else { Ln.w("data array doesn't contain secret key") null } } catch (e: InvalidProtocolBufferException) { e.printStackTrace() return null } } } }
gpl-3.0
d2d25ea49506d3270e90e1c14ab074ce
28.317597
104
0.649978
4.64852
false
false
false
false
square/sqldelight
sqldelight-compiler/src/main/kotlin/com/squareup/sqldelight/core/lang/SqlDelightFileType.kt
1
1089
/* * Copyright (C) 2016 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.sqldelight.core.lang import com.intellij.icons.AllIcons import com.intellij.openapi.fileTypes.LanguageFileType object SqlDelightFileType : LanguageFileType(SqlDelightLanguage) { private val ICON = AllIcons.Providers.Sqlite const val EXTENSION = "sq" const val FOLDER_NAME = "sqldelight" override fun getName() = "SqlDelight" override fun getDescription() = "SqlDelight" override fun getDefaultExtension() = EXTENSION override fun getIcon() = ICON }
apache-2.0
8940d610e50be987a26def71c582a1d0
34.129032
75
0.752984
4.338645
false
false
false
false
gradle/gradle
subprojects/docs/src/snippets/dependencyManagement/modelingFeatures-crossProjectPublications-advanced-published/kotlin/buildSrc/src/main/kotlin/com/acme/InstrumentedJarsPlugin.kt
3
3413
package com.acme import org.gradle.api.JavaVersion import org.gradle.api.Named import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.artifacts.Configuration import org.gradle.api.attributes.Bundling import org.gradle.api.attributes.Category import org.gradle.api.attributes.LibraryElements import org.gradle.api.attributes.Usage import org.gradle.api.attributes.java.TargetJvmVersion import org.gradle.api.component.AdhocComponentWithVariants import org.gradle.api.component.SoftwareComponentFactory import org.gradle.api.tasks.bundling.Jar import org.gradle.kotlin.dsl.creating import org.gradle.kotlin.dsl.getValue import org.gradle.kotlin.dsl.register import org.gradle.kotlin.dsl.named import javax.inject.Inject // tag::inject_software_component_factory[] class InstrumentedJarsPlugin @Inject constructor( private val softwareComponentFactory: SoftwareComponentFactory) : Plugin<Project> { // end::inject_software_component_factory[] override fun apply(project: Project) = project.run { val outgoingConfiguration = createOutgoingConfiguration() attachArtifact() configurePublication(outgoingConfiguration) addVariantToExistingComponent(outgoingConfiguration) } private fun Project.configurePublication(outgoing: Configuration) { // tag::create_adhoc_component[] // create an adhoc component val adhocComponent = softwareComponentFactory.adhoc("myAdhocComponent") // add it to the list of components that this project declares components.add(adhocComponent) // and register a variant for publication adhocComponent.addVariantsFromConfiguration(outgoing) { mapToMavenScope("runtime") } // end::create_adhoc_component[] } private fun Project.attachArtifact() { val instrumentedJar = tasks.register<Jar>("instrumentedJar") { archiveClassifier.set("instrumented") } artifacts { add("instrumentedJars", instrumentedJar) } } private fun Project.createOutgoingConfiguration(): Configuration { val instrumentedJars by configurations.creating { isCanBeConsumed = true isCanBeResolved = false attributes { attribute(Category.CATEGORY_ATTRIBUTE, objects.named(Category.LIBRARY)) attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME)) attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling.EXTERNAL)) attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, JavaVersion.current().majorVersion.toInt()) attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objects.named("instrumented-jar")) } } return instrumentedJars } private fun Project.addVariantToExistingComponent(outgoing: Configuration) { // tag::add_variant_to_existing_component[] val javaComponent = components.findByName("java") as AdhocComponentWithVariants javaComponent.addVariantsFromConfiguration(outgoing) { // dependencies for this variant are considered runtime dependencies mapToMavenScope("runtime") // and also optional dependencies, because we don't want them to leak mapToOptional() } // end::add_variant_to_existing_component[] } }
apache-2.0
eb06ae4f25e3147d73db56c392089b3f
39.630952
116
0.715793
4.868759
false
true
false
false
gradle/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/support/zip.kt
3
3569
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.support import org.gradle.api.internal.file.archive.ZipCopyAction.CONSTANT_TIME_FOR_ZIP_ENTRIES import org.gradle.util.internal.ZipSlip.safeZipEntryName import org.gradle.util.internal.TextUtil.normaliseFileSeparators import java.io.File import java.io.InputStream import java.io.OutputStream import java.util.zip.ZipEntry import java.util.zip.ZipFile import java.util.zip.ZipOutputStream fun zipTo(zipFile: File, baseDir: File) { zipTo(zipFile, baseDir, baseDir.walkReproducibly()) } internal fun File.walkReproducibly(): Sequence<File> = sequence { require(isDirectory) yield(this@walkReproducibly) var directories: List<File> = listOf(this@walkReproducibly) while (directories.isNotEmpty()) { val subDirectories = mutableListOf<File>() directories.forEach { dir -> dir.listFilesOrdered().partition { it.isDirectory }.let { (childDirectories, childFiles) -> yieldAll(childFiles) childDirectories.let { yieldAll(it) subDirectories.addAll(it) } } } directories = subDirectories } } private fun zipTo(zipFile: File, baseDir: File, files: Sequence<File>) { zipTo(zipFile, fileEntriesRelativeTo(baseDir, files)) } private fun fileEntriesRelativeTo(baseDir: File, files: Sequence<File>): Sequence<Pair<String, ByteArray>> = files.filter { it.isFile }.map { file -> val path = file.normalisedPathRelativeTo(baseDir) val bytes = file.readBytes() path to bytes } internal fun File.normalisedPathRelativeTo(baseDir: File) = normaliseFileSeparators(relativeTo(baseDir).path) fun zipTo(zipFile: File, entries: Sequence<Pair<String, ByteArray>>) { zipTo(zipFile.outputStream(), entries) } private fun zipTo(outputStream: OutputStream, entries: Sequence<Pair<String, ByteArray>>) { ZipOutputStream(outputStream).use { zos -> entries.forEach { entry -> val (path, bytes) = entry zos.putNextEntry( ZipEntry(path).apply { time = CONSTANT_TIME_FOR_ZIP_ENTRIES size = bytes.size.toLong() } ) zos.write(bytes) zos.closeEntry() } } } fun unzipTo(outputDirectory: File, zipFile: File) { ZipFile(zipFile).use { zip -> for (entry in zip.entries()) { unzipEntryTo(outputDirectory, zip, entry) } } } private fun unzipEntryTo(outputDirectory: File, zip: ZipFile, entry: ZipEntry) { val output = outputDirectory.resolve(safeZipEntryName(entry.name)) if (entry.isDirectory) { output.mkdirs() } else { output.parentFile.mkdirs() zip.getInputStream(entry).use { it.copyTo(output) } } } private fun InputStream.copyTo(file: File): Long = file.outputStream().use { copyTo(it) }
apache-2.0
b7407fbd84685690cc4c1319d8b4283e
26.882813
103
0.666853
4.188967
false
false
false
false
google/private-compute-libraries
javatests/com/google/android/libraries/pcc/chronicle/remote/RemoteRouterTest.kt
1
14727
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.remote import android.os.IBinder import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.android.libraries.pcc.chronicle.api.policy.Policy import com.google.android.libraries.pcc.chronicle.api.policy.builder.policy import com.google.android.libraries.pcc.chronicle.api.remote.ICancellationSignal import com.google.android.libraries.pcc.chronicle.api.remote.IResponseCallback import com.google.android.libraries.pcc.chronicle.api.remote.RemoteEntity import com.google.android.libraries.pcc.chronicle.api.remote.RemoteError import com.google.android.libraries.pcc.chronicle.api.remote.RemoteErrorMetadata.Type import com.google.android.libraries.pcc.chronicle.api.remote.RemoteRequest import com.google.android.libraries.pcc.chronicle.api.remote.RemoteRequestMetadata import com.google.android.libraries.pcc.chronicle.api.remote.RemoteResponse import com.google.android.libraries.pcc.chronicle.api.remote.server.RemoteStreamServer import com.google.android.libraries.pcc.chronicle.remote.handler.RemoteServerHandler import com.google.android.libraries.pcc.chronicle.remote.handler.RemoteServerHandlerFactory import com.google.common.truth.Truth.assertThat import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.doAnswer import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.eq import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.never import com.nhaarman.mockitokotlin2.spy import com.nhaarman.mockitokotlin2.times import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions import com.nhaarman.mockitokotlin2.whenever import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.isActive import kotlinx.coroutines.runBlocking import kotlinx.coroutines.suspendCancellableCoroutine import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class RemoteRouterTest { private lateinit var scope: CoroutineScope private lateinit var router: RemoteRouter private val context = mock<RemoteContext>() private val policyChecker = mock<RemotePolicyChecker>() private val handler = mock<RemoteServerHandler>() private val handlerFactory = mock<RemoteServerHandlerFactory> { on { buildServerHandler(any(), any()) } doReturn handler } private val clientDetailsProvider = mock<ClientDetailsProvider> { on { getClientDetails() } doReturn ClientDetails(1337, ClientDetails.IsolationType.DEFAULT_PROCESS) } @Before fun setUp() { scope = CoroutineScope(SupervisorJob()) router = RemoteRouter(scope, context, policyChecker, handlerFactory, clientDetailsProvider) } @After fun tearDown() { // The scope should always still be active after a test. assertThat(scope.isActive).isTrue() scope.cancel() } @Test fun serve_nullRequestOrNullCallback_doesNothing() { val request = RemoteRequest(RemoteRequestMetadata.getDefaultInstance()) val callback = mock<IResponseCallback.Stub>() router.serve(request = null, callback = callback) verifyNoMoreInteractions(callback) verifyNoMoreInteractions(context) verifyNoMoreInteractions(policyChecker) verifyNoMoreInteractions(handlerFactory) router.serve(request = request, callback = null) verifyNoMoreInteractions(callback) verifyNoMoreInteractions(context) verifyNoMoreInteractions(policyChecker) verifyNoMoreInteractions(handlerFactory) } @Test fun serve_serverNotFound_callsCallbackOnError(): Unit = runBlocking { whenever(context.findServer(any())).thenReturn(null) val errorDeferred = CompletableDeferred<RemoteError>() val callback = spy(OnErrorCallback(errorDeferred::complete)) router.serve(REQUEST, callback) // Death recipient should've been linked. callback.linkedToDeath.await() val e = errorDeferred.await() assertThat(e.metadata.errorType).isEqualTo(Type.UNSUPPORTED) assertThat(e) .hasMessageThat() .contains("Server not found for request with metadata: ${REQUEST.metadata}") // Death recipient should've been unlinked. callback.unlinkedToDeath.await() verify(callback, times(1)).provideCancellationSignal(any()) verify(callback, times(1)).onError(any()) verify(callback, never()).onComplete() } @Test fun serve_exceptionThrownFromPolicyChecker_callsCallbackOnError(): Unit = runBlocking { val server = mock<RemoteStreamServer<*>>() whenever(context.findServer(any())).thenReturn(server) whenever(policyChecker.checkAndGetPolicyOrThrow(any(), any(), any())).then { throw IllegalStateException() } val errorDeferred = CompletableDeferred<RemoteError>() val callback = spy(OnErrorCallback(errorDeferred::complete)) router.serve(REQUEST, callback) // Death recipient should've been linked. callback.linkedToDeath.await() val e = errorDeferred.await() assertThat(e.metadata.errorType).isEqualTo(Type.UNKNOWN) assertThat(e).hasMessageThat().contains(IllegalStateException::class.java.name) // Death recipient should've been unlinked. callback.unlinkedToDeath.await() verify(callback, times(1)).provideCancellationSignal(any()) verify(callback, times(1)).onError(any()) verify(callback, never()).onComplete() } @Test fun serve_exceptionThrownFromHandlerFactory_callsCallbackOnError(): Unit = runBlocking { val server = mock<RemoteStreamServer<*>>() whenever(context.findServer(any())).thenReturn(server) whenever(policyChecker.checkAndGetPolicyOrThrow(any(), any(), any())).thenReturn(POLICY) whenever(handlerFactory.buildServerHandler(any(), any())).then { throw IllegalArgumentException() } val errorDeferred = CompletableDeferred<RemoteError>() val callback = spy(OnErrorCallback(errorDeferred::complete)) router.serve(REQUEST, callback) // Death recipient should've been linked. callback.linkedToDeath.await() val e = errorDeferred.await() assertThat(e.metadata.errorType).isEqualTo(Type.UNKNOWN) assertThat(e).hasMessageThat().contains(IllegalArgumentException::class.java.name) // Death recipient should've been unlinked. callback.unlinkedToDeath.await() verify(callback, times(1)).provideCancellationSignal(any()) verify(callback, times(1)).onError(any()) verify(callback, never()).onComplete() } @Test fun serve_callsHandlerHandle_beforeCallingComplete(): Unit = runBlocking { val onCompleteCalled = CompletableDeferred<Unit>() val handlerCalled = CompletableDeferred<Unit>() val handlerShouldProceed = CompletableDeferred<Unit>() val callback = spy(OnCompleteCallback { onCompleteCalled.complete(Unit) }) val handler = object : RemoteServerHandler { override suspend fun handle( policy: Policy?, input: List<RemoteEntity>, callback: IResponseCallback, ) { assertThat(policy).isEqualTo(POLICY) assertThat(input).isEqualTo(ENTITIES) assertThat(callback).isSameInstanceAs(callback) handlerCalled.complete(Unit) handlerShouldProceed.await() } } whenever(context.findServer(any())).thenReturn(mock()) whenever(policyChecker.checkAndGetPolicyOrThrow(any(), any(), any())).thenReturn(POLICY) whenever(handlerFactory.buildServerHandler(any(), any())).thenReturn(handler) router.serve(REQUEST, callback) // Death recipient should've been linked. callback.linkedToDeath.await() handlerCalled.await() handlerShouldProceed.complete(Unit) onCompleteCalled.await() // Death recipient should've been unlinked. callback.unlinkedToDeath.await() verify(callback, times(1)).provideCancellationSignal(any()) verify(callback, times(1)).onComplete() verify(callback, never()).onError(any()) } @Test fun serve_callsHandlerHandle_exceptionThrown_goesToCallbackOnError(): Unit = runBlocking { val onError = CompletableDeferred<RemoteError>() val callback = spy(OnErrorCallback(onError::complete)) val handler = object : RemoteServerHandler { override suspend fun handle( policy: Policy?, input: List<RemoteEntity>, callback: IResponseCallback, ): Unit = throw IllegalStateException("Oops") } whenever(context.findServer(any())).thenReturn(mock()) whenever(policyChecker.checkAndGetPolicyOrThrow(any(), any(), any())).thenReturn(POLICY) whenever(handlerFactory.buildServerHandler(any(), any())).thenReturn(handler) router.serve(REQUEST, callback) // Death recipient should've been linked. callback.linkedToDeath.await() val error = onError.await() assertThat(error.metadata.errorType).isEqualTo(Type.UNKNOWN) assertThat(error).hasMessageThat().contains(IllegalStateException::class.java.name) // Death recipient should've been unlinked. callback.unlinkedToDeath.await() verify(callback, times(1)).provideCancellationSignal(any()) verify(callback, times(1)).onError(any()) verify(callback, never()).onComplete() } @Test fun serve_cancellationSignal_cancelsOngoingHandlerHandle(): Unit = runBlocking { val onComplete = CompletableDeferred<Unit>() val onCancellationSignal = CompletableDeferred<ICancellationSignal>() val handleCalled = CompletableDeferred<Unit>() val callback = spy(OnCompleteCallback(onCancellationSignal::complete) { onComplete.complete(Unit) }) val cancelled = CompletableDeferred<Unit>() val handler = object : RemoteServerHandler { override suspend fun handle( policy: Policy?, input: List<RemoteEntity>, callback: IResponseCallback, ): Unit = suspendCancellableCoroutine { continuation -> continuation.invokeOnCancellation { cancelled.complete(Unit) } handleCalled.complete(Unit) } } whenever(context.findServer(any())).thenReturn(mock()) whenever(policyChecker.checkAndGetPolicyOrThrow(any(), any(), any())).thenReturn(POLICY) whenever(handlerFactory.buildServerHandler(any(), any())).thenReturn(handler) router.serve(REQUEST, callback) // Death recipient should've been linked. callback.linkedToDeath.await() val signal = onCancellationSignal.await() // Wait for the handle to have been used, it should now be suspending its coroutine. handleCalled.await() // Use the cancellation signal to cause cancellation. signal.cancel() // Wait for the handle to be notified. cancelled.await() // On complete should be called onComplete.await() // Death recipient should've been unlinked. callback.unlinkedToDeath.await() verify(callback, times(1)).provideCancellationSignal(any()) verify(callback, times(1)).onComplete() verify(callback, never()).onError(any()) } @Test fun serve_callbackDeathRecipientTriggered_cancelsOperation() = runBlocking { val cancelled = CompletableDeferred<Unit>() val handlerCalled = CompletableDeferred<Unit>() val handler = object : RemoteServerHandler { override suspend fun handle( policy: Policy?, input: List<RemoteEntity>, callback: IResponseCallback, ): Unit = suspendCancellableCoroutine { continuation -> // Suspend the coroutine, but don't resume... continuation.invokeOnCancellation { cancelled.complete(Unit) } handlerCalled.complete(Unit) } } whenever(context.findServer(any())).thenReturn(mock()) whenever(policyChecker.checkAndGetPolicyOrThrow(any(), any(), any())).thenReturn(POLICY) whenever(handlerFactory.buildServerHandler(any(), any())).thenReturn(handler) val callback = OnCompleteCallback {} router.serve(REQUEST, callback) val deathRecipient = callback.linkedToDeath.await() handlerCalled.await() // Now that the handler is suspending, use the death recipient and wait for the handler to be // canceled. deathRecipient.binderDied() cancelled.await() } abstract class AbstractIResponseCallback : IResponseCallback.Stub() { val linkedToDeath = CompletableDeferred<IBinder.DeathRecipient>() val unlinkedToDeath = CompletableDeferred<Unit>() private val spyBinder by lazy(LazyThreadSafetyMode.NONE) { spy(super.asBinder()) { on { linkToDeath(any(), eq(0)) } doAnswer { invocation -> linkedToDeath.complete(invocation.arguments[0] as IBinder.DeathRecipient) invocation.callRealMethod() Unit } on { unlinkToDeath(any(), eq(0)) } doAnswer { invocation -> unlinkedToDeath.complete(Unit) invocation.callRealMethod() as Boolean } } } override fun onData(data: RemoteResponse) = Unit override fun onError(error: RemoteError) = Unit override fun onComplete() = Unit override fun provideCancellationSignal(signal: ICancellationSignal) = Unit override fun asBinder(): IBinder = spyBinder } open class OnCompleteCallback( private val receiveCancellationSignal: (ICancellationSignal) -> Unit = {}, private val doOnComplete: () -> Unit, ) : AbstractIResponseCallback() { override fun onComplete() = doOnComplete() override fun provideCancellationSignal(signal: ICancellationSignal) = receiveCancellationSignal(signal) } open class OnErrorCallback(private val doOnError: (RemoteError) -> Unit) : AbstractIResponseCallback() { override fun onError(error: RemoteError) = doOnError(error) } companion object { private val POLICY = policy("MyPolicy", "Testing") private val ENTITIES = listOf(RemoteEntity(), RemoteEntity(), RemoteEntity()) private val REQUEST = RemoteRequest(RemoteRequestMetadata.getDefaultInstance(), ENTITIES) } }
apache-2.0
de9d2d5554877d022bb14e2d134303ed
36.664962
97
0.732464
4.923771
false
false
false
false
openbase/jul
module/exception/src/main/java/org/openbase/jul/exception/ExceptionProcessor.kt
1
4953
package org.openbase.jul.exception /*- * #%L * JUL Exception * %% * Copyright (C) 2015 - 2022 openbase.org * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ /** * @author vdasilva */ object ExceptionProcessor { /** * Method returns the message of the initial cause of the given throwable. * If the throwable does not provide a message its class name is returned. * * @param throwable the throwable to detect the message. * * @return the message as string. */ @JvmStatic fun getInitialCauseMessage(throwable: Throwable?): String { val cause = getInitialCause(throwable) return if (cause!!.localizedMessage == null) { cause.javaClass.simpleName } else cause.localizedMessage } /** * Method returns the initial cause of the given throwable. * * @param throwable the throwable to detect the message. * * @return the cause as throwable. */ @JvmStatic fun getInitialCause(throwable: Throwable?): Throwable? { if (throwable == null) { FatalImplementationErrorException(ExceptionProcessor::class.java, NotAvailableException("cause")) } var cause = throwable while (cause!!.cause != null) { cause = cause.cause } return cause } /** * Set the given `initialCause` as initial cause of the given `throwable`. * * @param throwable the throwable to extend. * @param initialCause the new initial cause. * * @return the new cause chain. */ @JvmStatic fun setInitialCause(throwable: Throwable?, initialCause: Throwable?): Throwable? { getInitialCause(throwable)!!.initCause(initialCause) return throwable } /** * Method checks if the initial cause of the given throwable is related to any system shutdown routine. * In more detail, an initial cause is related to the system shutdown when it is an instance of the `ShutdownInProgressException` class. * * @param throwable the top level cause. * * @return returns true if the given throwable is caused by a system shutdown, otherwise false. */ @JvmStatic fun isCausedBySystemShutdown(throwable: Throwable?): Boolean { return getInitialCause(throwable) is ShutdownInProgressException } /** * Method checks if any cause of the given throwable is related to any thread interruption. * * @param throwable the top level cause. * * @return returns true if the given throwable is caused by any thread interruption, otherwise false. */ @JvmStatic fun isCausedByInterruption(throwable: Throwable?): Boolean { var cause = throwable ?: return false // initial check if (cause is InterruptedException) { return true } // check causes while (cause.cause != null) { cause = cause.cause?: return false if (cause is InterruptedException) { return true } } // no interruption found return false } /** * Method throws an interrupted exception if the given `throwable` is caused by a system shutdown. * * @param throwable the throwable to check. * @param <T> the type of the `throwable` * * @return the bypassed `throwable` * * @throws InterruptedException is thrown if the system shutdown was initiated. </T> */ @JvmStatic @Throws(InterruptedException::class) fun <T : Throwable?> interruptOnShutdown(throwable: T): T { return if (isCausedBySystemShutdown(throwable)) { throw InterruptedException(getInitialCauseMessage(throwable)) } else { throwable } } } val Throwable.initialCauseMessage get() = ExceptionProcessor.getInitialCauseMessage(this) val Throwable.initialCause get() = ExceptionProcessor.getInitialCause(this) val Throwable.causedBySystemShutdown get() = ExceptionProcessor.isCausedBySystemShutdown(this) val Throwable.causedByInterruption get() = ExceptionProcessor.isCausedByInterruption(this) fun Throwable.setInitialCause(initialCause: Throwable?) = ExceptionProcessor.setInitialCause(this, initialCause)
lgpl-3.0
3fb6cd5c5cc1613c12c96e060d42c51e
33.395833
140
0.663234
4.818093
false
false
false
false
premnirmal/StockTicker
app/src/main/kotlin/com/github/premnirmal/ticker/portfolio/AddPositionViewModel.kt
1
1463
package com.github.premnirmal.ticker.portfolio import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.liveData import androidx.lifecycle.viewModelScope import com.github.premnirmal.ticker.model.StocksProvider import com.github.premnirmal.ticker.network.data.Holding import com.github.premnirmal.ticker.network.data.Position import com.github.premnirmal.ticker.network.data.Quote import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class AddPositionViewModel @Inject constructor(private val stocksProvider: StocksProvider) : ViewModel() { val quote: LiveData<Quote> get() = _quote private val _quote = MutableLiveData<Quote>() fun getPosition(symbol: String): Position? { return stocksProvider.getPosition(symbol) } fun loadQuote(symbol: String) = viewModelScope.launch { _quote.value = getQuote(symbol) } fun removePosition(symbol: String, holding: Holding) { viewModelScope.launch { stocksProvider.removePosition(symbol, holding) loadQuote(symbol) } } fun addHolding(symbol: String, shares: Float, price: Float) = liveData { val holding = stocksProvider.addHolding(symbol, shares, price) emit(holding) loadQuote(symbol) } private fun getQuote(symbol: String): Quote { return checkNotNull(stocksProvider.getStock(symbol)) } }
gpl-3.0
fad3ceb7dea7e6026f24f280940f6e0f
30.148936
106
0.778537
4.216138
false
false
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/preferences/NotificationSelectionDialogFragment.kt
1
5527
package com.battlelancer.seriesguide.preferences import android.app.Application import android.app.Dialog import android.content.DialogInterface import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatDialogFragment import androidx.appcompat.widget.SwitchCompat import androidx.core.view.isGone import androidx.fragment.app.viewModels import androidx.lifecycle.AndroidViewModel import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import androidx.sqlite.db.SimpleSQLiteQuery import com.battlelancer.seriesguide.R import com.battlelancer.seriesguide.SgApp import com.battlelancer.seriesguide.databinding.DialogNotificationSelectionBinding import com.battlelancer.seriesguide.provider.SeriesGuideContract.SgShow2Columns import com.battlelancer.seriesguide.provider.SeriesGuideDatabase.Tables import com.battlelancer.seriesguide.provider.SgRoomDatabase import com.battlelancer.seriesguide.shows.database.SgShow2Notify import com.battlelancer.seriesguide.settings.DisplaySettings import com.google.android.material.dialog.MaterialAlertDialogBuilder import org.greenrobot.eventbus.EventBus /** * A dialog displaying a list of shows with switches to turn notifications on or off. */ class NotificationSelectionDialogFragment : AppCompatDialogFragment() { private var binding: DialogNotificationSelectionBinding? = null private lateinit var adapter: SelectionAdapter private val model by viewModels<NotificationSelectionModel>() override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val binding = DialogNotificationSelectionBinding.inflate(layoutInflater) this.binding = binding adapter = SelectionAdapter(onItemClickListener) binding.apply { recyclerViewSelection.layoutManager = LinearLayoutManager(context) recyclerViewSelection.adapter = adapter } model.shows.observe(this) { shows -> val hasNoData = shows.isEmpty() this.binding?.textViewSelectionEmpty?.isGone = !hasNoData this.binding?.recyclerViewSelection?.isGone = hasNoData adapter.submitList(shows) } return MaterialAlertDialogBuilder(requireContext()) .setView(binding.root) .create() } override fun onDestroyView() { super.onDestroyView() binding = null } override fun onDismiss(dialog: DialogInterface) { super.onDismiss(dialog) EventBus.getDefault().post(PreferencesActivityImpl.UpdateSummariesEvent()) } private val onItemClickListener = object : SelectionAdapter.OnItemClickListener { override fun onItemClick(showId: Long, notify: Boolean) { SgApp.getServicesComponent(requireContext()).showTools().storeNotify(showId, notify) } } class NotificationSelectionModel(application: Application) : AndroidViewModel(application) { val shows by lazy { val orderClause = if (DisplaySettings.isSortOrderIgnoringArticles(application)) { SgShow2Columns.SORT_TITLE_NOARTICLE } else { SgShow2Columns.SORT_TITLE } SgRoomDatabase.getInstance(application).sgShow2Helper() .getShowsNotifyStates( SimpleSQLiteQuery( "SELECT ${SgShow2Columns._ID}, ${SgShow2Columns.TITLE}, ${SgShow2Columns.NOTIFY} " + "FROM ${Tables.SG_SHOW} " + "ORDER BY $orderClause" ) ) } } class SelectionAdapter(private val onItemClickListener: OnItemClickListener) : ListAdapter<SgShow2Notify, SelectionAdapter.ViewHolder>(SelectionDiffCallback()) { interface OnItemClickListener { fun onItemClick(showId: Long, notify: Boolean) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_notification_selection, parent, false) return ViewHolder(view, onItemClickListener) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val show = getItem(position) holder.showId = show.id holder.switchCompat.text = show.title holder.switchCompat.isChecked = show.notify } class ViewHolder( itemView: View, onItemClickListener: OnItemClickListener ) : RecyclerView.ViewHolder(itemView) { val switchCompat: SwitchCompat = itemView.findViewById(R.id.switchItemSelection) var showId = 0L init { itemView.setOnClickListener { onItemClickListener.onItemClick(showId, switchCompat.isChecked) } } } class SelectionDiffCallback : DiffUtil.ItemCallback<SgShow2Notify>() { override fun areItemsTheSame(oldItem: SgShow2Notify, newItem: SgShow2Notify): Boolean = oldItem.id == newItem.id override fun areContentsTheSame( oldItem: SgShow2Notify, newItem: SgShow2Notify ): Boolean = oldItem == newItem } } }
apache-2.0
c1a65511c81dd2c0b37ed1559ceea493
37.657343
108
0.69061
5.571573
false
false
false
false
michaeimm/kmn_bot-tool
app/src/main/java/tw/shounenwind/kmnbottool/activities/TeamActivity.kt
1
12296
package tw.shounenwind.kmnbottool.activities import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.view.View import android.widget.* import androidx.appcompat.app.AlertDialog import androidx.preference.PreferenceManager import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.request.RequestOptions import kotlinx.android.synthetic.main.activity_team.* import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.jetbrains.anko.intentFor import tw.shounenwind.kmnbottool.R import tw.shounenwind.kmnbottool.gson.BoxData import tw.shounenwind.kmnbottool.gson.ChipData import tw.shounenwind.kmnbottool.gson.Pet import tw.shounenwind.kmnbottool.skeleton.BaseActivity import tw.shounenwind.kmnbottool.util.CommandExecutor.battleHell import tw.shounenwind.kmnbottool.util.CommandExecutor.battleNormal import tw.shounenwind.kmnbottool.util.CommandExecutor.battleUltraHell import tw.shounenwind.kmnbottool.util.LogUtil import tw.shounenwind.kmnbottool.util.glide.CircularViewTarget import tw.shounenwind.kmnbottool.util.glide.GlideApp import tw.shounenwind.kmnbottool.widget.ProgressDialog class TeamActivity : BaseActivity() { private var boxData: BoxData? = null private var chipData: ChipData? = null private var oldTeam: Int = 0 private val team by lazy(LazyThreadSafetyMode.NONE) { findViewById<Spinner>(R.id.team)!! } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_team) prepareScreen() boxData = intent.getParcelableExtra("boxData") chipData = intent.getParcelableExtra("chipData") readTeamInfo() } private fun prepareScreen() { bindToolbarHomeButton() val teamArray = arrayOf( "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ) val teamAdapter = ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_dropdown_item, teamArray) teamAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) team.adapter = teamAdapter team.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { writeTeamInfo() readTeamInfo() } override fun onNothingSelected(parent: AdapterView<*>) { } } cardViewTeam.setOnClickListener { team.performClick() } cardViewAttacter.setOnClickListener { startActivityForResultWithTransition( intentFor<BoxActivity>( "selectFor" to "attacker", "boxData" to boxData ), FOR_RESULT_ATTACKER ) } cardViewAttacter.setOnLongClickListener { val target = tvAttacterName.text.toString() val fakeAttacker = Pet() fakeAttacker.name = target val petIndex = boxData!!.pets.indexOf(fakeAttacker) if (petIndex != -1) { val intent = intentFor<DetailActivity>() intent.putExtra("pet", boxData!!.pets[petIndex]) startActivityWithTransition(intent) true }else { false } } cardViewSupporter.setOnClickListener { startActivityForResultWithTransition( intentFor<BoxActivity>( "selectFor" to "supporter", "boxData" to boxData ), FOR_RESULT_SUPPORTER ) } cardViewSupporter.setOnLongClickListener { val target = tvSupporterName.text.toString() val fakeSupporter = Pet() fakeSupporter.name = target val petIndex = boxData!!.pets.indexOf(fakeSupporter) if (petIndex != -1) { val intent = intentFor<DetailActivity>() intent.putExtra("pet", boxData!!.pets[petIndex]) startActivityWithTransition(intent) true }else { false } } if (chipData?.chips?.isNotEmpty() == true) { cardViewChips.visibility = View.VISIBLE } btnBotBattleNormal.setOnClickListener { var target = tvAttacterName.text.toString() if (target == getString(R.string.no_select)) { Toast.makeText(this, R.string.no_selection, Toast.LENGTH_SHORT).show() return@setOnClickListener } if (tvSupporterName.text.toString() != getString(R.string.no_select)) { target += " " + tvSupporterName.text.toString() } target += " " + tvChips.text battleNormal(target) } btnBotBattleHell.setOnClickListener { var target = tvAttacterName.text.toString() if (target == getString(R.string.no_select)) { Toast.makeText(this, R.string.no_selection, Toast.LENGTH_SHORT).show() return@setOnClickListener } if (tvSupporterName.text.toString() != getString(R.string.no_select)) { target += " " + tvSupporterName.text.toString() } target += " " + tvChips.text battleHell(target) } btnBotBattleUltraHell.setOnClickListener { var target = tvAttacterName.text.toString() if (target == getString(R.string.no_select)) { Toast.makeText(this, R.string.no_selection, Toast.LENGTH_SHORT).show() return@setOnClickListener } if (tvSupporterName.text.toString() != getString(R.string.no_select)) { target += " " + tvSupporterName.text.toString() } target += " " + tvChips.text battleUltraHell(target) } cardViewChips.setOnClickListener { openChipDialog() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode != RESULT_OK) return when (requestCode) { FOR_RESULT_ATTACKER -> { val monsterName = data!!.getStringExtra("name") tvAttacterName.text = monsterName writeTeamInfo() readTeamInfo() } FOR_RESULT_SUPPORTER -> { val monsterName = data!!.getStringExtra("name") tvSupporterName.text = monsterName writeTeamInfo() readTeamInfo() } } } @SuppressLint("ApplySharedPref") private fun writeTeamInfo() { var defaultAttacker = "attacker" var defaultSupporter = "supporter" when (oldTeam) { 0 -> { } else -> { defaultAttacker = "attacter$oldTeam" defaultSupporter = "supporter$oldTeam" } } PreferenceManager .getDefaultSharedPreferences(this) .edit() .putString(defaultAttacker, tvAttacterName.text.toString()) .putString(defaultSupporter, tvSupporterName.text.toString()) .putInt("team", team.selectedItemPosition) .commit() } private fun readTeamInfo() { if (isFinishing) return val progressDialog = ProgressDialog(this).apply { setContent(getString(R.string.loading)) setCancelable(false) show() } GlobalScope.launch { val sharedPref = PreferenceManager.getDefaultSharedPreferences(this@TeamActivity) val defaultAttacker: String? val defaultSupporter: String? val defaultTeam = sharedPref.getInt("team", 0) val pets = boxData!!.pets oldTeam = defaultTeam when (defaultTeam) { 0 -> { defaultAttacker = sharedPref.getString("attacker", getString(R.string.no_select)) defaultSupporter = sharedPref.getString("supporter", getString(R.string.no_select)) } else -> { defaultAttacker = sharedPref.getString("attacter$defaultTeam", getString(R.string.no_select)) defaultSupporter = sharedPref.getString("supporter$defaultTeam", getString(R.string.no_select)) } } val fakeAttacker = Pet() fakeAttacker.name = defaultAttacker!! val attackerIndex = pets.indexOf(fakeAttacker) if (attackerIndex == -1 || defaultAttacker == getString(R.string.no_select)){ runOnUiThread { tvAttacterName.text = getString(R.string.no_select) GlideApp.with(this@TeamActivity) .clear(findViewById<View>(R.id.attacter_img)) } }else{ val monster = pets[attackerIndex] runOnUiThread { tvAttacterName.text = monster.name val imageView = findViewById<ImageView>(R.id.attacter_img) GlideApp.with(this@TeamActivity) .asBitmap() .load(monster.image) .apply(RequestOptions().centerCrop() .diskCacheStrategy(DiskCacheStrategy.DATA) ) .centerCrop() .into(CircularViewTarget(this@TeamActivity, imageView)) } } val fakeSupporter = Pet() fakeSupporter.name = defaultSupporter!! val supporterIndex = pets.indexOf(fakeSupporter) if (supporterIndex == -1 || defaultSupporter == getString(R.string.no_select)){ runOnUiThread { tvSupporterName.text = getString(R.string.no_select) GlideApp.with(this@TeamActivity) .clear(findViewById<View>(R.id.supporter_img)) } }else{ val monster = pets[supporterIndex] runOnUiThread { tvSupporterName.text = monster.name val imageView = findViewById<ImageView>(R.id.supporter_img) GlideApp.with(this@TeamActivity) .asBitmap() .load(monster.image) .apply(RequestOptions().centerCrop() .diskCacheStrategy(DiskCacheStrategy.DATA) ) .centerCrop() .into(CircularViewTarget(this@TeamActivity, imageView)) } } runOnUiThread { team.setSelection(defaultTeam) LogUtil.catchAndIgnore { progressDialog.dismiss() } } } } private fun openChipDialog() { val chips = chipData!!.chips val options = ArrayList<String>(chips.size) chips.forEach { chip -> options.add(chip.name + "\n" + chip.component) } AlertDialog.Builder(this) .setTitle(R.string.chips) .setItems(options.toTypedArray()) { _, which -> tvChips.text = chips[which].name } .show() } companion object { private const val FOR_RESULT_ATTACKER = 0 private const val FOR_RESULT_SUPPORTER = 1 } }
apache-2.0
7376d7744b822b14de5818efbb6c3ec5
37.428125
116
0.546682
5.496647
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-permissions-bukkit/src/main/kotlin/com/rpkit/permissions/bukkit/command/charactergroup/CharacterGroupViewCommand.kt
1
8405
package com.rpkit.permissions.bukkit.command.charactergroup import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.bukkit.extension.levenshtein import com.rpkit.core.service.Services import com.rpkit.permissions.bukkit.RPKPermissionsBukkit import com.rpkit.permissions.bukkit.group.RPKGroupService import com.rpkit.players.bukkit.profile.RPKProfileDiscriminator import com.rpkit.players.bukkit.profile.RPKProfileName import com.rpkit.players.bukkit.profile.RPKProfileService import net.md_5.bungee.api.ChatColor import net.md_5.bungee.api.chat.BaseComponent import net.md_5.bungee.api.chat.ClickEvent import net.md_5.bungee.api.chat.HoverEvent import net.md_5.bungee.api.chat.TextComponent import net.md_5.bungee.api.chat.hover.content.Text import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class CharacterGroupViewCommand(private val plugin: RPKPermissionsBukkit) : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { if (sender !is Player) { sender.sendMessage(plugin.messages.notFromConsole) return true } if (!sender.hasPermission("rpkit.permissions.command.character.group.view")) { sender.sendMessage(plugin.messages.noPermissionCharacterGroupView) return true } if (args.size < 2) { sender.sendMessage(plugin.messages.characterGroupViewUsage) return true } val groupService = Services[RPKGroupService::class.java] if (groupService == null) { sender.sendMessage(plugin.messages.noGroupService) return true } val profileService = Services[RPKProfileService::class.java] if (profileService == null) { sender.sendMessage(plugin.messages.noProfileService) return true } if (!args[0].contains("#")) { sender.sendMessage(plugin.messages.characterGroupViewInvalidProfileName) return true } val nameParts = args[0].split("#") val name = nameParts[0] val discriminator = nameParts[1].toIntOrNull() if (discriminator == null) { sender.sendMessage(plugin.messages.characterGroupViewInvalidProfileName) return true } profileService.getProfile(RPKProfileName(name), RPKProfileDiscriminator(discriminator)).thenAccept getProfile@{ profile -> if (profile == null) { sender.sendMessage(plugin.messages.characterGroupViewInvalidProfile) return@getProfile } val characterService = Services[RPKCharacterService::class.java] if (characterService == null) { sender.sendMessage(plugin.messages.noCharacterService) return@getProfile } characterService.getCharacters(profile).thenAcceptAsync getCharacters@{ characters -> if (characters.isEmpty()) { sender.sendMessage(plugin.messages.noCharacter) return@getCharacters } val character = characters.minByOrNull { args.drop(1).joinToString(" ").levenshtein(it.name) } if (character == null) { sender.sendMessage(plugin.messages.noCharacter) return@getCharacters } sender.sendMessage( plugin.messages.characterGroupViewTitle.withParameters( character = character ) ) for (group in groupService.getGroups(character).join()) { val message = plugin.messages.groupViewItem.withParameters(group = group) val messageComponents = mutableListOf<BaseComponent>() var chatColor: ChatColor? = null var chatFormat: ChatColor? = null var messageBuffer = StringBuilder() var i = 0 while (i < message.length) { if (message[i] == ChatColor.COLOR_CHAR) { appendComponent(messageComponents, messageBuffer, chatColor, chatFormat) messageBuffer = StringBuilder() if (message[i + 1] == 'x') { chatColor = ChatColor.of("#${message[i + 2]}${message[i + 4]}${message[i + 6]}${message[i + 8]}${message[i + 10]}${message[i + 12]}") i += 13 } else { val colorOrFormat = ChatColor.getByChar(message[i + 1]) if (colorOrFormat?.color != null) { chatColor = colorOrFormat chatFormat = null } if (colorOrFormat?.color == null) { chatFormat = colorOrFormat } if (colorOrFormat == ChatColor.RESET) { chatColor = null chatFormat = null } i += 2 } } else if (message.substring( i, (i + "\${reorder}".length).coerceAtMost(message.length) ) == "\${reorder}" ) { val reorderButton = TextComponent("\u292d").also { if (chatColor != null) { it.color = chatColor } if (chatFormat != null) { it.isObfuscated = chatFormat == ChatColor.MAGIC it.isBold = chatFormat == ChatColor.BOLD it.isStrikethrough = chatFormat == ChatColor.STRIKETHROUGH it.isUnderlined = chatFormat == ChatColor.UNDERLINE it.isItalic = chatFormat == ChatColor.ITALIC } } reorderButton.hoverEvent = HoverEvent( HoverEvent.Action.SHOW_TEXT, listOf(Text("Click to switch ${group.name.value}'s priority with another group")) ) reorderButton.clickEvent = ClickEvent( ClickEvent.Action.RUN_COMMAND, "/charactergroup prepareswitchpriority ${profile.name + profile.discriminator} ${character.name} ${group.name.value}" ) messageComponents.add(reorderButton) i += "\${reorder}".length } else { messageBuffer.append(message[i++]) } } appendComponent(messageComponents, messageBuffer, chatColor, chatFormat) sender.spigot().sendMessage(*messageComponents.toTypedArray()) } } } return true } private fun appendComponent( messageComponents: MutableList<BaseComponent>, messageBuffer: StringBuilder, chatColor: ChatColor?, chatFormat: ChatColor? ) { messageComponents.add(TextComponent(messageBuffer.toString()).also { if (chatColor != null) { it.color = chatColor } if (chatFormat != null) { it.isObfuscated = chatFormat == ChatColor.MAGIC it.isBold = chatFormat == ChatColor.BOLD it.isStrikethrough = chatFormat == ChatColor.STRIKETHROUGH it.isUnderlined = chatFormat == ChatColor.UNDERLINE it.isItalic = chatFormat == ChatColor.ITALIC } }) } }
apache-2.0
0b322da7d011ad11b8e32d00afe7518c
47.866279
157
0.523974
5.95255
false
false
false
false
Burning-Man-Earth/iBurn-Android
iBurn/src/main/java/com/gaiagps/iburn/database/DataProvider.kt
1
16709
package com.gaiagps.iburn.database import android.content.ContentValues import android.content.Context import com.gaiagps.iburn.AudioTourManager import com.gaiagps.iburn.CurrentDateProvider import com.gaiagps.iburn.PrefsHelper import com.gaiagps.iburn.api.typeadapter.PlayaDateTypeAdapter import com.gaiagps.iburn.view.Utils import com.gaiagps.iburn.DateUtil import com.mapbox.mapboxsdk.geometry.VisibleRegion import io.reactivex.Flowable import io.reactivex.Observable import io.reactivex.rxkotlin.Flowables import io.reactivex.schedulers.Schedulers import timber.log.Timber import java.util.* import java.util.concurrent.atomic.AtomicBoolean /** * Class for interaction with our database via Reactive streams. * This is intended as an experiment to replace our use of [android.content.ContentProvider] * as it does not meet all of our needs (e.g: Complex UNION queries not possible with Schematic's * generated version, and I believe manually writing a ContentProvider is too burdensome and error-prone) * * * Created by davidbrodsky on 6/22/15. */ class DataProvider private constructor(private val context: Context, private val db: AppDatabase, private val interceptor: DataProvider.QueryInterceptor?) { private val apiDateFormat = PlayaDateTypeAdapter.buildIso8601Format() interface QueryInterceptor { fun onQueryIntercepted(query: String, tables: Iterable<String>): String } private val upgradeLock = AtomicBoolean(false) fun beginUpgrade() { upgradeLock.set(true) } fun endUpgrade() { upgradeLock.set(false) // TODO : Trigger Room observers // Trigger all SqlBrite observers via reflection (uses private method) // try { // Method method = db.getClass().getDeclaredMethod("sendTableTrigger", Set.class); // method.setAccessible(true); // method.invoke(db, new HashSet<>(PlayaDatabase.ALL_TABLES)); // } catch (SecurityException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { // Timber.w(e, "Failed to notify observers on endUpgrade"); // } } fun deleteCamps(): Int { return clearTable(Camp.TABLE_NAME) } private fun clearTable(tablename: String): Int { return db.openHelper.writableDatabase.delete(tablename, null, null) } fun observeCamps(): Flowable<List<Camp>> { return db.campDao().all } fun observeCampFavorites(): Flowable<List<Camp>> { // TODO : Honor upgradeLock? return db.campDao().favorites } fun observeCampsByName(query: String): Flowable<List<Camp>> { // TODO : Honor upgradeLock val wildQuery = addWildcardsToQuery(query) return db.campDao().findByName(wildQuery) } fun observeCampByPlayaId(playaId: String): Flowable<Camp> { return db.campDao().findByPlayaId(playaId) } fun beginTransaction() { db.beginTransaction() // BriteDatabase.Transaction t = db.newTransaction(); // transactionStack.push(t); } fun setTransactionSuccessful() { if (!db.inTransaction()) { return } db.setTransactionSuccessful() } fun endTransaction() { if (!db.inTransaction()) { return } // TODO: Don't allow this call to proceed without prior call to beginTransaction db.endTransaction() } fun insert(table: String, values: ContentValues) { db.openHelper.writableDatabase.insert(table, 0, values) // TODO : wtf is the int here? } fun delete(table: String): Int { when (table) { Camp.TABLE_NAME -> return deleteCamps() Art.TABLE_NAME -> return deleteArt() Event.TABLE_NAME -> return deleteEvents() else -> Timber.w("Cannot clear unknown table name '%s'", table) } return 0 } fun deleteEvents(): Int { return clearTable(Event.TABLE_NAME) // return db.getOpenHelper().getWritableDatabase().delete(Event.TABLE_NAME, "*", null); // Cursor result = db.query("DELETE FROM event; VACUUM", null); // if (result != null) result.close(); } fun observeEventsOnDayOfTypes(day: String, types: ArrayList<String>?, includeExpired: Boolean, eventTiming: String): Flowable<List<Event>> { // TODO : Honor upgradeLock? val wildDay = addWildcardsToQuery(day) val nowDate = CurrentDateProvider.getCurrentDate() val now = Utils.convertDateToString(nowDate) val allDayStart = Utils.convertDateToString( DateUtil.getAllDayStartDateTime(day)) val allDayEnd = Utils.convertDateToString( DateUtil.getAllDayEndDateTime(day)) if (types == null || types.isEmpty()) { if(eventTiming=="timed"){ if(includeExpired == true) { return db.eventDao().findByDayTimed(wildDay, allDayStart,allDayEnd) } else{ return db.eventDao().findByDayNoExpiredTimed(wildDay, now, allDayStart,allDayEnd) } } else{ return db.eventDao().findByDayAllDay(wildDay,allDayStart, allDayEnd) } } else { if(eventTiming=="timed"){ if(includeExpired == true) { return db.eventDao().findByDayAndTypeTimed(wildDay,types, allDayStart,allDayEnd) } else{ return db.eventDao().findByDayAndTypeNoExpiredTimed(wildDay, types,now, allDayStart,allDayEnd) } } else{ return db.eventDao().findByDayAndTypeAllDay(wildDay,types, allDayStart, allDayEnd) } } } fun observeEventsHostedByCamp(camp: Camp): Flowable<List<Event>> { return db.eventDao().findByCampPlayaId(camp.playaId) } fun observeOtherOccurrencesOfEvent(event: Event): Flowable<List<Event>> { return db.eventDao().findOtherOccurrences(event.playaId, event.id) } fun observeEventFavorites(): Flowable<List<Event>> { // TODO : Honor upgradeLock? return db.eventDao().favorites } fun observeEventBetweenDates(start: Date, end: Date): Flowable<List<Event>> { val startDateStr = apiDateFormat.format(start) val endDateStr = apiDateFormat.format(end) // TODO : Honor upgradeLock? Timber.d("Start time between %s and %s", startDateStr, endDateStr) return db.eventDao().findInDateRange(startDateStr, endDateStr) } fun deleteArt(): Int { return clearTable(Art.TABLE_NAME) // return db.getOpenHelper().getWritableDatabase().delete(Art.TABLE_NAME, null, null); // Cursor result = db.query("DELETE FROM art; VACUUM", null); // if (result != null) result.close(); } fun observeArt(): Flowable<List<Art>> { // TODO : Honor upgradeLock? return db.artDao().all } fun observeArtFavorites(): Flowable<List<Art>> { // TODO : Honor upgradeLock? return db.artDao().favorites } fun observeArtWithAudioTour(): Flowable<List<Art>> { // TODO : Honor upgradeLock? return db.artDao().all.map { it.filter { AudioTourManager.hasAudioTour(context, it.playaId) } } } /** * Observe all favorites. * * * Note: This query automatically adds in Event.startTime (and 0 values for all non-events), * since we always want to show this data for an event. */ fun observeFavorites(): Flowable<SectionedPlayaItems> { // TODO : Honor upgradeLock // TODO : Return structure with metadata on how many art, camps, events etc? return Flowables.combineLatest( db.artDao().favorites, db.campDao().favorites, db.eventDao().favorites) { arts, camps, events -> val sections = ArrayList<IntRange>(3) val items = ArrayList<PlayaItem>(arts.size + camps.size + events.size) var lastRangeEnd = 0 if (camps.size > 0) { items.addAll(camps) val campRangeEnd = items.size sections.add(IntRange(lastRangeEnd, campRangeEnd)) lastRangeEnd = campRangeEnd } if (arts.size > 0) { items.addAll(arts) val artRangeEnd = items.size sections.add(IntRange(lastRangeEnd, artRangeEnd)) lastRangeEnd = artRangeEnd } if (events.size > 0) { items.addAll(events) val eventsRangeEnd = items.size sections.add(IntRange(lastRangeEnd, eventsRangeEnd)) lastRangeEnd = eventsRangeEnd } SectionedPlayaItems(data = items, ranges = sections) } } /** * Observe all results for a name query. * * * Note: This query automatically adds in Event.startTime (and 0 values for all non-events), * since we always want to show this data for an event. */ fun observeNameQuery(query: String): Flowable<SectionedPlayaItems> { // TODO : Honor upgradeLock // TODO : Return structure with metadata on how many art, camps, events etc? val wildQuery = addWildcardsToQuery(query) return Flowables.combineLatest( db.artDao().findByName(wildQuery), db.campDao().findByName(wildQuery), db.eventDao().findByName(wildQuery), db.userPoiDao().findByName(wildQuery)) { arts, camps, events, userpois -> val sections = ArrayList<IntRange>(4) val items = ArrayList<PlayaItem>(arts.size + camps.size + events.size) var lastRangeEnd = 0 if (camps.size > 0) { items.addAll(camps) val campRangeEnd = items.size sections.add(IntRange(lastRangeEnd, campRangeEnd)) lastRangeEnd = campRangeEnd } if (arts.size > 0) { items.addAll(arts) val artRangeEnd = items.size sections.add(IntRange(lastRangeEnd, artRangeEnd)) lastRangeEnd = artRangeEnd } if (events.size > 0) { items.addAll(events) val eventsRangeEnd = items.size sections.add(IntRange(lastRangeEnd, eventsRangeEnd)) lastRangeEnd = eventsRangeEnd } if (userpois.size > 0) { items.addAll(userpois) val userPoiRangeEnd = items.size sections.add(IntRange(lastRangeEnd, userPoiRangeEnd)) lastRangeEnd = userPoiRangeEnd } SectionedPlayaItems(data = items, ranges = sections) } } /** * Returns ongoing events in [region], favorites, and user-added markers */ fun observeAllMapItemsInVisibleRegion(region: VisibleRegion): Flowable<List<PlayaItem>> { // TODO : Honor upgradeLock // Warning: The following is very ethnocentric to Earth C-137 North-Western ... Quadrasphere(?) val maxLat = region.farRight.latitude.toFloat() val minLat = region.nearRight.latitude.toFloat() val maxLon = region.farRight.longitude.toFloat() val minLon = region.farLeft.longitude.toFloat() return Flowables.combineLatest( db.artDao().favorites, db.campDao().favorites, db.eventDao().findInRegionOrFavorite(minLat, maxLat, minLon, maxLon), db.userPoiDao().all) { arts, camps, events, userpois -> val all = ArrayList<PlayaItem>(arts.size + camps.size + events.size + userpois.size) all.addAll(arts) all.addAll(camps) all.addAll(events) all.addAll(userpois) all } } /** * Returns favorites and user-added markers only */ fun observeUserAddedMapItemsOnly(): Flowable<List<PlayaItem>> { // TODO : Honor upgradeLock val nowDate = CurrentDateProvider.getCurrentDate() val now = Utils.convertDateToString(nowDate) return Flowables.combineLatest( db.artDao().favorites, db.campDao().favorites, db.eventDao().getNonExpiredFavorites(now), db.userPoiDao().all) { arts, camps, events, userpois -> val all = ArrayList<PlayaItem>(arts.size + camps.size + events.size + userpois.size) all.addAll(arts) all.addAll(camps) all.addAll(events) all.addAll(userpois) all } } fun getUserPoi(): Flowable<List<UserPoi>> { return db.userPoiDao().all } fun getUserPoiByPlayaId(playaId: String): Flowable<UserPoi> { return db.userPoiDao().findByPlayaId(playaId) } fun insertUserPoi(poi: UserPoi) { db.userPoiDao().insert(poi) } fun deleteUserPoi(poi: UserPoi) { db.userPoiDao().delete(poi) } fun update(item: PlayaItem) { if (item is Art) { db.artDao().update(item) } else if (item is Event) { db.eventDao().update(item) } else if (item is Camp) { db.campDao().update(item) } else if (item is UserPoi) { db.userPoiDao().update(item) } else { Timber.e("Cannot update item of unknown type") } } fun toggleFavorite(item: PlayaItem) { // TODO : Really don't like mutable DBB objects, so hide the field twiddling here in case // I can remove it from the PlayaItem API item.isFavorite = !item.isFavorite Timber.d("Setting item %s favorite %b", item.name, item.isFavorite) update(item) } private fun interceptQuery(query: String, table: String): String { return interceptQuery(query, setOf(table)) } private fun interceptQuery(query: String, tables: Iterable<String>): String { if (interceptor == null) return query return interceptor.onQueryIntercepted(query, tables) } companion object { /** * Version of database schema */ const val BUNDLED_DATABASE_VERSION: Long = 1 /** * Version of database data and mbtiles. This is basically the unix time at which bundled data was provided to this build. */ val RESOURCES_VERSION: Long = 1503171563000L // Unix time of creation private var provider: DataProvider? = null // private ArrayDeque<BriteDatabase.Transaction> transactionStack = new ArrayDeque<>(); fun getInstance(context: Context): Observable<DataProvider> { // TODO : This ain't thread safe if (provider != null) return Observable.just(provider!!) val prefs = PrefsHelper(context) return Observable.just(getSharedDb(context)) .subscribeOn(Schedulers.io()) .doOnNext { database -> prefs.databaseVersion = BUNDLED_DATABASE_VERSION prefs.setBaseResourcesVersion(RESOURCES_VERSION) } .map { sqlBrite -> DataProvider(context, sqlBrite, Embargo(prefs)) } .doOnNext { dataProvider -> provider = dataProvider } } fun makeProjectionString(projection: Array<String>): String { val builder = StringBuilder() for (column in projection) { builder.append(column) builder.append(',') } // Remove the last comma return builder.substring(0, builder.length - 1) } /** * Add wildcards to the beginning and end of a query term * @return "%{@param query}%" */ private fun addWildcardsToQuery(query: String): String { return "%$query%" } } data class SectionedPlayaItems(val data: List<PlayaItem>, val ranges: List<IntRange>) }
mpl-2.0
7e3031484e7a71803a42a29c83623167
33.594203
156
0.58651
4.81944
false
false
false
false
fynances/fynances-desktop
mainui/src/main/kotlin/fynances/desktop/Styles.kt
1
623
package fynances.desktop import javafx.geometry.Pos import tornadofx.Stylesheet import tornadofx.box import tornadofx.cssclass import tornadofx.px class Styles : Stylesheet() { companion object { val mainView by cssclass() val accountsView by cssclass() val currenciesView by cssclass() } init { select(mainView) { padding = box(20.px) alignment = Pos.CENTER minWidth = 250.px spacing = 10.px } select(accountsView, currenciesView) { minWidth = 250.px minHeight = 250.px } } }
apache-2.0
f9a3f5d2a073b396dbee70dea8158f8c
21.285714
46
0.5939
4.614815
false
false
false
false
etesync/android
app/src/main/java/com/etesync/syncadapter/ui/etebase/ImportCollectionFragment.kt
1
3490
package com.etesync.syncadapter.ui.etebase import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.commit import com.etesync.syncadapter.CachedCollection import com.etesync.syncadapter.Constants import com.etesync.syncadapter.R import com.etesync.syncadapter.ui.BaseActivity import com.etesync.syncadapter.ui.importlocal.ImportFragment import com.etesync.syncadapter.ui.importlocal.LocalCalendarImportFragment import com.etesync.syncadapter.ui.importlocal.LocalContactImportFragment class ImportCollectionFragment : Fragment() { private val model: AccountViewModel by activityViewModels() private val collectionModel: CollectionViewModel by activityViewModels() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val ret = inflater.inflate(R.layout.import_actions_list, container, false) setHasOptionsMenu(true) if (savedInstanceState == null) { collectionModel.observe(this) { (activity as? BaseActivity?)?.supportActionBar?.setTitle(R.string.import_dialog_title) if (container != null) { initUi(inflater, ret, it) } } } return ret } private fun initUi(inflater: LayoutInflater, v: View, cachedCollection: CachedCollection) { val accountHolder = model.value!! var card = v.findViewById<View>(R.id.import_file) var img = card.findViewById<View>(R.id.action_icon) as ImageView var text = card.findViewById<View>(R.id.action_text) as TextView img.setImageResource(R.drawable.ic_file_white) text.setText(R.string.import_button_file) card.setOnClickListener { parentFragmentManager.commit { add(ImportFragment.newInstance(accountHolder.account, cachedCollection), null) } } card = v.findViewById(R.id.import_account) img = card.findViewById<View>(R.id.action_icon) as ImageView text = card.findViewById<View>(R.id.action_text) as TextView img.setImageResource(R.drawable.ic_account_circle_white) text.setText(R.string.import_button_local) card.setOnClickListener { if (cachedCollection.collectionType == Constants.ETEBASE_TYPE_CALENDAR) { parentFragmentManager.commit { replace(R.id.fragment_container, LocalCalendarImportFragment.newInstance(accountHolder.account, cachedCollection.col.uid)) addToBackStack(null) } } else if (cachedCollection.collectionType == Constants.ETEBASE_TYPE_ADDRESS_BOOK) { parentFragmentManager.commit { replace(R.id.fragment_container, LocalContactImportFragment.newInstance(accountHolder.account, cachedCollection.col.uid)) addToBackStack(null) } } // FIXME: should be in the fragments once we kill legacy (activity as? BaseActivity?)?.supportActionBar?.setTitle(R.string.import_select_account) } if (collectionModel.value!!.collectionType == Constants.ETEBASE_TYPE_TASKS) { card.visibility = View.GONE } } }
gpl-3.0
782b9db1c9ffd45d338278f923b2c53b
43.189873
142
0.689685
4.840499
false
false
false
false
madtcsa/AppManager
app/src/main/java/com/md/appmanager/async/UninstallInBackground.kt
1
2140
package com.md.appmanager.async import android.app.Activity import android.content.Context import android.content.Intent import android.os.AsyncTask import com.afollestad.materialdialogs.MaterialDialog import com.md.appmanager.AppInfo import com.md.appmanager.R import com.md.appmanager.activities.MainActivity import com.md.appmanager.utils.UtilsApp import com.md.appmanager.utils.UtilsDialog import com.md.appmanager.utils.UtilsRoot class UninstallInBackground(private val context: Context, private val dialog: MaterialDialog, private val appInfo: AppInfo) : AsyncTask<Void, String, Boolean>() { private val activity: Activity = context as Activity override fun doInBackground(vararg voids: Void): Boolean? { var status: Boolean? = false if (UtilsApp.checkPermissions(activity)!!) { status = UtilsRoot.uninstallWithRootPermission(appInfo.source!!) } return status } override fun onPostExecute(status: Boolean?) { super.onPostExecute(status) dialog.dismiss() if (status!!) { val materialDialog = UtilsDialog.showUninstalled(context, appInfo) materialDialog.callback(object : MaterialDialog.ButtonCallback() { override fun onPositive(dialog: MaterialDialog?) { UtilsRoot.rebootSystem() dialog!!.dismiss() } }) materialDialog.callback(object : MaterialDialog.ButtonCallback() { override fun onNegative(dialog: MaterialDialog?) { dialog!!.dismiss() val intent = Intent(context, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK activity.finish() context.startActivity(intent) } }) materialDialog.show() } else { UtilsDialog.showTitleContent(context, context.resources.getString(R.string.dialog_root_required), context.resources.getString(R.string.dialog_root_required_description)) } } }
gpl-3.0
b4fb3811761b0da09207b0d83e6815ed
38.648148
181
0.659813
4.965197
false
false
false
false
christophpickl/kpotpourri
http4k/src/main/kotlin/com/github/christophpickl/kpotpourri/http4k/api.kt
1
8717
package com.github.christophpickl.kpotpourri.http4k import com.fasterxml.jackson.core.type.TypeReference import com.github.christophpickl.kpotpourri.common.KPotpourriException import com.github.christophpickl.kpotpourri.http4k.BasicAuthMode.BasicAuthDisabled import com.github.christophpickl.kpotpourri.http4k.StatusCheckMode.Anything import com.github.christophpickl.kpotpourri.http4k.internal.HeadersMap import com.github.christophpickl.kpotpourri.http4k.internal.Http4kImpl import com.github.christophpickl.kpotpourri.http4k.internal.HttpClient import com.github.christophpickl.kpotpourri.http4k.internal.HttpClientFactoryDetector import com.github.christophpickl.kpotpourri.http4k.internal.MutableMetaMap import com.github.christophpickl.kpotpourri.http4k.internal.mapper import kotlin.reflect.KClass /** * Core entry point to build a [Http4k] instance in a DSL falvour. */ fun buildHttp4k(withBuilder: Http4kBuilder.() -> Unit = {}): Http4k { val builder = Http4kBuilder() withBuilder.invoke(builder) return builder.end() } /** * Http4k can be globally configured consisting of the following interfaces. */ interface GlobalHttp4kConfigurable : BaseUrlConfigurable, BasicAuthConfigurable, HeadersConfigurable, StatusCheckConfigurable, QueryParamConfigurable /** * Core DSL class to prepare a http4k instance, configuring global options (which can be overridden per request). */ class Http4kBuilder : GlobalHttp4kConfigurable { /** Global URL query parameters for each request. */ override val queryParams: MutableMap<String, String> = HashMap() /** Global HTTP headers. */ override val headers: HeadersMap = HeadersMap() /** By default the base URL is not defined/used and reach request must be an absolute URL. */ override var baseUrl: BaseUrl = NoBaseUrl /** By default basic authentication is disabled. */ override var basicAuth: BasicAuthMode = BasicAuthDisabled /** By default any HTTP status code is ok and will not throw an exception (depending on concrete HTTP implementation). */ override var statusCheck: StatusCheckMode = Anything internal var overrideHttpClient: HttpClient? = null /** Actually not visible to the outside, but still must be public for per-implementation extensions. */ val _implMetaMap = MutableMetaMap() /** * Detects (or using overridden) HTTP client implementation based on classpath availability. */ fun end(): Http4k { val restClient = if (overrideHttpClient != null) { overrideHttpClient!! } else { val httpClientFactory = HttpClientFactoryDetector().detect() httpClientFactory.build(_implMetaMap) } return Http4kImpl(restClient, this) } } // in order to reifie generic type, must not be in an interface /** Reified version of GET. */ inline fun <reified R : Any> Http4k.get(url: String, noinline withOpts: BodylessRequestOpts.() -> Unit = {}) = getGeneric(url, object: TypeReference<R>() {}, withOpts) /** Reified version of POST. */ inline fun <reified R : Any> Http4k.post(url: String, noinline withOpts: BodyfullRequestOpts.() -> Unit = {}) = postGeneric(url, object: TypeReference<R>() {}, withOpts) /** Reified version of PUT. */ inline fun <reified R : Any> Http4k.put(url: String, noinline withOpts: BodyfullRequestOpts.() -> Unit = {}) = putGeneric(url, object: TypeReference<R>() {}, withOpts) /** Reified version of DELETE. */ inline fun <reified R : Any> Http4k.delete(url: String, noinline withOpts: BodylessRequestOpts.() -> Unit = {}) = deleteGeneric(url, object: TypeReference<R>() {}, withOpts) /** Reified version of PATCH. */ inline fun <reified R : Any> Http4k.patch(url: String, noinline withOpts: BodyfullRequestOpts.() -> Unit = {}) = patchGeneric(url, object: TypeReference<R>() {}, withOpts) /** * Core interface to execute HTTP requests for any method (GET, POST, ...) configurable via request options. * * return type: either any jackson unmarshallable object, or an [Response4k] instance by default. * url: combined with optional global base URL * body: something which will be marshalled by jackson */ interface Http4k { /** GET response with explicity return type. */ fun <R : Any> getReturning(url: String, returnType: KClass<R>, withOpts: BodylessRequestOpts.() -> Unit = {}): R /** GET response for generic return types. */ fun <R : Any> getGeneric(url: String, returnType: TypeReference<R>, withOpts: BodylessRequestOpts.() -> Unit = {}): R /** POST response with return type set to [Response4k]. */ fun <R : Any> postAndReturnResponse(url: String, withOpts: BodyfullRequestOpts.() -> Unit = {}) = postReturning(url, Response4k::class, { withOpts(this) }) /** POST response with explicity return type. */ fun <R : Any> postReturning(url: String, returnType: KClass<R>, withOpts: BodyfullRequestOpts.() -> Unit = {}): R /** POST response for generic return types. */ fun <R : Any> postGeneric(url: String, returnType: TypeReference<R>, withOpts: BodyfullRequestOpts.() -> Unit = {}): R /** PUT response with return type set to [Response4k]. */ fun <R : Any> putAndReturnResponse(url: String, body: Any, withOpts: BodyfullRequestOpts.() -> Unit = {}) = putReturning(url, Response4k::class, { requestBody(body); withOpts(this) }) /** PUT response with explicity return type. */ fun <R : Any> putReturning(url: String, returnType: KClass<R>, withOpts: BodyfullRequestOpts.() -> Unit = {}): R /** PUT response for generic return types. */ fun <R : Any> putGeneric(url: String, returnType: TypeReference<R>, withOpts: BodyfullRequestOpts.() -> Unit = {}): R /** DELETE response with explicity return type. */ fun <R : Any> deleteReturning(url: String, returnType: KClass<R>, withOpts: BodylessRequestOpts.() -> Unit = {}): R /** DELETE response for generic return types. */ fun <R : Any> deleteGeneric(url: String, returnType: TypeReference<R>, withOpts: BodylessRequestOpts.() -> Unit = {}): R /** PATCH response with return type set to [Response4k]. */ fun <R : Any> patchAndReturnResponse(url: String, withOpts: BodyfullRequestOpts.() -> Unit = {}) = patchReturning(url, Response4k::class, { withOpts(this) }) /** PATCH response with explicity return type. */ fun <R : Any> patchReturning(url: String, returnType: KClass<R>, withOpts: BodyfullRequestOpts.() -> Unit = {}): R /** PATCH response for generic return types. */ fun <R : Any> patchGeneric(url: String, returnType: TypeReference<R>, withOpts: BodyfullRequestOpts.() -> Unit = {}): R } /** * Core request object abstraction. */ data class Request4k( val method: HttpMethod4k, val url: String, val headers: Map<String, String> = emptyMap(), val requestBody: DefiniteRequestBody? = null ) { companion object {}// for extensions init { // for simplicity sake no perfectly clean design but lazy check for data integrity if (!method.isRequestBodySupported && requestBody != null) { throw Http4kException("Invalid request! HTTP method [$method] does not support request body: $requestBody") } } /** * Don't render authorization header. */ override fun toString() = "Request4k(" + "method=$method, " + "url=$url, " + "headers=${headerWithoutAuthorizationSecret()}, " + "requestBody=<<$requestBody>>" + ")" private fun headerWithoutAuthorizationSecret(): Map<String, String> { val newHeaders = HashMap<String, String>(headers.size) headers.forEach { (k, v) -> if ("authorization" == k.toLowerCase()) { newHeaders += k to "xxxxx" } else { newHeaders += k to v } } return newHeaders } } /** * Core response object abstraction. */ data class Response4k( /** HTTP status code. */ val statusCode: StatusCode, /** Eagerly response body as a string. */ val bodyAsString: String, /** Response headers, obviously. */ val headers: Map<String, String> = emptyMap() ) { companion object // test extensions /** * Transform the response body to a custom JSON object. */ fun <T : Any> readJson(targetType: KClass<T>): T { // MINOR could do also here an annotation check (if option is enabled to do so) return mapper.readValue(bodyAsString, targetType.java) } } /** * Global custom exception type. */ open class Http4kException(message: String, cause: Exception? = null) : KPotpourriException(message, cause)
apache-2.0
e82bd7f08b0257a59ec9e446c07ffa0e
41.730392
187
0.68246
4.369424
false
false
false
false
STUDIO-apps/GeoShare_Android
mobile/src/main/java/uk/co/appsbystudio/geoshare/utils/ProfileSelectionResult.kt
1
3492
package uk.co.appsbystudio.geoshare.utils import android.app.Activity import android.app.Activity.RESULT_OK import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Environment import android.provider.MediaStore import android.widget.Toast import com.google.firebase.database.FirebaseDatabase import com.google.firebase.storage.FirebaseStorage import com.theartofdev.edmodo.cropper.CropImage import com.theartofdev.edmodo.cropper.CropImageView import uk.co.appsbystudio.geoshare.base.MainView import uk.co.appsbystudio.geoshare.setup.InitialSetupView import java.io.File import java.io.FileOutputStream import java.io.IOException import java.util.* class ProfileSelectionResult(private var main: MainView? = null, private var initial: InitialSetupView? = null) { fun profilePictureResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?, uid: String?) { if (resultCode == RESULT_OK) { when (requestCode) { 1 -> { val imageFileName = "profile_picture" val storageDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES) val image = File(storageDir, "$imageFileName.png") CropImage.activity(Uri.fromFile(image)) .setGuidelines(CropImageView.Guidelines.ON) .setAspectRatio(1, 1).setRequestedSize(256, 256) .setFixAspectRatio(true) .start(activity) } 2 -> { val uri = data!!.data if (uri != null) CropImage.activity(uri) .setGuidelines(CropImageView.Guidelines.ON) .setAspectRatio(1, 1).setRequestedSize(256, 256) .setFixAspectRatio(true).start(activity) } } } if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && data != null && uid != null) { val result = CropImage.getActivityResult(data) if (resultCode == RESULT_OK) { val resultUri = result.uri val storageReference = FirebaseStorage.getInstance().reference val profileRef = storageReference.child("profile_pictures/$uid.png") profileRef.putFile(resultUri) .addOnSuccessListener { FirebaseDatabase.getInstance().getReference("picture").child(uid).setValue(Date().time) initial?.onNext() try { val bitmap = MediaStore.Images.Media.getBitmap(activity.contentResolver, resultUri) val file = File(activity.cacheDir, "$uid.png") val fileOutputStream = FileOutputStream(file) bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream) main?.updateProfilePicture() } catch (e: IOException) { e.printStackTrace() } }.addOnFailureListener { Toast.makeText(activity, "Hmm...Something went wrong.\nPlease check your internet connection and try again.", Toast.LENGTH_LONG).show() } } } } }
apache-2.0
27f06a8d6f1f2d453c7d297ccdc2c03f
44.947368
186
0.575888
5.298938
false
false
false
false
jean79/yested_fw
src/jsMain/kotlin/net/yested/ext/moment/moment.kt
1
6878
package net.yested.ext.moment import net.yested.core.properties.Property import net.yested.core.properties.bind @JsModule("moment") @JsNonModule @JsName("moment") external private fun moment_js(): MomentJs = definedExternally @JsModule("moment") @JsNonModule @JsName("moment") external private fun moment_js(millisecondsSinceUnixEpoch: Double): MomentJs = definedExternally @JsModule("moment") @JsNonModule @JsName("moment") external private fun moment_js(input: String, format: String = definedExternally): MomentJs = definedExternally external class MomentJs { fun format(formatString: String? = definedExternally): String = definedExternally // This would be Long except that Kotlin's Long is a Javascript Object. fun valueOf(): Number = definedExternally fun millisecond(value: Int? = definedExternally): Int = definedExternally fun second(value: Int? = definedExternally): Int = definedExternally fun minute(value: Int? = definedExternally): Int = definedExternally fun hour(value: Int? = definedExternally): Int = definedExternally fun date(value: Int? = definedExternally): Int = definedExternally fun day(value: Int? = definedExternally): Int = definedExternally fun weekday(value: Int? = definedExternally): Int = definedExternally fun isoWeekday(value: Int? = definedExternally): Int = definedExternally fun dayOfYear(value: Int? = definedExternally): Int = definedExternally fun week(value: Int? = definedExternally): Int = definedExternally fun isoWeek(value: Int? = definedExternally): Int = definedExternally fun month(value: Int? = definedExternally): Int = definedExternally fun quarter(value: Int? = definedExternally): Int = definedExternally fun year(value: Int? = definedExternally): Int = definedExternally fun weekYear(value: Int? = definedExternally): Int = definedExternally fun isoWeekYear(value: Int? = definedExternally): Int = definedExternally fun weeksInYear(): Int = definedExternally fun locale(localeName: String): Unit = definedExternally fun unix():Int = definedExternally fun unix(t:Int): Unit = definedExternally } class Moment(private val moment: MomentJs) { /** Returns the default ISO format: 2018-03-22T05:55:49-06:00 */ fun format(): String = moment.format() fun format(format: String): String = moment.format(format) fun format(format: FormatString): String = moment.format(format.toString()) val millisecondsSinceUnixEpoch: Long get() = moment.valueOf().toLong() var unix: Int get() = moment.unix() set(value) { moment.unix(value) } var millisecond: Int get() = moment.millisecond() set(value) { moment.millisecond(value) } var second: Int get() = moment.second() set(value) { moment.second(value) } var minute: Int get() = moment.minute() set(value) { moment.minute(value) } var hour: Int get() = moment.hour() set(value) { moment.hour(value) } var dayOfMonth: Int get() = moment.date() set(value) { moment.date(value) } var dayOfYear: Int get() = moment.dayOfYear() set(value) { moment.dayOfYear(value) } var month: Int get() = moment.month() set(value) { moment.month(value) } var year: Int get() = moment.year() set(value) { moment.year(value) } companion object { fun now(): Moment = Moment(moment_js()) fun parse(input: String): Moment = Moment(moment_js(input)) fun parse(input: String, format: String): Moment = Moment(moment_js(input, format)) fun parseMillisecondsSinceUnixEpoch(millisecondsSinceUnixEpoch: Long): Moment { return fromMillisecondsSinceUnixEpoch(millisecondsSinceUnixEpoch) } fun fromMillisecondsSinceUnixEpoch(millisecondsSinceUnixEpoch: Long): Moment { requireNotNull(millisecondsSinceUnixEpoch) return fromMillisecondsSinceUnixEpoch(millisecondsSinceUnixEpoch.toDouble()) } fun fromMillisecondsSinceUnixEpoch(millisecondsSinceUnixEpoch: Double): Moment { requireNotNull(millisecondsSinceUnixEpoch) return Moment(moment_js(millisecondsSinceUnixEpoch)) } fun setLocale(localeName: String) { moment_js().locale(localeName) } } } class FormatElement (val str: String) { fun plus(b: FormatElement): FormatString { return FormatString(arrayListOf(this, b)) } operator fun plus(b: String): FormatString { return FormatString(arrayListOf(this, FormatElement(b))) } } class FormatString(private val elements: MutableList<FormatElement> = arrayListOf()) { operator fun plus(b: FormatElement): FormatString { elements.add(b) return FormatString(elements) } operator fun plus(b: String): FormatString { elements.add(FormatElement(b)) return FormatString(elements) } override fun toString(): String = elements.map { it.str }.joinToString(separator = "") } class Digit(private val oneDigitFactory: ()-> FormatElement, private val twoDigitsFactory: ()-> FormatElement, private val fourDigitsFactory: ()-> FormatElement) { val oneDigit: FormatElement get() = oneDigitFactory() val twoDigits: FormatElement get() = twoDigitsFactory() val fourDigits: FormatElement get() = fourDigitsFactory() } class FormatStringBuilder() { val year: Digit = Digit({throw UnsupportedOperationException("bla")}, {FormatElement("YY")}, {FormatElement("YYYY")}) val month: Digit = Digit({FormatElement("M")}, {FormatElement("MM")}, {throw UnsupportedOperationException()}) val dayOfMonth: Digit = Digit({FormatElement("D")}, {FormatElement("DD")}, {throw UnsupportedOperationException()}) val hour24: Digit = Digit({FormatElement("H")}, {FormatElement("HH")}, {throw UnsupportedOperationException()}) val hour12: Digit = Digit({FormatElement("h")}, {FormatElement("hh")}, {throw UnsupportedOperationException()}) val minutes: Digit = Digit({FormatElement("m")}, {FormatElement("mm")}, {throw UnsupportedOperationException()}) val seconds: Digit = Digit({FormatElement("s")}, {FormatElement("ss")}, {throw UnsupportedOperationException()}) } fun format(init: FormatStringBuilder.() -> FormatString): FormatString { return FormatStringBuilder().init() } fun Property<Moment?>.asText(formatString: String): Property<String> { return this.bind( transform = { if (it == null) "" else it.format(formatString) }, reverse = { if (it.isEmpty()) null else Moment.parse(it, formatString) }) }
mit
a6f3b2d84a018dc62ac9889bc9b5a3d2
38.757225
163
0.670253
4.902352
false
false
false
false
harkwell/khallware
tools/src/main/kotlin/com/khallware/api/util/datastore.kt
1
10459
// Copyright Kevin D.Hall 2018 package com.khallware.api.util import java.sql.DriverManager import java.sql.Connection import java.sql.Statement import java.util.Properties import java.math.BigDecimal class Datastore(props: Properties) { var initialized = false var connection : Connection? = null val jdbcurl = props.getProperty("jdbc_url","jdbc:sqlite:apis.db") val driver = props.getProperty("jdbc_driver", "org.sqlite.JDBC") fun initialize() { if (!initialized) { Class.forName(driver).newInstance() connection = DriverManager.getConnection(jdbcurl) } initialized = true } fun listTags() : ArrayList<Tag> { val retval = ArrayList<Tag>() val sql = "SELECT id,name FROM tags" initialize() connection!!.createStatement().use { var rsltSet = it.executeQuery(sql) while (rsltSet.next()) { with (rsltSet) { retval.add(Tag( getInt("id"), getString("name"))) } } } return(retval) } fun addTag(tag: Tag, parent: Int = 1) : Int { var retval = -1 val sql = """ INSERT INTO tags (name,user,group_,parent) VALUES (?,?,?,?) """ initialize() connection!!.prepareStatement( sql, Statement.RETURN_GENERATED_KEYS).use { it.setString(1, tag.name) it.setInt(2, tag.user) it.setInt(3, tag.group) it.setInt(4, parent) it.execute() val rsltset = it.getGeneratedKeys() if (rsltset.next()) { retval = rsltset.getInt(1) } } return(retval) } fun listBookmarks() : ArrayList<Bookmark> { val retval = ArrayList<Bookmark>() val sql = """ SELECT id,name,url,rating, ( SELECT count(*) FROM bookmark_tags WHERE bookmark = b.id ) AS numtags FROM bookmarks b """ initialize() connection!!.createStatement().use { var rsltSet = it.executeQuery(sql) while (rsltSet.next()) { with (rsltSet) { retval.add(Bookmark( getInt("id"), getString("name"), getString("url"), getString("rating"), getInt("numtags"))) } } } return(retval) } fun addBookmark(bookmark: Bookmark, tag: Int = 1) { val sql1 = """ INSERT INTO bookmarks (name,user,url,group_,rating) VALUES (?,?,?,?,?) """ val sql2 = """ INSERT INTO bookmark_tags (bookmark,tag) VALUES (?,?) """ var id = -1 initialize() connection!!.prepareStatement( sql1, Statement.RETURN_GENERATED_KEYS).use { it.setString(1, bookmark.name) it.setInt(2, bookmark.user) it.setString(3, bookmark.url) it.setInt(4, bookmark.group) it.setString(5, bookmark.rating) it.execute() val rsltset = it.getGeneratedKeys() if (rsltset.next()) { id = rsltset.getInt(1) } } connection!!.prepareStatement(sql2).use { it.setInt(1, id) it.setInt(2, tag) it.execute() } } fun listLocations() : ArrayList<Location> { val retval = ArrayList<Location>() val sql = """ SELECT id,name,latitude,longitude,address, description, ( SELECT count(*) FROM location_tags WHERE location = l.id ) AS numtags FROM locations l """ initialize() connection!!.createStatement().use { var rsltSet = it.executeQuery(sql) while (rsltSet.next()) { with (rsltSet) { retval.add(Location( getInt("id"), getString("name"), BigDecimal(getDouble("lat")), BigDecimal(getDouble("lon")), getString("address"), getString("description"), getInt("numtags"))) } } } return(retval) } fun listContacts() : ArrayList<Contact> { val retval = ArrayList<Contact>() val sql = """ SELECT id,name,uid,email,phone,title,address, organization,vcard,description, ( SELECT count(*) FROM contact_tags WHERE contact = c.id ) AS numtags FROM contacts c """ initialize() connection!!.createStatement().use { var rsltSet = it.executeQuery(sql) while (rsltSet.next()) { with (rsltSet) { retval.add(Contact( getInt("id"), getString("name"), getString("uid"), getString("email"), getString("phone"), getString("title"), getString("address"), getString("organization"), getString("vcard"), getString("description"), getInt("numtags"))) } } } return(retval) } fun listPhotos() : ArrayList<Photo> { val retval = ArrayList<Photo>() val sql = """ SELECT id,name,path,md5sum,description, ( SELECT count(*) FROM photo_tags WHERE photo = p.id ) AS numtags FROM photos p """ initialize() connection!!.createStatement().use { var rsltSet = it.executeQuery(sql) while (rsltSet.next()) { with (rsltSet) { retval.add(Photo( getInt("id"), getString("name"), getString("path"), getString("md5sum"), getString("description"), getInt("numtags"))) } } } return(retval) } fun addPhoto(photo: Photo, tag: Int = 1) { val sql1 = """ INSERT INTO photos (name,path,md5sum,user,group_, description) VALUES (?,?,?,?,?,?) """ val sql2 = """ INSERT INTO photo_tags (photo,tag) VALUES (?,?) """ var id = -1 initialize() connection!!.prepareStatement( sql1, Statement.RETURN_GENERATED_KEYS).use { it.setString(1, photo.name) it.setString(2, photo.path) it.setString(3, photo.md5sum) it.setInt(4, photo.user) it.setInt(5, photo.group) it.setString(6, photo.desc) it.execute() val rsltset = it.getGeneratedKeys() if (rsltset.next()) { id = rsltset.getInt(1) } } connection!!.prepareStatement(sql2).use { it.setInt(1, id) it.setInt(2, tag) it.execute() } } fun listFileItems() : ArrayList<FileItem> { val retval = ArrayList<FileItem>() val sql = """ SELECT id,name,ext,mime,path,md5sum,description, ( SELECT count(*) FROM fileitem_tags WHERE fileitem = f.id ) AS numtags FROM fileitems f """ initialize() connection!!.createStatement().use { var rsltSet = it.executeQuery(sql) while (rsltSet.next()) { with (rsltSet) { retval.add(FileItem( getInt("id"), getString("name"), getString("ext"), getString("md5sum"), getString("description"), getString("mime"), getString("path"), getInt("numtags"))) } } } return(retval) } fun addFileItem(fileitem: FileItem, tag: Int = 1) { val sql1 = """ INSERT INTO fileitems (name,ext,mime,path,md5sum, user,group_, description) VALUES (?,?,?,?,?,?,?,?) """ val sql2 = """ INSERT INTO fileitem_tags (fileitem,tag) VALUES (?,?) """ var id = -1 initialize() connection!!.prepareStatement( sql1, Statement.RETURN_GENERATED_KEYS).use { it.setString(1, fileitem.name) it.setString(2, fileitem.ext) it.setString(3, fileitem.mime) it.setString(4, fileitem.path) it.setString(5, fileitem.md5sum) it.setInt(6, fileitem.user) it.setInt(7, fileitem.group) it.setString(8, fileitem.desc) it.execute() val rsltset = it.getGeneratedKeys() if (rsltset.next()) { id = rsltset.getInt(1) } } connection!!.prepareStatement(sql2).use { it.setInt(1, id) it.setInt(2, tag) it.execute() } } fun addSound(sound: Sound, tag: Int = 1) { val sql1 = """ INSERT INTO sounds (name,path,md5sum, user,group_,description,title,artist,genre, album,publisher) VALUES (?,?,?,?,?,?,?,?,?,?,?) """ val sql2 = """ INSERT INTO sound_tags (sound,tag) VALUES (?,?) """ var id = -1 initialize() connection!!.prepareStatement( sql1, Statement.RETURN_GENERATED_KEYS).use { it.setString(1, sound.name) it.setString(2, sound.path) it.setString(3, sound.md5sum) it.setInt(4, sound.user) it.setInt(5, sound.group) it.setString(6, sound.desc) it.setString(7, sound.title) it.setString(8, sound.artist) it.setString(9, sound.genre) it.setString(10, sound.album) it.setString(11, sound.publisher) it.execute() val rsltset = it.getGeneratedKeys() if (rsltset.next()) { id = rsltset.getInt(1) } } connection!!.prepareStatement(sql2).use { it.setInt(1, id) it.setInt(2, tag) it.execute() } } fun listSounds() : ArrayList<Sound> { val retval = ArrayList<Sound>() val sql = """ SELECT id,name,path,md5sum,title,artist,genre, album,publisher,description, ( SELECT count(*) FROM sound_tags WHERE sound = s.id ) AS numtags FROM sounds s """ initialize() connection!!.createStatement().use { var rsltSet = it.executeQuery(sql) while (rsltSet.next()) { with (rsltSet) { retval.add(Sound( getInt("id"), getString("name"), getString("path"), getString("md5sum"), getString("description"), getString("title"), getString("artist"), getString("genre"), getString("album"), getString("publisher"), getInt("numtags"))) } } } return(retval) } fun listVideos() : ArrayList<Video> { val retval = ArrayList<Video>() val sql = """ SELECT id,name,path,md5sum,description, ( SELECT count(*) FROM video_tags WHERE video = v.id ) AS numtags FROM videos v """ initialize() connection!!.createStatement().use { var rsltSet = it.executeQuery(sql) while (rsltSet.next()) { with (rsltSet) { retval.add(Video( getInt("id"), getString("name"), getString("path"), getString("md5sum"), getString("description"), getInt("numtags"))) } } } return(retval) } fun addVideo(video: Video, tag: Int = 1) { val sql1 = """ INSERT INTO videos (name,path,md5sum,user,group_, description) VALUES (?,?,?,?,?,?) """ val sql2 = """ INSERT INTO video_tags (video,tag) VALUES (?,?) """ var id = -1 initialize() connection!!.prepareStatement( sql1, Statement.RETURN_GENERATED_KEYS).use { it.setString(1, video.name) it.setString(2, video.path) it.setString(3, video.md5sum) it.setInt(4, video.user) it.setInt(5, video.group) it.setString(6, video.desc) it.execute() val rsltset = it.getGeneratedKeys() if (rsltset.next()) { id = rsltset.getInt(1) } } connection!!.prepareStatement(sql2).use { it.setInt(1, id) it.setInt(2, tag) it.execute() } } }
gpl-3.0
d5aebc962f6931701278467d41753489
21.018947
66
0.599101
3.252177
false
false
false
false
f-droid/fdroidclient
libs/download/src/commonMain/kotlin/org/fdroid/download/Mirror.kt
1
2141
package org.fdroid.download import io.ktor.http.URLBuilder import io.ktor.http.URLParserException import io.ktor.http.Url import io.ktor.http.appendPathSegments import mu.KotlinLogging public data class Mirror @JvmOverloads constructor( val baseUrl: String, val location: String? = null, ) { public val url: Url by lazy { try { URLBuilder(baseUrl.trimEnd('/')).build() // we fall back to a non-existent URL if someone tries to sneak in an invalid mirror URL to crash us // to make it easier for potential callers } catch (e: URLParserException) { val log = KotlinLogging.logger {} log.warn { "Someone gave us an invalid URL: $baseUrl" } URLBuilder("http://127.0.0.1:64335").build() } catch (e: IllegalArgumentException) { val log = KotlinLogging.logger {} log.warn { "Someone gave us an invalid URL: $baseUrl" } URLBuilder("http://127.0.0.1:64335").build() } } public fun getUrl(path: String): Url { return URLBuilder(url).appendPathSegments(path).build() } public fun isOnion(): Boolean = url.isOnion() public fun isLocal(): Boolean = url.isLocal() public fun isHttp(): Boolean = url.protocol.name.startsWith("http") public companion object { @JvmStatic public fun fromStrings(list: List<String>): List<Mirror> = list.map { Mirror(it) } } } internal fun Mirror?.isLocal(): Boolean = this?.isLocal() == true internal fun Url.isOnion(): Boolean = host.endsWith(".onion") /** * Returns true when no proxy should be used for connecting to this [Url]. */ internal fun Url.isLocal(): Boolean { if (!host.matches(Regex("[0-9.]{7,15}"))) return false if (host.startsWith("172.")) { val second = host.substring(4..6) if (!second.endsWith('.')) return false val num = second.trimEnd('.').toIntOrNull() ?: return false return num in 16..31 } return host.startsWith("169.254.") || host.startsWith("10.") || host.startsWith("192.168.") || host == "127.0.0.1" }
gpl-3.0
783368341b394ef13ee49b2a26fc98de
32.453125
112
0.621672
4.016886
false
false
false
false
SUPERCILEX/Robot-Scouter
app/server/functions/src/main/kotlin/com/supercilex/robotscouter/server/utils/types/Functions.kt
1
3017
@file:Suppress( "INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "unused", "PropertyName" ) package com.supercilex.robotscouter.server.utils.types import kotlin.js.Json import kotlin.js.Promise val functions by lazy { js("require('firebase-functions')").unsafeCast<Functions>() } val admin by lazy { val admin = js("require('firebase-admin')").unsafeCast<Admin>() admin.initializeApp() admin } external val SDK_VERSION: String = definedExternally external val apps: Array<App> = definedExternally external interface AppOptions { var credential: Credential? get() = definedExternally; set(value) = definedExternally var databaseAuthVariableOverride: Any? get() = definedExternally; set(value) = definedExternally var databaseURL: String? get() = definedExternally; set(value) = definedExternally var storageBucket: String? get() = definedExternally; set(value) = definedExternally var projectId: String? get() = definedExternally; set(value) = definedExternally } external interface Credential { fun getAccessToken(): Promise<GoogleOAuthAccessToken> } external interface GoogleOAuthAccessToken { val access_token: String val expires_in: Number } external interface App { val name: String val options: AppOptions fun firestore(): Firestore fun delete(): Promise<Unit> } external interface AuthContext { var uid: String var token: Any } external interface EventContext { val eventId: String val timestamp: String val eventType: String val params: Json val authType: String? get() = definedExternally val auth: AuthContext? get() = definedExternally } external class Change<out T>(before: T? = definedExternally, after: T? = definedExternally) { val before: T = definedExternally val after: T = definedExternally companion object { fun <T> fromObjects(before: T, after: T): Change<T> = definedExternally fun <T> fromJSON(json: ChangeJson, customizer: ((any: Any) -> T)? = definedExternally): Change<T> = definedExternally } } external interface ChangeJson { val before: Any? get() = definedExternally val after: Any? get() = definedExternally val fieldMask: String? get() = definedExternally } external class Functions { val firestore: NamespaceBuilder = definedExternally val pubsub: Pubsub = definedExternally val https: Https = definedExternally val auth: FunctionsAuth = definedExternally fun runWith(options: dynamic): Functions fun config(): dynamic } external class Admin { fun initializeApp(options: AppOptions? = definedExternally, name: String? = definedExternally): App = definedExternally fun app(name: String? = definedExternally): App = definedExternally fun firestore(app: App? = definedExternally): Firestore = definedExternally fun auth(app: App? = definedExternally): Auth = definedExternally }
gpl-3.0
05fc6278902c0c16853a3f7730faebce
31.095745
125
0.718595
4.557402
false
false
false
false
beyama/winter
winter-compiler/src/main/java/io/jentz/winter/compiler/KotlinMetadataExt.kt
1
1271
package io.jentz.winter.compiler import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.metadata.ImmutableKmProperty import com.squareup.kotlinpoet.metadata.ImmutableKmType import com.squareup.kotlinpoet.metadata.KotlinPoetMetadataPreview import kotlinx.metadata.Flag import kotlinx.metadata.KmClassifier import kotlinx.metadata.KmProperty import kotlinx.metadata.jvm.jvmInternalName @KotlinPoetMetadataPreview val ImmutableKmProperty.hasAccessibleSetter: Boolean get() = Flag.IS_PUBLIC(setterFlags) || Flag.IS_INTERNAL(setterFlags) val KmProperty.isNullable: Boolean get() = Flag.Type.IS_NULLABLE(returnType.flags) @KotlinPoetMetadataPreview fun ImmutableKmType.asTypeName(): TypeName { val tokens = (classifier as KmClassifier.Class).name.jvmInternalName.split("/") val packageParts = tokens.dropLast(1) val classParts = tokens.last().split("$") val className = ClassName(packageParts.joinToString("."), *classParts.toTypedArray()) if (arguments.isNotEmpty()) { val args = arguments.mapNotNull { it.type?.asTypeName() } return className.parameterizedBy(args) } return className }
apache-2.0
48f750a493ec4c4024135db3dde226d8
40
90
0.79701
4.491166
false
false
false
false
chrisbanes/tivi
data/src/main/java/app/tivi/data/mappers/TmdbShowResultsPageToTiviShows.kt
1
1890
/* * Copyright 2018 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 app.tivi.data.mappers import app.tivi.data.entities.ImageType import app.tivi.data.entities.ShowTmdbImage import app.tivi.data.entities.TiviShow import com.uwetrottmann.tmdb2.entities.TvShowResultsPage import javax.inject.Inject import javax.inject.Singleton @Singleton class TmdbShowResultsPageToTiviShows @Inject constructor( private val tmdbShowMapper: TmdbBaseShowToTiviShow ) : Mapper<TvShowResultsPage, List<Pair<TiviShow, List<ShowTmdbImage>>>> { override suspend fun map(from: TvShowResultsPage): List<Pair<TiviShow, List<ShowTmdbImage>>> { return from.results.map { val show = tmdbShowMapper.map(it) val images = ArrayList<ShowTmdbImage>() if (it.poster_path != null) { images += ShowTmdbImage( showId = 0, path = it.poster_path, isPrimary = true, type = ImageType.POSTER ) } if (it.backdrop_path != null) { images += ShowTmdbImage( showId = 0, path = it.backdrop_path, isPrimary = true, type = ImageType.BACKDROP ) } show to images } } }
apache-2.0
c16e598055fd3da899296f5a4d5cfaa9
34
98
0.626984
4.554217
false
false
false
false
actions-on-google/actions-on-google-java
src/main/kotlin/com/google/actions/api/DefaultApp.kt
1
3938
/* * Copyright 2018 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.actions.api import com.google.actions.api.response.ResponseBuilder import org.slf4j.LoggerFactory import java.util.concurrent.CompletableFuture /** * Default implementation of an Actions App. This class provides most of the * functionality of an App such as request parsing and routing. */ abstract class DefaultApp : App { val errorMsg_badReturnValue = "The return value of an intent handler" + " must be ActionResponse or CompletableFuture<ActionResponse>" private companion object { val LOG = LoggerFactory.getLogger(DefaultApp::class.java.name) } /** * Creates an ActionRequest for the specified JSON and metadata. * @param inputJson The input JSON. * @param headers Map containing metadata, usually from the HTTP request * headers. */ abstract fun createRequest(inputJson: String, headers: Map<*, *>?): ActionRequest /** * @return A ResponseBuilder for this App. */ abstract fun getResponseBuilder(request: ActionRequest): ResponseBuilder override fun handleRequest( inputJson: String?, headers: Map<*, *>?): CompletableFuture<String> { if (inputJson == null || inputJson.isEmpty()) { return handleError("Invalid or empty JSON") } val request: ActionRequest val future: CompletableFuture<ActionResponse> try { request = createRequest(inputJson, headers) future = routeRequest(request) } catch (e: Exception) { return handleError(e) } return future .thenApply { it.toJson() } .exceptionally { throwable -> throwable.message } } @Throws(Exception::class) fun routeRequest(request: ActionRequest): CompletableFuture<ActionResponse> { val intent = request.intent val forIntentType = ForIntent::class.java for (method in javaClass.declaredMethods) { if (method.isAnnotationPresent(forIntentType)) { val annotation = method.getAnnotation(forIntentType) val forIntent = annotation as ForIntent if (forIntent.value == intent) { val result = method.invoke(this, request) return if (result is ActionResponse) { CompletableFuture.completedFuture(result) } else if (result is CompletableFuture<*>) { result as CompletableFuture<ActionResponse> } else { LOG.warn(errorMsg_badReturnValue) throw Exception(errorMsg_badReturnValue) } } } } // Unable to find a method with the annotation matching the intent. LOG.warn("Intent handler not found: {}", intent) throw Exception("Intent handler not found - $intent") } fun handleError(exception: Exception): CompletableFuture<String> { exception.printStackTrace() return handleError(exception.message) } private fun handleError(message: String?): CompletableFuture<String> { val future = CompletableFuture<String>() future.completeExceptionally(Exception(message)) return future } }
apache-2.0
cd8d9066e5ab91feeb0d49d920e265e2
36.150943
81
0.640427
5.094437
false
false
false
false
devunt/ika
app/src/main/kotlin/org/ozinger/ika/service/command/commands/AdminServiceCommands.kt
1
7029
package org.ozinger.ika.service.command.commands import org.jetbrains.exposed.sql.transactions.transaction import org.ozinger.ika.annotation.ServiceCommand import org.ozinger.ika.channel.OutgoingPacketChannel import org.ozinger.ika.command.CHGHOST import org.ozinger.ika.command.FMODE import org.ozinger.ika.command.NOTICE import org.ozinger.ika.database.models.Account import org.ozinger.ika.definition.* import org.ozinger.ika.enumeration.Permission import org.ozinger.ika.serialization.format.IRCFormat import org.ozinger.ika.serialization.serializer.ChannelModeChangelistSerializer import org.ozinger.ika.serialization.serializer.UserModeChangelistSerializer import org.ozinger.ika.service.Service import org.ozinger.ika.state.IRCChannels import org.ozinger.ika.state.IRCUsers object AdminServiceCommands { @ServiceCommand( name = "공지", aliases = ["ANN", "ANNOUNCE"], syntax = "<내용>", summary = "모든 IRC 채널에 공지사항을 출력합니다.", description = "NOTICE를 이용해 채널 라인으로 출력하므로 주의하십시오.\n" + "명령을 실행하는 순간 발송하므로 명령을 실행하기 전 다시 한번 공지사항의 내용을 확인해주세요.\n", permission = Permission.ADMIN, ) suspend fun announce(sender: UniversalUserId, content: String) { Service.sendMessageAsServiceUser(sender, "${IRCChannels.size}개 채널에 공지사항을 발송합니다.") IRCChannels.forEach { Service.sendAsServiceUser(NOTICE(it.name, " \u0002[공지]\u0002 $content")) } Service.sendMessageAsServiceUser(sender, "${IRCChannels.size}개 채널에 공지사항을 발송했습니다.") } @ServiceCommand( name = "모드", aliases = ["MODE"], syntax = "<대상> {모드}", summary = "특정 대상의 모드를 강제로 변경합니다.", description = "이 명령을 사용할 시 해당 유저 혹은 채널의 모드를 강제로 변경합니다.", permission = Permission.ADMIN, ) suspend fun mode(sender: UniversalUserId, target: String, modeChange: String) { if (target.startsWith("#")) { val channelName = ChannelName(target) if (channelName !in IRCChannels) { Service.sendErrorMessageAsServiceUser(sender, "\u0002$target\u0002 채널이 존재하지 않습니다.") return } val ircChannel = IRCChannels[channelName] val modeChangelist = try { IRCFormat.decodeFromString(ChannelModeChangelistSerializer, modeChange) } catch (ex: Throwable) { Service.sendErrorMessageAsServiceUser(sender, "모드 파싱에 실패했습니다.") return } val transform = { mode: IMode -> if (mode is EphemeralMemberMode) { val user = IRCUsers.first { it.nickname.equals(mode.target, ignoreCase = true) } MemberMode(user.id, mode.mode) } else { mode } } val transformedModeChangelist = try { ModeChangelist( adding = modeChangelist.adding.map(transform).toSet(), removing = modeChangelist.removing.map(transform).toSet(), ) } catch (ex: NoSuchElementException) { Service.sendErrorMessageAsServiceUser(sender, "모드 변환에 실패했습니다.") return } Service.sendAsServiceUser(FMODE(channelName, ircChannel.timestamp, transformedModeChangelist)) Service.sendMessageAsServiceUser(sender, "\u0002$target\u0002 채널에 \u0002$modeChange\u0002 모드를 적용했습니다.") } else { val user = IRCUsers.firstOrNull { it.nickname.equals(target, ignoreCase = true) } if (user == null) { Service.sendErrorMessageAsServiceUser(sender, "\u0002$target\u0002 사용자가 존재하지 않습니다.") return } val modeChangelist = try { IRCFormat.decodeFromString(UserModeChangelistSerializer, modeChange) } catch (ex: Throwable) { Service.sendErrorMessageAsServiceUser(sender, "모드 파싱에 실패했습니다.") return } Service.sendAsServiceUser(FMODE(user.id, user.timestamp, modeChangelist)) Service.sendMessageAsServiceUser(sender, "\u0002$target\u0002 사용자에 \u0002$modeChange\u0002 모드를 적용했습니다.") } } @ServiceCommand( name = "강제비밀번호변경", aliases = ["FCHANGEPASSWORD"], syntax = "<계정명> <새 비밀번호>", summary = "오징어 IRC 네트워크에 등록되어 있는 계정의 비밀번호를 강제로 변경합니다.", description = "이 명령을 사용할 시 해당 계정의 비밀번호를 강제로 변경합니다.", permission = Permission.ADMIN, ) suspend fun forceChangePassword(sender: UniversalUserId, accountName: String, password: String) { val account = transaction { Account.getByNickname(accountName) } if (account == null) { Service.sendErrorMessageAsServiceUser(sender, "\u0002$accountName\u0002 계정이 존재하지 않습니다.") return } transaction { account.changePassword(password) } Service.sendMessageAsServiceUser( sender, "\u0002$accountName\u0002 계정의 비밀번호가 \u0002${password}\u0002 (으)로 강제 변경되었습니다." ) } @ServiceCommand( name = "강제가상호스트변경", aliases = ["FCHANGEVHOST"], syntax = "<계정명> [새 가상 호스트]", summary = "오징어 IRC 네트워크에 등록되어 있는 계정의 가상 호스트를 강제로 변경합니다.", description = "이 명령을 사용할 시 해당 계정의 가상 호스트를 강제로 설정하거나 삭제할 수 있습니다.", permission = Permission.ADMIN, ) suspend fun forceChangeVhost(sender: UniversalUserId, accountName: String, vhost: String?) { val account = transaction { Account.getByNickname(accountName) } if (account == null) { Service.sendErrorMessageAsServiceUser(sender, "\u0002$accountName\u0002 계정이 존재하지 않습니다.") return } transaction { account.vhost = vhost ?: "" } if (vhost != null) { OutgoingPacketChannel.sendAsServer(CHGHOST(sender, vhost)) } Service.sendMessageAsServiceUser( sender, "\u0002$accountName\u0002 계정의 가상 호스트가 \u0002${vhost}\u0002 (으)로 강제 변경되었습니다." ) } }
agpl-3.0
bfeac7c56d0f90b7e6185af3e94aa4a0
37.677215
116
0.616266
4.101342
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/lang/core/types/ty/Ty.kt
1
2206
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.types.ty import org.rust.lang.core.psi.RsTypeParameter import org.rust.lang.core.resolve.ImplLookup typealias Substitution = Map<TyTypeParameter, Ty> typealias TypeMapping = MutableMap<TyTypeParameter, Ty> val emptySubstitution: Substitution = emptyMap() /** * Represents both a type, like `i32` or `S<Foo, Bar>`, as well * as an unbound constructor `S`. * * The name `Ty` is short for `Type`, inspired by the Rust * compiler. */ interface Ty { /** * Checks if `other` type may be represented as this type. * * Note that `t1.unifyWith(t2)` is not the same as `t2.unifyWith(t1)`. */ fun unifyWith(other: Ty, lookup: ImplLookup): UnifyResult /** * Substitute type parameters for their values * * This works for `struct S<T> { field: T }`, when we * know the type of `T` and want to find the type of `field`. */ fun substitute(subst: Substitution): Ty = this /** * Bindings between formal type parameters and actual type arguments. */ val typeParameterValues: Substitution get() = emptySubstitution /** * User visible string representation of a type */ override fun toString(): String } enum class Mutability { MUTABLE, IMMUTABLE; val isMut: Boolean get() = this == MUTABLE companion object { fun valueOf(mutable: Boolean): Mutability = if (mutable) MUTABLE else IMMUTABLE } } fun Ty.getTypeParameter(name: String): TyTypeParameter? { return typeParameterValues.keys.find { it.toString() == name } } fun getMoreCompleteType(ty1: Ty, ty2: Ty): Ty { return when { ty1 is TyUnknown -> ty2 ty1 is TyNever -> ty2 ty1 is TyInteger && ty2 is TyInteger && ty1.isKindWeak -> ty2 ty1 is TyFloat && ty2 is TyFloat && ty1.isKindWeak -> ty2 else -> ty1 } } fun Substitution.substituteInValues(map: Substitution): Substitution = mapValues { (_, value) -> value.substitute(map) } fun Substitution.get(psi: RsTypeParameter): Ty? { return get(TyTypeParameter.named((psi))) }
mit
5c3a068fae3f20e0f71fd29fa6a6ed3c
26.575
74
0.658658
3.932264
false
false
false
false
uber/RIBs
android/demos/compose/src/main/kotlin/com/uber/rib/compose/root/main/logged_in/tic_tac_toe/TicTacToeView.kt
1
3579
/* * Copyright (C) 2021. Uber Technologies * * 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.uber.rib.compose.root.main.logged_in.tic_tac_toe import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.uber.rib.compose.util.EventStream @OptIn(ExperimentalFoundationApi::class) @Composable fun TicTacToeView(viewModel: State<TicTacToeViewModel>, eventStream: EventStream<TicTacToeEvent>) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Top, modifier = Modifier .fillMaxSize() .background(Color.Blue) ) { Text("Current Player: ${viewModel.value.currentPlayer}", color = Color.White) Box( modifier = Modifier .aspectRatio(1f) .fillMaxSize() ) { LazyVerticalGrid(columns = GridCells.Fixed(3), modifier = Modifier.fillMaxSize()) { val board = viewModel.value.board items(9) { i -> val row = i / 3 val col = i % 3 Text( text = when (board.cells[row][col]) { Board.MarkerType.CROSS -> "X" Board.MarkerType.NOUGHT -> "O" else -> " " }, textAlign = TextAlign.Center, modifier = Modifier .fillMaxWidth() .aspectRatio(1f) .padding(16.dp) .background(Color.LightGray) .clickable( enabled = board.cells[row][col] == null, onClick = { eventStream.notify(TicTacToeEvent.BoardClick(BoardCoordinate(row, col))) } ) .padding(32.dp) ) } } } } } @Preview @Composable fun ProductSelectionViewPreview() { val board = Board() board.cells[0][2] = Board.MarkerType.CROSS board.cells[1][0] = Board.MarkerType.NOUGHT board.cells[2][1] = Board.MarkerType.CROSS val viewModel = remember { mutableStateOf(TicTacToeViewModel("James", board)) } TicTacToeView(viewModel, EventStream()) }
apache-2.0
99a1fa5983388ac96334a27e5170e473
35.151515
99
0.700754
4.354015
false
false
false
false
wuseal/JsonToKotlinClass
src/main/kotlin/wu/seal/jsontokotlin/model/codeelements/KName.kt
1
1814
package wu.seal.jsontokotlin.model.codeelements /** * Name class * Created by Seal.Wu on 2017/9/21. */ interface IKName { fun getName(rawName: String): String } abstract class KName : IKName { private val suffix = "X" protected val illegalNameList = listOf( "as", "break", "class", "continue", "do", "else", "false", "for", "fun", "if", "in", "interface", "is", "null" , "object", "package", "return", "super", "this", "throw", "true", "try", "typealias", "val", "var", "when", "while" ) protected val illegalCharacter = listOf( "\\+", "\\-", "\\*", "/", "%", "=", "&", "\\|", "!", "\\[", "\\]", "\\{", "\\}", "\\(", "\\)", "\\\\", "\"", "_" , ",", ":", "\\?", "\\>", "\\<", "@", ";", "'", "\\`", "\\~", "\\$", "\\^", "#", "\\", "/", " ", "\t", "\n" ) protected val nameSeparator = listOf(" ", "_", "\\-", ":","\\.") /** * remove the start number or whiteSpace characters in this string */ protected fun removeStartNumberAndIllegalCharacter(it: String): String { val numberAndIllegalCharacters = listOf(*illegalCharacter.toTypedArray(), "\\d") val firstNumberAndIllegalCharactersRegex = "^(${numberAndIllegalCharacters.toRegex()})+".toRegex() return it.trim().replaceFirst(firstNumberAndIllegalCharactersRegex, "") } protected fun toBeLegalName(name: String): String { val tempName = name.replace(illegalCharacter.toRegex(), "") return if (tempName in illegalNameList) { tempName + suffix } else { tempName } } /** * array string into regex match patten that could match any element of the array */ protected fun Iterable<String>.toRegex() = joinToString(separator = "|").toRegex() }
gpl-3.0
7ae9c58f07773c58c2e70498f4c516fa
27.793651
128
0.53473
4.113379
false
false
false
false
NordicSemiconductor/Android-nRF-Toolbox
app/src/main/java/no/nordicsemi/android/nrftoolbox/view/FeatureButton.kt
1
4724
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.nrftoolbox.view import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import no.nordicsemi.android.theme.ScreenSection import no.nordicsemi.android.nrftoolbox.R @Composable fun FeatureButton( @DrawableRes iconId: Int, @StringRes nameCode: Int, @StringRes name: Int, isRunning: Boolean? = null, @StringRes description: Int? = null, onClick: () -> Unit ) { ScreenSection(onClick = onClick) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { val color = if (isRunning == true) { colorResource(id = R.color.nordicGrass) } else { MaterialTheme.colorScheme.secondary } Image( painter = painterResource(iconId), contentDescription = stringResource(id = name), contentScale = ContentScale.Crop, colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.onSecondary), modifier = Modifier .size(64.dp) .clip(CircleShape) .background(color) .padding(16.dp) ) Spacer(modifier = Modifier.size(16.dp)) Column(modifier = Modifier.weight(1f)) { Text( modifier = Modifier.fillMaxWidth(), text = stringResource(id = name), style = MaterialTheme.typography.bodyLarge, textAlign = TextAlign.Center ) description?.let { Spacer(modifier = Modifier.size(4.dp)) Text( modifier = Modifier.fillMaxWidth(), text = stringResource(id = it), style = MaterialTheme.typography.labelMedium, textAlign = TextAlign.Center, color = MaterialTheme.colorScheme.onSurfaceVariant ) } } } } } @Preview @Composable private fun FeatureButtonPreview() { FeatureButton(R.drawable.ic_csc, R.string.csc_module, R.string.csc_module_full) { } }
bsd-3-clause
32e1cb2df406ab5ae87e5d25900c3b4a
38.366667
89
0.67464
4.915713
false
false
false
false
SimpleTimeTracking/StandaloneClient
src/main/kotlin/org/stt/gui/jfx/FramelessButton.kt
1
1106
package org.stt.gui.jfx import javafx.scene.Node import javafx.scene.control.Button internal class FramelessButton(node: Node) : Button() { private var releasedStyle = STYLE_NORMAL init { graphic = node style = STYLE_NORMAL setOnMousePressed { style = STYLE_PRESSED } setOnMouseReleased { style = releasedStyle } setOnMouseEntered { setStyleAndReleaseStyle(STYLE_HOVER) } setOnMouseExited { setStyleAndReleaseStyle(STYLE_NORMAL) } } private fun setStyleAndReleaseStyle(style: String) { setStyle(style) releasedStyle = style } companion object { private const val STYLE_HOVER = "-fx-background-color: transparent; -fx-padding: 5; -fx-effect: innershadow(gaussian, rgba(60, 100, 220, 0.8), 20, 0.5, 2, 2);" private const val STYLE_NORMAL = "-fx-background-color: transparent; -fx-padding: 5; -fx-effect: null" private const val STYLE_PRESSED = "-fx-background-color: transparent; -fx-padding: 7 4 3 6; -fx-effect: innershadow(gaussian, rgba(60, 100, 220, 0.8), 20, 0.5, 2, 2);" } }
gpl-3.0
5b2456d519e3c8fedff48071520d3350
33.5625
175
0.667269
3.736486
false
false
false
false
TheFallOfRapture/Morph
src/main/kotlin/com/morph/engine/script/ScriptContainer.kt
2
1237
package com.morph.engine.script import com.morph.engine.core.Game import com.morph.engine.entities.Component import com.morph.engine.entities.Entity import com.morph.engine.util.ScriptUtils import java.util.* /** * Created on 7/5/2017. */ class ScriptContainer(private val game: Game) : Component() { private val behaviors: HashMap<String, EntityBehavior> = HashMap() fun addBehavior(filename: String) { ScriptUtils.getScriptBehaviorAsync(filename).subscribe({ behavior -> val eBehavior = behavior as EntityBehavior eBehavior.setGame(game) eBehavior.self = parent behaviors[filename] = eBehavior eBehavior.init() eBehavior.start() }) } fun replaceBehavior(filename: String, newBehavior: EntityBehavior) { newBehavior.setGame(game) newBehavior.self = parent behaviors.replace(filename, newBehavior) newBehavior.start() } fun removeBehavior(filename: String) { val behavior = behaviors[filename] behaviors.remove(filename) behavior?.destroy() } fun getBehaviors(): List<EntityBehavior> { return ArrayList<EntityBehavior>(behaviors.values) } }
mit
c56868fa24aead024e660b6d3063369a
28.452381
76
0.67017
4.514599
false
false
false
false
travisobregon/kotlin-koans
src/i_introduction/_5_String_Templates/n05StringTemplates.kt
1
1180
package i_introduction._5_String_Templates import util.TODO import util.doc5 fun example1(a: Any, b: Any) = "This is some text in which variables ($a, $b) appear." fun example2(a: Any, b: Any) = "You can write it in a Java way as well. Like this: " + a + ", " + b + "!" fun example3(c: Boolean, x: Int, y: Int) = "Any expression can be used: ${if (c) x else y}" fun example4() = """ You can use raw strings to write multiline text. There is no escaping here, so raw strings are useful for writing regex patterns, you don't need to escape a backslash by a backslash. String template entries (${42}) are allowed here. """ fun getPattern() = """\d{2}\.\d{2}\.\d{4}""" fun example() = "13.06.1992".matches(getPattern().toRegex()) //true val month = "(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)" fun todoTask5(): Nothing = TODO( """ Task 5. Copy the body of 'getPattern()' to the 'task5()' function below and rewrite it in such a way that it matches '13 JUN 1992'. Use the 'month' variable. """, documentation = doc5(), references = { getPattern(); month }) fun task5() = """\d{2} $month \d{4}"""
mit
1b52690edd86e7c034a35852b3cb12a0
30.052632
91
0.622881
3.259669
false
false
false
false
blackbbc/Tucao
app/src/main/kotlin/me/sweetll/tucao/business/download/adapter/DownloadingVideoAdapter.kt
1
7236
package me.sweetll.tucao.business.download.adapter import android.widget.CheckBox import android.widget.ImageView import android.widget.LinearLayout import com.chad.library.adapter.base.BaseMultiItemQuickAdapter import com.chad.library.adapter.base.BaseViewHolder import com.chad.library.adapter.base.entity.MultiItemEntity import com.trello.rxlifecycle2.kotlin.bindToLifecycle import io.reactivex.android.schedulers.AndroidSchedulers import me.sweetll.tucao.R import me.sweetll.tucao.business.download.DownloadActivity import me.sweetll.tucao.model.json.Part import me.sweetll.tucao.model.json.StateController import me.sweetll.tucao.model.json.Video import me.sweetll.tucao.business.video.VideoActivity import me.sweetll.tucao.extension.DownloadHelpers import me.sweetll.tucao.extension.load import me.sweetll.tucao.extension.logD import me.sweetll.tucao.extension.toast import me.sweetll.tucao.rxdownload.RxDownload import me.sweetll.tucao.rxdownload.entity.DownloadEvent import me.sweetll.tucao.rxdownload.entity.DownloadStatus import java.util.concurrent.TimeUnit class DownloadingVideoAdapter(val downloadActivity: DownloadActivity, data: MutableList<MultiItemEntity>?): BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder>(data) { companion object { const val TYPE_VIDEO = 0 const val TYPE_PART = 1 } val rxDownload: RxDownload by lazy { RxDownload.getInstance(mContext) } init { addItemType(TYPE_VIDEO, R.layout.item_downloaded_video) addItemType(TYPE_PART, R.layout.item_downloaded_part) } override fun convert(helper: BaseViewHolder, item: MultiItemEntity) { when (helper.itemViewType) { TYPE_VIDEO -> { val video = item as Video helper.setText(R.id.text_title, video.title) helper.setGone(R.id.text_size, false) val thumbImg = helper.getView<ImageView>(R.id.img_thumb) thumbImg.load(mContext, video.thumb) helper.setGone(R.id.checkbox, video.checkable) val checkBox = helper.getView<CheckBox>(R.id.checkbox) checkBox.isChecked = video.checked checkBox.setOnCheckedChangeListener { _, checked -> video.checked = checked updateMenu() } helper.itemView.setOnClickListener { if (video.checkable) { checkBox.isChecked = !checkBox.isChecked video.subItems.forEach { it.checked = checkBox.isChecked } if (video.isExpanded) { notifyItemRangeChanged(helper.adapterPosition + 1, video.subItems.size) } updateMenu() } else { if (video.isExpanded) { collapse(helper.adapterPosition) } else { expand(helper.adapterPosition) } } } helper.getView<LinearLayout>(R.id.linear_detail).setOnClickListener { VideoActivity.intentTo(mContext, video.hid) } } TYPE_PART -> { val part = item as Part part.stateController = StateController(helper.getView(R.id.text_size), helper.getView(R.id.img_status), helper.getView(R.id.progress)) helper.setText(R.id.text_title, part.title) rxDownload.receive(part.vid) .bindToLifecycle(downloadActivity) .sample(500, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ (status, downloadSize, totalSize) -> "接收下载状态....".logD() val newEvent = DownloadEvent(status, downloadSize, totalSize) if (part.flag == DownloadStatus.COMPLETED) { // DownloadHelpers.saveDownloadPart(part) } else { part.stateController?.setEvent(newEvent) } }, { error -> error.printStackTrace() error.message?.toast() }) helper.setGone(R.id.checkbox, part.checkable) val checkBox = helper.getView<CheckBox>(R.id.checkbox) checkBox.isChecked = part.checked checkBox.setOnCheckedChangeListener { _, checked -> part.checked = checked updateMenu() } helper.itemView.setOnClickListener { if (part.checkable) { checkBox.isChecked = !checkBox.isChecked val parentVideo = data.find { video -> (video is Video) && video.subItems.any { it.vid == part.vid } } as Video val currentPosition = parentVideo.subItems.indexOf(part) val newParentChecked = parentVideo.subItems.all(Part::checked) if (newParentChecked != parentVideo.checked) { parentVideo.checked = newParentChecked notifyItemChanged(helper.adapterPosition - 1 - currentPosition) } updateMenu() } else { val parentVideo = data.find { video -> (video is Video) && video.subItems.any { it.vid == part.vid } } as Video val callback = object : DownloadHelpers.Callback { override fun startDownload() { DownloadHelpers.resumeDownload(parentVideo, part) } override fun pauseDownload() { DownloadHelpers.pauseDownload(part) } } part.stateController?.handleClick(callback) } } } } } fun updateMenu() { val deleteEnabled = data.any { when (it) { is Video -> it.checked is Part -> it.checked else -> false } } val isPickAll = data.all { when (it) { is Video -> it.checked is Part -> it.checked else -> false } } downloadActivity.updateBottomMenu(deleteEnabled, isPickAll) } override fun getItemViewType(position: Int): Int { val type = super.getItemViewType(position) return type } }
mit
053d334e9fc383193d715ed1186de51a
40.757225
174
0.520626
5.587007
false
false
false
false
openMF/android-client
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/savingsaccountactivate/SavingsAccountActivateFragment.kt
1
5904
/* * This project is licensed under the open source MPL V2. * See https://github.com/openMF/android-client/blob/master/LICENSE.md */ package com.mifos.mifosxdroid.online.savingsaccountactivate import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import androidx.fragment.app.DialogFragment import butterknife.BindView import butterknife.ButterKnife import butterknife.OnClick import com.mifos.api.GenericResponse import com.mifos.mifosxdroid.R import com.mifos.mifosxdroid.core.MifosBaseActivity import com.mifos.mifosxdroid.core.MifosBaseFragment import com.mifos.mifosxdroid.core.util.Toaster import com.mifos.mifosxdroid.uihelpers.MFDatePicker import com.mifos.mifosxdroid.uihelpers.MFDatePicker.OnDatePickListener import com.mifos.objects.accounts.savings.DepositType import com.mifos.utils.Constants import com.mifos.utils.DateHelper import com.mifos.utils.FragmentConstants import com.mifos.utils.SafeUIBlockingUtility import java.util.* import javax.inject.Inject /** * Created by Tarun on 01/06/17. * Fragment to allow user to select a date for account approval. * It uses the same layout as Savings Account Approve Fragment. */ class SavingsAccountActivateFragment : MifosBaseFragment(), OnDatePickListener, SavingsAccountActivateMvpView { val LOG_TAG = javaClass.simpleName @JvmField @BindView(R.id.tv_approval_date_on) var tvActivateDateHeading: TextView? = null @JvmField @BindView(R.id.tv_approval_date) var tvActivationDate: TextView? = null @JvmField @BindView(R.id.btn_approve_savings) var btnActivateSavings: Button? = null @JvmField @BindView(R.id.et_savings_approval_reason) var etSavingsActivateReason: EditText? = null @JvmField @Inject var mSavingsAccountActivatePresenter: SavingsAccountActivatePresenter? = null lateinit var rootView: View var activationDate: String? = null var savingsAccountNumber = 0 var savingsAccountType: DepositType? = null private var mfDatePicker: DialogFragment? = null private var safeUIBlockingUtility: SafeUIBlockingUtility? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity as MifosBaseActivity?)!!.activityComponent.inject(this) if (arguments != null) { savingsAccountNumber = requireArguments().getInt(Constants.SAVINGS_ACCOUNT_NUMBER) savingsAccountType = requireArguments().getParcelable(Constants.SAVINGS_ACCOUNT_TYPE) } setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment activity?.actionBar?.setDisplayHomeAsUpEnabled(true) rootView = inflater.inflate(R.layout.dialog_fragment_approve_savings, null) ButterKnife.bind(this, rootView) mSavingsAccountActivatePresenter!!.attachView(this) safeUIBlockingUtility = SafeUIBlockingUtility(activity, getString(R.string.savings_account_loading_message)) showUserInterface() return rootView } override fun showUserInterface() { etSavingsActivateReason!!.visibility = View.GONE tvActivateDateHeading!!.text = resources.getString(R.string.activated_on) mfDatePicker = MFDatePicker.newInsance(this) tvActivationDate!!.text = MFDatePicker.getDatePickedAsString() activationDate = tvActivationDate!!.text.toString() showActivationDate() } @OnClick(R.id.btn_approve_savings) fun onClickActivateSavings() { val hashMap = HashMap<String, Any?>() hashMap["dateFormat"] = "dd MMMM yyyy" hashMap["activatedOnDate"] = activationDate hashMap["locale"] = "en" mSavingsAccountActivatePresenter!!.activateSavings(savingsAccountNumber, hashMap) } @OnClick(R.id.tv_approval_date) fun onClickApprovalDate() { mfDatePicker!!.show(requireActivity().supportFragmentManager, FragmentConstants.DFRAG_DATE_PICKER) } override fun onDatePicked(date: String) { tvActivationDate!!.text = date activationDate = date showActivationDate() } fun showActivationDate() { activationDate = DateHelper.getDateAsStringUsedForCollectionSheetPayload(activationDate) .replace("-", " ") } override fun showSavingAccountActivatedSuccessfully(genericResponse: GenericResponse?) { Toaster.show(tvActivateDateHeading, resources.getString(R.string.savings_account_activated)) Toast.makeText(activity, "Savings Activated", Toast.LENGTH_LONG).show() requireActivity().supportFragmentManager.popBackStack() } override fun showError(message: String?) { Toast.makeText(activity, message, Toast.LENGTH_LONG).show() } override fun showProgressbar(b: Boolean) { if (b) { safeUIBlockingUtility!!.safelyBlockUI() } else { safeUIBlockingUtility!!.safelyUnBlockUI() } } override fun onDestroyView() { super.onDestroyView() mSavingsAccountActivatePresenter!!.detachView() } companion object { fun newInstance(savingsAccountNumber: Int, type: DepositType?): SavingsAccountActivateFragment { val savingsAccountApproval = SavingsAccountActivateFragment() val args = Bundle() args.putInt(Constants.SAVINGS_ACCOUNT_NUMBER, savingsAccountNumber) args.putParcelable(Constants.SAVINGS_ACCOUNT_TYPE, type) savingsAccountApproval.arguments = args return savingsAccountApproval } } }
mpl-2.0
c09867646310c656a732fe5a10e92277
36.373418
116
0.722392
4.907731
false
false
false
false
TangHao1987/intellij-community
plugins/settings-repository/src/IcsUrlBuilder.kt
28
704
package org.jetbrains.settingsRepository import com.intellij.openapi.components.RoamingType import com.intellij.openapi.util.SystemInfo val PROJECTS_DIR_NAME: String = "_projects/" private fun getOsFolderName() = when { SystemInfo.isMac -> "_mac" SystemInfo.isWindows -> "_windows" SystemInfo.isLinux -> "_linux" SystemInfo.isFreeBSD -> "_freebsd" SystemInfo.isUnix -> "_unix" else -> "_unknown" } fun buildPath(path: String, roamingType: RoamingType, projectKey: String? = null): String { fun String.osIfNeed() = if (roamingType == RoamingType.PER_OS) "${getOsFolderName()}/$this" else this return if (projectKey == null) path.osIfNeed() else "$PROJECTS_DIR_NAME$projectKey/$path" }
apache-2.0
8761b44eabddfd24f5b47609bedb4d65
32.571429
103
0.730114
3.868132
false
false
false
false
apiote/Bimba
app/src/main/java/ml/adamsprogs/bimba/models/Departure.kt
1
3497
package ml.adamsprogs.bimba.models import android.content.Context import ml.adamsprogs.bimba.Declinator import ml.adamsprogs.bimba.R import ml.adamsprogs.bimba.rollTime import ml.adamsprogs.bimba.safeSplit import java.util.* data class Departure(val line: String, val mode: List<Int>, val time: Int, val lowFloor: Boolean, //time in seconds since midnight val modification: List<String>, val headsign: String, val vm: Boolean = false, var tomorrow: Boolean = false, val onStop: Boolean = false, val ticketMachine: Int= TICKET_MACHINE_NONE) { val isModified: Boolean get() { return modification.isNotEmpty() } override fun toString(): String { return "$line|${mode.joinToString(";")}|$time|$lowFloor|${modification.joinToString(";")}|$headsign|$vm|$tomorrow|$onStop|$ticketMachine" } fun copy(): Departure { return Departure.fromString(this.toString()) } companion object { const val TICKET_MACHINE_NONE = 0 const val TICKET_MACHINE_AUTOMAT = 1 const val TICKET_MACHINE_DRIVER = 2 fun fromString(string: String): Departure { val array = string.split("|") if (array.size != 10) throw IllegalArgumentException() val modification = array[4].safeSplit(";")!! return Departure(array[0], array[1].safeSplit(";")!!.map { Integer.parseInt(it) }, Integer.parseInt(array[2]), array[3] == "true", modification, array[5], array[6] == "true", array[7] == "true", array[8] == "true", Integer.parseInt(array[9])) } } fun timeTill(relativeTo: Int): Int { var time = this.time if (this.tomorrow) time += 24 * 60 * 60 return (time - relativeTo) / 60 } val lineText: String = line fun timeTillText(context: Context, relativeTime: Boolean = true): String { val now = Calendar.getInstance() val departureTime = Calendar.getInstance().rollTime(time) if (tomorrow) departureTime.add(Calendar.DAY_OF_MONTH, 1) val departureIn = ((departureTime.timeInMillis - now.timeInMillis) / (1000 * 60)).toInt() return if (departureIn > 60 || departureIn < 0 || !relativeTime) context.getString(R.string.departure_at, "${String.format("%02d", departureTime.get(Calendar.HOUR_OF_DAY))}:${String.format("%02d", departureTime.get(Calendar.MINUTE))}") else if (departureIn > 0 && !onStop) context.getString(Declinator.decline(departureIn), departureIn.toString()) else if (departureIn == 0 && !onStop) context.getString(R.string.in_a_moment) else if (departureIn == 0) context.getString(R.string.now) else context.getString(R.string.just_departed) } fun timeAtMessage(context: Context): String { val departureTime = Calendar.getInstance().rollTime(time) if (tomorrow) departureTime.add(Calendar.DAY_OF_MONTH, 1) return context.getString(R.string.departure_at, "${String.format("%02d", departureTime.get(Calendar.HOUR_OF_DAY))}:${String.format("%02d", departureTime.get(Calendar.MINUTE))}") + if (isModified) " " + modification.joinToString("; ", "(", ")") else "" } }
gpl-3.0
3daf979355415d772782a5e19e147799
39.674419
182
0.595939
4.344099
false
false
false
false
vilnius/tvarkau-vilniu
app/src/main/java/lt/vilnius/tvarkau/fragments/NewReportFragment.kt
1
25702
package lt.vilnius.tvarkau.fragments import android.Manifest import android.app.Activity import android.app.DatePickerDialog import android.app.Dialog import android.app.ProgressDialog import android.app.TimePickerDialog import android.content.Intent import android.location.Address import android.location.Geocoder import android.os.Bundle import android.support.design.widget.TextInputLayout import android.support.v4.app.ActivityOptionsCompat import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.support.v7.content.res.AppCompatResources import android.util.Patterns import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.DatePicker import android.widget.EditText import android.widget.TimePicker import android.widget.Toast import com.google.android.gms.location.places.ui.PlacePicker import com.google.android.gms.maps.model.LatLng import kotlinx.android.synthetic.main.app_bar.* import kotlinx.android.synthetic.main.fragment_new_report.* import kotlinx.android.synthetic.main.image_picker_dialog.view.* import lt.vilnius.tvarkau.FullscreenImageActivity import lt.vilnius.tvarkau.R import lt.vilnius.tvarkau.activity.ActivityConstants import lt.vilnius.tvarkau.activity.ReportRegistrationActivity import lt.vilnius.tvarkau.activity.available import lt.vilnius.tvarkau.activity.googlePlayServicesAvailability import lt.vilnius.tvarkau.activity.resolutionDialog import lt.vilnius.tvarkau.activity.resultCode import lt.vilnius.tvarkau.api.ApiError import lt.vilnius.tvarkau.entity.Profile import lt.vilnius.tvarkau.entity.ReportEntity import lt.vilnius.tvarkau.entity.ReportType import lt.vilnius.tvarkau.extensions.gone import lt.vilnius.tvarkau.extensions.observe import lt.vilnius.tvarkau.extensions.observeNonNull import lt.vilnius.tvarkau.extensions.visible import lt.vilnius.tvarkau.extensions.withViewModel import lt.vilnius.tvarkau.mvp.presenters.NewReportData import lt.vilnius.tvarkau.utils.FieldAwareValidator import lt.vilnius.tvarkau.utils.FormatUtils.formatLocalDateTime import lt.vilnius.tvarkau.utils.KeyboardUtils import lt.vilnius.tvarkau.utils.PermissionUtils import lt.vilnius.tvarkau.utils.PersonalCodeValidator import lt.vilnius.tvarkau.utils.ProgressState import lt.vilnius.tvarkau.viewmodel.NewReportViewModel import lt.vilnius.tvarkau.views.adapters.NewProblemPhotosPagerAdapter import org.threeten.bp.Duration import org.threeten.bp.LocalDateTime import org.threeten.bp.ZoneOffset import pl.aprilapps.easyphotopicker.DefaultCallback import pl.aprilapps.easyphotopicker.EasyImage import timber.log.Timber import java.io.File import java.util.* import java.util.Calendar.DAY_OF_MONTH import java.util.Calendar.HOUR_OF_DAY import java.util.Calendar.MINUTE import java.util.Calendar.MONTH import java.util.Calendar.YEAR @Screen( navigationMode = NavigationMode.BACK, trackingScreenName = ActivityConstants.SCREEN_NEW_REPORT ) class NewReportFragment : BaseFragment(), NewProblemPhotosPagerAdapter.OnPhotoClickedListener { private var googlePlayServicesResolutionDialog: Dialog? = null private lateinit var viewModel: NewReportViewModel var locationCords: LatLng? = null var imageFiles = ArrayList<File>() private var progressDialog: ProgressDialog? = null private val validateParkingViolationData: Boolean get() = reportType.isParkingViolation private val shouldDisplayPhotoInstructions: Boolean get() { val delta = System.currentTimeMillis() - appPreferences.photoInstructionsLastSeen.get() return reportType.isParkingViolation && Duration.ofMillis(delta).toDays() >= 1 } private val reportType by lazy { arguments!!.getParcelable<ReportType>(KEY_REPORT_TYPE) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) savedInstanceState?.let { locationCords = it.getParcelable(SAVE_LOCATION) imageFiles = it.getSerializable(SAVE_PHOTOS) as ArrayList<File> } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_new_report, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setHasOptionsMenu(true) with(activity!! as AppCompatActivity) { setSupportActionBar(toolbar) supportActionBar?.title = reportType.title } problem_images_view_pager.adapter = NewProblemPhotosPagerAdapter(imageFiles, this) problem_images_view_pager.offscreenPageLimit = 3 problem_images_view_pager_indicator.setViewPager(problem_images_view_pager) problem_images_view_pager_indicator.gone() report_problem_location.setOnClickListener { onProblemLocationClicked(it) } report_problem_take_photo.setOnClickListener { onTakePhotoClicked() } report_problem_date_time.setOnClickListener { onProblemDateTimeClicked() } } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.new_problem_toolbar_menu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { onGoBack() true } R.id.action_send -> { activity!!.currentFocus?.let { KeyboardUtils.closeSoftKeyboard(activity!!, it) } viewModel.submit(createValidator()) true } else -> super.onOptionsItemSelected(item) } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = withViewModel(viewModelFactory) { observeNonNull(errorEvents, ::showError) observeNonNull(validationError, ::showValidationError) observeNonNull(progressState, ::handleProgressState) observeNonNull(submittedReport, ::onReportSubmitted) observe(personalData, ::showParkingViolationFields) } viewModel.initWith(reportType) EasyImage.configuration(context!!).setAllowMultiplePickInGallery(true) } private fun showParkingViolationFields(profile: Profile?) { new_report_date_time_container.visible() new_report_licence_plate_container.visible() val drawable = AppCompatResources.getDrawable(context!!, R.drawable.ic_autorenew) report_problem_date_time.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null) report_problem_date_time.setOnTouchListener { view, event -> val DRAWABLE_RIGHT = 2 var result = false val ediText = view as EditText if (event.action == MotionEvent.ACTION_UP) { if (event.rawX >= (ediText.right - ediText.compoundDrawables[DRAWABLE_RIGHT].bounds.width())) { report_problem_date_time.setText(formatLocalDateTime(LocalDateTime.now())) result = true } } result } new_report_personal_code_container.visible() new_report_email_container.visible() new_report_name_container.visible() report_problem_personal_data_agreement.visible() profile?.let { report_problem_submitter_email.setText(it.email) report_problem_submitter_name.setText(it.name) report_problem_submitter_personal_code.setText(it.personalCode) } } private fun createValidator(): FieldAwareValidator<NewReportData> { val data = NewReportData( reportType = reportType, description = report_problem_description.text.toString(), address = report_problem_location.text.toString(), latitude = locationCords?.latitude, longitude = locationCords?.longitude, dateTime = report_problem_date_time.text.toString(), email = report_problem_submitter_email.text.toString(), name = report_problem_submitter_name.text.toString(), personalCode = report_problem_submitter_personal_code.text.toString(), photoUrls = imageFiles, licencePlate = report_problem_licence_plate_number.text.toString() ) var validator = FieldAwareValidator.of(data) .validate( { it.address.isNotBlank() }, report_problem_location_wrapper.id, getText(R.string.error_problem_location_is_empty) ) .validate( { report_problem_description.text.isNotBlank() }, report_problem_description_wrapper.id, getText(R.string.error_problem_description_is_empty) ) if (validateParkingViolationData) { validator = validator .validate( { it.licencePlate?.isNotBlank() ?: false }, report_problem_licence_plate_number_wrapper.id, getString(R.string.error_new_report_fill_licence_plate) ) .validate( { it.dateTime?.isNotBlank() ?: false }, report_problem_date_time_wrapper.id, getString(R.string.error_report_fill_date_time) ) .validate( { it.email?.isNotBlank() ?: false }, report_problem_submitter_email_wrapper.id, getString(R.string.error_profile_fill_email) ) .validate( { Patterns.EMAIL_ADDRESS.matcher(it.email).matches() }, report_problem_submitter_email_wrapper.id, getString(R.string.error_profile_email_invalid) ) .validate( { it.name?.isNotBlank() ?: false }, report_problem_submitter_name_wrapper.id, getText(R.string.error_profile_fill_name).toString() ) .validate( { it.name!!.split(" ").size >= 2 }, report_problem_submitter_name_wrapper.id, getText(R.string.error_profile_name_invalid).toString() ) .validate( { it.personalCode?.isNotBlank() ?: false }, report_problem_submitter_personal_code_wrapper.id, getText(R.string.error_new_report_enter_personal_code).toString() ) .validate( { PersonalCodeValidator.validate(it.personalCode!!) }, report_problem_submitter_personal_code_wrapper.id, getText(R.string.error_new_report_invalid_personal_code).toString() ) .validate( { it.photoUrls.size >= 2 }, 0, getText(R.string.error_minimum_photo_requirement).toString() ) } return validator } private fun showValidationError(error: FieldAwareValidator.ValidationException) { report_problem_location_wrapper.isErrorEnabled = false report_problem_description_wrapper.isErrorEnabled = false report_problem_date_time_wrapper.isErrorEnabled = false report_problem_submitter_name_wrapper.isErrorEnabled = false report_problem_submitter_personal_code_wrapper.isErrorEnabled = false report_problem_submitter_email_wrapper.isErrorEnabled = false report_problem_licence_plate_number_wrapper.isErrorEnabled = false view?.findViewById<TextInputLayout>(error.viewId)?.let { it.error = error.message } ?: Toast.makeText(context!!, error.message, Toast.LENGTH_SHORT).show() } private fun showError(error: Throwable) { val message = if (error is ApiError && error.isValidationError) { error.firstErrorMessage } else { getString(R.string.error_submitting_problem) } Toast.makeText(context!!, message, Toast.LENGTH_SHORT).show() } private fun onReportSubmitted(report: ReportEntity) { activity!!.currentFocus?.run { KeyboardUtils.closeSoftKeyboard(activity!!, this) } Toast.makeText(context!!, R.string.problem_successfully_sent, Toast.LENGTH_SHORT).show() (activity!! as ReportRegistrationActivity).onReportSubmitted() } //TODO restore after image upload implemented private fun fillReportDateTime(dateTime: String) { report_problem_date_time.setText(dateTime) } //TODO restore after image upload implemented private fun displayImages(imageFiles: List<File>) { this.imageFiles.addAll(imageFiles) problem_images_view_pager.adapter!!.notifyDataSetChanged() if (this.imageFiles.size > 1) { problem_images_view_pager_indicator.visible() problem_images_view_pager.currentItem = this.imageFiles.lastIndex } } fun onTakePhotoClicked() { if (PermissionUtils.isAllPermissionsGranted(activity!!, TAKE_PHOTO_PERMISSIONS)) { openPhotoSelectorDialog(shouldDisplayPhotoInstructions) } else { requestPermissions(TAKE_PHOTO_PERMISSIONS, ActivityConstants.REQUEST_CODE_TAKE_PHOTO_PERMISSIONS) } } private fun openPhotoSelectorDialog(displayPhotoInstructions: Boolean) { activity!!.currentFocus?.let { KeyboardUtils.closeSoftKeyboard(activity!!, it) } if (displayPhotoInstructions) { arguments!!.putBoolean(KEY_TAKE_PHOTO, true) (activity!! as ReportRegistrationActivity).displayPhotoInstructions() return } val imagePickerDialogBuilder = AlertDialog.Builder(context!!, R.style.MyDialogTheme) val view = LayoutInflater.from(context!!).inflate(R.layout.image_picker_dialog, null) val cameraButton = view.camera_button val galleryButton = view.gallery_button if (!EasyImage.canDeviceHandleGallery(context!!)) { galleryButton.gone() } imagePickerDialogBuilder .setTitle(R.string.add_photos) .setView(view) .setPositiveButton(R.string.cancel) { dialog, whichButton -> dialog.dismiss() } .create() val imagePickerDialog = imagePickerDialogBuilder.show() cameraButton.setOnClickListener { EasyImage.openCamera(this, 0) imagePickerDialog.dismiss() } galleryButton.setOnClickListener { EasyImage.openGallery(this, 0) imagePickerDialog.dismiss() } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { when (requestCode) { ActivityConstants.REQUEST_CODE_TAKE_PHOTO_PERMISSIONS -> if (PermissionUtils.isAllPermissionsGranted( activity!!, TAKE_PHOTO_PERMISSIONS ) ) { openPhotoSelectorDialog(shouldDisplayPhotoInstructions) } else { Toast.makeText(context!!, R.string.error_need_camera_and_storage_permission, Toast.LENGTH_SHORT).show() } ActivityConstants.REQUEST_CODE_MAP_PERMISSION -> if (PermissionUtils.isAllPermissionsGranted( activity!!, MAP_PERMISSIONS ) ) { showPlacePicker(view!!) } else { Toast.makeText(context!!, R.string.error_need_location_permission, Toast.LENGTH_SHORT).show() } else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } private fun isEditedByUser(): Boolean { return report_problem_description.text.isNotBlank() || report_problem_location.text.isNotBlank() || imageFiles.isNotEmpty() } private fun onGoBack() { if (report_problem_description.hasFocus()) { KeyboardUtils.closeSoftKeyboard(activity!!, report_problem_description) } if (isEditedByUser()) { AlertDialog.Builder(context!!, R.style.MyDialogTheme) .setMessage(getString(R.string.discard_changes_title)) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.discard_changes_positive) { dialog, whichButton -> activity!!.onBackPressed() } .setNegativeButton(R.string.discard_changes_negative, null).show() } else { activity!!.onBackPressed() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { EasyImage.handleActivityResult(requestCode, resultCode, data, activity!!, object : DefaultCallback() { override fun onImagePickerError(e: Exception?, source: EasyImage.ImageSource?, type: Int) { Toast.makeText(activity!!, R.string.photo_capture_error, Toast.LENGTH_SHORT).show() Timber.w(e, "Unable to take a picture") } override fun onImagesPicked(imageFiles: List<File>, source: EasyImage.ImageSource, type: Int) { viewModel.onImagesPicked(imageFiles) } override fun onCanceled(source: EasyImage.ImageSource?, type: Int) { if (source == EasyImage.ImageSource.CAMERA) { val photoFile = EasyImage.lastlyTakenButCanceledPhoto(context!!) photoFile?.delete() } } }) if (resultCode == Activity.RESULT_OK) { when (requestCode) { ActivityConstants.REQUEST_CODE_PLACE_PICKER -> { val geocoder = Geocoder(context!!) val place = PlacePicker.getPlace(context!!, data) val addresses = mutableListOf<Address>() place.latLng?.let { locationCords = it try { geocoder.getFromLocation(it.latitude, it.longitude, 1)?.let { addresses.addAll(it) } } catch (e: Throwable) { Timber.e(GeocoderException(e)) } } val firstAddress = addresses.firstOrNull() if (firstAddress?.locality != null) { val address = firstAddress.getAddressLine(0) report_problem_location_wrapper.error = null report_problem_location.setText(address) } else { // Mostly when Geocoder throws IOException // backup solution which in not 100% reliable val addressSlice = place.address ?.split(", ".toRegex()) ?.dropLastWhile(String::isEmpty) ?.toTypedArray() val addressText = if (addressSlice == null || addressSlice.isEmpty()) { locationCords?.let { "${it.latitude}; ${it.longitude}" } } else { addressSlice[0] } if (addressText.isNullOrEmpty()) { report_problem_location_wrapper.error = getText(R.string.error_failed_to_determine_address) report_problem_location.text = null } else { report_problem_location_wrapper.error = null report_problem_location.setText(addressText) } } } } } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelable(SAVE_LOCATION, locationCords) outState.putSerializable(SAVE_PHOTOS, imageFiles) } private fun onProblemLocationClicked(view: View) { if (PermissionUtils.isAllPermissionsGranted(activity!!, MAP_PERMISSIONS)) { showPlacePicker(view) } else { requestPermissions(MAP_PERMISSIONS, ActivityConstants.REQUEST_CODE_MAP_PERMISSION) } } private fun showPlacePicker(view: View) { val googlePlayServicesAvailability = activity!!.googlePlayServicesAvailability() if (googlePlayServicesAvailability.available()) { val intent = PlacePicker.IntentBuilder().build(activity!!) val bundle = ActivityOptionsCompat.makeScaleUpAnimation(view, 0, 0, view.width, view.height).toBundle() startActivityForResult(intent, ActivityConstants.REQUEST_CODE_PLACE_PICKER, bundle) } else { analytics.trackGooglePlayServicesError(googlePlayServicesAvailability.resultCode()) googlePlayServicesResolutionDialog?.dismiss() googlePlayServicesResolutionDialog = googlePlayServicesAvailability.resolutionDialog(activity!!) googlePlayServicesResolutionDialog?.show() } } private fun onProblemDateTimeClicked() { val calendar = Calendar.getInstance() calendar.time = Date() val year = calendar.get(YEAR) val month = calendar.get(MONTH) val day = calendar.get(DAY_OF_MONTH) val dialogDatePicker = DatePickerDialog( activity!!, { _: DatePicker, selectedYear: Int, selectedMonth: Int, selectedDay: Int -> calendar.set(YEAR, selectedYear) calendar.set(MONTH, selectedMonth) calendar.set(DAY_OF_MONTH, selectedDay) TimePickerDialog(activity!!, { _: TimePicker, hour: Int, minutes: Int -> calendar.set(HOUR_OF_DAY, hour) calendar.set(MINUTE, minutes) val dateTime = LocalDateTime.of( calendar.get(YEAR), calendar.get(MONTH) + 1, //LocalDateTime expects month starting from 1 instead of 0 calendar.get(DAY_OF_MONTH), calendar.get(HOUR_OF_DAY), calendar.get(MINUTE) ) report_problem_date_time.setText(formatLocalDateTime(dateTime)) }, 0, 0, true).show() }, year, month, day ) dialogDatePicker.datePicker.maxDate = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() dialogDatePicker.setTitle(null) dialogDatePicker.show() } override fun onPhotoClicked(position: Int, photos: List<String>) { val intent = Intent(activity!!, FullscreenImageActivity::class.java) intent.putExtra(FullscreenImageActivity.EXTRA_PHOTOS, photos.toTypedArray()) intent.putExtra(FullscreenImageActivity.EXTRA_IMAGE_POSITION, position) startActivity(intent) } private fun handleProgressState(progressState: ProgressState) { when (progressState) { ProgressState.show -> showProgress() ProgressState.hide -> hideProgress() } } private fun showProgress() { if (progressDialog == null) { progressDialog = ProgressDialog(context!!).apply { setMessage(getString(R.string.sending_problem)) setProgressStyle(ProgressDialog.STYLE_SPINNER) setCancelable(false) } } progressDialog?.show() } private fun hideProgress() { progressDialog?.dismiss() } override fun onResume() { super.onResume() if (arguments!!.containsKey(KEY_TAKE_PHOTO)) { arguments!!.remove(KEY_TAKE_PHOTO) openPhotoSelectorDialog(displayPhotoInstructions = false) } } override fun onDestroy() { EasyImage.clearConfiguration(context!!) super.onDestroy() } override fun onDestroyView() { progressDialog?.dismiss() super.onDestroyView() } companion object { val TAKE_PHOTO_PERMISSIONS = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA) val MAP_PERMISSIONS = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION) const val PARKING_VIOLATIONS = "Transporto priemonių stovėjimo tvarkos pažeidimai" private const val SAVE_LOCATION = "location" private const val SAVE_PHOTOS = "photos" const val KEY_REPORT_TYPE = "report_type" const val KEY_TAKE_PHOTO = "take_photo" fun newInstance(reportType: ReportType): NewReportFragment { return NewReportFragment().apply { arguments = Bundle().apply { putParcelable(KEY_REPORT_TYPE, reportType) } } } } class GeocoderException(cause: Throwable) : RuntimeException(cause) }
mit
12c506ed939b91629a29a01e7e0f33dd
38.843411
119
0.626561
5.07785
false
false
false
false
cfig/Nexus_boot_image_editor
bbootimg/src/main/kotlin/bootloader_message/BootloaderMsgAB.kt
1
1613
// Copyright 2021 [email protected] // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cfig.bootloader_message import cfig.io.Struct3 import org.slf4j.LoggerFactory import java.io.FileInputStream class BootloaderMsgAB( //offset 2k, size 2k var slotSuffix: String = "", var updateChannel: String = "", var reserved: ByteArray = byteArrayOf() ) { companion object { private const val FORMAT_STRING = "32s128s1888b" const val SIZE = 2048 private val log = LoggerFactory.getLogger(BootloaderMsgAB::class.java.simpleName) init { assert(SIZE == Struct3(FORMAT_STRING).calcSize()) } } constructor(fis: FileInputStream) : this() { val info = Struct3(FORMAT_STRING).unpack(fis) this.slotSuffix = info[0] as String this.updateChannel = info[1] as String this.reserved = info[2] as ByteArray } fun encode(): ByteArray { return Struct3(FORMAT_STRING).pack( this.slotSuffix, this.updateChannel, byteArrayOf()) } }
apache-2.0
1ae7352de68e5ab2ef7382da9272e720
31.918367
89
0.66646
4.211488
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/advancement/criteria/AbstractCriterion.kt
1
2985
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.advancement.criteria import org.lanternpowered.api.util.ToStringHelper import org.lanternpowered.api.util.collections.toImmutableSet import org.spongepowered.api.advancement.criteria.AdvancementCriterion import org.spongepowered.api.advancement.criteria.AndCriterion import org.spongepowered.api.advancement.criteria.OperatorCriterion import org.spongepowered.api.advancement.criteria.OrCriterion abstract class AbstractCriterion internal constructor(private val name: String) : AdvancementCriterion { override fun getName(): String = this.name override fun and(vararg criteria: AdvancementCriterion): AdvancementCriterion = this.and(criteria.asList()) override fun and(criteria: Iterable<AdvancementCriterion>): AdvancementCriterion = build(AndCriterion::class.java, sequenceOf(this) + criteria.asSequence(), ::LanternAndCriterion) override fun or(vararg criteria: AdvancementCriterion): AdvancementCriterion = this.or(criteria.asList()) override fun or(criteria: Iterable<AdvancementCriterion>): AdvancementCriterion = build(OrCriterion::class.java, sequenceOf(this) + criteria.asSequence(), ::LanternOrCriterion) override fun toString(): String = this.toStringHelper().toString() open fun toStringHelper(): ToStringHelper = ToStringHelper(this) .add("name", this.name) companion object { @JvmStatic fun getRecursiveCriteria(criterion: AdvancementCriterion): Collection<AdvancementCriterion> = if (criterion is AbstractOperatorCriterion) criterion.recursiveChildren else listOf(criterion) fun build( type: Class<out OperatorCriterion>, criteria: Sequence<AdvancementCriterion>, function: (Set<AdvancementCriterion>) -> AdvancementCriterion ): AdvancementCriterion { val builder = mutableListOf<AdvancementCriterion>() for (criterion in criteria) this.build(type, criterion, builder) if (builder.isEmpty()) return EmptyCriterion return if (builder.size == 1) builder[0] else function(builder.toImmutableSet()) } private fun build(type: Class<out OperatorCriterion>, criterion: AdvancementCriterion, criteria: MutableList<AdvancementCriterion>) { if (criterion === EmptyCriterion) return if (type.isInstance(criterion)) { criteria.addAll((criterion as OperatorCriterion).criteria) } else { criteria.add(criterion) } } } }
mit
8c46f0e04df15c71eafb9572f28593ff
41.642857
141
0.697822
5.236842
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/util/guice/InjectionPointProvider.kt
1
3135
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.util.guice import com.google.inject.Binder import com.google.inject.Binding import com.google.inject.Module import com.google.inject.Provider import com.google.inject.matcher.AbstractMatcher import com.google.inject.spi.DependencyAndSource import com.google.inject.spi.ProviderInstanceBinding import com.google.inject.spi.ProvisionListener import org.lanternpowered.api.util.type.typeToken import java.lang.reflect.Executable import java.lang.reflect.Field /** * Allows injecting the [InjectionPoint] in [Provider]s. */ class InjectionPointProvider : AbstractMatcher<Binding<*>>(), Module, ProvisionListener, Provider<InjectionPoint> { private var injectionPoint: InjectionPoint? = null override fun get(): InjectionPoint? = this.injectionPoint override fun matches(binding: Binding<*>) = binding is ProviderInstanceBinding<*> && binding.userSuppliedProvider === this override fun <T> onProvision(provision: ProvisionListener.ProvisionInvocation<T>) { try { this.injectionPoint = this.findInjectionPoint(provision.dependencyChain) provision.provision() } finally { this.injectionPoint = null } } private fun findInjectionPoint(dependencyChain: List<DependencyAndSource>): InjectionPoint? { if (dependencyChain.size < 3) AssertionError("Provider is not included in the dependency chain").printStackTrace() // @Inject InjectionPoint is the last, so we can skip it for (i in dependencyChain.size - 2 downTo 0) { val dependency = dependencyChain[i].dependency ?: return null val spiInjectionPoint = dependency.injectionPoint if (spiInjectionPoint != null) { val source = spiInjectionPoint.declaringType.type.typeToken return when (val member = spiInjectionPoint.member) { is Field -> LanternInjectionPoint.Field(source, member.genericType.typeToken, member.annotations, member) is Executable -> { val parameterAnnotations = member.parameterAnnotations val parameterTypes = member.genericParameterTypes val index = dependency.parameterIndex LanternInjectionPoint.Parameter(source, parameterTypes[index].typeToken, parameterAnnotations[index], member, index) } else -> throw IllegalStateException("Unsupported Member type: ${member.javaClass.name}") } } } return null } override fun configure(binder: Binder) { binder.bind(InjectionPoint::class.java).toProvider(this) binder.bindListener(this, this) } }
mit
63d546a6d3d3a5ab915892cf3c02d9ef
40.8
126
0.676236
4.984102
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/common/identity/DuchyIdentity.kt
1
3802
// Copyright 2020 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.common.identity import com.google.protobuf.ByteString import io.grpc.BindableService import io.grpc.Context import io.grpc.Contexts import io.grpc.Metadata import io.grpc.ServerCall import io.grpc.ServerCallHandler import io.grpc.ServerInterceptor import io.grpc.ServerInterceptors import io.grpc.ServerServiceDefinition import io.grpc.Status import io.grpc.stub.AbstractStub import io.grpc.stub.MetadataUtils /** * Details about an authenticated Duchy. * * @property[id] Stable identifier for a duchy. */ data class DuchyIdentity(val id: String) { init { requireNotNull(DuchyInfo.getByDuchyId(id)) { "Duchy $id is unknown; known Duchies are ${DuchyInfo.ALL_DUCHY_IDS}" } } } val duchyIdentityFromContext: DuchyIdentity get() = requireNotNull(DUCHY_IDENTITY_CONTEXT_KEY.get()) { "gRPC context is missing key $DUCHY_IDENTITY_CONTEXT_KEY" } private const val KEY_NAME = "duchy-identity" val DUCHY_IDENTITY_CONTEXT_KEY: Context.Key<DuchyIdentity> = Context.key(KEY_NAME) val DUCHY_ID_METADATA_KEY: Metadata.Key<String> = Metadata.Key.of(KEY_NAME, Metadata.ASCII_STRING_MARSHALLER) /** * Add an interceptor that sets DuchyIdentity in the context. * * Note that this doesn't provide any guarantees that the Duchy is who it claims to be -- that is * still required. * * To install in a server, wrap a service with: * ``` * yourService.withDuchyIdentities() * ``` * On the client side, use [withDuchyId]. */ class DuchyTlsIdentityInterceptor : ServerInterceptor { override fun <ReqT, RespT> interceptCall( call: ServerCall<ReqT, RespT>, headers: Metadata, next: ServerCallHandler<ReqT, RespT> ): ServerCall.Listener<ReqT> { val authorityKeyIdentifiers: List<ByteString> = authorityKeyIdentifiersFromCurrentContext if (authorityKeyIdentifiers.isEmpty()) { call.close( Status.UNAUTHENTICATED.withDescription("No authorityKeyIdentifiers found"), Metadata() ) return object : ServerCall.Listener<ReqT>() {} } for (authorityKeyIdentifier in authorityKeyIdentifiers) { val duchyInfo = DuchyInfo.getByRootCertificateSkid(authorityKeyIdentifier) ?: continue val context = Context.current().withValue(DUCHY_IDENTITY_CONTEXT_KEY, DuchyIdentity(duchyInfo.duchyId)) return Contexts.interceptCall(context, call, headers, next) } call.close(Status.UNAUTHENTICATED.withDescription("No Duchy identity found"), Metadata()) return object : ServerCall.Listener<ReqT>() {} } } /** Convenience helper for [DuchyTlsIdentityInterceptor]. */ fun BindableService.withDuchyIdentities(): ServerServiceDefinition = ServerInterceptors.interceptForward( this, AuthorityKeyServerInterceptor(), DuchyTlsIdentityInterceptor() ) /** * Sets metadata key "duchy_id" on all outgoing requests. * * Usage: val someStub = SomeServiceCoroutineStub(channel).withDuchyId("MyDuchyId") */ fun <T : AbstractStub<T>> T.withDuchyId(duchyId: String): T { val extraHeaders = Metadata() extraHeaders.put(DUCHY_ID_METADATA_KEY, duchyId) return withInterceptors(MetadataUtils.newAttachHeadersInterceptor(extraHeaders)) }
apache-2.0
78314e8233536a87673b165c3321fc04
32.946429
97
0.745923
4.16886
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/duchy/deploy/gcloud/server/GcsRequisitionFulfillmentServer.kt
1
1607
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.duchy.deploy.gcloud.server import org.wfanet.measurement.common.commandLineMain import org.wfanet.measurement.duchy.deploy.common.server.RequisitionFulfillmentServer import org.wfanet.measurement.gcloud.gcs.GcsFromFlags import org.wfanet.measurement.gcloud.gcs.GcsStorageClient import picocli.CommandLine /** Implementation of [RequisitionFulfillmentServer] using Google Cloud Storage (GCS). */ @CommandLine.Command( name = "GcsRequisitionFulfillmentServer", description = ["Server daemon for ${RequisitionFulfillmentServer.SERVICE_NAME} service."], mixinStandardHelpOptions = true, showDefaultValues = true ) class GcsRequisitionFulfillmentServer : RequisitionFulfillmentServer() { @CommandLine.Mixin private lateinit var gcsFlags: GcsFromFlags.Flags override fun run() { val gcs = GcsFromFlags(gcsFlags) run(GcsStorageClient.fromFlags(gcs)) } } fun main(args: Array<String>) = commandLineMain(GcsRequisitionFulfillmentServer(), args)
apache-2.0
738b208a8bbca4f78587ad3bbb44b946
40.205128
92
0.787803
4.539548
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/common/k8s/testing/KindCluster.kt
1
3556
/* * Copyright 2022 The Cross-Media Measurement Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wfanet.measurement.common.k8s.testing import io.kubernetes.client.util.Config import java.io.InputStream import java.nio.file.Path import java.util.UUID import java.util.logging.Logger import org.jetbrains.annotations.Blocking import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement import org.wfanet.measurement.common.k8s.KubernetesClient /** * [TestRule] for a Kubernetes cluster in [KinD](https://kind.sigs.k8s.io/). * * This assumes that you have KinD installed and in your path. This creates a cluster using `kind * create cluster` and attempts to delete it using `kind delete cluster`. These commands may have * other side effects. */ class KindCluster : TestRule { lateinit var uuid: UUID private set val name: String by lazy { "kind-$uuid" } val nameOption: String by lazy { "--name=$name" } lateinit var k8sClient: KubernetesClient private set override fun apply(base: Statement, description: Description): Statement { return object : Statement() { override fun evaluate() { uuid = UUID.randomUUID() runCommand("kind", "create", "cluster", nameOption) try { val apiClient = runCommand("kind", "get", "kubeconfig", nameOption) { Config.fromConfig(it) } k8sClient = KubernetesClient(apiClient) base.evaluate() } finally { runCommand("kind", "delete", "cluster", nameOption) } } } } @Blocking fun loadImage(archivePath: Path) { runCommand("kind", "load", "image-archive", archivePath.toString(), nameOption) } @Blocking fun exportLogs(outputDir: Path) { runCommand("kind", "export", "logs", outputDir.toString(), nameOption) } companion object { private val logger = Logger.getLogger(this::class.java.name) @Blocking private fun runCommand(vararg command: String) { logger.fine { "Running `${command.joinToString(" ")}`" } val process: Process = ProcessBuilder(*command) .redirectOutput(ProcessBuilder.Redirect.INHERIT) .redirectError(ProcessBuilder.Redirect.INHERIT) .start() val exitCode: Int = process.waitFor() check(exitCode == 0) { "`${command.joinToString(" ")}` failed with exit code $exitCode" } } @Blocking private inline fun <T> runCommand( vararg command: String, consumeOutput: (InputStream) -> T ): T { logger.fine { "Running `${command.joinToString(" ")}`" } val process: Process = ProcessBuilder(*command).start() val result = process.inputStream.use { consumeOutput(it) } val exitCode: Int = process.waitFor() check(exitCode == 0) { val errOutput = process.errorStream.bufferedReader().use { it.readText() } "`${command.joinToString(" ")}` failed with exit code $exitCode\n$errOutput" } return result } } }
apache-2.0
867eec87adbeb95c13b47c277d2edcb9
31.925926
97
0.67829
4.208284
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/editor/typedhandlers/LatexQuoteInsertHandler.kt
1
5799
package nl.hannahsten.texifyidea.editor.typedhandlers import com.intellij.codeInsight.editorActions.TypedHandlerDelegate import com.intellij.openapi.editor.CaretModel import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiFile import nl.hannahsten.texifyidea.file.LatexFileType import nl.hannahsten.texifyidea.lang.commands.LatexGenericRegularCommand import nl.hannahsten.texifyidea.settings.TexifySettings import nl.hannahsten.texifyidea.util.getOpenAndCloseQuotes import nl.hannahsten.texifyidea.util.inVerbatim import nl.hannahsten.texifyidea.util.insertUsepackage import kotlin.math.min /** * This class performs smart quote substitution. When this is enabled, it will replace double quotes " and single quotes ' with the appropriate LaTeX symbols. * * @author Thomas Schouten */ open class LatexQuoteInsertHandler : TypedHandlerDelegate() { override fun charTyped(char: Char, project: Project, editor: Editor, file: PsiFile): Result { // Only do this for latex files and if the option is enabled if (file.fileType != LatexFileType || TexifySettings.getInstance().automaticQuoteReplacement == TexifySettings.QuoteReplacement.NONE) { return super.charTyped(char, project, editor, file) } val document = editor.document val caret = editor.caretModel val offset = caret.offset // Disable in verbatim context. val psi = file.findElementAt(offset) if (psi?.inVerbatim() == true) return super.charTyped(char, project, editor, file) // Only do smart things with double and single quotes if (char != '"' && char != '\'') { return super.charTyped(char, project, editor, file) } // Check if we are not out of the document range if (offset - 1 < 0 || offset - 1 >= document.textLength) { return super.charTyped(char, project, editor, file) } insertReplacement(document, file, caret, offset, char) return super.charTyped(char, project, editor, file) } /** * Insert either opening or closing quotes. * * This behaviour is inspired by the smart quotes functionality of TeXworks, source: * https://github.com/TeXworks/texworks/blob/2f902e2e429fad3e2bbb56dff07c823d1108adf4/src/CompletingEdit.cpp#L762 */ private fun insertReplacement(document: Document, file: PsiFile, caret: CaretModel, offset: Int, char: Char) { val replacementPair = getOpenAndCloseQuotes(char) val openingQuotes = replacementPair.first val closingQuotes = if (TexifySettings.getInstance().automaticQuoteReplacement == TexifySettings.QuoteReplacement.CSQUOTES) "" else replacementPair.second // The default replacement of the typed double quotes is a pair of closing quotes var isOpeningQuotes = false // Always use opening quotes at the beginning of the document if (offset == 1) { isOpeningQuotes = true } else { // Character before the cursor val previousChar = document.getText(TextRange.from(offset - 2, 1)) if ((previousChar.firstOrNull())?.isLetter() == true && char == '\'') return // Don't replace when trying to type an escaped quote \" if (previousChar == "\\") return // Assume that if the previous char is a space, we are not closing anything if (previousChar == " ") { isOpeningQuotes = true } // After opening brackets, also use opening quotes if (previousChar == "{" || previousChar == "[" || previousChar == "(") { isOpeningQuotes = true } // If we are not closing the quotes, assume we are opening it (instead of doing nothing) if (TexifySettings.getInstance().automaticQuoteReplacement == TexifySettings.QuoteReplacement.CSQUOTES && document.getText(TextRange.from(min(offset, document.textLength - 1), 1)) != "}" ) { isOpeningQuotes = true } } val replacement = if (isOpeningQuotes) openingQuotes else closingQuotes // Insert the replacement of the typed character, recall the offset is now right behind the inserted char document.deleteString(offset - 1, offset) document.insertString(offset - 1, replacement) // Move the cursor behind the replacement which replaced the typed char caret.moveToOffset(min(offset + replacement.length - 1, document.textLength)) handleCsquotesInsertion(document, file, isOpeningQuotes, caret, char) } /** * Special behaviour for \enquote, because it is a command, not just opening and closing quotes. */ private fun handleCsquotesInsertion(document: Document, file: PsiFile, isOpeningQuotes: Boolean, caret: CaretModel, char: Char) { if (TexifySettings.getInstance().automaticQuoteReplacement == TexifySettings.QuoteReplacement.CSQUOTES) { if (isOpeningQuotes) { // Insert } after the cursor to close the command document.insertString(caret.offset, "}") } else { // Instead of typing closing quotes, skip over the closing } caret.moveToOffset(caret.offset + 1) } // Package dependencies if (char == '"') { file.insertUsepackage(LatexGenericRegularCommand.ENQUOTE.dependency) } else { file.insertUsepackage(LatexGenericRegularCommand.ENQUOTE_STAR.dependency) } } } }
mit
022241ad9b70fa3e455fa049a0fc3a9d
42.283582
162
0.663045
4.964897
false
false
false
false
Kushki/kushki-android
kushki/src/main/java/com/kushkipagos/kushki/KushkiClient.kt
1
9378
package com.kushkipagos.kushki import com.kushkipagos.exceptions.KushkiException import com.kushkipagos.models.* import java.io.* import java.net.HttpURLConnection import java.net.URL import java.security.InvalidKeyException import java.security.NoSuchAlgorithmException import java.security.spec.InvalidKeySpecException import java.util.* import javax.crypto.BadPaddingException import javax.crypto.IllegalBlockSizeException import javax.crypto.NoSuchPaddingException internal class KushkiClient(private val environment: Environment, private val publicMerchantId: String , private val regional: Boolean) { constructor(environment: Environment, publicMerchantId: String) : this(environment, publicMerchantId, false) private val kushkiJsonBuilder: KushkiJsonBuilder = KushkiJsonBuilder() @Throws(KushkiException::class) fun getScienceSession(card: Card): SiftScienceObject { var bin:String = card.toJsonObject().getString("number").toString().substring(0, 6) var lastDigits:String = card.toJsonObject().getString("number").toString().substring(card.toJsonObject().getString("number").length - 4) return createSiftScienceSession(bin, lastDigits, publicMerchantId) } @Throws(KushkiException::class) fun createSiftScienceSession(bin: String, lastDigits: String, merchantId: String): SiftScienceObject { var userId:String ="" var sessionId:String="" var uuid: UUID = UUID.randomUUID() if(merchantId ==""){ userId = "" sessionId ="" }else { userId = merchantId+bin+lastDigits sessionId =uuid.toString() } return SiftScienceObject(kushkiJsonBuilder.buildJson(userId, sessionId)) } @Throws(KushkiException::class) fun post(endpoint: String, requestBody: String): Transaction { try { val connection = prepareConnection(endpoint, requestBody) return Transaction(parseResponse(connection)) } catch (e: Exception) { when(e) { is BadPaddingException, is IllegalBlockSizeException, is NoSuchAlgorithmException, is NoSuchPaddingException, is InvalidKeyException, is InvalidKeySpecException, is IOException -> { throw KushkiException(e) } else -> throw e } } } @Throws(KushkiException::class) fun post_secure(endpoint: String, requestBody: String): SecureValidation { System.out.println("request--Body") System.out.println(requestBody) try { val connection = prepareConnection(endpoint, requestBody) return SecureValidation(parseResponse(connection)) } catch (e: Exception) { when(e) { is BadPaddingException, is IllegalBlockSizeException, is NoSuchAlgorithmException, is NoSuchPaddingException, is InvalidKeyException, is InvalidKeySpecException, is IOException -> { throw KushkiException(e) } else -> throw e } } } @Throws(KushkiException::class) fun get (endpoint: String): BankList { try { val connection = prepareGetConnection(endpoint) return BankList(parseResponse(connection)) } catch (e: Exception) { when(e) { is BadPaddingException, is IllegalBlockSizeException, is NoSuchAlgorithmException, is NoSuchPaddingException, is InvalidKeyException, is InvalidKeySpecException, is IOException -> { throw KushkiException(e) } else -> throw e } } } @Throws(KushkiException::class) fun get_bin (endpoint: String): BinInfo { try { val connection = prepareGetConnection(endpoint) return BinInfo(parseResponse(connection)) } catch (e: Exception) { when(e) { is BadPaddingException, is IllegalBlockSizeException, is NoSuchAlgorithmException, is NoSuchPaddingException, is InvalidKeyException, is InvalidKeySpecException, is IOException -> { throw KushkiException(e) } else -> throw e } } } @Throws(KushkiException::class) fun get_merchant_settings (endpoint: String): MerchantSettings { try { val connection = prepareGetConnection(endpoint) return MerchantSettings(parseResponse(connection)) } catch (e: Exception) { when(e) { is BadPaddingException, is IllegalBlockSizeException, is NoSuchAlgorithmException, is NoSuchPaddingException, is InvalidKeyException, is InvalidKeySpecException, is IOException -> { throw KushkiException(e) } else -> throw e } } } @Throws(KushkiException::class) fun get_cybersourceJWT (endpoint: String):CyberSourceJWT{ try { val connection = prepareGetConnection(endpoint) return CyberSourceJWT(parseResponse(connection)) } catch (e: Exception) { when(e) { is BadPaddingException, is IllegalBlockSizeException, is NoSuchAlgorithmException, is NoSuchPaddingException, is InvalidKeyException, is InvalidKeySpecException, is IOException -> { throw KushkiException(e) } else -> throw e } } } @Throws(KushkiException::class) fun post_card_secure(endpoint: String, requestBody: String): CardSecureValidation { System.out.println("request--Body") System.out.println(requestBody) try { val connection = prepareConnection(endpoint, requestBody) return CardSecureValidation(parseResponse(connection)) } catch (e: Exception) { when(e) { is BadPaddingException, is IllegalBlockSizeException, is NoSuchAlgorithmException, is NoSuchPaddingException, is InvalidKeyException, is InvalidKeySpecException, is IOException -> { throw KushkiException(e) } else -> throw e } } } @Throws(IOException::class) private fun prepareConnection(endpoint: String, requestBody: String): HttpURLConnection { var urlDestination:String = environment.url if(regional) { when (environment) { KushkiEnvironment.PRODUCTION -> urlDestination = KushkiEnvironment.PRODUCTION_REGIONAL.url KushkiEnvironment.TESTING -> urlDestination = KushkiEnvironment.UAT_REGIONAL.url } } val url = URL(urlDestination + endpoint) System.out.println(url) val connection = url.openConnection() as HttpURLConnection connection.requestMethod = "POST" connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8") connection.setRequestProperty("public-merchant-id", publicMerchantId) connection.readTimeout = 25000 connection.connectTimeout = 30000 connection.doOutput = true val dataOutputStream = DataOutputStream(connection.outputStream) dataOutputStream.writeBytes(requestBody) dataOutputStream.flush() dataOutputStream.close() return connection } @Throws(IOException::class) private fun prepareGetConnection(endpoint: String):HttpURLConnection{ var urlDestination:String = environment.url if(regional) { when (environment) { KushkiEnvironment.PRODUCTION -> urlDestination = KushkiEnvironment.PRODUCTION_REGIONAL.url KushkiEnvironment.TESTING -> urlDestination = KushkiEnvironment.UAT_REGIONAL.url } } val url = URL(urlDestination + endpoint) System.out.println(url) val connection = url.openConnection() as HttpURLConnection connection.requestMethod = "GET" connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8") connection.setRequestProperty("Public-Merchant-Id", publicMerchantId) connection.readTimeout = 25000 connection.connectTimeout = 30000 return connection } @Throws(IOException::class) private fun parseResponse(connection: HttpURLConnection): String { val responseInputStream = getResponseInputStream(connection) val reader = BufferedReader(InputStreamReader(responseInputStream, "UTF-8")) val stringBuilder = StringBuilder() reader.forEachLine { stringBuilder.append(it) } System.out.println(stringBuilder.toString()) return stringBuilder.toString() } @Throws(IOException::class) private fun getResponseInputStream(connection: HttpURLConnection): InputStream { if (connection.responseCode >= HttpURLConnection.HTTP_BAD_REQUEST) { return connection.errorStream } else { return connection.inputStream } } }
mit
549d92e5ab7ac8632d612d2170325362
36.071146
144
0.632118
5.700912
false
false
false
false
PaulWoitaschek/Voice
logging/core/src/main/kotlin/voice/logging/core/Logger.kt
1
2246
package voice.logging.core import java.io.PrintWriter import java.io.StringWriter object Logger { fun v(message: String) { log(severity = Severity.Verbose, message = message, throwable = null) } fun d(message: String) { log(severity = Severity.Debug, message = message, throwable = null) } fun d(throwable: Throwable) { log(severity = Severity.Debug, message = null, throwable = throwable) } fun i(message: String) { log(severity = Severity.Info, message = message, throwable = null) } fun w(message: String) { log(severity = Severity.Warn, message = message, throwable = null) } fun w(throwable: Throwable, message: String? = null) { log(severity = Severity.Warn, message = message, throwable = throwable) } fun e(message: String) { log(severity = Severity.Error, message = message, throwable = null) } fun e(throwable: Throwable, message: String) { log(severity = Severity.Error, message = message, throwable = throwable) } private var writers: Set<LogWriter> = emptySet() fun install(writer: LogWriter) { writers = writers + writer } /** * This logic is borrowed from Timber: https://github.com/JakeWharton/timber */ private fun log(severity: Severity, message: String?, throwable: Throwable?) { var messageResult = message if (messageResult.isNullOrEmpty()) { if (throwable == null) { return // Swallow message if it's null and there's no throwable. } messageResult = getStackTraceString(throwable) } else { if (throwable != null) { messageResult += "\n" + getStackTraceString(throwable) } } writers.forEach { it.log(severity, messageResult, throwable) } } private fun getStackTraceString(t: Throwable): String { // Don't replace this with Log.getStackTraceString() - it hides // UnknownHostException, which is not what we want. val sw = StringWriter(256) val pw = PrintWriter(sw, false) t.printStackTrace(pw) pw.flush() return sw.toString() } enum class Severity { Verbose, Debug, Info, Warn, Error, } } interface LogWriter { fun log(severity: Logger.Severity, message: String, throwable: Throwable?) }
gpl-3.0
f449d1f278faae90b1901459ef17ae41
24.235955
80
0.661621
4.046847
false
false
false
false
maxplanck76er/vertx-kafka-client
src/main/kotlin/io/vertx/kotlin/kafka/client/common/TopicPartition.kt
1
767
package io.vertx.kotlin.kafka.client.common import io.vertx.kafka.client.common.TopicPartition /** * A function providing a DSL for building [io.vertx.kafka.client.common.TopicPartition] objects. * * Represent information related to a partition for a topic * * @param partition Set the partition number * @param topic Set the topic name * * <p/> * NOTE: This function has been automatically generated from the [io.vertx.kafka.client.common.TopicPartition original] using Vert.x codegen. */ fun TopicPartition( partition: Int? = null, topic: String? = null): TopicPartition = io.vertx.kafka.client.common.TopicPartition().apply { if (partition != null) { this.setPartition(partition) } if (topic != null) { this.setTopic(topic) } }
apache-2.0
73882fb57670cd5f01810f9077694f15
27.407407
141
0.724902
3.759804
false
false
false
false
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/data/api/model/ThreadType.kt
1
2619
package me.ykrank.s1next.data.api.model import android.text.TextUtils import com.github.ykrank.androidtools.util.L import com.github.ykrank.androidtools.util.LooperUtil import me.ykrank.s1next.data.api.model.wrapper.HtmlDataWrapper import org.jsoup.Jsoup import paperparcel.PaperParcel import paperparcel.PaperParcelable import java.util.* /** * Created by ykrank on 2016/7/31 0031. */ @PaperParcel class ThreadType : PaperParcelable { var typeId: String? = null var typeName: String? = null constructor() constructor(typeId: String, typeName: String) { this.typeId = typeId this.typeName = typeName } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ThreadType if (typeId != other.typeId) return false if (typeName != other.typeName) return false return true } override fun hashCode(): Int { var result = typeId?.hashCode() ?: 0 result = 31 * result + (typeName?.hashCode() ?: 0) return result } companion object { @JvmField val CREATOR = PaperParcelThreadType.CREATOR /** * Extracts [Quote] from XML string. * * @param html raw html * @return if no type, return empty list. */ @Throws fun fromXmlString(html: String?): List<ThreadType> { LooperUtil.enforceOnWorkThread() val types = ArrayList<ThreadType>() try { val document = Jsoup.parse(html) HtmlDataWrapper.preAlertHtml(document) HtmlDataWrapper.preTreatHtml(document) val typeIdElements = document.select("#typeid>option") for (i in typeIdElements.indices) { val element = typeIdElements[i] val typeId = element.attr("value").trim() val typeName = element.text() types.add(ThreadType(typeId, typeName)) } } catch (e: Exception) { L.leaveMsg("Source:" + html) throw e } return types } fun nameOf(types: List<ThreadType>?, typeId: String): String? { if (types == null || types.isEmpty()) { return null } for (type in types) { if (TextUtils.equals(type.typeId, typeId)) { return type.typeName } } return null } } }
apache-2.0
558736d91f679e18f586555b23ce5ae3
27.78022
71
0.560519
4.718919
false
false
false
false
AgileVentures/MetPlus_resumeCruncher
core/src/test/kotlin/org/metplus/cruncher/resume/UploadResumeTest.kt
1
7055
package org.metplus.cruncher.resume import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.fail import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.metplus.cruncher.rating.CrunchResumeProcessSpy import org.metplus.cruncher.rating.CruncherMetaData internal class UploadResumeTest { private lateinit var resumeRepository: ResumeRepository private lateinit var uploadResume: UploadResume private lateinit var resumeFileRepository: ResumeFileRepository private lateinit var cruncherResumeProcessSpy: CrunchResumeProcessSpy @BeforeEach fun setup() { resumeRepository = ResumeRepositoryFake() resumeFileRepository = ResumeFileRepositoryFake() cruncherResumeProcessSpy = CrunchResumeProcessSpy() uploadResume = UploadResume(resumeRepository, resumeFileRepository, cruncherResumeProcessSpy) } @Test fun `when resume does not exist, it creates a new resume and enqueues the resume to be processed`() { val newResume = Resume( userId = "someUserId", fileType = "pdf", filename = "some_file_name.pdf", cruncherData = mapOf() ) val fileInputStream = FileInputStreamFake("some content") assertThat(uploadResume.process(userId = "someUserId", resumeName = "some_file_name.pdf", file = fileInputStream, size = 1, observer = object : UploadResumeObserver<Boolean> { override fun onException(exception: Exception, resume: Resume): Boolean { fail("Called onException when onSuccess was expected") return false } override fun onSuccess(resume: Resume): Boolean { return true } override fun onEmptyFile(resume: Resume): Boolean { fail("Called onEmptyFile when onSuccess was expected") return false } }) as Boolean).isTrue() assertThat(resumeRepository.getByUserId("someUserId")) .isEqualToComparingFieldByField(newResume) assertThat(resumeFileRepository.getByUserId("someUserId")) .isNotNull assertThat(cruncherResumeProcessSpy.nextWorkInQueue()).isEqualTo(newResume) } @Test fun `when resume exists, it overrides with new resume and saves the file and enqueues the resume to be processed`() { resumeRepository.save(Resume( filename = "some_file_name.pdf", fileType = "pdf", userId = "someUserId", cruncherData = mapOf("cruncher1" to CruncherMetaData(metaData = hashMapOf())) )) val newResume = Resume( userId = "someUserId", fileType = "doc", filename = "some_other_file.doc", cruncherData = mapOf() ) val fileInputStream = FileInputStreamFake("some content") assertThat(uploadResume.process(userId = "someUserId", resumeName = "some_other_file.doc", file = fileInputStream, size = 1, observer = object : UploadResumeObserver<Boolean> { override fun onException(exception: Exception, resume: Resume): Boolean { fail("Called onException when onSuccess was expected") return false } override fun onSuccess(resume: Resume): Boolean { return true } override fun onEmptyFile(resume: Resume): Boolean { fail("Called onEmptyFile when onSuccess was expected") return false } }) as Boolean).isTrue() assertThat(resumeRepository.getByUserId("someUserId")) .isEqualToComparingFieldByField(newResume) assertThat(cruncherResumeProcessSpy.nextWorkInQueue()).isEqualTo(newResume) } @Test fun `when resume file is empty, it does not save the file and call the onEmptyFile observer`() { val fileInputStream = FileInputStreamFake("some content") assertThat(uploadResume.process(userId = "someUserId", resumeName = "some_other_file.doc", file = fileInputStream, size = 0, observer = object : UploadResumeObserver<Boolean> { override fun onException(exception: Exception, resume: Resume): Boolean { fail("Called onException when onEmptyFile was expected") return false } override fun onSuccess(resume: Resume): Boolean { fail("Called onSuccess when onSuccess was expected") return false } override fun onEmptyFile(resume: Resume): Boolean { return true } }) as Boolean).isTrue() assertThat(resumeRepository.getByUserId("someUserId")).isNull() assertThat(cruncherResumeProcessSpy.nextWorkInQueue()).isNull() } @Test fun `when resume throw exception while saving, it does not save the file and call the onException observer`() { resumeRepository = ResumeRepositoryStub() (resumeRepository as ResumeRepositoryStub).throwOnSave = Exception("Some exception") uploadResume = UploadResume(resumeRepository, resumeFileRepository, cruncherResumeProcessSpy) val fileInputStream = FileInputStreamFake("some content") assertThat(uploadResume.process(userId = "someUserId", resumeName = "some_other_file.doc", file = fileInputStream, size = 1, observer = object : UploadResumeObserver<Boolean> { override fun onException(exception: Exception, resume: Resume): Boolean { assertThat(exception.message).isEqualTo("Some exception") return true } override fun onSuccess(resume: Resume): Boolean { fail("Called onSuccess when onSuccess was expected") return false } override fun onEmptyFile(resume: Resume): Boolean { fail("Called onException when onEmptyFile was expected") return false } }) as Boolean).isTrue() try { resumeFileRepository.getByUserId("someUserId") fail("Exception should have been thrown") } catch (exception: ResumeNotFound) { assertThat(cruncherResumeProcessSpy.nextWorkInQueue()).isNull() } } }
gpl-3.0
2efba7e2da5988a6d79f682b11890b3f
41.245509
121
0.581999
6.232332
false
false
false
false
bravelocation/yeltzland-android
app/src/main/java/com/bravelocation/yeltzlandnew/views/TweetBodyView.kt
1
1817
package com.bravelocation.yeltzlandnew.views import androidx.compose.foundation.text.ClickableText import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.withStyle import com.bravelocation.yeltzlandnew.tweet.DisplayTweet import com.bravelocation.yeltzlandnew.ui.AppColors import com.bravelocation.yeltzlandnew.ui.AppTypography import com.bravelocation.yeltzlandnew.utilities.LinkHelper @Composable fun TweetBodyView(tweet: DisplayTweet) { val context = LocalContext.current val tweetParts = tweet.textParts() val tweetString = buildAnnotatedString { tweetParts.forEach { part -> if (part.highlight() && part.linkUrl != null) { pushStringAnnotation(tag = "URL", annotation = part.linkUrl) withStyle(style = SpanStyle(color = AppColors.linkColor())) { append(part.text) } pop() } else { withStyle(style = SpanStyle(color = MaterialTheme.colors.onBackground)) { append(part.text) } } } } ClickableText( text = tweetString, style = AppTypography.body, onClick = { offset -> // We check if there is an *URL* annotation attached to the text // at the clicked position tweetString.getStringAnnotations(tag = "URL", start = offset, end = offset) .firstOrNull()?.let { annotation -> LinkHelper.openExternalUrl(context, annotation.item) } } ) }
mit
eeea662d0eadd9535323acb9baab94b1
35.36
89
0.636764
4.9375
false
false
false
false
daugeldauge/NeePlayer
compose/src/main/java/com/neeplayer/compose/NowPlayingBottomSheet.kt
1
6885
package com.neeplayer.compose import androidx.annotation.DrawableRes import androidx.compose.animation.Crossfade import androidx.compose.foundation.* import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material.BottomSheetScaffold import androidx.compose.material.BottomSheetValue import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Slider import androidx.compose.material.Text import androidx.compose.material.rememberBottomSheetScaffoldState import androidx.compose.material.ripple.rememberRipple import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.compose.rememberImagePainter import coil.size.Scale @Composable fun NowPlayingBottomSheetContent( state: NowPlayingState?, sheetValue: BottomSheetValue, actions: NowPlayingActions, ) { Box { Body(state = state, actions = actions) Crossfade(targetState = sheetValue) { value -> if (value == BottomSheetValue.Collapsed) { Header(state = state, onPlayPauseClick = { actions.playOrPause() }) } } } } @Composable private fun Body(state: NowPlayingState?, actions: NowPlayingActions) { Column { Image( painter = rememberImagePainter(data = state?.album?.art) { scale(Scale.FIT) }, modifier = Modifier.fillMaxWidth().aspectRatio(1f), contentDescription = null, ) Spacer(modifier = Modifier.weight(1f)) Column( modifier = Modifier .padding(16.dp) .fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { Text( style = MaterialTheme.typography.body1.copy(fontSize = 22.sp), text = state?.song?.title.orEmpty(), maxLines = 1, overflow = TextOverflow.Ellipsis, ) Text( style = MaterialTheme.typography.body2.copy(fontSize = 18.sp), text = "${state?.artist?.name} — ${state?.album?.title}", maxLines = 1, overflow = TextOverflow.Ellipsis, ) } Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center, ) { MusicControl(R.drawable.ic_fast_rewind_black_48dp) { actions.playPrevious() } MusicControl(state.playPauseResource()) { actions.playOrPause() } MusicControl(R.drawable.ic_fast_forward_black_48dp) { actions.playNext() } } Box(modifier = Modifier.padding(8.dp)) { Slider( value = state?.progress?.toFloat() ?: 0f, valueRange = 0f..(state?.song?.duration?.toFloat() ?: 1f), onValueChange = { value -> actions.seekTo(value.toLong()) }, ) Row(modifier = Modifier .padding(start = 8.dp, end = 8.dp, top = 40.dp) .align(Alignment.BottomCenter)) { Text( style = MaterialTheme.typography.caption, text = state?.progress.formatDuration(), ) Spacer(modifier = Modifier.weight(1f)) Text( style = MaterialTheme.typography.caption, text = state?.song?.duration.formatDuration(), ) } } Spacer(modifier = Modifier.weight(1f)) } } @Composable private fun Header(state: NowPlayingState?, onPlayPauseClick: () -> Unit = {}) { Row( modifier = Modifier .height(72.dp) .background(MaterialTheme.colors.background) .padding(4.dp), verticalAlignment = Alignment.CenterVertically, ) { Image( painter = rememberImagePainter(data = state?.album?.art) { scale(Scale.FIT) }, contentDescription = null, modifier = Modifier.size(64.dp), ) Column(modifier = Modifier .weight(1f) .padding(start = 12.dp, end = 12.dp)) { Text( text = state?.song?.title.orEmpty(), maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.body1 ) Text( text = state?.artist?.name.orEmpty(), maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.body2 ) } MusicControl(iconResource = state.playPauseResource(), width = 48.dp, onClick = onPlayPauseClick) } } @Composable private fun MusicControl( @DrawableRes iconResource: Int, width: Dp = 88.dp, onClick: () -> Unit = {}, ) { Box( modifier = Modifier .width(width) .clickable( onClick = onClick, indication = rememberRipple(bounded = false, radius = 56.dp), interactionSource = remember { MutableInteractionSource() }, ), contentAlignment = Alignment.Center, ) { Icon(painter = painterResource(id = iconResource), contentDescription = null) } } private fun NowPlayingState?.playPauseResource() = if (this?.playing != true) R.drawable.ic_play_arrow_black_48dp else R.drawable.ic_pause_black_48dp @Preview @Composable fun PreviewNowPlayingScreen() = NeeTheme { Body(NowPlayingState( playlist = listOf(PlaylistItem( song = Sample.songs.first(), album = Sample.albums.first().album, artist = Sample.artists.first(), )), position = 0, playing = true, progress = 0, ), AppStateContainer()) }
mit
df8bb751b33d766963fa36c67d587c9d
30.429224
102
0.615139
4.776544
false
false
false
false
didi/DoraemonKit
Android/dokit-mc/src/main/java/com/didichuxing/doraemonkit/kit/mc/oldui/record/DoKitMcDatasFragment.kt
1
3515
package com.didichuxing.doraemonkit.kit.mc.oldui.record import android.os.Bundle import android.view.View import android.widget.TextView import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.didichuxing.doraemonkit.extension.doKitGlobalScope import com.didichuxing.doraemonkit.kit.core.BaseFragment import com.didichuxing.doraemonkit.kit.mc.ui.adapter.McCaseInfo import com.didichuxing.doraemonkit.kit.mc.ui.adapter.McCaseListAdapter import com.didichuxing.doraemonkit.kit.test.mock.http.HttpMockServer import com.didichuxing.doraemonkit.kit.mc.utils.McCaseUtils import com.didichuxing.doraemonkit.kit.test.DoKitTestManager import com.didichuxing.doraemonkit.mc.R import com.didichuxing.doraemonkit.util.ToastUtils import com.didichuxing.doraemonkit.widget.recyclerview.DividerItemDecoration import kotlinx.coroutines.delay import kotlinx.coroutines.launch /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2020/12/10-10:52 * 描 述: * 修订历史: * ================================================ */ class DoKitMcDatasFragment : BaseFragment() { private lateinit var mRv: RecyclerView private lateinit var mEmpty: TextView private lateinit var mAdapter: McCaseListAdapter override fun onRequestLayout(): Int { return R.layout.dk_fragment_mc_datas } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mRv = findViewById(R.id.rv) mEmpty = findViewById(R.id.tv_empty) mAdapter = McCaseListAdapter(mutableListOf<McCaseInfo>()) mAdapter.setOnItemClickListener { adapter, _, pos -> val item = adapter.data[pos] as McCaseInfo if (item.isChecked) { for (i in adapter.data) { (i as McCaseInfo).isChecked = false } McCaseUtils.saveCaseId("") } else { for (i in adapter.data) { (i as McCaseInfo).isChecked = false } item.isChecked = true McCaseUtils.saveCaseId(item.caseId) ToastUtils.showShort("用例: ${item.caseName} 已被选中") } if (DoKitTestManager.isHostMode()) { doKitGlobalScope.launch { delay(100) adapter.notifyDataSetChanged() } } else { adapter.notifyDataSetChanged() } } mRv.apply { adapter = mAdapter layoutManager = LinearLayoutManager(requireActivity()) val decoration = DividerItemDecoration(DividerItemDecoration.VERTICAL) decoration.setDrawable(resources.getDrawable(R.drawable.dk_divider)) addItemDecoration(decoration) } lifecycleScope.launch { val data = HttpMockServer.caseList<McCaseInfo>().data data?.let { if (it.isEmpty()) { mEmpty.visibility = View.VISIBLE } else { val caseId = McCaseUtils.loadCaseId() it.forEach { info -> info.isChecked = caseId == info.caseId } mAdapter.setList(it) } } } } }
apache-2.0
f6bfca69d0aae525c51645dfeb490e37
34.27551
82
0.606306
4.889675
false
false
false
false
calintat/Units
app/src/main/java/com/calintat/units/activities/MainActivity.kt
1
7726
package com.calintat.units.activities import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.net.Uri import android.os.Bundle import android.support.annotation.IdRes import android.support.customtabs.CustomTabsIntent import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.support.v7.app.AppCompatDelegate import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.text.Editable import android.view.Gravity import android.widget.EditText import com.calintat.alps.getBoolean import com.calintat.alps.getInt import com.calintat.alps.getString import com.calintat.alps.putInt import com.calintat.units.R import com.calintat.units.api.Converter import com.calintat.units.api.Item import com.calintat.units.recycler.Adapter import com.calintat.units.ui.MainUI import com.calintat.units.utils.BillingHelper import com.calintat.units.utils.CurrencyHelper import org.jetbrains.anko.* import org.jetbrains.anko.sdk21.listeners.textChangedListener class MainActivity : AppCompatActivity() { companion object { private val KEY_ID = "com.calintat.units.KEY_ID" private val KEY_INPUT = "com.calintat.units.KEY_INPUT" } private val ui = MainUI() private var id: Int? = null private var position: Int? = null private var billingHelper: BillingHelper? = null private val adapter by lazy { Adapter(this) } private val currency get() = id == R.id.navigation_currency private val currencyAuto get() = getInt("pref_currency", 0) == 0 //---------------------------------------------------------------------------------------------- override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ui.setContentView(this) setTheme() setToolbar() setMainContent() setNavigationView() init(savedInstanceState) billingHelper = BillingHelper(this) } override fun onDestroy() { super.onDestroy() billingHelper?.destroy() } override fun onResume() { super.onResume() refreshActionMenu() refreshRecyclerView() refreshNavigationView() } override fun onBackPressed() { when { ui.drawerLayout.isDrawerOpen(Gravity.START) -> ui.drawerLayout.closeDrawers() else -> super.onBackPressed() } } override fun onSaveInstanceState(outState: Bundle) { id?.let { outState.putInt(KEY_ID, it) } outState.putString(KEY_INPUT, ui.editText.text.toString()) super.onSaveInstanceState(outState) } //---------------------------------------------------------------------------------------------- private fun init(savedInstanceState: Bundle?) { val defaultId = getInt(KEY_ID).takeIf { Item.isIdSafe(it) } ?: R.id.navigation_length if (savedInstanceState == null) { /* opened from launcher or app shortcut */ selectId(Item.get(intent)?.id ?: defaultId) } else { /* orientation change, activity resumed, etc */ selectId(savedInstanceState.getInt(KEY_ID, defaultId)) ui.editText.setText(savedInstanceState.getString(KEY_INPUT)) } } private fun selectId(@IdRes id: Int) { this.id = id if (currency && currencyAuto) actionRefresh() putInt(KEY_ID, id) refreshActionMenu() val item = Item.get(id) ?: return adapter.units = Converter.retrieveUnits(item) selectPosition(0) ui.toolbar.setBackgroundResource(item.color) ui.drawerLayout.setStatusBarBackground(item.colorDark) } private fun selectPosition(position: Int) { this.position = position refreshRecyclerView() ui.textView1.setText(adapter.units[position].label) ui.textView2.setText(adapter.units[position].shortLabel) } private fun setTheme() { AppCompatDelegate.setDefaultNightMode(getInt("pref_theme", 1)) } private fun setToolbar() { ui.toolbar.inflateMenu(R.menu.action) ui.toolbar.setOnMenuItemClickListener { when (it.itemId) { R.id.action_refresh -> actionRefresh() R.id.action_clear -> actionClear() } true } ui.toolbar.setNavigationIcon(R.drawable.ic_action_menu) ui.toolbar.setNavigationOnClickListener { ui.drawerLayout.openDrawer(Gravity.START) } ui.toolbar.overflowIcon = ContextCompat.getDrawable(this, R.drawable.ic_action_overflow) } private fun setMainContent() { ui.editText.afterTextChanged { refreshActionMenu(); refreshRecyclerView() } adapter.onClick = { selectPosition(it) } adapter.onLongClick = { copyToClipboard(it) } ui.recyclerView.adapter = adapter ui.recyclerView.layoutManager = LinearLayoutManager(this) ui.recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL)) } private fun setNavigationView() { ui.navigationView.inflateMenu(R.menu.navigation) ui.navigationView.setNavigationItemSelectedListener { ui.drawerLayout.closeDrawers() when (it.itemId) { R.id.navigation_settings -> startActivity<SettingsActivity>() R.id.navigation_feedback -> gotoFeedback() R.id.navigation_donation -> makeDonation() else -> selectId(it.itemId) } true } } private fun actionClear() = ui.editText.text.clear() private fun actionRefresh() = CurrencyHelper.loadData { if (it.date != getString("pref_currency_date", "2017-08-01")) { it.persist(this) refreshRecyclerView() longToast(getString(R.string.msg_retrieved_exchange_rates, it.date)) } else if (!currencyAuto) toast(R.string.err_rates_are_already_up_to_date) } private fun refreshActionMenu() { ui.toolbar.menu.findItem(R.id.action_clear).isVisible = ui.editText.text.isNotEmpty() ui.toolbar.menu.findItem(R.id.action_refresh).isVisible = currency && !currencyAuto } private fun refreshRecyclerView() { val num = ui.editText.text.toString().toDoubleOrNull() ?: Double.NaN position?.let { adapter.input = adapter.units[it].selfToBase(this, num) } } private fun refreshNavigationView() { ui.navigationView.menu.setGroupVisible(R.id.science, getBoolean("pref_science", true)) ui.navigationView.menu.setGroupVisible(R.id.medical, getBoolean("pref_medical", false)) } private fun gotoFeedback() { val builder = CustomTabsIntent.Builder() builder.build().launchUrl(this, Uri.parse("https://github.com/calintat/units/issues")) } private fun makeDonation() { val title = getString(R.string.navigation_donation) val items = listOf("£0.99", "£1.99", "£2.99", "£3.99", "£4.99", "£9.99") selector(title, items) { _, index -> billingHelper?.makeDonation("donation$index") } } private fun copyToClipboard(text: String) { val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipboardManager.primaryClip = ClipData.newPlainText("conversion output", text) toast(R.string.msg_clipboard) } private fun EditText.afterTextChanged(listener: (Editable?) -> Unit) { textChangedListener { afterTextChanged(listener) } } }
apache-2.0
222451c38d22f35ffabd08651d2b44e8
25.261905
102
0.65013
4.619988
false
false
false
false
pr0ves/PokemonGoBot
src/main/kotlin/ink/abb/pogo/scraper/tasks/ProcessPokestops.kt
2
2882
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package ink.abb.pogo.scraper.tasks import ink.abb.pogo.api.cache.Pokestop import ink.abb.pogo.scraper.Bot import ink.abb.pogo.scraper.Context import ink.abb.pogo.scraper.Settings import ink.abb.pogo.scraper.Task import ink.abb.pogo.scraper.util.Log import ink.abb.pogo.scraper.util.map.distance import ink.abb.pogo.scraper.util.pokemon.distance import ink.abb.pogo.scraper.util.map.inRangeForLuredPokemon import java.util.* import java.util.concurrent.TimeUnit /** * Task that handles catching pokemon, activating stops, and walking to a new target. */ class ProcessPokestops(var pokestops: List<Pokestop>) : Task { val refetchTime = TimeUnit.SECONDS.toMillis(30) var lastFetch: Long = 0 private val lootTimeouts = HashMap<String, Long>() var startPokestop: Pokestop? = null override fun run(bot: Bot, ctx: Context, settings: Settings) { var writeCampStatus = false if (lastFetch + refetchTime < bot.api.currentTimeMillis()) { writeCampStatus = true lastFetch = bot.api.currentTimeMillis() if (settings.allowLeaveStartArea) { try { val newStops = ctx.api.map.getPokestops(ctx.api.latitude, ctx.api.longitude, 9) if (newStops.size > 0) { pokestops = newStops } } catch (e: Exception) { // ignored failed request } } } val sortedPokestops = pokestops.sortedWith(Comparator { a, b -> a.distance.compareTo(b.distance) }) if (startPokestop == null) startPokestop = sortedPokestops.first() if (settings.lootPokestop) { val loot = LootOneNearbyPokestop(sortedPokestops, lootTimeouts) try { bot.task(loot) } catch (e: Exception) { ctx.pauseWalking.set(false) } } if (settings.campLurePokestop > 0 && !ctx.pokemonInventoryFullStatus.get() && settings.catchPokemon) { val luresInRange = sortedPokestops.filter { it.inRangeForLuredPokemon() && it.fortData.hasLureInfo() } if (luresInRange.size >= settings.campLurePokestop) { if (writeCampStatus) { Log.green("${luresInRange.size} lure(s) in range, pausing") } return } } val walk = Walk(sortedPokestops, lootTimeouts) bot.task(walk) } }
gpl-3.0
f4f28e63459a9b991408d30ff5c84569
35.025
110
0.61728
4.346908
false
false
false
false
siarhei-luskanau/android-samples
fileprovider-camera/app/src/main/java/siarhei/luskanau/example/camera/app/MainActivity.kt
1
2853
package siarhei.luskanau.example.camera.app import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory import com.example.camera.library.FileProviderUtils import siarhei.luskanau.example.camera.app.databinding.ActivityMainBinding import java.util.Locale class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ActivityMainBinding.inflate(LayoutInflater.from(this)) .also { binding = it setContentView(binding.root) } val takePictureLauncher = registerForActivityResult(ActivityResultContracts.TakePicture()) { val uri = FileProviderUtils.getFileProviderUri(this, CAMERA_TEMP_FILE_NAME) showImageUri(uri) } binding.cameraButton.setOnClickListener { FileProviderUtils.deleteFile(this, CAMERA_TEMP_FILE_NAME) val uri = FileProviderUtils.getFileProviderUri(this, CAMERA_TEMP_FILE_NAME) takePictureLauncher.launch(uri) } val getContentLauncher = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { showImageUri(it) } binding.galleryButton.setOnClickListener { getContentLauncher.launch( PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) ) } showImageUri(null) } @Suppress("TooGenericExceptionCaught") private fun showImageUri(uri: Uri?) { binding.imageUriTextView.text = String.format(Locale.ENGLISH, "Uri: %s", uri.toString()) try { uri?.let { val bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri)) val roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(resources, bitmap) .apply { isCircular = true } binding.roundedImageView.setImageDrawable(roundedBitmapDrawable) binding.imageView.setImageURI(null) binding.imageView.setImageURI(uri) } ?: run { binding.imageView.setImageResource(R.drawable.ic_android_24dp) binding.roundedImageView.setImageResource(R.drawable.ic_android_24dp) } } catch (t: Throwable) { binding.imageUriTextView.text = t.toString() } } companion object { private const val CAMERA_TEMP_FILE_NAME = "camera_temp.jpg" } }
mit
3735bc97f23a95ec69a414a5e7bca182
38.082192
103
0.685594
5.273567
false
false
false
false
kiruto/kotlin-android-mahjong
mahjanmodule/src/main/kotlin/dev/yuriel/kotmahjan/rules/yaku/yakuimpl/03_門前清模和.kt
1
1713
/* * The MIT License (MIT) * * Copyright (c) 2016 yuriel<[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.yuriel.kotmahjan.rules.yaku.yakuimpl import dev.yuriel.kotmahjan.models.PlayerContext import dev.yuriel.kotmahjan.models.RoundContext import dev.yuriel.kotmahjan.rules.MentsuSupport /** * Created by yuriel on 7/24/16. */ fun 門前清模和Impl(r: RoundContext?, p: PlayerContext?, s: MentsuSupport): Boolean { if (r == null || p == null) { return false } var isOpen = false for (mentsu in s.allMentsu) { if (mentsu.isOpen) { isOpen = true } } return p.isTsumo() && !isOpen }
mit
1270815b5603e71686fdcfb9c6e8e539
36.866667
81
0.724016
4.026005
false
false
false
false
is00hcw/anko
dsl/src/org/jetbrains/android/anko/generator/layoutParamsUtils.kt
2
2724
/* * 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. */ package org.jetbrains.android.anko.generator import org.jetbrains.android.anko.* import org.jetbrains.android.anko.annotations.ExternalAnnotation import org.jetbrains.android.anko.utils.fqName import org.jetbrains.android.anko.utils.getConstructors import org.objectweb.asm.tree.ClassNode //return a pair<viewGroup, layoutParams> or null if the viewGroup doesn't contain custom LayoutParams fun GenerationState.extractLayoutParams(viewGroup: ClassNode): LayoutElement? { fun findActualLayoutParamsClass(viewGroup: ClassNode): ClassNode? { fun findForParent() = findActualLayoutParamsClass(classTree.findNode(viewGroup)!!.parent!!.data) val generateMethod = viewGroup.methods.firstOrNull { method -> method.name == "generateLayoutParams" && method.args.size() == 1 && method.args[0].internalName == "android/util/AttributeSet" } ?: return findForParent() val returnTypeClass = classTree.findNode(generateMethod.returnType.internalName)!!.data if (!returnTypeClass.fqName.startsWith(viewGroup.fqName)) return findForParent() return if (returnTypeClass.isLayoutParams) returnTypeClass else findForParent() } val lpInnerClassName = viewGroup.innerClasses?.firstOrNull { it.name.contains("LayoutParams") } val lpInnerClass = lpInnerClassName?.let { classTree.findNode(it.name)!!.data } val externalAnnotations = config.annotationManager.findAnnotationsFor(viewGroup.fqName) val hasGenerateLayoutAnnotation = ExternalAnnotation.GenerateLayout in externalAnnotations val hasGenerateViewAnnotation = ExternalAnnotation.GenerateView in externalAnnotations if (hasGenerateViewAnnotation || (lpInnerClass == null && !hasGenerateLayoutAnnotation)) return null val actualLayoutParamsClass = findActualLayoutParamsClass(viewGroup).let { if (it != null && it.name != "android/view/ViewGroup\$LayoutParams") it else null } return (actualLayoutParamsClass ?: lpInnerClass)?.let { clazz -> LayoutElement(viewGroup, clazz, clazz.getConstructors().filter { it.isPublic }) } }
apache-2.0
54aa929dd6e0affcaa802d4bf428818c
47.660714
104
0.748532
4.712803
false
false
false
false
Orchextra/orchextra-android-sdk
geofence/src/main/java/com/gigigo/orchextra/geofence/OxGeofenceImp.kt
1
6361
/* * Created by Orchextra * * Copyright (C) 2017 Gigigo Mobile Services SL * * 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.gigigo.orchextra.geofence import android.Manifest import android.app.Application import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.preference.PreferenceManager import androidx.core.content.ContextCompat import com.gigigo.orchextra.core.domain.entities.GeoMarketing import com.gigigo.orchextra.core.domain.triggers.OxTrigger import com.gigigo.orchextra.core.utils.LogUtils import com.gigigo.orchextra.core.utils.LogUtils.LOGD import com.gigigo.orchextra.core.utils.LogUtils.LOGE import com.gigigo.orchextra.geofence.utils.toGeofence import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.location.Geofence import com.google.android.gms.location.GeofencingClient import com.google.android.gms.location.GeofencingRequest import com.google.android.gms.location.LocationServices import com.google.android.gms.tasks.OnCompleteListener import com.google.android.gms.tasks.Task class OxGeofenceImp private constructor( private val context: Application, private val geofencingClient: GeofencingClient ) : OxTrigger<List<GeoMarketing>>, OnCompleteListener<Void> { private var geofenceList: List<Geofence> = ArrayList() private var geofencePendingIntent: PendingIntent? = null override fun init() { if (geofenceList.isEmpty()) { LOGD(TAG, "geofences list is empty") return } connectWithCallbacks() addGeofences() } override fun setConfig(config: List<GeoMarketing>) { geofenceList = config.map { saveGeofenceRadius(context, it.code, it.radius) it.toGeofence() } } override fun finish() { removeGeofences() } private fun addGeofences() { if ( ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ) { geofencingClient.addGeofences(getGeofencingRequest(), getGeofencePendingIntent()) .addOnCompleteListener(this) } else { throw SecurityException("Geofence trigger needs ACCESS_FINE_LOCATION permission") } } private fun removeGeofences() { geofencingClient.removeGeofences(getGeofencePendingIntent()).addOnCompleteListener(this) } private fun getGeofencePendingIntent(): PendingIntent { if (geofencePendingIntent != null) { return geofencePendingIntent as PendingIntent } val intent = Intent(context, GeofenceBroadcastReceiver::class.java) geofencePendingIntent = PendingIntent.getBroadcast( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT ) return geofencePendingIntent as PendingIntent } private fun connectWithCallbacks() { val googleApiClient = GoogleApiClient.Builder(context) .addApi(LocationServices.API) .addConnectionCallbacks(connectionAddListener) .addOnConnectionFailedListener(connectionFailedListener) .build() googleApiClient.connect() } private val connectionAddListener = object : GoogleApiClient.ConnectionCallbacks { override fun onConnected(bundle: Bundle?) { LOGD(TAG, "connectionAddListener") } override fun onConnectionSuspended(i: Int) { LOGD(TAG, "onConnectionSuspended") } } private val connectionFailedListener = GoogleApiClient.OnConnectionFailedListener { LOGE(TAG, "connectionFailedListener") } override fun onComplete(task: Task<Void>) { if (task.isSuccessful) { updateGeofencesAdded(!getGeofencesAdded()) val message = if (getGeofencesAdded()) context.getString(R.string.geofences_added) else context.getString(R.string.geofences_removed) LOGD(TAG, "onComplete: $message") } else { task.exception?.let { LOGE(TAG, it.message ?: "no exception message") val errorMessage = GeofenceErrorMessages.getErrorString(context, it) LOGE(TAG, "onComplete: $errorMessage") } } } private fun getGeofencingRequest(): GeofencingRequest { val builder = GeofencingRequest.Builder() builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER) builder.addGeofences(geofenceList) return builder.build() } private fun getGeofencesAdded(): Boolean { return PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(GEOFENCES_ADDED_KEY, false) } private fun updateGeofencesAdded(added: Boolean) { PreferenceManager.getDefaultSharedPreferences(context) .edit() .putBoolean(GEOFENCES_ADDED_KEY, added) .apply() } companion object Factory { private val TAG = LogUtils.makeLogTag(OxGeofenceImp::class.java) private const val GEOFENCES_ADDED_KEY = "GEOFENCES_ADDED_KEY" fun create(context: Application) = OxGeofenceImp(context, LocationServices.getGeofencingClient(context)) fun saveGeofenceRadius(context: Context, code: String, radius: Int) { PreferenceManager.getDefaultSharedPreferences(context) .edit() .putInt(code, radius) .apply() } fun getGeofenceRadius(context: Context,code: String):Int { return PreferenceManager.getDefaultSharedPreferences(context) .getInt(code, -1) } } }
apache-2.0
a3ec376089e17966abae9d922586a475
33.956044
96
0.686684
4.981206
false
false
false
false
Jire/Abendigo
src/main/kotlin/org/abendigo/csgo/CSGO.kt
2
876
@file:JvmName("CSGO") package org.abendigo.csgo import org.abendigo.Addressable import org.abendigo.cached.Cached import org.jire.arrowhead.Module import org.jire.arrowhead.get import org.jire.arrowhead.processByName val csgo by lazy(LazyThreadSafetyMode.NONE) { processByName("csgo.exe")!! } val csgoModule by lazy(LazyThreadSafetyMode.NONE) { csgo.modules["csgo.exe"]!! } const val ENTITY_SIZE = 16 const val GLOW_OBJECT_SIZE = 56 inline fun <reified T : Any> cached(address: Int, offset: Int = 0) = Cached<T>({ csgo[address + offset] }) inline fun <reified T : Any> cached(address: Long, offset: Int = 0): Cached<T> = cached(address.toInt(), offset) inline fun <reified T : Any> cached(module: Module, offset: Int = 0) = Cached({ module.get<T>(offset) }) inline fun <reified T : Any> Addressable.cached(offset: Int = 0): Cached<T> = cached(this.address, offset)
gpl-3.0
ce7aa2d7e39fe6220efa8f3ab66f2807
34.08
112
0.729452
3.356322
false
false
false
false
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/util/value/ValueItemViewHolder.kt
1
1907
package ffc.app.util.value import android.support.annotation.ColorInt import android.support.annotation.ColorRes import android.support.annotation.DrawableRes import android.support.v4.content.ContextCompat import android.support.v7.widget.RecyclerView import android.view.View import android.widget.ImageView import android.widget.TextView import ffc.android.gone import ffc.app.R import org.jetbrains.anko.find import org.jetbrains.anko.findOptional class ValueItemViewHolder(view: View) : RecyclerView.ViewHolder(view) { private val captionView: TextView private val labelView: TextView private val valueView: TextView private val iconView: ImageView? init { captionView = itemView.find(R.id.captionView) labelView = itemView.find(R.id.labelView) valueView = itemView.find(R.id.valueView) iconView = itemView.findOptional(R.id.iconView) } fun bind(value: Value) { bind(value.label, value.value, value.caption, value.color, value.colorRes, value.iconRes) } fun bind( label: String?, value: String = "-", caption: String? = null, @ColorInt color: Int? = null, @ColorRes colorRes: Int? = null, @DrawableRes iconRes: Int? = null ) { with(itemView) { labelView.text = label?.trim() labelView.visibility = if (label.isNullOrBlank()) View.GONE else View.VISIBLE valueView.text = value.trim() captionView.text = caption?.trim() captionView.visibility = if (caption == null) View.GONE else View.VISIBLE color?.let { valueView.setTextColor(it) } colorRes?.let { valueView.setTextColor(ContextCompat.getColor(context, it)) } iconView?.let { it.setImageResource(iconRes ?: 0) } } } fun hindLabel() { labelView.gone() } }
apache-2.0
18791a08ac765aa9d3b3d01e7cabdd18
31.322034
97
0.661772
4.247216
false
false
false
false
pennlabs/penn-mobile-android
PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/Gym.kt
1
1729
package com.pennapps.labs.pennmobile.classes import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import org.joda.time.DateTime import org.joda.time.Interval import java.util.LinkedList class Gym { // fields from parsing JSON @SerializedName("hours") @Expose private val hoursList: List<GymHours>? = null @Expose val name: String? = null // other fields private var intervalList: List<Interval>? = null // check if we've already gotten the hours. if we have, just return it, if not, get it val hours: List<Interval>? get() { if (intervalList != null) { return intervalList ?: hours } val tempMutableList: MutableList<Interval> = LinkedList() if (hoursList == null) { return null } for (g in hoursList) { tempMutableList.add(g.interval) } intervalList = tempMutableList return intervalList } val isOpen: Boolean get() { hours // update interval list val current = DateTime() intervalList?.let { intervals -> for (i in intervals) { if (i.contains(current)) { return true } } } return false } /*fun currentInterval(): Interval { val current = DateTime() for (i in intervalList!!) { if (i.contains(current)) { return i } } // if this isn't open right now, throw exception throw IllegalStateException() }*/ }
mit
300d7f9466a76ec876759a2340a9bffb
25.6
90
0.53557
4.94
false
false
false
false
stripe/stripe-android
example/src/main/java/com/stripe/example/activity/BecsDebitPaymentMethodActivity.kt
1
1441
package com.stripe.example.activity import android.os.Bundle import androidx.lifecycle.Observer import com.stripe.android.view.BecsDebitWidget import com.stripe.example.databinding.BecsDebitActivityBinding class BecsDebitPaymentMethodActivity : StripeIntentActivity() { private val viewBinding: BecsDebitActivityBinding by lazy { BecsDebitActivityBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(viewBinding.root) viewModel.inProgress.observe(this, { enableUi(!it) }) viewModel.status.observe(this, Observer(viewBinding.status::setText)) viewBinding.element.validParamsCallback = object : BecsDebitWidget.ValidParamsCallback { override fun onInputChanged(isValid: Boolean) { viewBinding.payButton.isEnabled = isValid viewBinding.saveButton.isEnabled = isValid } } viewBinding.payButton.setOnClickListener { viewBinding.element.params?.let { createAndConfirmPaymentIntent("au", it) } } viewBinding.saveButton.setOnClickListener { viewBinding.element.params?.let { createAndConfirmSetupIntent("au", it) } } } private fun enableUi(enabled: Boolean) { viewBinding.payButton.isEnabled = enabled viewBinding.saveButton.isEnabled = enabled } }
mit
559247ac0ce76e179b99bc2d90454182
35.025
96
0.70923
5.259124
false
false
false
false
nimakro/tornadofx
src/main/java/tornadofx/Lib.kt
1
14629
package tornadofx import javafx.beans.InvalidationListener import javafx.beans.property.* import javafx.beans.value.* import javafx.collections.* import javafx.collections.transformation.FilteredList import javafx.collections.transformation.SortedList import javafx.geometry.Insets import javafx.scene.control.ListView import javafx.scene.control.TableView import javafx.scene.input.Clipboard import javafx.scene.input.ClipboardContent import javafx.scene.input.DataFormat import java.io.File import java.util.function.Predicate /** * A wrapper for an observable list of items that can be bound to a list control like TableView, ListView etc. * * The wrapper makes the data sortable and filterable. Configure a filter by setting the * predicate property or by calling filterWhen to automatically update the predicate when * an observable value changes. * ** Usage: * * ```kotlin * val table = TableView<Person>() * val data = SortedFilteredList(persons).bindTo(table) * ``` * * Items can be updated by calling `data.items.setAll` or `data.items.addAll` at a later time. */ @Suppress("UNCHECKED_CAST") class SortedFilteredList<T>( val items: ObservableList<T> = FXCollections.observableArrayList(), initialPredicate: (T) -> Boolean = { true }, val filteredItems: FilteredList<T> = FilteredList(items, initialPredicate), val sortedItems: SortedList<T> = SortedList(filteredItems)) : ObservableList<T> { init { items.onChange { refilter() } } // Should setAll be forwarded to the underlying list? This might be needed for full editing capabilities, // but will affect the ordering of the underlying list var setAllPassThrough = false override val size: Int get() = sortedItems.size override fun contains(element: T) = element in sortedItems override fun containsAll(elements: Collection<T>) = sortedItems.containsAll(elements) override fun get(index: Int) = sortedItems[index] override fun indexOf(element: T) = sortedItems.indexOf(element) override fun isEmpty() = sortedItems.isEmpty() override fun iterator() = sortedItems.iterator() override fun lastIndexOf(element: T) = sortedItems.lastIndexOf(element) override fun add(element: T) = items.add(element) override fun add(index: Int, element: T) { val item = sortedItems[index] val backingIndex = items.indexOf(item) if (backingIndex > -1) { items.add(backingIndex, element) } } override fun addAll(index: Int, elements: Collection<T>): Boolean { val item = sortedItems[index] val backingIndex = items.indexOf(item) if (backingIndex > -1) { return items.addAll(backingIndex, elements) } return false } override fun addAll(elements: Collection<T>) = items.addAll(elements) override fun clear() = items.clear() override fun listIterator() = sortedItems.listIterator() override fun listIterator(index: Int) = sortedItems.listIterator(index) override fun remove(element: T) = items.remove(element) override fun removeAll(elements: Collection<T>) = items.removeAll(elements) override fun removeAt(index: Int): T? { val item = sortedItems[index] val backingIndex = items.indexOf(item) return if (backingIndex > -1) { items.removeAt(backingIndex) } else { null } } override fun subList(fromIndex: Int, toIndex: Int): MutableList<T> { val item = sortedItems[fromIndex] val backingFromIndex = items.indexOf(item) if (backingFromIndex > -1) { return items.subList(backingFromIndex, items.indexOf(sortedItems[toIndex])) } return mutableListOf() } override fun removeAll(vararg elements: T) = items.removeAll(elements) override fun addAll(vararg elements: T) = items.addAll(elements) override fun remove(from: Int, to: Int) { val item = sortedItems[from] val backingFromIndex = items.indexOf(item) if (backingFromIndex > -1) { items.remove(backingFromIndex, items.indexOf(sortedItems[to])) } } override fun retainAll(vararg elements: T) = items.retainAll(elements) override fun retainAll(elements: Collection<T>) = items.retainAll(elements) override fun removeListener(listener: ListChangeListener<in T>?) { sortedItems.removeListener(listener) } override fun removeListener(listener: InvalidationListener?) { sortedItems.removeListener(listener) } override fun addListener(listener: ListChangeListener<in T>?) { sortedItems.addListener(listener) } override fun addListener(listener: InvalidationListener?) { sortedItems.addListener(listener) } override fun setAll(col: MutableCollection<out T>?) = if (setAllPassThrough) items.setAll(col) else false override fun setAll(vararg elements: T) = items.setAll(*elements) /** * Support editing of the sorted/filtered list. Useful to support editing support in ListView/TableView etc */ override fun set(index: Int, element: T): T { val item = sortedItems[index] val backingIndex = items.indexOf(item) if (backingIndex > -1) { items[backingIndex] = element } return item } /** * Force the filtered list to refilter it's items based on the current predicate without having to configure a new predicate. * Avoid reassigning the property value as that would impede binding. */ fun refilter() { val p = predicate if (p != null) { filteredItems.predicate = Predicate { p(it) } } } val predicateProperty: ObjectProperty<(T) -> Boolean> = object : SimpleObjectProperty<(T) -> Boolean>() { override fun set(newValue: ((T) -> Boolean)) { super.set(newValue) filteredItems.predicate = Predicate { newValue(it) } } } var predicate by predicateProperty /** * Bind this data object to the given TableView. * * The `tableView.items` is set to the underlying sortedItems. * * The underlying sortedItems.comparatorProperty` is automatically bound to `tableView.comparatorProperty`. */ fun bindTo(tableView: TableView<T>): SortedFilteredList<T> = apply { tableView.items = this sortedItems.comparatorProperty().bind(tableView.comparatorProperty()) } /** * Bind this data object to the given ListView. * * The `listView.items` is set to the underlying sortedItems. * */ fun bindTo(listView: ListView<T>): SortedFilteredList<T> = apply { listView.items = this } /** * Update the filter predicate whenever the given observable changes. The filter expression * receives both the observable value and the current list item to evaluate. * * Convenient for filtering based on a TextField: * * <pre> * textfield { * promptText = "Filtrering" * data.filterWhen(textProperty(), { query, item -> item.matches(query) } ) * } * </pre> */ fun <Q> filterWhen(observable: ObservableValue<Q>, filterExpr: (Q, T) -> Boolean) { observable.addListener { observableValue, oldValue, newValue -> predicate = { filterExpr(newValue, it) } } } } fun <T> List<T>.observable(): ObservableList<T> = FXCollections.observableList(this) fun <T> Set<T>.observable(): ObservableSet<T> = FXCollections.observableSet(this) fun <K, V> Map<K, V>.observable(): ObservableMap<K, V> = FXCollections.observableMap(this) fun Clipboard.setContent(op: ClipboardContent.() -> Unit) { val content = ClipboardContent() op(content) setContent(content) } fun Clipboard.putString(value: String) = setContent { putString(value) } fun Clipboard.putFiles(files: MutableList<File>) = setContent { putFiles(files) } fun Clipboard.put(dataFormat: DataFormat, value: Any) = setContent { put(dataFormat, value) } inline fun <T> ChangeListener(crossinline listener: (observable: ObservableValue<out T>?, oldValue: T, newValue: T) -> Unit): ChangeListener<T> = javafx.beans.value.ChangeListener<T> { observable, oldValue, newValue -> listener(observable, oldValue, newValue) } /** * Listen for changes to this observable. Optionally only listen x times. * The lambda receives the changed value when the change occurs, which may be null, */ fun <T> ObservableValue<T>.onChangeTimes(times: Int, op: (T?) -> Unit) { var counter = 0 val listener = object : ChangeListener<T> { override fun changed(observable: ObservableValue<out T>?, oldValue: T, newValue: T) { if (++counter == times) { removeListener(this) } op(newValue) } } addListener(listener) } fun <T> ObservableValue<T>.onChangeOnce(op: (T?) -> Unit) = onChangeTimes(1, op) fun <T> ObservableValue<T>.onChange(op: (T?) -> Unit) = apply { addListener { o, oldValue, newValue -> op(newValue) } } fun ObservableBooleanValue.onChange(op: (Boolean) -> Unit) = apply { addListener { o, old, new -> op(new ?: false) } } fun ObservableIntegerValue.onChange(op: (Int) -> Unit) = apply { addListener { o, old, new -> op((new ?: 0).toInt()) } } fun ObservableLongValue.onChange(op: (Long) -> Unit) = apply { addListener { o, old, new -> op((new ?: 0L).toLong()) } } fun ObservableFloatValue.onChange(op: (Float) -> Unit) = apply { addListener { o, old, new -> op((new ?: 0f).toFloat()) } } fun ObservableDoubleValue.onChange(op: (Double) -> Unit) = apply { addListener { o, old, new -> op((new ?: 0.0).toDouble()) } } fun <T> ObservableList<T>.onChange(op: (ListChangeListener.Change<out T>) -> Unit) = apply { addListener(ListChangeListener { op(it) }) } /** * Create a proxy property backed by calculated data based on a specific property. The setter * must return the new value for the backed property. * The scope of the getter and setter will be the receiver property */ fun <R, T> proxyprop(receiver: Property<R>, getter: Property<R>.() -> T, setter: Property<R>.(T) -> R): ObjectProperty<T> = object : SimpleObjectProperty<T>() { init { receiver.onChange { fireValueChangedEvent() } } override fun invalidated() { receiver.value = setter(receiver, super.get()) } override fun get() = getter.invoke(receiver) override fun set(v: T) { receiver.value = setter(receiver, v) super.set(v) } } /** * Create a proxy double property backed by calculated data based on a specific property. The setter * must return the new value for the backed property. * The scope of the getter and setter will be the receiver property */ fun <R> proxypropDouble(receiver: Property<R>, getter: Property<R>.() -> Double, setter: Property<R>.(Double) -> R): DoubleProperty = object : SimpleDoubleProperty() { init { receiver.onChange { fireValueChangedEvent() } } override fun invalidated() { receiver.value = setter(receiver, super.get()) } override fun get() = getter.invoke(receiver) override fun set(v: Double) { receiver.value = setter(receiver, v) super.set(v) } } fun insets(all: Number) = Insets(all.toDouble(), all.toDouble(), all.toDouble(), all.toDouble()) fun insets(horizontal: Number? = null, vertical: Number? = null) = Insets( vertical?.toDouble() ?: 0.0, horizontal?.toDouble() ?: 0.0, vertical?.toDouble() ?: 0.0, horizontal?.toDouble() ?: 0.0 ) fun insets( top: Number? = null, right: Number? = null, bottom: Number? = null, left: Number? = null ) = Insets( top?.toDouble() ?: 0.0, right?.toDouble() ?: 0.0, bottom?.toDouble() ?: 0.0, left?.toDouble() ?: 0.0 ) fun Insets.copy( top: Number? = null, right: Number? = null, bottom: Number? = null, left: Number? = null ) = Insets( top?.toDouble() ?: this.top, right?.toDouble() ?: this.right, bottom?.toDouble() ?: this.bottom, left?.toDouble() ?: this.left ) fun Insets.copy( horizontal: Number? = null, vertical: Number? = null ) = Insets( vertical?.toDouble() ?: this.top, horizontal?.toDouble() ?: this.right, vertical?.toDouble() ?: this.bottom, horizontal?.toDouble() ?: this.left ) val Insets.horizontal get() = (left + right) / 2 val Insets.vertical get() = (top + bottom) / 2 val Insets.all get() = (left + right + top + bottom) / 4 fun String.isLong() = toLongOrNull() != null fun String.isInt() = toIntOrNull() != null fun String.isDouble() = toDoubleOrNull() != null fun String.isFloat() = toFloatOrNull() != null /** * [forEach] with Map.Entree as receiver. */ inline fun <K, V> Map<K, V>.withEach(action: Map.Entry<K, V>.() -> Unit) = forEach(action) /** * [forEach] with the element as receiver. */ inline fun <T> Iterable<T>.withEach(action: T.() -> Unit) = forEach(action) /** * [forEach] with the element as receiver. */ inline fun <T> Sequence<T>.withEach(action: T.() -> Unit) = forEach(action) /** * [forEach] with the element as receiver. */ inline fun <T> Array<T>.withEach(action: T.() -> Unit) = forEach(action) /** * [map] with Map.Entree as receiver. */ inline fun <K, V, R> Map<K, V>.mapEach(action: Map.Entry<K, V>.() -> R) = map(action) /** * [map] with the element as receiver. */ inline fun <T, R> Iterable<T>.mapEach(action: T.() -> R) = map(action) /** * [map] with the element as receiver. */ fun <T, R> Sequence<T>.mapEach(action: T.() -> R) = map(action) /** * [map] with the element as receiver. */ inline fun <T, R> Array<T>.mapEach(action: T.() -> R) = map(action) /** * [mapTo] with Map.Entree as receiver. */ inline fun <K, V, R, C : MutableCollection<in R>> Map<K, V>.mapEachTo(destination: C, action: Map.Entry<K, V>.() -> R) = mapTo(destination, action) /** * [mapTo] with the element as receiver. */ inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapEachTo(destination: C, action: T.() -> R) = mapTo(destination, action) /** * [mapTo] with the element as receiver. */ fun <T, R, C : MutableCollection<in R>> Sequence<T>.mapEachTo(destination: C, action: T.() -> R) = mapTo(destination, action) /** * [mapTo] with the element as receiver. */ fun <T, R, C : MutableCollection<in R>> Array<T>.mapEachTo(destination: C, action: T.() -> R) = mapTo(destination, action)
apache-2.0
887d98f686c51808198344c1058475e9
33.750594
167
0.651446
3.985018
false
false
false
false
Soya93/Extract-Refactoring
platform/script-debugger/debugger-ui/src/FunctionScopesValueGroup.kt
5
1657
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.xdebugger.frame.XCompositeNode import com.intellij.xdebugger.frame.XValueChildrenList import com.intellij.xdebugger.frame.XValueGroup import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.done import org.jetbrains.debugger.values.FunctionValue import org.jetbrains.rpc.LOG import java.util.* internal class FunctionScopesValueGroup(private val functionValue: FunctionValue, private val variableContext: VariableContext) : XValueGroup("Function scopes") { override fun computeChildren(node: XCompositeNode) { node.setAlreadySorted(true) functionValue.resolve() .done(node) { val scopes = it.scopes if (scopes == null || scopes.size == 0) { node.addChildren(XValueChildrenList.EMPTY, true) } else { createAndAddScopeList(node, Arrays.asList(*scopes), variableContext, null) } } .rejected { Promise.logError(LOG, it) node.setErrorMessage(it.message!!) } } }
apache-2.0
c06304889f0f2754a03251e3a4ecefda
35.043478
162
0.722993
4.418667
false
false
false
false
attila-kiss-it/querydsl
querydsl-kotlin-codegen/src/main/kotlin/com/querydsl/kotlin/codegen/KotlinProjectionSerializer.kt
2
4505
/* * Copyright 2021, The Querydsl Team (http://www.querydsl.com/team) * * 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.querydsl.kotlin.codegen import com.querydsl.codegen.CodegenModule import com.querydsl.codegen.EntityType import com.querydsl.codegen.GeneratedAnnotationResolver import com.querydsl.codegen.ProjectionSerializer import com.querydsl.codegen.SerializerConfig import com.querydsl.codegen.TypeMappings import com.querydsl.codegen.utils.CodeWriter import com.querydsl.codegen.utils.model.Type import com.querydsl.core.types.ConstructorExpression import com.querydsl.core.types.Expression import com.squareup.kotlinpoet.AnnotationSpec import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.ParameterSpec import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.TypeSpec import com.squareup.kotlinpoet.WildcardTypeName import com.squareup.kotlinpoet.asClassName import com.squareup.kotlinpoet.joinToCode import javax.inject.Inject import javax.inject.Named open class KotlinProjectionSerializer @Inject constructor( private val mappings: TypeMappings, @Named(CodegenModule.GENERATED_ANNOTATION_CLASS) private val generatedAnnotationClass: Class<out Annotation> = GeneratedAnnotationResolver.resolveDefault() ) : ProjectionSerializer { protected open fun intro(model: EntityType): TypeSpec.Builder { val queryType = mappings.getPathClassName(model, model) return TypeSpec.classBuilder(queryType) .superclass(ConstructorExpression::class.parameterizedBy(model)) .addKdoc("${queryType.canonicalName} is a Querydsl Projection type for ${model.simpleName}") .addAnnotation(AnnotationSpec.builder(generatedAnnotationClass).addMember("%S", javaClass.name).build()) .addType(introCompanion(model)) } protected open fun introCompanion(model: EntityType): TypeSpec { return TypeSpec.companionObjectBuilder() .addProperty(PropertySpec.builder("serialVersionUID", Long::class, KModifier.CONST, KModifier.PRIVATE).initializer("%L", model.hashCode()).build()) .build() } protected open fun TypeSpec.Builder.outro(type: EntityType, writer: CodeWriter) { val queryType: Type = mappings.getPathType(type, type, false) FileSpec.builder(queryType.packageName, queryType.simpleName) .addType(build()) .build() .writeTo(writer) } override fun serialize(model: EntityType, serializerConfig: SerializerConfig, writer: CodeWriter) { val builder = intro(model) val sizes: MutableSet<Int> = mutableSetOf() for (c in model.constructors) { val asExpr = sizes.add(c.parameters.size) builder.addFunction( FunSpec.constructorBuilder() .addParameters(c.parameters.map { ParameterSpec.builder( it.name, when { !asExpr -> mappings.getExprType(it.type, model, false, false, true).asTypeName() it.type.isFinal -> Expression::class.parameterizedBy(it.type.asTypeName()) else -> Expression::class.asClassName().parameterizedBy(WildcardTypeName.producerOf(it.type.asTypeName())) } ).build() }) .callSuperConstructor(model.asClassNameStatement(), c.parameters.map { it.type.asClassNameStatement() }.joinToCode(", ", "arrayOf(", ")"), *c.parameters.map { CodeBlock.of("%L", it.name) }.toTypedArray() ) .build() ) } builder.outro(model, writer) } }
apache-2.0
535617ad6b16d58c98a1b491f493666b
45.9375
159
0.693008
4.8493
false
false
false
false
qikh/mini-block-chain
src/main/kotlin/mbc/network/message/HelloMessage.kt
1
1242
package mbc.network.message import org.spongycastle.asn1.* /** * HELLO消息, */ class HelloMessage(val version: Int, val clientId: String, val listenPort: Int, val nodeId: String) : Message { override fun code(): Byte = MessageCodes.HELLO.code override fun encode(): ByteArray { val v = ASN1EncodableVector() v.add(ASN1Integer(version.toLong())) v.add(DERUTF8String(clientId)) v.add(ASN1Integer(listenPort.toLong())) v.add(DERUTF8String(nodeId)) return DERSequence(v).encoded } companion object { fun decode(bytes: ByteArray): HelloMessage? { val v = ASN1InputStream(bytes).readObject() if (v != null) { val seq = ASN1Sequence.getInstance(v) val version = ASN1Integer.getInstance(seq.getObjectAt(0))?.value?.toInt() val clientId = DERUTF8String.getInstance(seq.getObjectAt(1))?.string val listenPort = ASN1Integer.getInstance(seq.getObjectAt(2))?.value?.toInt() val nodeId = DERUTF8String.getInstance(seq.getObjectAt(3))?.string if (version != null && clientId != null && listenPort != null && nodeId != null) { return HelloMessage(version, clientId, listenPort, nodeId) } } return null } } }
apache-2.0
cc12e2a06515014bc80ca1eea508a403
27.090909
111
0.661812
3.8625
false
false
false
false
inorichi/tachiyomi-extensions
src/ru/mangaclub/src/eu/kanade/tachiyomi/extension/ru/mangaclub/Mangaclub.kt
1
7683
package eu.kanade.tachiyomi.extension.ru.mangaclub import android.net.Uri import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.FormBody import okhttp3.OkHttpClient import okhttp3.Request import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat import java.util.Locale class Mangaclub : ParsedHttpSource() { // Info override val name: String = "MangaClub" override val baseUrl: String = "https://mangaclub.ru" override val lang: String = "ru" override val supportsLatest: Boolean = false override val client: OkHttpClient = network.cloudflareClient // Popular override fun popularMangaRequest(page: Int): Request = GET("$baseUrl/page/$page/", headers) override fun popularMangaNextPageSelector(): String = "a i.icon-right-open" override fun popularMangaSelector(): String = "div.shortstory" override fun popularMangaFromElement(element: Element): SManga = SManga.create().apply { thumbnail_url = element.select("img").attr("abs:src") element.select(".title > a").apply { title = this.text().substringBefore("/").trim() setUrlWithoutDomain(this.attr("abs:href")) } } // Latest override fun latestUpdatesRequest(page: Int): Request = popularMangaRequest(page) override fun latestUpdatesNextPageSelector(): String = popularMangaNextPageSelector() override fun latestUpdatesSelector(): String = popularMangaSelector() override fun latestUpdatesFromElement(element: Element): SManga = popularMangaFromElement(element) // Search override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { if (query.isNotBlank()) { val formBody = FormBody.Builder() .add("do", "search") .add("subaction", "search") .add("search_start", page.toString()) .add("full_search", "0") .add("result_from", ((page - 1) * 8 + 1).toString()) .add("story", query) .build() val searchHeaders = headers.newBuilder().add("Content-Type", "application/x-www-form-urlencoded").build() return POST("$baseUrl/index.php?do=search", searchHeaders, formBody) } val uri = Uri.parse(baseUrl).buildUpon() for (filter in filters) { if (filter is Tag && filter.values[filter.state].isNotEmpty()) { uri.appendEncodedPath("tags/${filter.values[filter.state]}") } } uri.appendPath("page").appendPath(page.toString()) return GET(uri.toString(), headers) } override fun searchMangaNextPageSelector(): String = popularMangaNextPageSelector() override fun searchMangaSelector(): String = popularMangaSelector() override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element) // Details override fun mangaDetailsParse(document: Document): SManga = SManga.create().apply { thumbnail_url = document.select("div.image img").attr("abs:src") title = document.select(".title").text().substringBefore("/").trim() author = document.select("a[href*=author]").text().trim() artist = author status = when (document.select("a[href*=status_translation]")?.first()?.text()) { "Продолжается" -> SManga.ONGOING "Завершен" -> SManga.COMPLETED else -> SManga.UNKNOWN } description = document.select("div.description").text().trim() genre = document.select("div.info a[href*=tags]").joinToString(", ") { it.text() } } // Chapters override fun chapterListSelector(): String = ".chapter-item" override fun chapterFromElement(element: Element): SChapter = SChapter.create().apply { val link = element.select("a") name = link.text().trim() chapter_number = name.substringAfter("Глава").replace(",", ".").trim().toFloat() setUrlWithoutDomain(link.attr("abs:href")) date_upload = parseDate(element.select(".date").text().trim()) } private fun parseDate(date: String): Long { return SimpleDateFormat("dd.MM.yyyy", Locale.US).parse(date)?.time ?: 0 } // Pages override fun pageListParse(document: Document): List<Page> = mutableListOf<Page>().apply { document.select(".manga-lines-page a").forEach { add(Page(it.attr("data-p").toInt(), "", baseUrl.replace("//", "//img.") + "/" + it.attr("data-i"))) } } override fun imageUrlParse(document: Document): String = throw Exception("imageUrlParse Not Used") // Filters private class Categories(values: Array<Pair<String, String>>) : Filter.Select<String>("Категории", values.map { it.first }.toTypedArray()) private class Tag(values: Array<String>) : Filter.Select<String>("Жанр", values) private class Sort(values: List<Pair<String, String>>) : Filter.Sort( "Сортировать результат поиска", values.map { it.first }.toTypedArray(), Selection(2, false) ) private class Status : Filter.Select<String>( "Статус", arrayOf("", "Завершен", "Продолжается", "Заморожено/Заброшено") ) override fun getFilterList() = FilterList( Filter.Header("NOTE: Filters are ignored if using text search."), Tag(tag) ) private val categoriesArray = arrayOf( Pair("", ""), Pair("Манга", "1"), Pair("Манхва", "2"), Pair("Маньхуа", "3"), Pair("Веб-манхва", "6") ) private val tag = arrayOf( "", "Боевые искусства", "Боевик", "Вампиры", "Гарем", "Гендерная интрига", "Героическое фэнтези", "Додзинси", "Дзёсэй", "Драма", "Детектив", "Игра", "История", "Киберпанк", "Комедия", "Мистика", "Меха", "Махо-сёдзё", "Научная фантастика", "Повседневность", "Приключения", "Психология", "Романтика", "Самурайский боевик", "Сверхъестественное", "Сёдзё", "Сёдзё для взрослых", "Сёдзё-ай", "Сёнэн", "Сёнэн-ай", "Спокон", "Сэйнэн", "Спорт", "Трагедия", "Триллер", "Ужасы", "Фантастика", "Фэнтези", "Школа", "Эротика", "Этти", "Юри", "Яой" ) private val sortables = listOf( Pair("По заголовку", "title"), Pair("По количеству комментариев", "comm_num"), Pair("По количеству просмотров", "news_read"), Pair("По имени автора", "autor"), Pair("По рейтингу", "rating") ) }
apache-2.0
5a45db09e137b84e756b6fcf2eba7445
34.929293
117
0.615125
4.028313
false
false
false
false
ohmae/DmsExplorer
mobile/src/main/java/net/mm2d/dmsexplorer/log/Param.kt
1
2201
/* * Copyright (c) 2018 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.dmsexplorer.log /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ internal object Param { const val ACHIEVEMENT_ID = "achievement_id" const val CHARACTER = "character" const val TRAVEL_CLASS = "travel_class" const val CONTENT_TYPE = "content_type" const val CURRENCY = "currency" const val COUPON = "coupon" const val START_DATE = "start_date" const val END_DATE = "end_date" const val FLIGHT_NUMBER = "flight_number" const val GROUP_ID = "group_id" const val ITEM_CATEGORY = "item_category" const val ITEM_ID = "item_id" const val ITEM_LOCATION_ID = "item_location_id" const val ITEM_NAME = "item_name" const val LOCATION = "location" const val LEVEL = "level" const val LEVEL_NAME = "level_name" const val METHOD = "method" const val NUMBER_OF_NIGHTS = "number_of_nights" const val NUMBER_OF_PASSENGERS = "number_of_passengers" const val NUMBER_OF_ROOMS = "number_of_rooms" const val DESTINATION = "destination" const val ORIGIN = "origin" const val PRICE = "price" const val QUANTITY = "quantity" const val SCORE = "score" const val SHIPPING = "shipping" const val TRANSACTION_ID = "transaction_id" const val SEARCH_TERM = "search_term" const val SUCCESS = "success" const val TAX = "tax" const val VALUE = "value" const val VIRTUAL_CURRENCY_NAME = "virtual_currency_name" const val CAMPAIGN = "campaign" const val SOURCE = "source" const val MEDIUM = "medium" const val TERM = "term" const val CONTENT = "content" const val ACLID = "aclid" const val CP1 = "cp1" const val ITEM_BRAND = "item_brand" const val ITEM_VARIANT = "item_variant" const val ITEM_LIST = "item_list" const val CHECKOUT_STEP = "checkout_step" const val CHECKOUT_OPTION = "checkout_option" const val CREATIVE_NAME = "creative_name" const val CREATIVE_SLOT = "creative_slot" const val AFFILIATION = "affiliation" const val INDEX = "index" }
mit
e9691affd4d534127d75c7a7534656ad
33.68254
61
0.664989
3.541329
false
false
false
false
vimeo/stag-java
stag-library-compiler/src/test/java/com/vimeo/stag/processor/dummy/DummyMapClass.kt
2
1921
/* * The MIT License (MIT) * <p/> * Copyright (c) 2016 Vimeo * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.vimeo.stag.processor.dummy class DummyMapClass : MutableMap<Any, Any> { override val size: Int get() = 0 override fun containsKey(key: Any) = false override fun containsValue(value: Any) = false override fun get(key: Any): Any? = null override fun isEmpty() = true override val entries: MutableSet<MutableMap.MutableEntry<Any, Any>> get() = mutableSetOf() override val keys: MutableSet<Any> get() = mutableSetOf() override val values: MutableCollection<Any> get() = mutableListOf() override fun clear() {} override fun put(key: Any, value: Any): Nothing? = null override fun putAll(from: Map<out Any, Any>) {} override fun remove(key: Any): Nothing? = null }
mit
737fc413a0e2a8dbb903a8264f3b0473
34.574074
81
0.709006
4.307175
false
false
false
false
felipebz/sonar-plsql
zpa-core/src/main/kotlin/org/sonar/plsqlopen/symbols/ScopeImpl.kt
1
3117
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plsqlopen.symbols import com.felipebz.flr.api.AstNode import org.sonar.plugins.plsqlopen.api.PlSqlGrammar import org.sonar.plugins.plsqlopen.api.symbols.Scope import org.sonar.plugins.plsqlopen.api.symbols.Symbol import java.util.* class ScopeImpl(private val outer: Scope?, private val node: AstNode, override val isAutonomousTransaction: Boolean = false, private val hasExceptionHandler: Boolean = false, override val isOverridingMember: Boolean = false) : Scope { private var identifier: String? = null override val symbols = mutableListOf<Symbol>() override fun tree() = node override fun outer() = outer override fun identifier(): String? { if (identifier == null) { identifier = "" val identifierNode = node.getFirstChildOrNull(PlSqlGrammar.IDENTIFIER_NAME, PlSqlGrammar.UNIT_NAME) if (identifierNode != null) { this.identifier = identifierNode.tokenOriginalValue } } return identifier } override fun hasExceptionHandler() = hasExceptionHandler /** * @param kind of the symbols to look for * @return the symbols corresponding to the given kind */ override fun getSymbols(kind: Symbol.Kind) = symbols.filter { it.`is`(kind) }.toList() override fun getSymbolsAcessibleInScope(name: String, vararg kinds: Symbol.Kind): Deque<Symbol> { val result = ArrayDeque<Symbol>() var scope: Scope? = this while (scope != null) { scope.symbols.filterTo(result) { it.called(name) && (kinds.isEmpty() || kinds.contains(it.kind())) } scope = scope.outer() } return result } override fun addSymbol(symbol: Symbol) { symbols.add(symbol) } override fun getSymbol(name: String, vararg kinds: Symbol.Kind): Symbol? { var scope: Scope? = this while (scope != null) { for (s in scope.symbols) { if (s.called(name) && (kinds.isEmpty() || kinds.contains(s.kind()))) { return s } } scope = scope.outer() } return null } }
lgpl-3.0
edee6e467f843416138674898a0dec7e
34.022472
112
0.645172
4.452857
false
false
false
false
mike-neck/kuickcheck
core/src/main/kotlin/org/mikeneck/kuickcheck/runner/ClassPath.kt
1
2270
/* * Copyright 2016 Shinya Mochida * * Licensed under the Apache License,Version2.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.mikeneck.kuickcheck.runner import java.nio.file.* import java.nio.file.attribute.BasicFileAttributes import java.util.* import java.util.jar.JarFile interface ClassPath { fun listClasses(): List<ClassFile> } data class FileClassPath(val path: String): ClassPath { override fun listClasses(): List<ClassFile> { val path = Paths.get(path) if (Files.exists(path) == false) return emptyList() Files.walkFileTree(path, visitor) return visitor.list().map { it.toString() } .map { RealClassFile(path, it) } } interface DirectoryScanner: FileVisitor<Path> { fun list(): List<Path> } val visitor: DirectoryScanner = object: SimpleFileVisitor<Path>(), DirectoryScanner { val list = mutableListOf<Path>() override fun list(): List<Path> { return list.toList() } override fun visitFile(file: Path?, attrs: BasicFileAttributes?): FileVisitResult? { if (file != null) list.add(file) return FileVisitResult.CONTINUE } } } data class JarClassPath(val path: String): ClassPath { companion object { val KOTLIN = listOf("/kotlin-stdlib/", "/kotlin-runtime/", "/kotlin-reflect/") } override fun listClasses(): List<ClassFile> { val kotlinLib = KOTLIN.filter { path.contains(it) }.size > 0 if (kotlinLib) return emptyList() val jarFile = JarFile(path) return Collections.list(jarFile.entries()).filter { !it.isDirectory } .filter { it.name.startsWith("META-INF") == false } .map{ it.name } .map(::ZipClassFile) } }
apache-2.0
0ab2af3267d320c92fd95c347b1c0916
31.428571
92
0.655507
4.274953
false
false
false
false