content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* 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("|")
} | preview/robowrapper/src/org/jetbrains/kotlin/android/robowrapper/androidUtils/Gravity.kt | 2764865508 |
// 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()
}
}
} | plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHPRSubmittableTextField.kt | 509206525 |
/*
* 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)
}
} | app/src/test/kotlin/com/vrem/wifianalyzer/wifi/predicate/AnyPredicateTest.kt | 4117257996 |
// WITH_RUNTIME
fun getValue(i: Int): String = ""
fun associateWithTo() {
val destination = mutableMapOf<Int, String>()
arrayOf(1).<caret>associateTo(destination) { it to getValue(it) }
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceAssociateFunction/associateWithTo/array.kt | 1975504829 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.VcsConfiguration.StandardConfirmation.ADD
import com.intellij.openapi.vcs.VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY
import com.intellij.openapi.vcs.VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY
import com.intellij.openapi.vcs.changes.ChangeListListener
import com.intellij.openapi.vcs.changes.ChangeListManagerImpl
import com.intellij.openapi.vcs.changes.VcsIgnoreManager
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.project.isDirectoryBased
import com.intellij.project.stateStore
import com.intellij.util.concurrency.QueueProcessor
import com.intellij.vfs.AsyncVfsEventsListener
import com.intellij.vfs.AsyncVfsEventsPostProcessor
import org.jetbrains.annotations.TestOnly
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.write
internal const val ASKED_ADD_EXTERNAL_FILES_PROPERTY = "ASKED_ADD_EXTERNAL_FILES" //NON-NLS
private val LOG = logger<ExternallyAddedFilesProcessorImpl>()
/**
* Extend [VcsVFSListener] to automatically add/propose to add into VCS files that were created not by IDE (externally created).
*/
internal class ExternallyAddedFilesProcessorImpl(project: Project,
private val parentDisposable: Disposable,
private val vcs: AbstractVcs,
private val addChosenFiles: (Collection<VirtualFile>) -> Unit)
: FilesProcessorWithNotificationImpl(project, parentDisposable), FilesProcessor, AsyncVfsEventsListener, ChangeListListener {
private val UNPROCESSED_FILES_LOCK = ReentrantReadWriteLock()
private val queue = QueueProcessor<Collection<VirtualFile>> { files -> processFiles(files) }
private val unprocessedFiles = mutableSetOf<VirtualFile>()
private val vcsManager = ProjectLevelVcsManager.getInstance(project)
private val vcsIgnoreManager = VcsIgnoreManager.getInstance(project)
fun install() {
runReadAction {
if (!project.isDisposed) {
project.messageBus.connect(parentDisposable).subscribe(ChangeListListener.TOPIC, this)
AsyncVfsEventsPostProcessor.getInstance().addListener(this, this)
}
}
}
override fun unchangedFileStatusChanged(upToDate: Boolean) {
if (!upToDate) return
if (!needProcessExternalFiles()) return
val files: Set<VirtualFile>
UNPROCESSED_FILES_LOCK.write {
files = unprocessedFiles.toHashSet()
unprocessedFiles.clear()
}
if (files.isEmpty()) return
if (needDoForCurrentProject()) {
LOG.debug("Add external files to ${vcs.displayName} silently ", files)
addChosenFiles(doFilterFiles(files))
}
else {
LOG.debug("Process external files and prompt to add if needed to ${vcs.displayName} ", files)
queue.add(files)
}
}
override fun filesChanged(events: List<VFileEvent>) {
if (!needProcessExternalFiles()) return
LOG.debug("Got events", events)
val configDir = project.getProjectConfigDir()
val externallyAddedFiles =
events.asSequence()
.filter {
it.isFromRefresh &&
it is VFileCreateEvent &&
!isProjectConfigDirOrUnderIt(configDir, it.parent)
}
.mapNotNull(VFileEvent::getFile)
.toList()
if (externallyAddedFiles.isEmpty()) return
LOG.debug("Got external files from VFS events", externallyAddedFiles)
UNPROCESSED_FILES_LOCK.write {
unprocessedFiles.addAll(externallyAddedFiles)
}
}
private fun doNothingSilently() = vcsManager.getStandardConfirmation(ADD, vcs).value == DO_NOTHING_SILENTLY
private fun needProcessExternalFiles(): Boolean {
if (doNothingSilently()) return false
if (!Registry.`is`("vcs.process.externally.added.files")) return false
return true
}
override fun dispose() {
super.dispose()
queue.clear()
UNPROCESSED_FILES_LOCK.write {
unprocessedFiles.clear()
}
}
override val notificationDisplayId: String = VcsNotificationIdsHolder.EXTERNALLY_ADDED_FILES
override val askedBeforeProperty = ASKED_ADD_EXTERNAL_FILES_PROPERTY
override val doForCurrentProjectProperty: String get() = throw UnsupportedOperationException() // usages overridden
override val showActionText: String = VcsBundle.message("external.files.add.notification.action.view")
override val forCurrentProjectActionText: String = VcsBundle.message("external.files.add.notification.action.add")
override val muteActionText: String = VcsBundle.message("external.files.add.notification.action.mute")
override val viewFilesDialogTitle: String? = VcsBundle.message("external.files.add.view.dialog.title", vcs.displayName)
override fun notificationTitle() = ""
override fun notificationMessage(): String = VcsBundle.message("external.files.add.notification.message", vcs.displayName)
override fun doActionOnChosenFiles(files: Collection<VirtualFile>) {
addChosenFiles(files)
}
override fun setForCurrentProject(isEnabled: Boolean) {
if (isEnabled) vcsManager.getStandardConfirmation(ADD, vcs).value = DO_ACTION_SILENTLY
VcsConfiguration.getInstance(project).ADD_EXTERNAL_FILES_SILENTLY = true
}
override fun needDoForCurrentProject() =
vcsManager.getStandardConfirmation(ADD, vcs).value == DO_ACTION_SILENTLY
&& VcsConfiguration.getInstance(project).ADD_EXTERNAL_FILES_SILENTLY
override fun doFilterFiles(files: Collection<VirtualFile>): Collection<VirtualFile> {
val parents = files.toHashSet()
return ChangeListManagerImpl.getInstanceImpl(project).unversionedFiles
.asSequence()
.filterNot(vcsIgnoreManager::isPotentiallyIgnoredFile)
.filter { isUnder(parents, it) }
.toSet()
}
private fun isUnder(parents: Set<VirtualFile>, child: VirtualFile) = generateSequence(child) { it.parent }.any { it in parents }
private fun isProjectConfigDirOrUnderIt(configDir: VirtualFile?, file: VirtualFile) =
configDir != null && VfsUtilCore.isAncestor(configDir, file, false)
private fun Project.getProjectConfigDir(): VirtualFile? {
if (!isDirectoryBased || isDefault) return null
val projectConfigDir = stateStore.directoryStorePath?.let(LocalFileSystem.getInstance()::findFileByNioFile)
if (projectConfigDir == null) {
LOG.warn("Cannot find project config directory for non-default and non-directory based project ${name}")
}
return projectConfigDir
}
@TestOnly
fun waitForEventsProcessedInTestMode() {
assert(ApplicationManager.getApplication().isUnitTestMode)
queue.waitFor()
}
}
| platform/vcs-impl/src/com/intellij/openapi/vcs/ExternallyAddedFilesProcessorImpl.kt | 1157297256 |
// 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())
}
)
}
}
}
| plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleBuildIssuesMiscImportingTest.kt | 2084406873 |
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtProperty
// OPTIONS: usages
data class A(public val field: Int) {
public val field<caret>: String
}
fun main(args: Array<String>) {
val a = A(10)
println(a.field)
}
// DISABLE-ERRORS | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findPropertyUsages/kt7656.0.kt | 1958906759 |
// 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)
}
| plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/tree/elements.kt | 3502645151 |
// PROBLEM: none
// WITH_RUNTIME
fun bar(f: () -> Unit) {}
fun bar(f: (Int) -> Unit) {}
fun test() {
bar { -><caret> }
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantLambdaArrow/notApplicableOverload.kt | 1029070580 |
fun foo2(f: (Int) -> Unit) {
f(1)
}
fun main(args: String) {
foo2(<caret>fun(i: Int) {
val p = i
})
} | plugins/kotlin/idea/tests/testData/intentions/anonymousFunctionToLambda/fullParam.kt | 180349128 |
package test
val prop = ":)" | plugins/kotlin/jps/jps-plugin/tests/testData/incremental/withJava/kotlinUsedInJava/propertyRenamed/prop.kt | 437160567 |
package io.urho3d
import android.content.Context
import org.libsdl.app.SDLActivity
import java.io.File
open class UrhoActivity : SDLActivity() {
companion object {
private val regex = Regex("^lib(.*)\\.so$")
@JvmStatic
fun getLibraryNames(context: Context) = File(context.applicationInfo.nativeLibraryDir)
.listFiles { _, it -> regex.matches(it) }!!
.sortedBy { it.lastModified() }
.map {
regex.find(it.name)?.groupValues?.last() ?: throw IllegalStateException()
}
}
}
| android/urho3d-lib/src/main/java/io/urho3d/UrhoActivity.kt | 985955274 |
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)
}
}
| plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/gradle/GradleProjectModuleOperationProvider.kt | 2216445666 |
// 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
}
| platform/platform-impl/src/com/intellij/internal/ui/uiDslShowcase/DemoComponents.kt | 988816702 |
// 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.jps.incremental.artifacts
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.PathUtil
import com.intellij.util.io.directoryContent
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.io.zipFile
import org.jetbrains.jps.api.GlobalOptions
import org.jetbrains.jps.builders.CompileScopeTestBuilder
import org.jetbrains.jps.incremental.artifacts.LayoutElementTestUtil.archive
import org.jetbrains.jps.incremental.artifacts.LayoutElementTestUtil.root
import org.jetbrains.jps.incremental.messages.BuildMessage
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.util.JpsPathUtil
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.security.DigestInputStream
import java.security.MessageDigest
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.jar.JarFile
import java.util.zip.CRC32
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import java.util.zip.ZipOutputStream
import kotlin.io.path.inputStream
class ArtifactBuilderTest : ArtifactBuilderTestCase() {
fun testFileCopy() {
val a = addArtifact(root().fileCopy(createFile("file.txt", "foo")))
buildAll()
assertOutput(a, directoryContent { file("file.txt", "foo") })
}
fun testDir() {
val a = addArtifact(
root()
.fileCopy(createFile("abc.txt"))
.dir("dir")
.fileCopy(createFile("xxx.txt", "bar"))
)
buildAll()
assertOutput(a, directoryContent {
file("abc.txt")
dir("dir") {
file("xxx.txt", "bar")
}
})
}
fun testArchive() {
val a = addArtifact(
root()
.archive("xxx.zip")
.fileCopy(createFile("X.class", "data"))
.dir("dir")
.fileCopy(createFile("Y.class"))
)
buildAll()
assertOutput(a, directoryContent {
zip("xxx.zip") {
file("X.class", "data")
dir("dir") {
file("Y.class")
}
}
})
}
fun testTwoDirsInArchive() {
val dir1 = PathUtil.getParentPath(PathUtil.getParentPath(createFile("dir1/a/x.txt")))
val dir2 = PathUtil.getParentPath(PathUtil.getParentPath(createFile("dir2/a/y.txt")))
val a = addArtifact(
root()
.archive("a.jar")
.dirCopy(dir1)
.dirCopy(dir2)
.dir("a").fileCopy(createFile("z.txt"))
)
buildAll()
assertOutput(a, directoryContent {
zip("a.jar") {
dir("a") {
file("x.txt")
file("y.txt")
file("z.txt")
}
}
})
}
fun testArchiveInArchive() {
val a = addArtifact(
root()
.archive("a.jar")
.archive("b.jar")
.fileCopy(createFile("xxx.txt", "foo"))
)
buildAll()
assertOutput(a, directoryContent {
zip("a.jar") {
zip("b.jar") {
file("xxx.txt", "foo")
}
}
})
}
fun testIncludedArtifact() {
val included = addArtifact("included",
root()
.fileCopy(createFile("aaa.txt")))
val a = addArtifact(
root()
.dir("dir")
.artifact(included)
.end()
.fileCopy(createFile("bbb.txt"))
)
buildAll()
assertOutput(included, directoryContent { file("aaa.txt") })
assertOutput(a, directoryContent {
dir("dir") {
file("aaa.txt")
}
file("bbb.txt")
})
}
fun testMergeDirectories() {
val included = addArtifact("included",
root().dir("dir").fileCopy(createFile("aaa.class")))
val a = addArtifact(
root()
.artifact(included)
.dir("dir")
.fileCopy(createFile("bbb.class")))
buildAll()
assertOutput(a, directoryContent {
dir("dir") {
file("aaa.class")
file("bbb.class")
}
})
}
fun testCopyLibrary() {
val libDir = createDir("lib")
directoryContent {
zip("a.jar") { file("a.txt") }
}.generate(File(libDir))
val library = addProjectLibrary("lib", "$libDir/a.jar")
val a = addArtifact(root().lib(library))
buildAll()
assertOutput(a, directoryContent { zip("a.jar") { file("a.txt") } })
}
fun testModuleOutput() {
val file = createFile("src/A.java", "public class A {}")
val module = addModule("a", PathUtil.getParentPath(file))
val artifact = addArtifact(root().module(module))
buildArtifacts(artifact)
assertOutput(artifact, directoryContent { file("A.class") })
}
fun testModuleSources() {
val file = createFile("src/A.java", "class A{}")
val testFile = createFile("tests/ATest.java", "class ATest{}")
val m = addModule("m", PathUtil.getParentPath(file))
m.addSourceRoot(JpsPathUtil.pathToUrl(PathUtil.getParentPath(testFile)), JavaSourceRootType.TEST_SOURCE)
val a = addArtifact(root().moduleSource(m))
buildAll()
assertOutput(a, directoryContent {
file("A.java")
})
val b = createFile("src/B.java", "class B{}")
buildAll()
assertOutput(a, directoryContent {
file("A.java")
file("B.java")
})
delete(b)
buildAll()
assertOutput(a, directoryContent {
file("A.java")
})
}
fun testModuleSourcesWithPackagePrefix() {
val file = createFile("src/A.java", "class A{}")
val m = addModule("m", PathUtil.getParentPath(file))
val sourceRoot = assertOneElement(m.sourceRoots)
val typed = sourceRoot.asTyped(JavaSourceRootType.SOURCE)
assertNotNull(typed)
typed!!.properties.packagePrefix = "org.foo"
val a = addArtifact(root().moduleSource(m))
buildAll()
assertOutput(a, directoryContent {
dir("org") {
dir("foo") {
file("A.java")
}
}
})
}
fun testCopyResourcesFromModuleOutput() {
val file = createFile("src/a.xml", "")
JpsJavaExtensionService.getInstance().getCompilerConfiguration(myProject).addResourcePattern("*.xml")
val module = addModule("a", PathUtil.getParentPath(file))
val artifact = addArtifact(root().module(module))
buildArtifacts(artifact)
assertOutput(artifact, directoryContent { file("a.xml") })
}
fun testIgnoredFile() {
val file = createFile("a/.svn/a.txt")
createFile("a/svn/b.txt")
val a = addArtifact(root().parentDirCopy(PathUtil.getParentPath(file)))
buildAll()
assertOutput(a, directoryContent { dir("svn") { file("b.txt") }})
}
fun testIgnoredFileInArchive() {
val file = createFile("a/.svn/a.txt")
createFile("a/svn/b.txt")
val a = addArtifact(archive("a.jar").parentDirCopy(PathUtil.getParentPath(file)))
buildAll()
assertOutput(a, directoryContent { zip("a.jar") { dir("svn") { file("b.txt")}}})
}
fun testCopyExcludedFolder() {
//explicitly added excluded files should be copied (e.g. compile output)
val file = createFile("xxx/excluded/a.txt")
createFile("xxx/excluded/CVS")
val excluded = PathUtil.getParentPath(file)
val dir = PathUtil.getParentPath(excluded)
val module = addModule("myModule")
module.contentRootsList.addUrl(JpsPathUtil.pathToUrl(dir))
module.excludeRootsList.addUrl(JpsPathUtil.pathToUrl(excluded))
val a = addArtifact(root().dirCopy(excluded))
buildAll()
assertOutput(a, directoryContent { file("a.txt") })
}
fun testCopyExcludedFile() {
//excluded files under non-excluded directory should not be copied
val file = createFile("xxx/excluded/a.txt")
createFile("xxx/b.txt")
createFile("xxx/CVS")
val dir = PathUtil.getParentPath(PathUtil.getParentPath(file))
val module = addModule("myModule")
module.contentRootsList.addUrl(JpsPathUtil.pathToUrl(dir))
module.excludeRootsList.addUrl(JpsPathUtil.pathToUrl(PathUtil.getParentPath(file)))
val a = addArtifact(root().dirCopy(dir))
buildAll()
assertOutput(a, directoryContent { file("b.txt") })
}
fun testExtractDirectory() {
val jarFile = createXJarFile()
val a = addArtifact("a", root().dir("dir").extractedDir(jarFile, "/dir"))
buildAll()
assertOutput(a, directoryContent {
dir("dir") {
file("file.txt", "text")
}
})
}
@Throws(IOException::class)
fun testExtractDirectoryFromExcludedJar() {
val jarPath = createFile("dir/lib/j.jar")
val libDir = File(getOrCreateProjectDir(), "dir/lib")
directoryContent {
zip("j.jar") {
file("a.txt", "a")
}
}.generate(libDir)
val module = addModule("m")
val libDirPath = FileUtil.toSystemIndependentName(libDir.absolutePath)
module.contentRootsList.addUrl(JpsPathUtil.pathToUrl(PathUtil.getParentPath(libDirPath)))
module.excludeRootsList.addUrl(JpsPathUtil.pathToUrl(libDirPath))
val a = addArtifact("a", root().extractedDir(jarPath, ""))
buildAll()
assertOutput(a, directoryContent {
file("a.txt", "a")
})
}
fun testPackExtractedDirectory() {
val zipPath = createXJarFile()
val a = addArtifact("a", root().archive("a.jar").extractedDir(zipPath, "/dir"))
buildAll()
assertOutput(a, directoryContent { zip("a.jar") {
file("file.txt", "text")
}})
}
private fun Path.checksum(): String = inputStream().buffered().use { input ->
val digest = MessageDigest.getInstance("SHA-256")
DigestInputStream(input, digest).use {
var bytesRead = 0
val buffer = ByteArray(1024 * 8)
while (bytesRead != -1) {
bytesRead = it.read(buffer)
}
}
Base64.getEncoder().encodeToString(digest.digest())
}
fun `test jars build reproducibility`() {
myBuildParams[GlobalOptions.BUILD_DATE_IN_SECONDS] = (System.currentTimeMillis() / 1000).toString()
val jar = root().archive("a.jar")
.extractedDir(createXJarFile(), "/")
.dir("META-INF").fileCopy(createFile("src/MANIFEST.MF"))
.let { addArtifact("a", it).outputPath }
?.let { Paths.get(it).resolve("a.jar") }
requireNotNull(jar)
val checksums = (1..2).map {
// sleeping more than a second ensures different last modification time
// for the next iteration jar if the build date isn't provided or ignored
TimeUnit.SECONDS.sleep(2)
FileUtil.delete(jar.parent)
assert(!Files.exists(jar))
buildAll()
assert(Files.exists(jar))
jar.checksum()
}.distinct()
assert(checksums.count() == 1)
}
fun `test no duplicated directory entries for extracted directory packed into JAR file`() {
val zipPath = createXJarFile()
val a = addArtifact("a", root().archive("a.jar").extractedDir(zipPath, ""))
buildAll()
ZipFile(File(a.outputPath, "a.jar")).use {
assertNotNull(it.getEntry("dir/"))
assertNull(it.getEntry("dir//"))
}
}
private fun createXJarFile(): String {
val zipFile = zipFile {
dir("dir") {
file("file.txt", "text")
}
}.generateInTempDir()
return zipFile.toAbsolutePath().systemIndependentPath
}
fun testSelfIncludingArtifact() {
val a = addArtifact("a", root().fileCopy(createFile("a.txt")))
LayoutElementTestUtil.addArtifactToLayout(a, a)
assertBuildFailed(a)
}
fun testCircularInclusion() {
val a = addArtifact("a", root().fileCopy(createFile("a.txt")))
val b = addArtifact("b", root().fileCopy(createFile("b.txt")))
LayoutElementTestUtil.addArtifactToLayout(a, b)
LayoutElementTestUtil.addArtifactToLayout(b, a)
assertBuildFailed(a)
assertBuildFailed(b)
}
fun testArtifactContainingSelfIncludingArtifact() {
val c = addArtifact("c", root().fileCopy(createFile("c.txt")))
val a = addArtifact("a", root().artifact(c).fileCopy(createFile("a.txt")))
LayoutElementTestUtil.addArtifactToLayout(a, a)
val b = addArtifact("b", root().artifact(a).fileCopy(createFile("b.txt")))
buildArtifacts(c)
assertBuildFailed(b)
assertBuildFailed(a)
}
fun testArtifactContainingSelfIncludingArtifactWithoutOutput() {
val a = addArtifact("a", root().fileCopy(createFile("a.txt")))
LayoutElementTestUtil.addArtifactToLayout(a, a)
val b = addArtifact("b", root().artifact(a))
a.outputPath = null
assertBuildFailed(b)
}
//IDEA-73893
@Throws(IOException::class)
fun testManifestFileIsFirstEntry() {
val firstFile = createFile("src/A.txt")
val manifestFile = createFile("src/MANIFEST.MF")
val lastFile = createFile("src/Z.txt")
val a = addArtifact(archive("a.jar").dir("META-INF")
.fileCopy(firstFile).fileCopy(manifestFile).fileCopy(lastFile))
buildArtifacts(a)
val jarPath = a.outputPath!! + "/a.jar"
val jarFile = JarFile(File(jarPath))
jarFile.use {
val entries = it.entries()
assertTrue(entries.hasMoreElements())
val firstEntry = entries.nextElement()
assertEquals(JarFile.MANIFEST_NAME, firstEntry.name)
}
}
@Throws(IOException::class)
fun testPreserveCompressionMethodForEntryExtractedFromOneArchiveAndPackedIntoAnother() {
val path = createFile("data/a.jar")
val output = ZipOutputStream(BufferedOutputStream(FileOutputStream(File(path))))
try {
val entry = ZipEntry("a.txt")
val text = "text".toByteArray()
entry.method = ZipEntry.STORED
entry.size = text.size.toLong()
val crc32 = CRC32()
crc32.update(text)
entry.crc = crc32.value
output.putNextEntry(entry)
output.write(text)
output.closeEntry()
}
catch (e: Exception) {
e.printStackTrace()
}
finally {
output.close()
}
val a = addArtifact(archive("b.jar").extractedDir(path, ""))
buildAll()
assertOutput(a, directoryContent { zip("b.jar") { file("a.txt", "text") }})
val jarPath = a.outputPath!! + "/b.jar"
val zipFile = ZipFile(File(jarPath))
zipFile.use {
val entry = it.getEntry("a.txt")
assertNotNull(entry)
assertEquals(ZipEntry.STORED, entry.method)
}
}
fun testProperlyReportValueWithInvalidCrcInRepackedFile() {
val corruptedJar = PathManagerEx.findFileUnderCommunityHome("jps/jps-builders/testData/output/corruptedJar/incorrect-crc.jar")!!.absolutePath
val a = addArtifact(archive("a.jar").extractedDir(corruptedJar, ""))
val result = doBuild(CompileScopeTestBuilder.rebuild().artifacts(a))
result.assertFailed()
val message = result.getMessages(BuildMessage.Kind.ERROR).first()
assertTrue(message.messageText, message.messageText.contains("incorrect-crc.jar"));
}
fun testBuildModuleBeforeArtifactIfSomeDirectoryInsideModuleOutputIsCopiedToArtifact() {
val src = PathUtil.getParentPath(PathUtil.getParentPath(createFile("src/x/A.java", "package x; class A{}")))
val module = addModule("m", src)
val output = JpsJavaExtensionService.getInstance().getOutputDirectory(module, false)
val artifact = addArtifact(root().dirCopy(File(output, "x").absolutePath))
rebuildAllModulesAndArtifacts()
assertOutput(module, directoryContent { dir("x") { file("A.class") }})
assertOutput(artifact, directoryContent { file("A.class") })
}
fun testClearOutputOnRebuild() {
val file = createFile("d/a.txt")
val a = addArtifact(root().parentDirCopy(file))
buildAll()
createFileInArtifactOutput(a, "b.txt")
buildAllAndAssertUpToDate()
assertOutput(a, directoryContent {
file("a.txt")
file("b.txt")
})
rebuildAllModulesAndArtifacts()
assertOutput(a, directoryContent {
file("a.txt")
file("b.txt")
})
}
fun testDeleteOnlyOutputFileOnRebuildForArchiveArtifact() {
val file = createFile("a.txt")
val a = addArtifact(archive("a.jar").fileCopy(file))
buildAll()
createFileInArtifactOutput(a, "b.txt")
buildAllAndAssertUpToDate()
assertOutput(a, directoryContent {
zip("a.jar") { file("a.txt") }
file("b.txt")
})
rebuildAllModulesAndArtifacts()
assertOutput(a, directoryContent {
zip("a.jar") { file("a.txt") }
file("b.txt")
})
}
fun testDoNotCreateEmptyArchive() {
val file = createFile("dir/a.txt")
val a = addArtifact(archive("a.jar").parentDirCopy(file))
delete(file)
buildAll()
assertEmptyOutput(a)
}
fun testDoNotCreateEmptyArchiveInsideArchive() {
val file = createFile("dir/a.txt")
val a = addArtifact(archive("a.jar").archive("inner.jar").parentDirCopy(file))
delete(file)
buildAll()
assertEmptyOutput(a)
}
fun testDoNotCreateEmptyArchiveFromExtractedDirectory() {
val jarFile = createXJarFile()
val a = addArtifact("a", archive("a.jar").dir("dir").extractedDir(jarFile, "/xxx/"))
buildAll()
assertEmptyOutput(a)
}
fun testExtractNonExistentJarFile() {
val a = addArtifact(root().extractedDir("this-file-does-not-exist.jar", "/"))
buildAll()
assertEmptyOutput(a)
}
fun testRepackNonExistentJarFile() {
val a = addArtifact(archive("a.jar").extractedDir("this-file-does-not-exist.jar", "/").fileCopy(createFile("a.txt")))
buildAll()
assertOutput(a, directoryContent { zip("a.jar") {file("a.txt")}})
}
}
| jps/jps-builders/testSrc/org/jetbrains/jps/incremental/artifacts/ArtifactBuilderTest.kt | 840944060 |
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()
}
}
} | app/src/firebase/kotlin/info/dvkr/screenstream/ui/activity/AppUpdateActivity.kt | 2253047069 |
package com.github.kerubistan.kerub.planner.steps.vm.resume
import com.github.kerubistan.kerub.data.dynamic.VirtualMachineDynamicDao
import com.github.kerubistan.kerub.host.HostManager
import com.github.kerubistan.kerub.hypervisor.Hypervisor
import com.github.kerubistan.kerub.model.Host
import com.github.kerubistan.kerub.model.VirtualMachine
import com.github.kerubistan.kerub.model.VirtualMachineStatus
import com.github.kerubistan.kerub.model.dynamic.VirtualMachineDynamic
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito
import java.math.BigInteger
import java.util.UUID
class ResumeVirtualMachineExecutorTest{
val hostManager: HostManager = mock()
val hypervisor: Hypervisor = mock()
private val vmDynDao : VirtualMachineDynamicDao = mock()
val vm = VirtualMachine(
id = UUID.randomUUID(),
name = "vm-1"
)
val host = Host(
id = UUID.randomUUID(),
address = "host-1",
publicKey = "",
dedicated = true
)
private val vmDyn = VirtualMachineDynamic(
id = vm.id,
hostId = host.id,
status = VirtualMachineStatus.Paused,
memoryUsed = BigInteger.ZERO
)
@Before
fun setup() {
whenever(hostManager.getHypervisor(eq(host))).thenReturn(hypervisor)
}
@Test
fun execute() {
whenever(vmDynDao[eq(vm.id)]).thenReturn(vmDyn)
ResumeVirtualMachineExecutor(hostManager, vmDynDao).execute(ResumeVirtualMachine(vm, host))
verify(hypervisor).resume(Mockito.eq(vm) ?: vm)
}
@Test
fun executeWithoutData() {
whenever(vmDynDao[vm.id]).thenReturn(vmDyn)
ResumeVirtualMachineExecutor(hostManager, vmDynDao).execute(ResumeVirtualMachine(vm, host))
verify(hypervisor).resume(Mockito.eq(vm) ?: vm)
}
} | src/test/kotlin/com/github/kerubistan/kerub/planner/steps/vm/resume/ResumeVirtualMachineExecutorTest.kt | 1410279470 |
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
fun main(args: Array<String>) {
foo()
}
| backend.native/tests/serialization/use.kt | 287287239 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.datastore.rxjava3
import android.content.Context
import androidx.datastore.core.DataMigration
import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
import androidx.test.core.app.ApplicationProvider
import com.google.common.truth.Truth.assertThat
import io.reactivex.rxjava3.core.Single
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import java.io.FileOutputStream
val Context.rxDataStore by rxDataStore("file1", TestingSerializer())
val Context.rxdsWithMigration by rxDataStore(
"file2", TestingSerializer(),
produceMigrations = {
listOf(
object : DataMigration<Byte> {
override suspend fun shouldMigrate(currentData: Byte) = true
override suspend fun migrate(currentData: Byte) = 123.toByte()
override suspend fun cleanUp() {}
}
)
}
)
val Context.rxdsWithCorruptionHandler by rxDataStore(
"file3",
TestingSerializer(failReadWithCorruptionException = true),
corruptionHandler = ReplaceFileCorruptionHandler { 123 }
)
val Context.rxDataStoreForFileNameCheck by rxDataStore("file4", TestingSerializer())
@ExperimentalCoroutinesApi
class RxDataStoreDelegateTest {
@get:Rule
val tmp = TemporaryFolder()
private lateinit var context: Context
@Before
fun setUp() {
context = ApplicationProvider.getApplicationContext()
File(context.filesDir, "/datastore").deleteRecursively()
}
@Test
fun testBasic() {
assertThat(context.rxDataStore.data().blockingFirst()).isEqualTo(0)
assertThat(context.rxDataStore.updateDataAsync { Single.just(it.inc()) }.blockingGet())
.isEqualTo(1)
}
@Test
fun testWithMigration() {
assertThat(context.rxdsWithMigration.data().blockingFirst()).isEqualTo(123)
}
@Test
fun testCorruptedRunsCorruptionHandler() {
// File needs to exist or we don't actually hit the serializer:
File(context.filesDir, "datastore/file3").let { file ->
file.parentFile!!.mkdirs()
FileOutputStream(file).use {
it.write(0)
}
}
assertThat(context.rxdsWithCorruptionHandler.data().blockingFirst()).isEqualTo(123)
}
@Test
fun testCorrectFileNameUsed() {
context.rxDataStoreForFileNameCheck.updateDataAsync { Single.just(it.inc()) }.blockingGet()
context.rxDataStoreForFileNameCheck.dispose()
context.rxDataStoreForFileNameCheck.shutdownComplete().blockingAwait()
assertThat(
RxDataStoreBuilder(
{ File(context.filesDir, "datastore/file4") }, TestingSerializer()
).build().data().blockingFirst()
).isEqualTo(1)
}
} | datastore/datastore-rxjava3/src/androidTest/java/androidx/datastore/rxjava3/RxDataStoreDelegateTest.kt | 1161106015 |
/*
* 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)
}
} | core/uwb/uwb/src/main/java/androidx/core/uwb/impl/UwbControllerSessionScopeImpl.kt | 2742119233 |
// INTENTION_TEXT: Make primary constructor private
class C<caret>(val v: Int) | plugins/kotlin/idea/tests/testData/intentions/changeVisibility/private/noModifierListPrimaryConstructor.kt | 3467405901 |
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())
}
} | jvm/jvm-analysis-java-tests/testSrc/com/intellij/codeInspection/tests/java/test/junit/JavaJUnit5ConverterInspectionTest.kt | 2522704951 |
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
}
| src/main/kotlin/integrator/SamplerIntegrator.kt | 878820380 |
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())
} | jvm/jvm-analysis-kotlin-tests/testSrc/com/intellij/codeInspection/tests/kotlin/KotlinDependencyInspectionTest.kt | 2143807724 |
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()
}
| kobalt/src/Build.kt | 1913805499 |
// 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)
}
} | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/ToggleKotlinVariablesView.kt | 2731086730 |
// 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
}
}
}
| plugins/markdown/core/src/org/intellij/plugins/markdown/lang/psi/impl/MarkdownImage.kt | 1462001637 |
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtProperty
// OPTIONS: usages
class Foo {
companion object {
@JvmStatic
var <caret>foo = 1
}
}
// FIR_COMPARISON | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findPropertyUsages/jvmStaticProperty.0.kt | 3202043400 |
// ERROR: No value passed for parameter 'p'
fun foo(s: String, b: Boolean, p: Int){}
fun bar() {
<caret>foo("", true)
} | plugins/kotlin/idea/tests/testData/intentions/addNamesToCallArguments/incompleteCall.kt | 3479062878 |
public class TestingUse {
fun test6(funcLitfunc: ((x: Int) -> Int) -> Boolean, innerfunc: (y: Int) -> Int): Unit {
}
}
fun main() {
val funcInfunc = TestingUse().test6({<caret>f: (Int) -> Int -> f(5) > 20}, {x -> x + 2})
}
| plugins/kotlin/idea/tests/testData/intentions/removeExplicitLambdaParameterTypes/lambdaWithLambdaAsParam.kt | 3627388406 |
package c
fun c(param: a.A) {
a.a()
}
| plugins/kotlin/jps/jps-plugin/tests/testData/incremental/multiModule/common/twoDependants/module3_c.kt | 773945056 |
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
}
}
| Helpers/src/main/java/com/dg/controls/EditTextEx.kt | 329158985 |
// 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
}
}
| plugins/kotlin/common/src/org/jetbrains/kotlin/idea/util/IdeDescriptorRenderers.kt | 102229017 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage
import com.intellij.testFramework.UsefulTestCase.assertOneElement
import com.intellij.workspaceModel.storage.entities.*
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityStorageImpl
import com.intellij.workspaceModel.storage.impl.assertConsistency
import com.intellij.workspaceModel.storage.impl.exceptions.AddDiffException
import com.intellij.workspaceModel.storage.impl.external.ExternalEntityMappingImpl
import org.hamcrest.CoreMatchers
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
private fun WorkspaceEntityStorageBuilder.applyDiff(anotherBuilder: WorkspaceEntityStorageBuilder): WorkspaceEntityStorage {
val builder = createBuilderFrom(this)
builder.addDiff(anotherBuilder)
val storage = builder.toStorage()
storage.assertConsistency()
return storage
}
class DiffBuilderTest {
@JvmField
@Rule
val expectedException = ExpectedException.none()
@Test
fun `add entity`() {
val source = createEmptyBuilder()
source.addSampleEntity("first")
val target = createEmptyBuilder()
target.addSampleEntity("second")
val storage = target.applyDiff(source)
assertEquals(setOf("first", "second"), storage.entities(SampleEntity::class.java).mapTo(HashSet()) { it.stringProperty })
}
@Test
fun `remove entity`() {
val target = createEmptyBuilder()
val entity = target.addSampleEntity("hello")
val entity2 = target.addSampleEntity("hello")
val source = createBuilderFrom(target.toStorage())
source.removeEntity(entity)
val storage = target.applyDiff(source)
assertEquals(entity2, storage.singleSampleEntity())
}
@Test
fun `modify entity`() {
val target = createEmptyBuilder()
val entity = target.addSampleEntity("hello")
val source = createBuilderFrom(target.toStorage())
source.modifyEntity(ModifiableSampleEntity::class.java, entity) {
stringProperty = "changed"
}
val storage = target.applyDiff(source)
assertEquals("changed", storage.singleSampleEntity().stringProperty)
}
@Test
fun `remove removed entity`() {
val target = createEmptyBuilder()
val entity = target.addSampleEntity("hello")
val entity2 = target.addSampleEntity("hello")
val source = createBuilderFrom(target.toStorage())
target.removeEntity(entity)
target.assertConsistency()
source.assertConsistency()
source.removeEntity(entity)
val storage = target.applyDiff(source)
assertEquals(entity2, storage.singleSampleEntity())
}
@Test
fun `modify removed entity`() {
val target = createEmptyBuilder()
val entity = target.addSampleEntity("hello")
val source = createBuilderFrom(target.toStorage())
target.removeEntity(entity)
source.assertConsistency()
source.modifyEntity(ModifiableSampleEntity::class.java, entity) {
stringProperty = "changed"
}
val storage = target.applyDiff(source)
assertEquals(emptyList<SampleEntity>(), storage.entities(SampleEntity::class.java).toList())
}
@Test
fun `modify removed child entity`() {
val target = createEmptyBuilder()
val parent = target.addParentEntity("parent")
val child = target.addChildEntity(parent, "child")
val source = createBuilderFrom(target)
target.removeEntity(child)
source.modifyEntity(ModifiableParentEntity::class.java, parent) {
this.parentProperty = "new property"
}
source.modifyEntity(ModifiableChildEntity::class.java, child) {
this.childProperty = "new property"
}
val res = target.applyDiff(source) as WorkspaceEntityStorageImpl
res.assertConsistency()
assertOneElement(res.entities(ParentEntity::class.java).toList())
assertTrue(res.entities(ChildEntity::class.java).toList().isEmpty())
}
@Test
fun `remove modified entity`() {
val target = createEmptyBuilder()
val entity = target.addSampleEntity("hello")
val source = createBuilderFrom(target.toStorage())
target.modifyEntity(ModifiableSampleEntity::class.java, entity) {
stringProperty = "changed"
}
source.removeEntity(entity)
source.assertConsistency()
val storage = target.applyDiff(source)
assertEquals(emptyList<SampleEntity>(), storage.entities(SampleEntity::class.java).toList())
}
@Test
fun `add entity with refs at the same slot`() {
val target = createEmptyBuilder()
val source = createEmptyBuilder()
source.addSampleEntity("Another entity")
val parentEntity = target.addSampleEntity("hello")
target.addChildSampleEntity("data", parentEntity)
source.addDiff(target)
source.assertConsistency()
val resultingStorage = source.toStorage()
assertEquals(2, resultingStorage.entities(SampleEntity::class.java).toList().size)
assertEquals(1, resultingStorage.entities(ChildSampleEntity::class.java).toList().size)
assertEquals(resultingStorage.entities(SampleEntity::class.java).last(), resultingStorage.entities(ChildSampleEntity::class.java).single().parent)
}
@Test
fun `add remove and add with refs`() {
val source = createEmptyBuilder()
val target = createEmptyBuilder()
val parent = source.addSampleEntity("Another entity")
source.addChildSampleEntity("String", parent)
val parentEntity = target.addSampleEntity("hello")
target.addChildSampleEntity("data", parentEntity)
source.addDiff(target)
source.assertConsistency()
val resultingStorage = source.toStorage()
assertEquals(2, resultingStorage.entities(SampleEntity::class.java).toList().size)
assertEquals(2, resultingStorage.entities(ChildSampleEntity::class.java).toList().size)
assertNotNull(resultingStorage.entities(ChildSampleEntity::class.java).first().parent)
assertNotNull(resultingStorage.entities(ChildSampleEntity::class.java).last().parent)
assertEquals(resultingStorage.entities(SampleEntity::class.java).first(), resultingStorage.entities(ChildSampleEntity::class.java).first().parent)
assertEquals(resultingStorage.entities(SampleEntity::class.java).last(), resultingStorage.entities(ChildSampleEntity::class.java).last().parent)
}
@Test
fun `add dependency without changing entities`() {
val source = createEmptyBuilder()
val parent = source.addSampleEntity("Another entity")
source.addChildSampleEntity("String", null)
val target = createBuilderFrom(source)
val pchild = target.entities(ChildSampleEntity::class.java).single()
val pparent = target.entities(SampleEntity::class.java).single()
target.modifyEntity(ModifiableChildSampleEntity::class.java, pchild) {
this.parent = pparent
}
source.addDiff(target)
source.assertConsistency()
val resultingStorage = source.toStorage()
assertEquals(1, resultingStorage.entities(SampleEntity::class.java).toList().size)
assertEquals(1, resultingStorage.entities(ChildSampleEntity::class.java).toList().size)
assertEquals(resultingStorage.entities(SampleEntity::class.java).single(), resultingStorage.entities(ChildSampleEntity::class.java).single().parent)
}
@Test
fun `dependency to removed parent`() {
val source = createEmptyBuilder()
val parent = source.addParentEntity()
val target = createBuilderFrom(source)
target.addChildWithOptionalParentEntity(parent)
source.removeEntity(parent)
source.applyDiff(target)
}
@Test
fun `modify child and parent`() {
val source = createEmptyBuilder()
val parent = source.addParentEntity()
source.addChildEntity(parent)
val target = createBuilderFrom(source)
target.modifyEntity(ModifiableParentEntity::class.java, parent) {
this.parentProperty = "anotherValue"
}
source.addChildEntity(parent)
source.applyDiff(target)
}
@Test
fun `remove parent in both difs with dependency`() {
val source = createEmptyBuilder()
val parent = source.addParentEntity()
val target = createBuilderFrom(source)
target.addChildWithOptionalParentEntity(parent)
target.removeEntity(parent)
source.removeEntity(parent)
source.applyDiff(target)
}
@Test
fun `remove parent in both diffs`() {
val source = createEmptyBuilder()
val parent = source.addParentEntity()
val optionalChild = source.addChildWithOptionalParentEntity(null)
val target = createBuilderFrom(source)
target.modifyEntity(ModifiableChildWithOptionalParentEntity::class.java, optionalChild) {
this.optionalParent = parent
}
source.removeEntity(parent)
source.applyDiff(target)
}
@Test
fun `adding duplicated persistent ids`() {
expectedException.expectCause(CoreMatchers.isA(AddDiffException::class.java))
val source = createEmptyBuilder()
val target = createBuilderFrom(source)
target.addNamedEntity("Name")
source.addNamedEntity("Name")
source.applyDiff(target)
}
@Test
fun `modifying duplicated persistent ids`() {
expectedException.expectCause(CoreMatchers.isA(AddDiffException::class.java))
val source = createEmptyBuilder()
val namedEntity = source.addNamedEntity("Hello")
val target = createBuilderFrom(source)
source.addNamedEntity("Name")
target.modifyEntity(ModifiableNamedEntity::class.java, namedEntity) {
this.name = "Name"
}
source.applyDiff(target)
}
@Test
fun `checking external mapping`() {
val target = createEmptyBuilder()
target.addSampleEntity("Entity at index 0")
val source = createEmptyBuilder()
val sourceSample = source.addSampleEntity("Entity at index 1")
val mutableExternalMapping = source.getMutableExternalMapping<Any>("test.checking.external.mapping")
val anyObj = Any()
mutableExternalMapping.addMapping(sourceSample, anyObj)
target.addDiff(source)
val externalMapping = target.getExternalMapping<Any>("test.checking.external.mapping") as ExternalEntityMappingImpl<Any>
assertEquals(1, externalMapping.index.size)
}
@Test
fun `change source in diff`() {
val target = createEmptyBuilder()
val sampleEntity = target.addSampleEntity("Prop", MySource)
val source = createBuilderFrom(target)
source.changeSource(sampleEntity, AnotherSource)
target.addDiff(source)
target.assertConsistency()
val entitySourceIndex = target.indexes.entitySourceIndex
assertEquals(1, entitySourceIndex.index.size)
assertNotNull(entitySourceIndex.getIdsByEntry(AnotherSource)?.single())
}
@Test
fun `change source and data in diff`() {
val target = createEmptyBuilder()
val sampleEntity = target.addSampleEntity("Prop", MySource)
val source = createBuilderFrom(target)
source.changeSource(sampleEntity, AnotherSource)
source.modifyEntity(ModifiableSampleEntity::class.java, sampleEntity) {
stringProperty = "Prop2"
}
target.addDiff(source)
target.assertConsistency()
val entitySourceIndex = target.indexes.entitySourceIndex
assertEquals(1, entitySourceIndex.index.size)
assertNotNull(entitySourceIndex.getIdsByEntry(AnotherSource)?.single())
val updatedEntity = target.entities(SampleEntity::class.java).single()
assertEquals("Prop2", updatedEntity.stringProperty)
assertEquals(AnotherSource, updatedEntity.entitySource)
}
@Test
fun `change source in target`() {
val target = createEmptyBuilder()
val sampleEntity = target.addSampleEntity("Prop", MySource)
val source = createBuilderFrom(target)
target.changeSource(sampleEntity, AnotherSource)
source.modifyEntity(ModifiableSampleEntity::class.java, sampleEntity) {
this.stringProperty = "Updated"
}
target.addDiff(source)
target.assertConsistency()
val entitySourceIndex = target.indexes.entitySourceIndex
assertEquals(1, entitySourceIndex.index.size)
assertNotNull(entitySourceIndex.getIdsByEntry(AnotherSource)?.single())
}
@Test
fun `adding parent with child and shifting`() {
val parentAndChildProperty = "Bound"
val target = createEmptyBuilder()
target.addChildWithOptionalParentEntity(null, "Existing")
val source = createEmptyBuilder()
val parent = source.addParentEntity(parentAndChildProperty)
source.addChildWithOptionalParentEntity(parent, parentAndChildProperty)
target.addDiff(source)
val extractedParent = assertOneElement(target.entities(ParentEntity::class.java).toList())
val extractedOptionalChild = assertOneElement(extractedParent.optionalChildren.toList())
assertEquals(parentAndChildProperty, extractedOptionalChild.childProperty)
}
@Test
fun `adding parent with child and shifting and later connecting`() {
val parentAndChildProperty = "Bound"
val target = createEmptyBuilder()
target.addChildWithOptionalParentEntity(null, "Existing")
val source = createEmptyBuilder()
val child = source.addChildWithOptionalParentEntity(null, parentAndChildProperty)
val parent = source.addParentEntity(parentAndChildProperty)
source.modifyEntity(ModifiableParentEntity::class.java, parent) {
this.optionalChildren = this.optionalChildren + child
}
target.addDiff(source)
val extractedParent = assertOneElement(target.entities(ParentEntity::class.java).toList())
val extractedOptionalChild = assertOneElement(extractedParent.optionalChildren.toList())
assertEquals(parentAndChildProperty, extractedOptionalChild.childProperty)
}
@Test
fun `adding parent with child and shifting and later child connecting`() {
val parentAndChildProperty = "Bound"
val target = createEmptyBuilder()
target.addChildWithOptionalParentEntity(null, "Existing")
val source = createEmptyBuilder()
val child = source.addChildWithOptionalParentEntity(null, parentAndChildProperty)
val parent = source.addParentEntity(parentAndChildProperty)
source.modifyEntity(ModifiableChildWithOptionalParentEntity::class.java, child) {
this.optionalParent = parent
}
target.addDiff(source)
val extractedParent = assertOneElement(target.entities(ParentEntity::class.java).toList())
val extractedOptionalChild = assertOneElement(extractedParent.optionalChildren.toList())
assertEquals(parentAndChildProperty, extractedOptionalChild.childProperty)
}
@Test
fun `removing non-existing entity while adding the new one`() {
val initial = createEmptyBuilder()
val toBeRemoved = initial.addSampleEntity("En1")
val source = createBuilderFrom(initial)
initial.removeEntity(toBeRemoved)
val target = createBuilderFrom(initial.toStorage())
// In the incorrect implementation remove event will remove added entity
source.addSampleEntity("En2")
source.removeEntity(toBeRemoved)
target.addDiff(source)
assertOneElement(target.entities(SampleEntity::class.java).toList())
}
@Test
fun `remove entity and reference`() {
val initial = createEmptyBuilder()
val parentEntity = initial.addParentEntity()
val childEntity = initial.addChildWithOptionalParentEntity(parentEntity)
val source = createBuilderFrom(initial)
source.modifyEntity(ModifiableChildWithOptionalParentEntity::class.java, childEntity) {
this.childProperty = "newProp"
}
source.modifyEntity(ModifiableParentEntity::class.java, parentEntity) {
this.optionalChildren = emptySequence()
}
source.removeEntity(childEntity)
val res = initial.applyDiff(source)
assertTrue(res.entities(ChildWithOptionalParentEntity::class.java).toList().isEmpty())
val newParent = assertOneElement(res.entities(ParentEntity::class.java).toList())
assertTrue(newParent.optionalChildren.toList().isEmpty())
}
@Test
fun `remove reference to created entity`() {
val initial = createEmptyBuilder()
val parentEntity = initial.addParentEntity()
initial.addChildWithOptionalParentEntity(parentEntity)
val source = createBuilderFrom(initial)
source.addChildWithOptionalParentEntity(parentEntity)
source.modifyEntity(ModifiableParentEntity::class.java, parentEntity) {
this.optionalChildren = emptySequence()
}
val res = initial.applyDiff(source)
assertEquals(2, res.entities(ChildWithOptionalParentEntity::class.java).toList().size)
val newParent = assertOneElement(res.entities(ParentEntity::class.java).toList())
assertTrue(newParent.optionalChildren.toList().isEmpty())
}
}
| platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/DiffBuilderTest.kt | 482624764 |
package com.petukhovsky.jvaluer.cli.cmd
object UnknownCommand : Command {
override fun command(args: Array<String>) {
println("Unknown command. Type 'jv help' to display help")
}
override fun printHelp() {
Help.printHelp()
}
}
| src/main/kotlin/com/petukhovsky/jvaluer/cli/cmd/UnknownCommand.kt | 2507803030 |
package com.maubis.markdown.segmenter
class MarkdownSegmentBuilder {
var config: ISegmentConfig = InvalidSegment(MarkdownSegmentType.INVALID)
val builder: StringBuilder = StringBuilder()
fun build(): MarkdownSegment {
val text = builder.toString()
val segmentConfig = config
return when (segmentConfig) {
is LineStartSegment -> LineStartMarkdownSegment(segmentConfig, text)
is LineDelimiterSegment -> LineDelimiterMarkdownSegment(segmentConfig, text)
is MultilineDelimiterSegment -> MultilineDelimiterMarkdownSegment(segmentConfig, text)
is MultilineStartSegment -> MultilineStartMarkdownSegment(segmentConfig, text)
else -> NormalMarkdownSegment(segmentConfig, text)
}
}
}
abstract class MarkdownSegment {
/**
* The type of the segment
*/
abstract fun type(): MarkdownSegmentType
/**
* Strip the segment separators and return the text inside the segment which is formatted
*/
abstract fun strip(): String
/**
* Return the entire text which the segment contains including the delimiters
*/
abstract fun text(): String
}
class NormalMarkdownSegment(val config: ISegmentConfig, val text: String) : MarkdownSegment() {
override fun type() = config.type()
override fun strip(): String {
return text
}
override fun text(): String = text
}
class LineStartMarkdownSegment(val config: LineStartSegment, val text: String) : MarkdownSegment() {
override fun type() = config.type()
override fun strip(): String {
return text.removePrefix(config.lineStartToken)
}
override fun text(): String = text
}
class LineDelimiterMarkdownSegment(val config: LineDelimiterSegment, val text: String) : MarkdownSegment() {
override fun type() = config.type()
override fun strip(): String {
return text.removePrefix(config.lineStartToken).trim().removeSuffix(config.lineEndToken)
}
override fun text(): String = text
}
class MultilineDelimiterMarkdownSegment(val config: MultilineDelimiterSegment, val text: String) : MarkdownSegment() {
override fun type() = config.type()
override fun strip(): String {
return text.trim()
.removePrefix(config.multilineStartToken).trim()
.removeSuffix(config.multilineEndToken).trim()
}
override fun text(): String = text
}
class MultilineStartMarkdownSegment(val config: MultilineStartSegment, val text: String) : MarkdownSegment() {
override fun type() = config.type()
override fun strip(): String {
return text.trim()
.removePrefix(config.multilineStartToken).trim()
}
override fun text(): String = text
} | markdown/src/main/java/com/maubis/markdown/segmenter/MarkdownSegment.kt | 572751824 |
class A {
private class B {
private class D
}
private class C {
private val d = B.D()
}
} | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveNestedClass/deepPrivateClass/after/main.kt | 1258254585 |
package database.list
import com.onyx.persistence.query.IN
import com.onyx.persistence.query.cont
import com.onyx.persistence.query.eq
import com.onyx.persistence.query.startsWith
import com.onyx.persistence.IManagedEntity
import database.base.DatabaseBaseTest
import entities.OneToManyChildFetchEntity
import entities.OneToOneFetchEntity
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.util.*
import kotlin.reflect.KClass
import kotlin.test.assertEquals
@RunWith(Parameterized::class)
class OneToManyRelationshipEqualsTest(override var factoryClass: KClass<*>) : DatabaseBaseTest(factoryClass) {
@Before
fun seedData() {
var entity = OneToOneFetchEntity()
entity.id = "FIRST ONE"
entity.stringValue = "Some test string"
entity.dateValue = Date(1000)
entity.doublePrimitive = 3.3
entity.doubleValue = 1.1
entity.booleanValue = false
entity.booleanPrimitive = true
entity.longPrimitive = 1000L
entity.longValue = 323L
manager.saveEntity<IManagedEntity>(entity)
entity = OneToOneFetchEntity()
entity.id = "FIRST ONE1"
entity.stringValue = "Some test string1"
entity.dateValue = Date(1001)
entity.doublePrimitive = 3.31
entity.doubleValue = 1.11
entity.booleanValue = true
entity.booleanPrimitive = false
entity.longPrimitive = 1002L
entity.longValue = 322L
manager.saveEntity<IManagedEntity>(entity)
entity = OneToOneFetchEntity()
entity.id = "FIRST ONE2"
entity.stringValue = "Some test string1"
entity.dateValue = Date(1001)
entity.doublePrimitive = 3.31
entity.doubleValue = 1.11
entity.booleanValue = true
entity.booleanPrimitive = false
entity.longPrimitive = 1002L
entity.longValue = 322L
manager.saveEntity<IManagedEntity>(entity)
entity = OneToOneFetchEntity()
entity.id = "FIRST ONE3"
entity.stringValue = "Some test string2"
entity.dateValue = Date(1002)
entity.doublePrimitive = 3.32
entity.doubleValue = 1.12
entity.booleanValue = true
entity.booleanPrimitive = false
entity.longPrimitive = 1001L
entity.longValue = 321L
manager.saveEntity<IManagedEntity>(entity)
entity = OneToOneFetchEntity()
entity.id = "FIRST ONE3"
entity.stringValue = "Some test string3"
entity.dateValue = Date(1022)
entity.doublePrimitive = 3.35
entity.doubleValue = 1.126
entity.booleanValue = false
entity.booleanPrimitive = true
entity.longPrimitive = 1301L
entity.longValue = 322L
manager.saveEntity<IManagedEntity>(entity)
entity = OneToOneFetchEntity()
entity.id = "FIRST ONE4"
manager.saveEntity<IManagedEntity>(entity)
entity = OneToOneFetchEntity()
entity.id = "FIRST ONE5"
manager.saveEntity<IManagedEntity>(entity)
var entity2 = OneToManyChildFetchEntity()
entity2.id = "FIRST ONE"
entity2.stringValue = "Some test string"
entity2.dateValue = Date(1000)
entity2.doublePrimitive = 3.3
entity2.doubleValue = 1.1
entity2.booleanValue = false
entity2.booleanPrimitive = true
entity2.longPrimitive = 1000L
entity2.longValue = 323L
manager.saveEntity<IManagedEntity>(entity2)
entity2.parents = OneToOneFetchEntity()
entity2.parents!!.id = "FIRST ONE1"
manager.saveEntity<IManagedEntity>(entity2)
entity2 = OneToManyChildFetchEntity()
entity2.id = "FIRST ONE1"
entity2.stringValue = "Some test string1"
entity2.dateValue = Date(1001)
entity2.doublePrimitive = 3.31
entity2.doubleValue = 1.11
entity2.booleanValue = true
entity2.booleanPrimitive = false
entity2.longPrimitive = 1002L
entity2.longValue = 322L
manager.saveEntity<IManagedEntity>(entity2)
entity2.parents = OneToOneFetchEntity()
entity2.parents!!.id = "FIRST ONE2"
manager.saveEntity<IManagedEntity>(entity2)
entity2 = OneToManyChildFetchEntity()
entity2.id = "FIRST ONE2"
entity2.stringValue = "Some test string1"
entity2.dateValue = Date(1001)
entity2.doublePrimitive = 3.31
entity2.doubleValue = 1.11
entity2.booleanValue = true
entity2.booleanPrimitive = false
entity2.longPrimitive = 1002L
entity2.longValue = 322L
manager.saveEntity<IManagedEntity>(entity2)
entity2 = OneToManyChildFetchEntity()
entity2.id = "FIRST ONE3"
entity2.stringValue = "Some test string2"
entity2.dateValue = Date(1002)
entity2.doublePrimitive = 3.32
entity2.doubleValue = 1.12
entity2.booleanValue = true
entity2.booleanPrimitive = false
entity2.longPrimitive = 1001L
entity2.longValue = 321L
manager.saveEntity<IManagedEntity>(entity2)
entity2 = OneToManyChildFetchEntity()
entity2.id = "FIRST ONE3"
entity2.stringValue = "Some test string3"
entity2.dateValue = Date(1022)
entity2.doublePrimitive = 3.35
entity2.doubleValue = 1.126
entity2.booleanValue = false
entity2.booleanPrimitive = true
entity2.longPrimitive = 1301L
entity2.longValue = 322L
manager.saveEntity<IManagedEntity>(entity2)
entity2.parents = OneToOneFetchEntity()
entity2.parents!!.id = "FIRST ONE2"
manager.saveEntity<IManagedEntity>(entity2)
entity2.parents = OneToOneFetchEntity()
entity2.parents!!.id = "FIRST ONE3"
manager.saveEntity<IManagedEntity>(entity2)
entity2 = OneToManyChildFetchEntity()
entity2.id = "FIRST ONE4"
manager.saveEntity<IManagedEntity>(entity2)
entity2 = OneToManyChildFetchEntity()
entity2.id = "FIRST ONE5"
manager.saveEntity<IManagedEntity>(entity2)
}
@Test
fun testOneToOneHasRelationshipMeetsOne() {
val results = manager.list<OneToOneFetchEntity>(OneToOneFetchEntity::class.java, ("stringValue" eq "Some test string3") and ("children.id" eq "FIRST ONE3"))
assertEquals(1, results.size, "Expected 1 result")
}
@Test
fun testOneToOneHasRelationship() {
val results = manager.list<OneToOneFetchEntity>(OneToOneFetchEntity::class.java, ("stringValue" cont "Some test string") and ("children.id" eq "FIRST ONE3"))
assertEquals(1, results.size, "Expected 1 result")
}
@Test
fun testOneToOneNoMeetCriteriaRelationship() {
val results = manager.list<OneToOneFetchEntity>(OneToOneFetchEntity::class.java, ("stringValue" eq "Some te1st string3") and ("children.id" eq "FIRST ONE3"))
assertEquals(0, results.size, "Expected no results")
}
@Test
fun testOneToManyInCriteriaRelationship() {
val results = manager.list<OneToOneFetchEntity>(OneToOneFetchEntity::class.java, ("stringValue" startsWith "Some test string1") and ("children.id" IN arrayListOf("FIRST ONE3", "FIRST ONE2")))
assertEquals(0, results.size, "Expected no results")
}
} | onyx-database-tests/src/test/kotlin/database/list/OneToManyRelationshipEqualsTest.kt | 3431484219 |
package kotlin.prop<caret>erties.
import kotlin.properties.Delegates
class Test {
}
// EXIST: properties
// NOTHING_ELSE
| plugins/kotlin/completion/tests/testData/basic/common/InMiddleOfPackage.kt | 4075842607 |
// 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.run
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.junit.JunitKotlinTestFrameworkProvider
@Deprecated("Class is moved to the org.jetbrains.kotlin.idea.junit package.", level = DeprecationLevel.ERROR)
class KotlinJUnitRunConfigurationProducer {
companion object {
@Deprecated(
"Use getJavaTestEntity() instead.",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith(
"JunitKotlinTestFrameworkProvider.getJavaTestEntity(leaf, checkMethod = false)?.testClass",
"org.jetbrains.kotlin.idea.junit.JunitKotlinTestFrameworkProvider"
)
)
fun getTestClass(leaf: PsiElement): PsiClass? {
return JunitKotlinTestFrameworkProvider.getJavaTestEntity(leaf, checkMethod = false)?.testClass
}
}
} | plugins/kotlin/junit/src/org/jetbrains/kotlin/idea/junit/DeprecatedKotlinJUnitRunConfigurationProducer.kt | 609701291 |
// 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)
}
}
} | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/Version.kt | 317652381 |
// 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))
}
}
})
}
} | platform/statistics/devkit/src/com/intellij/internal/statistic/devkit/actions/CleanupEventsTestSchemeAction.kt | 3664693836 |
// LANGUAGE_VERSION: 1.1
// IS_APPLICABLE: true
// WITH_STDLIB
// AFTER-WARNING: Parameter 's' is never used
// AFTER-WARNING: Variable 'f' is never used
class Test {
fun test() {
with(Any()) {
val f = { s: String<caret> -> foo(s) }
}
}
fun foo(s: String) {}
} | plugins/kotlin/idea/tests/testData/intentions/convertLambdaToReference/version1_1/memberOuterScope.kt | 900032849 |
// WITH_STDLIB
// IS_APPLICABLE: false
class A(val n: Int) {
fun <caret>foo(): Nothing = throw Exception("foo")
}
fun test() {
A(1).foo()
} | plugins/kotlin/idea/tests/testData/intentions/convertFunctionToProperty/nothingFun.kt | 2708957617 |
// IS_APPLICABLE: true
fun foo() {
bar<String> <caret>{ it.toString() }
}
fun <T> bar(a: (Int)->T): T {
return a(1)
}
| plugins/kotlin/idea/tests/testData/intentions/moveLambdaInsideParentheses/moveLambda11.kt | 1509311369 |
package org.kkanojia.tasks.teamcity.common
import org.kkanojia.tasks.teamcity.models.TaskLine
import java.io.Serializable
data class TaskScanResult(val relativePath: String,
val charsetName: String,
val runTime: Long,
val tasks: List<TaskLine>) : Serializable
| tasks-teamcity-plugin-common/src/main/kotlin/org/kkanojia/tasks/teamcity/common/TaskScanResult.kt | 4265293090 |
// 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)
)
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateSetFunctionActionFactory.kt | 753304233 |
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
}
}
| fore-kt-core/src/main/java/co/early/fore/kt/core/logging/TagFormatter.kt | 1360162454 |
package com.restfeel.config
import com.sendgrid.SendGrid
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.env.Environment
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.mail.javamail.JavaMailSenderImpl
import java.util.*
/**
* Created by jack on 2017/3/29.
*/
@Configuration
class MailConfig {
@Autowired
private val env: Environment? = null
@Bean
fun javaMailSender(): JavaMailSender {
val mailSender = JavaMailSenderImpl()
val mailProperties = Properties()
mailSender.protocol = env!!.getProperty("mail.protocol")
mailSender.host = env?.getProperty("mail.host")
mailSender.port = Integer.parseInt(env?.getProperty("mail.port"))
mailSender.username = env?.getProperty("mail.username")
mailSender.password = env?.getProperty("mail.password")
mailProperties.put("mail.smtp.auth", env?.getProperty("mail.smtp.auth"))
mailProperties.put("mail.smtp.starttls.enable", env?.getProperty("mail.smtp.starttls.enable"))
mailProperties.put("mail.smtp.debug", env?.getProperty("mail.smtp.debug"))
mailProperties.put("mail.smtp.socketFactory.port", "465")
mailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
mailProperties.put("mail.smtps.ssl.trust", env?.getProperty("mail.smtps.ssl.trust"))
mailProperties.put("mail.smtps.ssl.checkserveridentity", env?.getProperty("mail.smtps.ssl.checkserveridentity"))
mailSender.javaMailProperties = mailProperties
return mailSender
}
@Bean
fun sendGrid(): SendGrid {
val sendgrid = SendGrid(env!!.getProperty("sendgrid.username"), env?.getProperty("sendgrid.password"))
return sendgrid
}
}
| src/main/kotlin/com/restfeel/config/MailConfig.kt | 3755860554 |
package com.amar.NoteDirector.extensions
import com.bumptech.glide.signature.ObjectKey
import java.io.File
fun String.getFileSignature() = ObjectKey(File(this).lastModified().toString())
| app/src/main/kotlin/com/amar/notesapp/extensions/string.kt | 2655095339 |
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",
)
}
}
| HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/body/RequestBodyActivity.kt | 1636189563 |
// GENERATED
package com.fkorotkov.openshift
import io.fabric8.openshift.api.model.BuildTriggerPolicy as model_BuildTriggerPolicy
import io.fabric8.openshift.api.model.GitLabIdentityProvider as model_GitLabIdentityProvider
import io.fabric8.openshift.api.model.IdentityProvider as model_IdentityProvider
import io.fabric8.openshift.api.model.WebHookTrigger as model_WebHookTrigger
fun model_BuildTriggerPolicy.`gitlab`(block: model_WebHookTrigger.() -> Unit = {}) {
if(this.`gitlab` == null) {
this.`gitlab` = model_WebHookTrigger()
}
this.`gitlab`.block()
}
fun model_IdentityProvider.`gitlab`(block: model_GitLabIdentityProvider.() -> Unit = {}) {
if(this.`gitlab` == null) {
this.`gitlab` = model_GitLabIdentityProvider()
}
this.`gitlab`.block()
}
| DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/openshift/gitlab.kt | 1886327880 |
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 ""
}
}
| src/commonMain/kotlin/com/github/h0tk3y/betterParse/lexer/LambdaToken.kt | 10351362 |
package cz.filipproch.reactor.demo.ui.main
import cz.filipproch.reactor.base.translator.ReactorTranslator
import cz.filipproch.reactor.demo.data.AwesomeNetworkModel
import cz.filipproch.reactor.ui.events.ViewCreatedEvent
import cz.filipproch.reactor.ui.events.whenViewCreatedFirstTime
import io.reactivex.ObservableTransformer
/**
* TODO
*
* @author Filip Prochazka (@filipproch)
*/
class MainTranslator : ReactorTranslator() {
override fun onCreated() {
val fetchPostDetail = ObservableTransformer<ViewCreatedEvent, MainUiModel> {
it.map { AwesomeNetworkModel.StuffRequest() }
.compose(AwesomeNetworkModel.fetchStuff)
.map {
when {
it.inProgress -> MainUiModel.LOADING
it.error != null -> MainUiModel.ERROR
it.stuffList != null -> MainUiModel.success("There is ${it.stuffList.size} stuff", "Thats a lot of stuff")
else -> MainUiModel.IDLE
}
}
.startWith(MainUiModel.IDLE)
}
translateToModel {
whenViewCreatedFirstTime()
.compose(fetchPostDetail)
}
}
} | demo/src/main/kotlin/cz/filipproch/reactor/demo/ui/main/MainTranslator.kt | 292041864 |
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)
}
} | src/main/kotlin/com/github/parkee/messenger/builder/request/MessengerRequestBuilder.kt | 1203606813 |
package com.github.parkee.messenger.model.settings
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonValue
enum class ThreadState(private val threadState: String) {
NEW_THREAD("new_thread");
@JsonCreator
fun fromString(threadState: String?): ThreadState? {
threadState ?: return null
return valueOf(threadState)
}
@JsonValue
override fun toString(): String {
return threadState
}
} | src/main/kotlin/com/github/parkee/messenger/model/settings/ThreadState.kt | 538682261 |
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)
}
}
| app/src/androidTest/java/com/breadwallet/util/Screens.kt | 1391499347 |
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("AddVarianceModifier")
package androidx.room.processor.cache
import androidx.room.processor.FieldProcessor
import androidx.room.vo.EmbeddedField
import androidx.room.vo.Entity
import androidx.room.vo.Pojo
import androidx.room.vo.Warning
import java.util.LinkedHashSet
import javax.lang.model.element.Element
import javax.lang.model.type.TypeMirror
/**
* A cache key can be used to avoid re-processing elements.
* <p>
* Each context has a cache variable that uses the same backing storage as the Root Context but
* adds current adapters and warning suppression list to the key.
*/
class Cache(val parent: Cache?, val converters: LinkedHashSet<TypeMirror>,
val suppressedWarnings: Set<Warning>) {
val entities: Bucket<EntityKey, Entity> = Bucket(parent?.entities)
val pojos: Bucket<PojoKey, Pojo> = Bucket(parent?.pojos)
inner class Bucket<K, T>(source: Bucket<K, T>?) {
private val entries: MutableMap<FullKey<K>, T> = source?.entries ?: mutableMapOf()
fun get(key: K, calculate: () -> T): T {
val fullKey = FullKey(converters, suppressedWarnings, key)
return entries.getOrPut(fullKey, {
calculate()
})
}
}
/**
* Key for Entity cache
*/
data class EntityKey(val element: Element)
/**
* Key for Pojo cache
*/
data class PojoKey(
val element: Element,
val scope: FieldProcessor.BindingScope,
val parent: EmbeddedField?)
/**
* Internal key representation with adapters & warnings included.
* <p>
* Converters are kept in a linked set since the order is important for the TypeAdapterStore.
*/
private data class FullKey<T>(
val converters: LinkedHashSet<TypeMirror>,
val suppressedWarnings: Set<Warning>,
val key: T)
}
| room/compiler/src/main/kotlin/androidx/room/processor/cache/Cache.kt | 3985467724 |
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) | src/main/kotlin/com/almasb/zeph/events/Events.kt | 240190663 |
/*
* Copyright 2019 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.featureflags.bukkit.event.featureflag
interface RPKFeatureFlagCreateEvent: RPKFeatureFlagEvent | bukkit/rpk-feature-flag-lib-bukkit/src/main/kotlin/com/rpkit/featureflags/bukkit/event/featureflag/RPKFeatureFlagCreateEvent.kt | 1398524688 |
package com.rpkit.players.bukkit.command.profile
import com.rpkit.players.bukkit.RPKPlayersBukkit
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
class ProfileCommand(private val plugin: RPKPlayersBukkit): CommandExecutor {
val profileNameCommand = ProfileNameCommand(plugin)
val profilePasswordCommand = ProfilePasswordCommand(plugin)
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (args.isEmpty()) {
sender.sendMessage(plugin.messages["profile-usage"])
return true
}
val newArgs = args.drop(1).toTypedArray()
return when (args[0].toLowerCase()) {
"name" -> profileNameCommand.onCommand(sender, command, label, newArgs)
"password" -> profilePasswordCommand.onCommand(sender, command, label, newArgs)
else -> {
sender.sendMessage(plugin.messages["profile-usage"])
true
}
}
}
} | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/command/profile/ProfileCommand.kt | 3224433074 |
package com.objectpartners.plummer.kotlin.calendar.input.handler
import java.io.BufferedReader
interface InputHandler<O> {
/**
* Read input from the supplied [BufferedReader] to generate a populated instance
* of [O].
*/
fun handle(source: BufferedReader): O
} | src/main/kotlin/com/objectpartners/plummer/kotlin/calendar/input/handler/InputHandler.kt | 1441279026 |
package de.markusfisch.android.binaryeye.actions.wifi
import de.markusfisch.android.binaryeye.simpleFail
import junit.framework.TestCase.*
import org.junit.Test
class WifiConnectorTest {
@Test
fun notWifi() {
assertNull(WifiConnector.parseMap("asdfz"))
}
@Test
fun wep() {
val info = simpleDataAccessor("WIFI:T:WEP;S:asdfz;P:password;;")
assertEquals("WEP", info.securityType)
assertEquals("asdfz", info.ssid)
assertEquals("password", info.password)
assertFalse(info.hidden)
}
@Test
fun anonymousIdentity() {
val info = simpleDataAccessor("WIFI:T:WPA2-EAP;S:wifi;P:password;I:ident;A:anonymous;;")
assertEquals("WPA2-EAP", info.securityType)
assertEquals("wifi", info.ssid)
assertEquals("password", info.password)
assertEquals("ident", info.identity)
assertEquals("anonymous", info.anonymousIdentity)
assertFalse(info.hidden)
}
@Test
fun anonymousIdentityAI() {
val info = simpleDataAccessor("WIFI:T:WPA2-EAP;S:wifi;P:password;I:ident;AI:anonymous;;")
assertEquals("WPA2-EAP", info.securityType)
assertEquals("wifi", info.ssid)
assertEquals("password", info.password)
assertEquals("ident", info.identity)
assertEquals("anonymous", info.anonymousIdentity)
assertFalse(info.hidden)
}
@Test
fun hidden() {
val info = simpleDataAccessor("WIFI:T:WPA;S:asdfz;P:password;H:true;;")
assertEquals("WPA", info.securityType)
assertEquals("asdfz", info.ssid)
assertEquals("password", info.password)
assertTrue(info.hidden)
}
@Test
fun nopass() {
val info = simpleDataAccessor("WIFI:T:nopass;S:asdfz;;")
assertEquals("nopass", info.securityType)
assertEquals("asdfz", info.ssid)
assertNull(info.password)
assertFalse(info.hidden)
}
@Test
fun plainUnsecured() {
val info = simpleDataAccessor("WIFI:S:asdfz;;")
assertEquals("", info.securityType)
assertEquals("asdfz", info.ssid)
assertNull(info.password)
assertFalse(info.hidden)
}
@Test
fun escaping() {
val info = simpleDataAccessor("""WIFI:S:\"ssid\\\;stillSSID\:\;x;;""")
assertEquals("", info.securityType)
assertEquals("\"ssid\\;stillSSID:;x", info.ssid)
assertNull(info.password)
assertFalse(info.hidden)
}
@Test
fun wrongEscaping() {
val info = simpleDataAccessor("""WIFI:S:\SSID":\;x;""")
assertEquals("", info.securityType)
assertEquals("\\SSID\":;x", info.ssid)
assertNull(info.password)
assertFalse(info.hidden)
}
private fun simpleDataAccessor(wifiString: String): WifiConnector.SimpleDataAccessor {
val map = WifiConnector.parseMap(wifiString)
?: simpleFail("parsing map of valid string fails ($wifiString)")
return WifiConnector.SimpleDataAccessor.of(map)
?: simpleFail("could not create SimpleDataAccessor of (potentially) valid map ($map of $wifiString)")
}
}
| app/src/test/kotlin/de/markusfisch/android/binaryeye/actions/wifi/WifiConnectorTest.kt | 2464155898 |
@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)
}
}
| extensions/rxjava3-extensions/src/main/kotlin/com/squareup/sqldelight/runtime/rx3/RxJavaExtensions.kt | 1404047554 |
package org.evomaster.core.search.service
import com.google.inject.Inject
import org.evomaster.core.EMConfig
/**
* Global state used in the search.
* Each gene should be able to access this shared, global state.
*
* Implementation detail: this is not implemented as static state singleton,
* due to all issues related to such design pattern.
* It is not injected with Guice either, due to how we sample and clone individuals,
* which are not injectable services.
*
* This instance is created only once per search (using Guice), and added manually
* each time an individual is sampled and cloned.
*/
class SearchGlobalState {
@Inject
lateinit var randomness: Randomness
private set
@Inject
lateinit var config: EMConfig
private set
@Inject
lateinit var time : SearchTimeController
private set
@Inject
lateinit var apc: AdaptiveParameterControl
private set
@Inject
lateinit var spa: StringSpecializationArchive
} | core/src/main/kotlin/org/evomaster/core/search/service/SearchGlobalState.kt | 3580653600 |
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
}
}
}
}
| crypto/src/main/java/io/oversec/one/crypto/sym/OversecKeystore2.kt | 435049586 |
/*
* 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
}
| sqldelight-compiler/src/main/kotlin/com/squareup/sqldelight/core/lang/SqlDelightFileType.kt | 3102205930 |
package com.example.sqldelight.hockey.data
import com.squareup.sqldelight.ColumnAdapter
actual typealias Date = kotlin.js.Date
actual class DateAdapter actual constructor() : ColumnAdapter<Date, Long> {
override fun encode(value: Date) = value.getTime().toLong()
override fun decode(databaseValue: Long) = Date(databaseValue)
}
| sample/common/src/jsMain/kotlin/com/example/sqldelight/hockey/data/Date.kt | 142444405 |
// Licensed under the MIT license. See LICENSE file in the project root
// for full license information.
package net.dummydigit.qbranch.compiler.symbols
import net.dummydigit.qbranch.compiler.SourceCodeInfo
import net.dummydigit.qbranch.compiler.Translator
internal abstract class Symbol(val sourceCodeInfo : SourceCodeInfo,
val type : SymbolType,
var name : String = "") {
abstract fun toTargetCode(gen : Translator) : String
} | compiler/src/main/kotlin/net/dummydigit/qbranch/compiler/symbols/Symbol.kt | 3954854034 |
package nice3point.by.schedule.CardSheduleFragment
import android.content.Context
import io.realm.RealmResults
import nice3point.by.schedule.Database.TableObject
interface iMCardFragment {
fun getScheduleDatabase(day: Int, week: Int, context: Context): RealmResults<TableObject>
fun closeRealm()
}
| app/src/main/java/nice3point/by/schedule/CardSheduleFragment/iMCardFragment.kt | 3170379865 |
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[]
}
}
| subprojects/docs/src/snippets/dependencyManagement/modelingFeatures-crossProjectPublications-advanced-published/kotlin/buildSrc/src/main/kotlin/com/acme/InstrumentedJarsPlugin.kt | 3975604843 |
/*
* Copyright 2020 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.configurationcache.serialization.codecs
import org.gradle.configurationcache.serialization.ReadContext
import org.gradle.configurationcache.serialization.WriteContext
object EnumCodec : EncodingProducer, Decoding {
override fun encodingForType(type: Class<*>): Encoding? =
EnumEncoding.takeIf { type.isEnum }
?: EnumSubTypeEncoding.takeIf { type.superclass?.isEnum == true }
override suspend fun ReadContext.decode(): Any? {
val enumClass = readClass()
val enumOrdinal = readSmallInt()
return enumClass.enumConstants[enumOrdinal]
}
}
private
object EnumEncoding : Encoding {
override suspend fun WriteContext.encode(value: Any) {
writeEnumValueOf(value::class.java, value)
}
}
private
object EnumSubTypeEncoding : Encoding {
override suspend fun WriteContext.encode(value: Any) {
writeEnumValueOf(value::class.java.superclass, value)
}
}
private
fun WriteContext.writeEnumValueOf(enumClass: Class<out Any>, enumValue: Any) {
writeClass(enumClass)
writeSmallInt((enumValue as Enum<*>).ordinal)
}
| subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/codecs/EnumCodec.kt | 2376355744 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* 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.
*/
@file:Suppress("UNUSED", "PublicApiImplicitType")
package jp.nephy.penicillin.endpoints.application
import jp.nephy.penicillin.core.request.action.JsonObjectApiAction
import jp.nephy.penicillin.core.request.parameters
import jp.nephy.penicillin.core.session.get
import jp.nephy.penicillin.endpoints.Application
import jp.nephy.penicillin.endpoints.Option
import jp.nephy.penicillin.models.ApplicationRateLimitStatus
/**
* Returns the current rate limits for methods belonging to the specified resource families.
*
* Each API resource belongs to a "resource family" which is indicated in its method documentation. The method's resource family can be determined from the first component of the path after the resource version.
*
* This method responds with a map of methods belonging to the families specified by the resources parameter, the current remaining uses for each of those resources within the current rate limiting window, and their expiration time in [epoch time](http://en.wikipedia.org/wiki/Unix_time). It also includes a rate_limit_context field that indicates the current access token or application-only authentication context.
*
* You may also issue requests to this method without any parameters to receive a map of all rate limited GET methods. If your application only uses a few of methods, you should explicitly provide a resources parameter with the specified resource families you work with.
*
* When using application-only auth, this method's response indicates the application-only auth rate limiting context.
*
* Read more about [API Rate Limiting](https://developer.twitter.com/en/docs/basics/rate-limiting) and [review the limits](https://developer.twitter.com/en/docs/basics/rate-limits).
*
* [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-settings)
*
* @param resources A comma-separated list of resource families you want to know the current rate limit disposition for. For best performance, only specify the resource families pertinent to your application. See [API Rate Limiting](https://developer.twitter.com/en/docs/basics/rate-limiting) for more information.
* @param options Optional. Custom parameters of this request.
* @receiver [Application] endpoint instance.
* @return [JsonObjectApiAction] for [ApplicationRateLimitStatus] model.
*/
fun Application.rateLimitStatus(
resources: List<String>? = null,
vararg options: Option
) = client.session.get("/1.1/application/rate_limit_status.json") {
parameters(
"resources" to resources?.joinToString(","),
*options
)
}.jsonObject<ApplicationRateLimitStatus>()
/**
* Shorthand extension property to [Application.rateLimitStatus].
* @see Application.rateLimitStatus
*/
val Application.rateLimitStatus
get() = rateLimitStatus()
| src/main/kotlin/jp/nephy/penicillin/endpoints/application/RateLimitStatus.kt | 3078568019 |
/*
* 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) }
| subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/support/zip.kt | 3003121214 |
/*
* Copyright 2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache
import org.gradle.internal.buildtree.BuildTreeWorkGraph
import org.gradle.internal.component.local.model.LocalComponentGraphResolveState
import org.gradle.internal.service.scopes.Scopes
import org.gradle.internal.service.scopes.ServiceScope
import org.gradle.util.Path
@ServiceScope(Scopes.BuildTree::class)
interface BuildTreeConfigurationCache {
/**
* Determines whether the cache entry can be loaded or needs to be stored or updated.
*/
fun initializeCacheEntry()
/**
* Loads the scheduled tasks from cache, if available, or else runs the given function to schedule the tasks and then
* writes the result to the cache.
*/
fun loadOrScheduleRequestedTasks(graph: BuildTreeWorkGraph, scheduler: (BuildTreeWorkGraph) -> BuildTreeWorkGraph.FinalizedGraph): WorkGraphResult
/**
* Loads the scheduled tasks from cache.
*/
fun loadRequestedTasks(graph: BuildTreeWorkGraph): BuildTreeWorkGraph.FinalizedGraph
/**
* Prepares to load or create a model. Does nothing if the cached model is available or else prepares to capture
* configuration fingerprints and validation problems and then runs the given function.
*/
fun maybePrepareModel(action: () -> Unit)
/**
* Loads the cached model, if available, or else runs the given function to create it and then writes the result to the cache.
*/
fun <T : Any> loadOrCreateModel(creator: () -> T): T
/**
* Loads a cached intermediate model, if available, or else runs the given function to create it and then writes the result to the cache.
*
* @param identityPath The project for which the model should be created, or null for a build scoped model.
*/
fun <T> loadOrCreateIntermediateModel(identityPath: Path?, modelName: String, creator: () -> T?): T?
/**
* Loads cached dependency resolution metadata for the given project, if available, or else runs the given function to create it and then writes the result to the cache.
*/
fun loadOrCreateProjectMetadata(identityPath: Path, creator: () -> LocalComponentGraphResolveState): LocalComponentGraphResolveState
/**
* Flushes any remaining state to the cache and closes any resources
*/
fun finalizeCacheEntry()
// This is a temporary property to allow migration from a root build scoped cache to a build tree scoped cache
val isLoaded: Boolean
// This is a temporary method to allow migration from a root build scoped cache to a build tree scoped cache
fun attachRootBuild(host: DefaultConfigurationCache.Host)
class WorkGraphResult(val graph: BuildTreeWorkGraph.FinalizedGraph, val wasLoadedFromCache: Boolean, val entryDiscarded: Boolean)
}
| subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/BuildTreeConfigurationCache.kt | 119838469 |
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.web.client
import org.springframework.core.ParameterizedTypeReference
import org.springframework.http.HttpEntity
import org.springframework.http.HttpMethod
import org.springframework.http.RequestEntity
import org.springframework.http.ResponseEntity
import org.springframework.web.client.RestClientException
import java.net.URI
/**
* Extension for [TestRestTemplate.getForObject] providing a `getForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.getForObject(url: String, vararg uriVariables: Any): T? =
getForObject(url, T::class.java, *uriVariables)
/**
* Extension for [TestRestTemplate.getForObject] providing a `getForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.getForObject(url: String, uriVariables: Map<String, Any?>): T? =
getForObject(url, T::class.java, uriVariables)
/**
* Extension for [TestRestTemplate.getForObject] providing a `getForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.getForObject(url: URI): T? =
getForObject(url, T::class.java)
/**
* Extension for [TestRestTemplate.getForEntity] providing a `getForEntity<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.getForEntity(url: URI): ResponseEntity<T> =
getForEntity(url, T::class.java)
/**
* Extension for [TestRestTemplate.getForEntity] providing a `getForEntity<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.getForEntity(url: String, vararg uriVariables: Any): ResponseEntity<T> =
getForEntity(url, T::class.java, *uriVariables)
/**
* Extension for [TestRestTemplate.getForEntity] providing a `getForEntity<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.getForEntity(url: String, uriVariables: Map<String, *>): ResponseEntity<T> =
getForEntity(url, T::class.java, uriVariables)
/**
* Extension for [TestRestTemplate.patchForObject] providing a `patchForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.patchForObject(url: String, request: Any? = null,
vararg uriVariables: Any): T? =
patchForObject(url, request, T::class.java, *uriVariables)
/**
* Extension for [TestRestTemplate.patchForObject] providing a `patchForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.patchForObject(url: String, request: Any? = null,
uriVariables: Map<String, *>): T? =
patchForObject(url, request, T::class.java, uriVariables)
/**
* Extension for [TestRestTemplate.patchForObject] providing a `patchForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.patchForObject(url: URI, request: Any? = null): T? =
patchForObject(url, request, T::class.java)
/**
* Extension for [TestRestTemplate.postForObject] providing a `postForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.postForObject(url: String, request: Any? = null,
vararg uriVariables: Any): T? =
postForObject(url, request, T::class.java, *uriVariables)
/**
* Extension for [TestRestTemplate.postForObject] providing a `postForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.postForObject(url: String, request: Any? = null,
uriVariables: Map<String, *>): T? =
postForObject(url, request, T::class.java, uriVariables)
/**
* Extension for [TestRestTemplate.postForObject] providing a `postForObject<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.postForObject(url: URI, request: Any? = null): T? =
postForObject(url, request, T::class.java)
/**
* Extension for [TestRestTemplate.postForEntity] providing a `postForEntity<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.postForEntity(url: String, request: Any? = null,
vararg uriVariables: Any): ResponseEntity<T> =
postForEntity(url, request, T::class.java, *uriVariables)
/**
* Extension for [TestRestTemplate.postForEntity] providing a `postForEntity<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.postForEntity(url: String, request: Any? = null,
uriVariables: Map<String, *>): ResponseEntity<T> =
postForEntity(url, request, T::class.java, uriVariables)
/**
* Extension for [TestRestTemplate.postForEntity] providing a `postForEntity<Foo>(...)`
* variant leveraging Kotlin reified type parameters. Like the original Java method, this
* extension is subject to type erasure. Use [exchange] if you need to retain actual
* generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.postForEntity(url: URI, request: Any? = null): ResponseEntity<T> =
postForEntity(url, request, T::class.java)
/**
* Extension for [TestRestTemplate.exchange] providing an `exchange<Foo>(...)`
* variant leveraging Kotlin reified type parameters. This extension is not subject to
* type erasure and retains actual generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.exchange(url: String, method: HttpMethod,
requestEntity: HttpEntity<*>? = null, vararg uriVariables: Any): ResponseEntity<T> =
exchange(url, method, requestEntity, object : ParameterizedTypeReference<T>() {}, *uriVariables)
/**
* Extension for [TestRestTemplate.exchange] providing an `exchange<Foo>(...)`
* variant leveraging Kotlin reified type parameters. This extension is not subject to
* type erasure and retains actual generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.exchange(url: String, method: HttpMethod,
requestEntity: HttpEntity<*>? = null, uriVariables: Map<String, *>): ResponseEntity<T> =
exchange(url, method, requestEntity, object : ParameterizedTypeReference<T>() {}, uriVariables)
/**
* Extension for [TestRestTemplate.exchange] providing an `exchange<Foo>(...)`
* variant leveraging Kotlin reified type parameters. This extension is not subject to
* type erasure and retains actual generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.exchange(url: URI, method: HttpMethod,
requestEntity: HttpEntity<*>? = null): ResponseEntity<T> =
exchange(url, method, requestEntity, object : ParameterizedTypeReference<T>() {})
/**
* Extension for [TestRestTemplate.exchange] providing an `exchange<Foo>(...)`
* variant leveraging Kotlin reified type parameters. This extension is not subject to
* type erasure and retains actual generic type arguments.
*
* @author Sebastien Deleuze
* @since 2.0.0
*/
@Throws(RestClientException::class)
inline fun <reified T : Any> TestRestTemplate.exchange(requestEntity: RequestEntity<*>): ResponseEntity<T> =
exchange(requestEntity, object : ParameterizedTypeReference<T>() {}) | spring-boot-project/spring-boot-test/src/main/kotlin/org/springframework/boot/test/web/client/TestRestTemplateExtensions.kt | 2483838722 |
/*
* 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)
}
}
| javatests/com/google/android/libraries/pcc/chronicle/remote/RemoteRouterTest.kt | 4118725792 |
package com.khmelenko.lab.varis.builddetails
import android.app.Activity
import dagger.Binds
import dagger.Module
import dagger.Subcomponent
import dagger.android.ActivityKey
import dagger.android.AndroidInjector
import dagger.multibindings.IntoMap
/**
* @author Dmytro Khmelenko ([email protected])
*/
@Module(subcomponents = [(BuildDetailsActivitySubcomponent::class)])
abstract class BuildDetailsActivityModule {
@Binds
@IntoMap
@ActivityKey(BuildDetailsActivity::class)
internal abstract fun bindBuildDetailsActivityInjectorFactory(
builder: BuildDetailsActivitySubcomponent.Builder): AndroidInjector.Factory<out Activity>
}
@Subcomponent
interface BuildDetailsActivitySubcomponent : AndroidInjector<BuildDetailsActivity> {
@Subcomponent.Builder
abstract class Builder : AndroidInjector.Builder<BuildDetailsActivity>()
}
| app-v3/src/main/java/com/khmelenko/lab/varis/builddetails/BuildDetailsActivityModule.kt | 3588221744 |
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)
| module/exception/src/main/java/org/openbase/jul/exception/ExceptionProcessor.kt | 3730435526 |
/*
* Notes Copyright (C) 2018 Nikhil Soni
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.nrs.nsnik.notes.dagger.components
import com.nrs.nsnik.notes.dagger.modules.NetworkModule
import com.nrs.nsnik.notes.dagger.scopes.ApplicationScope
import com.nrs.nsnik.notes.util.NetworkUtil
import dagger.Component
@ApplicationScope
@Component(modules = [(NetworkModule::class)])
abstract class NetworkComponent {
abstract fun getNetworkUtil(): NetworkUtil
} | app/src/main/java/com/nrs/nsnik/notes/dagger/components/NetworkComponent.kt | 2126622305 |
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))
}
} | app/src/main/kotlin/com/github/premnirmal/ticker/portfolio/AddPositionViewModel.kt | 1172335863 |
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
}
}
} | app/src/main/java/com/battlelancer/seriesguide/preferences/NotificationSelectionDialogFragment.kt | 308635738 |
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.composemail.model.repo
import com.example.composemail.model.data.MailEntryInfo
interface MailRepository {
suspend fun connect()
suspend fun getNextSetOfConversations(amount: Int): MailConversationsResponse
}
data class MailConversationsResponse(
val conversations: List<MailEntryInfo>,
val page: Int
) | demoProjects/ComposeMail/app/src/main/java/com/example/composemail/model/repo/MailRepository.kt | 3446675319 |
/*
* Copyright 2017 Alexey Shtanko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.shtanko.picasagallery.core.executor
import java.util.concurrent.Executor
interface ThreadExecutor : Executor | app/src/main/kotlin/io/shtanko/picasagallery/core/executor/ThreadExecutor.kt | 3704422752 |
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
}
} | app/src/main/java/tw/shounenwind/kmnbottool/activities/TeamActivity.kt | 1785772763 |
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
}
})
}
}
| bukkit/rpk-permissions-bukkit/src/main/kotlin/com/rpkit/permissions/bukkit/command/charactergroup/CharacterGroupViewCommand.kt | 3602105443 |
package com.rpkit.travel.bukkit.permissions
class TravelPermissions {
val parentWarpPermission = "rpkit.travel.command.warp"
}
| bukkit/rpk-travel-bukkit/src/main/kotlin/com/rpkit/travel/bukkit/permissions/TravelPermissions.kt | 3137447574 |
package icurves.graph
import javafx.geometry.Point2D
import javafx.scene.shape.Path
/**
*
*
* @author Almas Baimagambetov ([email protected])
*/
data class GraphCycle<V, E>(val nodes: List<V>, val edges: List<E>) {
lateinit var path: Path
lateinit var smoothingData: MutableList<Point2D>
fun length() = nodes.size
fun contains(node: V): Boolean {
for (n in nodes) {
if (n.toString() == node.toString()) {
return true
}
}
return false
}
// fun contains(zones: List<AbstractBasicRegion>): Boolean {
// val mappedNodes = nodes.map { it.zone.abstractZone }
//
// return mappedNodes.containsAll(zones)
// }
} | src/main/kotlin/icurves/graph/GraphCycle.kt | 1099925113 |
<!doctype html>
<html lang=en>
<head>
<meta charset='utf-8'>
<link href='/static/style.css' type='text/css' rel='stylesheet'>
<title>$Title</title>
</head>
<body>
<div id='Top'>Title of the page</div>
<div id='Menu'>$menu.Render(Menu)</div>
<div id='Container0'>
<div id='Container1'>
<div id='Left'>$left.Render(Left)</div>
<div id='Right'>$right.Render(Right)</div>
</div>
</div>
<div id='Bottom'>
Started: $Started; Hits: $Hits; Last client: $LastCliAddr
</div>
</body>
</html>
| examples/templates/layout.kt | 1234295801 |
package com.todoist.pojo
open class Tooltips(
open val scheduled: Set<String> = emptySet(),
open val seen: Set<String> = emptySet()
)
| src/main/java/com/todoist/pojo/Tooltips.kt | 2519182383 |
package fr.free.nrw.commons.utils
import android.app.ProgressDialog
import android.content.Context
import android.graphics.Bitmap
import fr.free.nrw.commons.TestCommonsApplication
import fr.free.nrw.commons.location.LatLng
import fr.free.nrw.commons.mwapi.OkHttpJsonApiClient
import io.reactivex.disposables.CompositeDisposable
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.mockito.MockitoAnnotations
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import java.io.File
import java.lang.reflect.Field
import java.lang.reflect.Method
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [21], application = TestCommonsApplication::class)
@LooperMode(LooperMode.Mode.PAUSED)
class ImageUtilsTest {
private lateinit var context: Context
@Mock
private lateinit var bitmap: Bitmap
@Mock
private lateinit var progressDialogWallpaper: ProgressDialog
@Mock
private lateinit var okHttpJsonApiClient: OkHttpJsonApiClient
@Mock
private lateinit var compositeDisposable: CompositeDisposable
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
context = RuntimeEnvironment.application.applicationContext
}
@Test
fun testCheckIfImageIsTooDarkCaseException() {
Assert.assertEquals(ImageUtils.checkIfImageIsTooDark("")
, ImageUtils.IMAGE_OK)
}
// Refer: testCheckIfImageIsTooDarkCaseException()
@Test
fun testCheckIfProperImageIsTooDark() {
Assert.assertEquals(ImageUtils.checkIfImageIsTooDark("src/test/resources/ImageTest/ok1.jpg")
, ImageUtils.IMAGE_OK)
Assert.assertEquals(ImageUtils.checkIfImageIsTooDark("src/test/resources/ImageTest/ok2.jpg")
, ImageUtils.IMAGE_OK)
Assert.assertEquals(ImageUtils.checkIfImageIsTooDark("src/test/resources/ImageTest/ok3.jpg")
, ImageUtils.IMAGE_OK)
Assert.assertEquals(ImageUtils.checkIfImageIsTooDark("src/test/resources/ImageTest/ok4.jpg")
, ImageUtils.IMAGE_OK)
}
// Refer: testCheckIfImageIsTooDarkCaseException()
@Test
fun testCheckIfDarkImageIsTooDark() {
Assert.assertEquals(ImageUtils.checkIfImageIsTooDark("src/test/resources/ImageTest/dark1.jpg")
, ImageUtils.IMAGE_DARK)
Assert.assertEquals(ImageUtils.checkIfImageIsTooDark("src/test/resources/ImageTest/dark2.jpg")
, ImageUtils.IMAGE_DARK)
}
@Test
fun testCheckIfImageIsTooDark() {
val tempFile = File.createTempFile("prefix", "suffix")
ImageUtils.checkIfImageIsTooDark(tempFile.absolutePath)
}
@Test
fun testSetWallpaper() {
val mockImageUtils = mock(ImageUtils::class.java)
val method: Method = ImageUtils::class.java.getDeclaredMethod(
"setWallpaper",
Context::class.java,
Bitmap::class.java
)
method.isAccessible = true
`when`(progressDialogWallpaper.isShowing).thenReturn(true)
val progressDialogWallpaperField: Field =
ImageUtils::class.java.getDeclaredField("progressDialogWallpaper")
progressDialogWallpaperField.isAccessible = true
progressDialogWallpaperField.set(mockImageUtils, progressDialogWallpaper)
method.invoke(mockImageUtils, context, bitmap)
}
@Test
fun testShowSettingAvatarProgressBar() {
val mockImageUtils = mock(ImageUtils::class.java)
val method: Method = ImageUtils::class.java.getDeclaredMethod(
"showSettingAvatarProgressBar",
Context::class.java
)
method.isAccessible = true
method.invoke(mockImageUtils, context)
}
@Test
fun testGetErrorMessageForResultCase0() {
ImageUtils.getErrorMessageForResult(context, 0)
}
@Test
fun testGetErrorMessageForResultCaseIMAGE_DARK() {
ImageUtils.getErrorMessageForResult(context, 1)
}
@Test
fun testGetErrorMessageForResultCaseIMAGE_BLURRY() {
ImageUtils.getErrorMessageForResult(context, 2)
}
@Test
fun testGetErrorMessageForResultCaseIMAGE_DUPLICATE() {
ImageUtils.getErrorMessageForResult(context, 4)
}
@Test
fun testGetErrorMessageForResultCaseIMAGE_GEOLOCATION_DIFFERENT() {
ImageUtils.getErrorMessageForResult(context, 8)
}
@Test
fun testGetErrorMessageForResultCaseFILE_FBMD() {
ImageUtils.getErrorMessageForResult(context, 16)
}
@Test
fun testGetErrorMessageForResultCaseFILE_NO_EXIF() {
ImageUtils.getErrorMessageForResult(context, 32)
}
@Test
fun testSetAvatarFromImageUrl() {
ImageUtils.setAvatarFromImageUrl(
context,
"",
"",
okHttpJsonApiClient,
compositeDisposable
)
}
@Test
fun testCheckImageGeolocationIsDifferentCaseNull() {
Assert.assertEquals(
ImageUtils.checkImageGeolocationIsDifferent(
"test",
null
), false
)
}
@Test
fun testCheckImageGeolocationIsDifferent() {
Assert.assertEquals(
ImageUtils.checkImageGeolocationIsDifferent(
"0.0|0.0",
LatLng(0.0, 0.0, 0f)
), false
)
}
@Test
fun testCheckIfImageIsDark() {
val mockImageUtils = mock(ImageUtils::class.java)
val method: Method = ImageUtils::class.java.getDeclaredMethod(
"checkIfImageIsDark",
Bitmap::class.java
)
method.isAccessible = true
method.invoke(mockImageUtils, null)
}
} | app/src/test/kotlin/fr/free/nrw/commons/utils/ImageUtilsTest.kt | 4078203350 |
package frc.team5333.core.commands
import frc.team5333.core.control.strategy.StrategyController
import frc.team5333.core.control.strategy.StrategyOperator
import frc.team5333.core.control.strategy.StrategySpeedTest
import jaci.openrio.toast.core.command.AbstractCommand
import jaci.openrio.toast.core.command.IHelpable
class CommandSpeedTest : AbstractCommand(), IHelpable {
override fun getCommandName(): String? = "speedtest"
override fun invokeCommand(argLength: Int, args: Array<out String>?, command: String?) {
var strat = StrategySpeedTest()
strat.then(StrategyOperator())
StrategyController.INSTANCE.setStrategy(strat)
}
override fun getHelp(): String? = "Conduct a Speed Test for 1 Second. Measuring the distance the Robot has covered on the field will give you the speed of the Robot in m/s"
} | src/main/kotlin/frc/team5333/core/commands/CommandSpeedTest.kt | 2621280447 |
@file:JvmName("RxTextView")
@file:JvmMultifileClass
package com.jakewharton.rxbinding4.widget
import android.view.KeyEvent
import android.widget.TextView
import android.widget.TextView.OnEditorActionListener
import androidx.annotation.CheckResult
import com.jakewharton.rxbinding4.internal.AlwaysTrue
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.android.MainThreadDisposable
import com.jakewharton.rxbinding4.internal.checkMainThread
/**
* Create an observable of editor action events on `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [TextView.OnEditorActionListener] to
* observe actions. Only one observable can be used for a view at a time.
*
* @param handled Predicate invoked each occurrence to determine the return value of the
* underlying [TextView.OnEditorActionListener].
*/
@CheckResult
@JvmOverloads
fun TextView.editorActionEvents(
handled: (TextViewEditorActionEvent) -> Boolean = AlwaysTrue
): Observable<TextViewEditorActionEvent> {
return TextViewEditorActionEventObservable(this, handled)
}
data class TextViewEditorActionEvent(
/** The view from which this event occurred. */
val view: TextView,
val actionId: Int,
val keyEvent: KeyEvent?
)
private class TextViewEditorActionEventObservable(
private val view: TextView,
private val handled: (TextViewEditorActionEvent) -> Boolean
) : Observable<TextViewEditorActionEvent>() {
override fun subscribeActual(observer: Observer<in TextViewEditorActionEvent>) {
if (!checkMainThread(observer)) {
return
}
val listener = Listener(view, observer, handled)
observer.onSubscribe(listener)
view.setOnEditorActionListener(listener)
}
private class Listener(
private val view: TextView,
private val observer: Observer<in TextViewEditorActionEvent>,
private val handled: (TextViewEditorActionEvent) -> Boolean
) : MainThreadDisposable(), OnEditorActionListener {
override fun onEditorAction(textView: TextView, actionId: Int, keyEvent: KeyEvent?): Boolean {
val event = TextViewEditorActionEvent(view, actionId, keyEvent)
try {
if (!isDisposed && handled(event)) {
observer.onNext(event)
return true
}
} catch (e: Exception) {
observer.onError(e)
dispose()
}
return false
}
override fun onDispose() {
view.setOnEditorActionListener(null)
}
}
}
| rxbinding/src/main/java/com/jakewharton/rxbinding4/widget/TextViewEditorActionEventObservable.kt | 273471848 |
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>)
}
| iBurn/src/main/java/com/gaiagps/iburn/database/DataProvider.kt | 2271641622 |
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.declarations
import net.perfectdreams.loritta.common.locale.LanguageManager
import net.perfectdreams.loritta.i18n.I18nKeysData
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.common.commands.CommandCategory
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandDeclarationWrapper
import net.perfectdreams.loritta.morenitta.utils.ecb.ECBManager
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.MoneyExecutor
class MoneyCommand(languageManager: LanguageManager) : CinnamonSlashCommandDeclarationWrapper(languageManager) {
companion object {
val I18N_PREFIX = I18nKeysData.Commands.Command.Money
// Remember, Discord Slash Commands have a limit of 25 options per command!
// The overflown options are taken out before being registered
val currencyIds = listOf(
"EUR",
"USD",
"BRL",
"JPY",
"BGN",
"CZK",
"DKK",
"GBP",
"HUF",
"PLN",
"RON",
"SEK",
"CHF",
"ISK",
"NOK",
"HRK",
"RUB",
"TRY",
"AUD",
"CAD",
"CNY",
"HKD",
"IDR",
// "shekel" triggers Discord's bad words check, for some reason
// https://canary.discord.com/channels/613425648685547541/916395737141620797/1022169074089861130
// "ILS",
"INR",
"KRW",
"MXN",
"MYR",
"NZD",
"PHP",
"SGD",
"THB",
"ZAR"
)
}
override fun declaration() = slashCommand(I18N_PREFIX.Label, CommandCategory.UTILS, I18N_PREFIX.Description) {
executor = { MoneyExecutor(it, it.ecbManager) }
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/utils/declarations/MoneyCommand.kt | 850547792 |
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
}
}
} | mainui/src/main/kotlin/fynances/desktop/Styles.kt | 3281548550 |
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images.declarations
import net.perfectdreams.gabrielaimageserver.client.GabrielaImageServerClient
import net.perfectdreams.loritta.common.locale.LanguageManager
import net.perfectdreams.loritta.i18n.I18nKeysData
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.common.commands.CommandCategory
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandDeclarationWrapper
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images.WolverineFrameExecutor
class WolverineFrameCommand(languageManager: LanguageManager) : CinnamonSlashCommandDeclarationWrapper(languageManager) {
companion object {
val I18N_PREFIX = I18nKeysData.Commands.Command.Wolverineframe
}
override fun declaration() = slashCommand(I18N_PREFIX.Label, CommandCategory.IMAGES, I18N_PREFIX.Description) {
executor = { WolverineFrameExecutor(it, it.gabrielaImageServerClient) }
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/images/declarations/WolverineFrameCommand.kt | 742624083 |
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
}
}
} | app/src/main/java/com/etesync/syncadapter/ui/etebase/ImportCollectionFragment.kt | 3488917009 |
package io.github.rosariopfernandes.rollapass.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Word(
@PrimaryKey
var id: Int?,
var word: String
) {
constructor(): this(null, "")
} | app/src/main/java/io/github/rosariopfernandes/rollapass/model/Word.kt | 1063044354 |
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))
}
}
} | app/src/main/java/com/md/appmanager/async/UninstallInBackground.kt | 313707176 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.