repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
iemejia/incubator-beam
learning/katas/kotlin/Core Transforms/Combine/Simple Function/test/org/apache/beam/learning/katas/coretransforms/combine/simple/TaskTest.kt
9
1549
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.learning.katas.coretransforms.combine.simple import org.apache.beam.learning.katas.coretransforms.combine.simple.Task.applyTransform import org.apache.beam.sdk.testing.PAssert import org.apache.beam.sdk.testing.TestPipeline import org.apache.beam.sdk.transforms.Create import org.junit.Rule import org.junit.Test class TaskTest { @get:Rule @Transient val testPipeline: TestPipeline = TestPipeline.create() @Test fun core_transforms_combine_simple_function() { val values = Create.of(10, 30, 50, 70, 90) val numbers = testPipeline.apply(values) val results = applyTransform(numbers) PAssert.that(results).containsInAnyOrder(250) testPipeline.run().waitUntilFinish() } }
apache-2.0
HabitRPG/habitica-android
wearos/src/main/java/com/habitrpg/wearos/habitica/models/user/Profile.kt
1
168
package com.habitrpg.wearos.habitica.models.user import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) class Profile { var name: String? = null }
gpl-3.0
fredyw/leetcode
src/main/kotlin/leetcode/Problem1824.kt
1
1206
package leetcode import kotlin.math.min /** * https://leetcode.com/problems/minimum-sideway-jumps/ */ class Problem1824 { fun minSideJumps(obstacles: IntArray): Int { return minSideJumps(obstacles, lane = 2, index = 0, memo = Array(obstacles.size) { IntArray(4) { -1 } }) } private fun minSideJumps(obstacles: IntArray, lane: Int, index: Int, memo: Array<IntArray>): Int { if (obstacles.size == index) { return 0 } if (obstacles[index] == lane) { return Int.MAX_VALUE } if (memo[index][lane] != -1) { return memo[index][lane] } val noSideJump = minSideJumps(obstacles, lane, index + 1, memo) var hasSideJump = Int.MAX_VALUE for (l in 1..3) { if (l == lane || obstacles[index] == l) { continue } var sideJump = minSideJumps(obstacles, l, index + 1, memo) if (sideJump != Int.MAX_VALUE) { sideJump++ } hasSideJump = min(hasSideJump, sideJump) } val min = min(noSideJump, hasSideJump) memo[index][lane] = min return min } }
mit
rhdunn/xquery-intellij-plugin
src/plugin-marklogic/main/uk/co/reecedunn/intellij/plugin/marklogic/xray/format/xunit/XRayXUnitTestSuites.kt
1
1914
/* * Copyright (C) 2021-2022 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.marklogic.xray.format.xunit import uk.co.reecedunn.intellij.plugin.core.xml.dom.XmlElement import uk.co.reecedunn.intellij.plugin.processor.test.TestStatistics import uk.co.reecedunn.intellij.plugin.processor.test.TestSuite import uk.co.reecedunn.intellij.plugin.processor.test.TestSuites import kotlin.math.max class XRayXUnitTestSuites(private val suites: XmlElement) : TestSuites { override val total: Int by lazy { suites.attribute("tests")!!.toInt() } override val passed: Int by lazy { max(total - ignored - failed - errors, 0) } override val ignored: Int by lazy { suites.attribute("skipped")!!.toInt() } override val failed: Int by lazy { suites.attribute("failures")!!.toInt() } override val errors: Int by lazy { // NOTE: The XRay xunit formatter has a bug where the errors attribute // does not match the total from the separate test suites. This is // because it includes the error:error element inside a failing xray:test. testSuites.sumOf { (it as TestStatistics).errors } } private val testSuitesList by lazy { suites.children("testsuite").map { XRayXUnitTestSuite(it) }.toList() } override val testSuites: Sequence<TestSuite> get() = testSuitesList.asSequence() }
apache-2.0
naturlecso/NaturShutd
app/src/main/java/hu/naturlecso/naturshutd/ui/adapter/HostListAdapter.kt
1
992
package hu.naturlecso.naturshutd.ui.adapter import android.content.Context import android.databinding.ViewDataBinding import java.util.ArrayList import hu.naturlecso.naturshutd.R import hu.naturlecso.naturshutd.databinding.HostItemBinding import hu.naturlecso.naturshutd.host.Host import hu.naturlecso.naturshutd.ui.viewmodel.HostItemViewModel class HostListAdapter(private val context: Context) : BaseMvvmRecyclerAdapter<Host>(R.layout.host_item) { private var items: List<Host> = emptyList() override fun bind(binding: ViewDataBinding, position: Int, item: Host) { (binding as HostItemBinding).viewmodel = HostItemViewModel(context, item) } override fun getItemCount(): Int = items.size override fun getItemId(position: Int): Long { return -1L //TODO items.get(position).id; } override fun getItem(position: Int): Host = items[position] fun swap(items: List<Host>) { this.items = items notifyDataSetChanged() } }
gpl-3.0
Jkly/gdx-box2d-kotlin
src/test/kotlin/pro/gramcode/box2d/dsl/BodyFixtureDslSpec.kt
1
1308
package pro.gramcode.box2d.dsl import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.physics.box2d.Fixture import com.badlogic.gdx.physics.box2d.Shape import com.badlogic.gdx.physics.box2d.World import com.nhaarman.mockito_kotlin.argThat import com.nhaarman.mockito_kotlin.spy import com.nhaarman.mockito_kotlin.verify import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.context import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it object BodyFixtureDslSpec : Spek({ describe("a body fixture DSL") { var world: World? = null beforeEachTest { world = World(Vector2.Zero, false) } afterEachTest { world?.dispose() } context("adding a body fixture") { it("should call the callback function with newly created fixture") { val callback = spy({ _:Fixture -> }) val callback2 = spy({ _:Fixture -> }) world!!.createBody { circle(callback) { } polygon(callback2) { } } verify(callback).invoke(argThat { shape.type == Shape.Type.Circle}) verify(callback2).invoke(argThat { shape.type == Shape.Type.Polygon}) } } } })
apache-2.0
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/injection/comment/ComposeCommentComponent.kt
2
568
package org.stepik.android.view.injection.comment import dagger.Subcomponent import org.stepik.android.view.comment.ui.dialog.ComposeCommentDialogFragment import org.stepik.android.view.injection.submission.SubmissionDataModule @Subcomponent(modules = [ CommentDataModule::class, ComposeCommentModule::class, SubmissionDataModule::class ]) interface ComposeCommentComponent { @Subcomponent.Builder interface Builder { fun build(): ComposeCommentComponent } fun inject(composeCommentDialogFragment: ComposeCommentDialogFragment) }
apache-2.0
dhleong/ideavim
src/com/maddyhome/idea/vim/command/Command.kt
1
2966
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * 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 2 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.maddyhome.idea.vim.command import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.editor.actionSystem.EditorAction import com.maddyhome.idea.vim.handler.EditorActionHandlerBase import java.util.* import javax.swing.KeyStroke /** * This represents a single Vim command to be executed. It may optionally include an argument if appropriate for * the command. The command has a count and a type. */ data class Command( var rawCount: Int, val actionId: String?, var action: AnAction?, val type: Type, var flags: EnumSet<CommandFlags> ) { init { if (action is EditorAction) { val handler = (action as EditorAction).handler if (handler is EditorActionHandlerBase) { handler.process(this) } } } var count: Int get() = rawCount.coerceAtLeast(1) set(value) { rawCount = value } var keys: List<KeyStroke> = emptyList() var argument: Argument? = null enum class Type { /** * Represents undefined commands. */ UNDEFINED, /** * Represents commands that actually move the cursor and can be arguments to operators. */ MOTION, /** * Represents commands that insert new text into the editor. */ INSERT, /** * Represents commands that remove text from the editor. */ DELETE, /** * Represents commands that change text in the editor. */ CHANGE, /** * Represents commands that copy text in the editor. */ COPY, PASTE, RESET, /** * Represents commands that select the register. */ SELECT_REGISTER, OTHER_READONLY, OTHER_WRITABLE, OTHER_READ_WRITE, /** * Represent commands that don't require an outer read or write action for synchronization. */ OTHER_SELF_SYNCHRONIZED, COMPLETION; val isRead: Boolean get() = when (this) { MOTION, COPY, SELECT_REGISTER, OTHER_READONLY, OTHER_READ_WRITE, COMPLETION -> true else -> false } val isWrite: Boolean get() = when (this) { INSERT, DELETE, CHANGE, PASTE, RESET, OTHER_WRITABLE, OTHER_READ_WRITE -> true else -> false } } }
gpl-2.0
MarcBob/SmartRecyclerViewAdapter
app/src/main/kotlin/bobzien/com/smartrecyclerviewadapter/ViewHolder/NumViewHolder.kt
1
944
package bobzien.com.smartrecyclerviewadapter.ViewHolder import android.content.Context import android.view.View import android.widget.TextView import bobzien.com.smartrecyclerviewadapter.R import bobzien.com.smartrecyclerviewadapter.SmartRecyclerViewAdapter.ViewHolder class NumViewHolder(context: Context, clazz: Class<Integer>, itemView: View?) : ViewHolder<Integer>(context, clazz, itemView) { protected lateinit var textView: TextView init { if (itemView != null) { textView = itemView.findViewById(R.id.text) as TextView } } override fun getInstance(itemView: View): ViewHolder<Any> { return NumViewHolder(context, getHandledClass() as Class<Integer>, itemView) as ViewHolder<Any> } override val layoutResourceId: Int get() = R.layout.list_item_num override fun bindViewHolder(item: Integer, selected: Boolean) { textView.text = item.toString() } }
apache-2.0
da1z/intellij-community
python/python-community-configure/src/com/jetbrains/python/newProject/steps/PyAddNewEnvironmentPanel.kt
1
3130
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.newProject.steps import com.intellij.openapi.projectRoots.Sdk import com.intellij.ui.ColoredListCellRenderer import com.intellij.util.ui.FormBuilder import com.jetbrains.python.sdk.PySdkSettings import com.jetbrains.python.sdk.add.PyAddNewCondaEnvPanel import com.jetbrains.python.sdk.add.PyAddNewEnvPanel import com.jetbrains.python.sdk.add.PyAddNewVirtualEnvPanel import com.jetbrains.python.sdk.add.PyAddSdkPanel import java.awt.BorderLayout import java.awt.event.ItemEvent import javax.swing.JComboBox import javax.swing.JList /** * @author vlan */ class PyAddNewEnvironmentPanel(existingSdks: List<Sdk>, newProjectPath: String?) : PyAddSdkPanel() { override val panelName = "New environment using" override val nameExtensionComponent: JComboBox<PyAddNewEnvPanel> override var newProjectPath: String? = newProjectPath set(value) { field = value for (panel in panels) { panel.newProjectPath = newProjectPath } } private val panels = listOf(PyAddNewVirtualEnvPanel(null, existingSdks, newProjectPath), PyAddNewCondaEnvPanel(null, existingSdks, newProjectPath)) var selectedPanel = panels.find { it.envName == PySdkSettings.instance.preferredEnvironmentType } ?: panels[0] private val listeners = mutableListOf<Runnable>() init { nameExtensionComponent = JComboBox(panels.toTypedArray()).apply { renderer = object : ColoredListCellRenderer<PyAddNewEnvPanel>() { override fun customizeCellRenderer(list: JList<out PyAddNewEnvPanel>, value: PyAddNewEnvPanel?, index: Int, selected: Boolean, hasFocus: Boolean) { val panel = value ?: return append(panel.envName) icon = panel.icon } } selectedItem = selectedPanel addItemListener { if (it.stateChange == ItemEvent.SELECTED) { val selected = it.item as? PyAddSdkPanel ?: return@addItemListener for (panel in panels) { val isSelected = panel == selected panel.isVisible = isSelected if (isSelected) { selectedPanel = panel } } for (listener in listeners) { listener.run() } } } } layout = BorderLayout() val formBuilder = FormBuilder.createFormBuilder().apply { for (panel in panels) { addComponent(panel) panel.isVisible = panel == selectedPanel } } add(formBuilder.panel, BorderLayout.NORTH) } override fun getOrCreateSdk(): Sdk? { val createdSdk = selectedPanel.getOrCreateSdk() PySdkSettings.instance.preferredEnvironmentType = selectedPanel.envName return createdSdk } override fun validateAll() = selectedPanel.validateAll() override fun addChangeListener(listener: Runnable) { for (panel in panels) { panel.addChangeListener(listener) } listeners += listener } }
apache-2.0
jainsahab/AndroidSnooper
Snooper/src/androidTest/java/com/prateekj/snooper/rules/DataResetRule.kt
1
1420
package com.prateekj.snooper.rules import androidx.test.platform.app.InstrumentationRegistry import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation import com.prateekj.snooper.database.SnooperDbHelper import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HEADER_TABLE_NAME import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HEADER_VALUE_TABLE_NAME import com.prateekj.snooper.networksnooper.database.HttpCallRecordContract.Companion.HTTP_CALL_RECORD_TABLE_NAME import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement class DataResetRule : TestRule { private val snooperDbHelper: SnooperDbHelper = SnooperDbHelper.getInstance(getInstrumentation().targetContext) override fun apply(base: Statement, description: Description): Statement { return object : Statement() { @Throws(Throwable::class) override fun evaluate() { try { base.evaluate() } finally { val database = snooperDbHelper.writableDatabase val tableToDelete = listOf( HEADER_VALUE_TABLE_NAME, HEADER_TABLE_NAME, HTTP_CALL_RECORD_TABLE_NAME ) for (table in tableToDelete) { database.delete(table, null, null) } database.close() } } } } }
apache-2.0
Maccimo/intellij-community
plugins/kotlin/jvm-debugger/test/testData/selectExpression/disallowMethodCalls/unaryExpression.kt
3
71
fun foo() { <caret>+1 } // DISALLOW_METHOD_CALLS // EXPECTED: null
apache-2.0
k9mail/k-9
backend/imap/src/test/java/com/fsck/k9/backend/imap/TestImapFolder.kt
2
5309
package com.fsck.k9.backend.imap import com.fsck.k9.mail.BodyFactory import com.fsck.k9.mail.FetchProfile import com.fsck.k9.mail.Flag import com.fsck.k9.mail.Message import com.fsck.k9.mail.MessageRetrievalListener import com.fsck.k9.mail.Part import com.fsck.k9.mail.store.imap.FetchListener import com.fsck.k9.mail.store.imap.ImapFolder import com.fsck.k9.mail.store.imap.ImapMessage import com.fsck.k9.mail.store.imap.OpenMode import com.fsck.k9.mail.store.imap.createImapMessage import java.util.Date open class TestImapFolder(override val serverId: String) : ImapFolder { override var mode: OpenMode? = null protected set override var messageCount: Int = 0 var wasExpunged: Boolean = false private set val isClosed: Boolean get() = mode == null private val messages = mutableMapOf<Long, Message>() private val messageFlags = mutableMapOf<Long, MutableSet<Flag>>() private var uidValidity: Long? = null fun addMessage(uid: Long, message: Message) { require(!messages.containsKey(uid)) { "Folder '$serverId' already contains a message with the UID $uid" } messages[uid] = message messageFlags[uid] = mutableSetOf() messageCount = messages.size } fun removeAllMessages() { messages.clear() messageFlags.clear() } fun setUidValidity(value: Long) { uidValidity = value } override fun open(mode: OpenMode) { this.mode = mode } override fun close() { mode = null } override fun exists(): Boolean { throw UnsupportedOperationException("not implemented") } override fun getUidValidity() = uidValidity override fun getMessage(uid: String): ImapMessage { return createImapMessage(uid) } override fun getUidFromMessageId(messageId: String): String? { throw UnsupportedOperationException("not implemented") } override fun getMessages( start: Int, end: Int, earliestDate: Date?, listener: MessageRetrievalListener<ImapMessage>? ): List<ImapMessage> { require(start > 0) require(end >= start) require(end <= messages.size) return messages.keys.sortedDescending() .slice((start - 1) until end) .map { createImapMessage(uid = it.toString()) } } override fun areMoreMessagesAvailable(indexOfOldestMessage: Int, earliestDate: Date?): Boolean { throw UnsupportedOperationException("not implemented") } override fun fetch( messages: List<ImapMessage>, fetchProfile: FetchProfile, listener: FetchListener?, maxDownloadSize: Int ) { if (messages.isEmpty()) return for (imapMessage in messages) { val uid = imapMessage.uid.toLong() val flags = messageFlags[uid].orEmpty().toSet() imapMessage.setFlags(flags, true) val storedMessage = this.messages[uid] ?: error("Message $uid not found") for (header in storedMessage.headers) { imapMessage.addHeader(header.name, header.value) } imapMessage.body = storedMessage.body listener?.onFetchResponse(imapMessage, isFirstResponse = true) } } override fun fetchPart( message: ImapMessage, part: Part, bodyFactory: BodyFactory, maxDownloadSize: Int ) { throw UnsupportedOperationException("not implemented") } override fun search( queryString: String?, requiredFlags: Set<Flag>?, forbiddenFlags: Set<Flag>?, performFullTextSearch: Boolean ): List<ImapMessage> { throw UnsupportedOperationException("not implemented") } override fun appendMessages(messages: List<Message>): Map<String, String>? { throw UnsupportedOperationException("not implemented") } override fun setFlags(flags: Set<Flag>, value: Boolean) { if (value) { for (messageFlagSet in messageFlags.values) { messageFlagSet.addAll(flags) } } else { for (messageFlagSet in messageFlags.values) { messageFlagSet.removeAll(flags) } } } override fun setFlags(messages: List<ImapMessage>, flags: Set<Flag>, value: Boolean) { for (message in messages) { val uid = message.uid.toLong() val messageFlagSet = messageFlags[uid] ?: error("Unknown message with UID $uid") if (value) { messageFlagSet.addAll(flags) } else { messageFlagSet.removeAll(flags) } } } override fun copyMessages(messages: List<ImapMessage>, folder: ImapFolder): Map<String, String>? { throw UnsupportedOperationException("not implemented") } override fun moveMessages(messages: List<ImapMessage>, folder: ImapFolder): Map<String, String>? { throw UnsupportedOperationException("not implemented") } override fun expunge() { mode = OpenMode.READ_WRITE wasExpunged = true } override fun expungeUids(uids: List<String>) { throw UnsupportedOperationException("not implemented") } }
apache-2.0
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/HasActualMarker.kt
2
1990
// 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.highlighter.markers import com.intellij.ide.util.DefaultPsiElementCellRenderer import com.intellij.psi.PsiElement import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.toDescriptor import org.jetbrains.kotlin.idea.util.actualsForExpected import org.jetbrains.kotlin.psi.KtDeclaration fun getPlatformActualTooltip(declaration: KtDeclaration): String? { val actualDeclarations = declaration.actualsForExpected().mapNotNull { it.toDescriptor() } val modulesString = getModulesStringForExpectActualMarkerTooltip(actualDeclarations) ?: return null return KotlinBundle.message("highlighter.prefix.text.has.actuals.in", modulesString) } fun KtDeclaration.allNavigatableActualDeclarations(): Set<KtDeclaration> = actualsForExpected() + findMarkerBoundDeclarations().flatMap { it.actualsForExpected().asSequence() } class ActualExpectedPsiElementCellRenderer : DefaultPsiElementCellRenderer() { override fun getContainerText(element: PsiElement?, name: String?) = "" } @Nls fun KtDeclaration.navigateToActualTitle() = KotlinBundle.message("highlighter.title.choose.actual.for", name.toString()) @Nls fun KtDeclaration.navigateToActualUsagesTitle() = KotlinBundle.message("highlighter.title.actuals.for", name.toString()) fun buildNavigateToActualDeclarationsPopup(element: PsiElement?): NavigationPopupDescriptor? { return element?.markerDeclaration?.let { val navigatableActualDeclarations = it.allNavigatableActualDeclarations() if (navigatableActualDeclarations.isEmpty()) return null return NavigationPopupDescriptor( navigatableActualDeclarations, it.navigateToActualTitle(), it.navigateToActualUsagesTitle(), ActualExpectedPsiElementCellRenderer() ) } }
apache-2.0
Hexworks/zircon
zircon.core/src/jvmTest/kotlin/org/hexworks/zircon/internal/resource/ColorThemesTest.kt
1
868
package org.hexworks.zircon.internal.resource import org.assertj.core.api.Assertions.assertThat import org.hexworks.zircon.api.ColorThemes import org.hexworks.zircon.api.component.ColorTheme import org.junit.Test class ColorThemesTest { @Test fun shouldContainAllThemes() { val themeCount = ColorThemes::class.members .filter { it.isFinal } .filterNot { it.name == "newBuilder" || it.name == "empty" } .map { accessor -> assertThat(accessor.call(ColorThemes)) .describedAs("Theme: ${accessor.name}") .isInstanceOf(ColorTheme::class.java) 1 }.reduce(Int::plus) assertThat(themeCount).isEqualTo(ENUM_THEMES.size) } companion object { private val ENUM_THEMES = ColorThemeResource.values().toList() } }
apache-2.0
android/connectivity-samples
UwbRanging/app/src/main/java/com/google/apps/hellouwb/ui/home/HomeViewModel.kt
1
3657
/* * * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.apps.hellouwb.ui.home import androidx.core.uwb.RangingPosition import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.google.apps.hellouwb.data.UwbRangingControlSource import com.google.apps.uwbranging.EndpointEvents import com.google.apps.uwbranging.UwbEndpoint import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.* class HomeViewModel(uwbRangingControlSource: UwbRangingControlSource) : ViewModel() { private val _uiState: MutableStateFlow<HomeUiState> = MutableStateFlow(HomeUiStateImpl(listOf(), listOf(), false)) private val endpoints = mutableListOf<UwbEndpoint>() private val endpointPositions = mutableMapOf<UwbEndpoint, RangingPosition>() private var isRanging = false private fun updateUiState(): HomeUiState { return HomeUiStateImpl( endpoints .mapNotNull { endpoint -> endpointPositions[endpoint]?.let { position -> ConnectedEndpoint(endpoint, position) } } .toList(), endpoints.filter { !endpointPositions.containsKey(it) }.toList(), isRanging ) } val uiState = _uiState.asStateFlow() init { uwbRangingControlSource .observeRangingResults() .onEach { result -> when (result) { is EndpointEvents.EndpointFound -> endpoints.add(result.endpoint) is EndpointEvents.UwbDisconnected -> endpointPositions.remove(result.endpoint) is EndpointEvents.PositionUpdated -> endpointPositions[result.endpoint] = result.position is EndpointEvents.EndpointLost -> { endpoints.remove(result.endpoint) endpointPositions.remove(result.endpoint) } else -> return@onEach } _uiState.update { updateUiState() } } .launchIn(viewModelScope) uwbRangingControlSource.isRunning .onEach { running -> isRanging = running if (!running) { endpoints.clear() endpointPositions.clear() } _uiState.update { updateUiState() } } .launchIn(CoroutineScope(Dispatchers.IO)) } private data class HomeUiStateImpl( override val connectedEndpoints: List<ConnectedEndpoint>, override val disconnectedEndpoints: List<UwbEndpoint>, override val isRanging: Boolean, ) : HomeUiState companion object { fun provideFactory( uwbRangingControlSource: UwbRangingControlSource ): ViewModelProvider.Factory = object : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return HomeViewModel(uwbRangingControlSource) as T } } } } interface HomeUiState { val connectedEndpoints: List<ConnectedEndpoint> val disconnectedEndpoints: List<UwbEndpoint> val isRanging: Boolean } data class ConnectedEndpoint(val endpoint: UwbEndpoint, val position: RangingPosition)
apache-2.0
Turbo87/intellij-rust
src/test/kotlin/org/rust/lang/core/parser/RustParsingTestCaseBase.kt
1
1669
package org.rust.lang.core.parser import com.intellij.lang.LanguageBraceMatching import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiErrorElement import com.intellij.psi.PsiFile import com.intellij.testFramework.ParsingTestCase import org.jetbrains.annotations.NonNls import org.rust.lang.RustLanguage import org.rust.lang.RustTestCase import org.rust.lang.RustTestCaseBase import org.rust.lang.core.RustParserDefinition import org.rust.ide.highlight.matcher.RustBraceMatcher abstract class RustParsingTestCaseBase(@NonNls dataPath: String) : ParsingTestCase("org/rust/lang/core/parser/fixtures/" + dataPath, "rs", true /*lowerCaseFirstLetter*/, RustParserDefinition()) , RustTestCase { final protected fun hasError(file: PsiFile): Boolean { var hasErrors = false file.accept(object : PsiElementVisitor() { override fun visitElement(element: PsiElement?) { if (element is PsiErrorElement) { hasErrors = true return } element!!.acceptChildren(this) } }) return hasErrors } override fun getTestDataPath(): String = "src/test/resources" override fun getTestName(lowercaseFirstLetter: Boolean): String? { val camelCase = super.getTestName(lowercaseFirstLetter) return RustTestCaseBase.camelToSnake(camelCase); } override fun setUp() { super.setUp() addExplicitExtension(LanguageBraceMatching.INSTANCE, RustLanguage, RustBraceMatcher()) } override fun tearDown() { super.tearDown() } }
mit
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/posts/prepublishing/PrepublishingPublishSettingsFragment.kt
1
2610
package org.wordpress.android.ui.posts.prepublishing import android.content.Context import android.os.Bundle import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.lifecycle.ViewModelProvider import org.wordpress.android.R import org.wordpress.android.WordPress import org.wordpress.android.ui.posts.PrepublishingScreenClosedListener import org.wordpress.android.ui.posts.PublishSettingsFragment import org.wordpress.android.ui.posts.PublishSettingsFragmentType.PREPUBLISHING_NUDGES import org.wordpress.android.ui.posts.PublishSettingsViewModel import org.wordpress.android.ui.utils.UiHelpers import org.wordpress.android.viewmodel.observeEvent import javax.inject.Inject class PrepublishingPublishSettingsFragment : PublishSettingsFragment() { @Inject lateinit var uiHelpers: UiHelpers private var closeListener: PrepublishingScreenClosedListener? = null override fun getContentLayout() = R.layout.prepublishing_published_settings_fragment override fun getPublishSettingsFragmentType() = PREPUBLISHING_NUDGES override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (requireActivity().applicationContext as WordPress).component().inject(this) viewModel = ViewModelProvider(requireActivity(), viewModelFactory) .get(PrepublishingPublishSettingsViewModel::class.java) } override fun onAttach(context: Context) { super.onAttach(context) closeListener = parentFragment as PrepublishingScreenClosedListener } override fun onDetach() { super.onDetach() closeListener = null } override fun setupContent(rootView: ViewGroup, viewModel: PublishSettingsViewModel) { val backButton = rootView.findViewById<View>(R.id.back_button) val toolbarTitle = rootView.findViewById<TextView>(R.id.toolbar_title) (viewModel as PrepublishingPublishSettingsViewModel).let { backButton.setOnClickListener { viewModel.onBackButtonClicked() } viewModel.navigateToHomeScreen.observeEvent(this, { closeListener?.onBackClicked() }) viewModel.updateToolbarTitle.observe(this, { uiString -> toolbarTitle.text = uiHelpers.getTextOfUiString( requireContext(), uiString ) }) } } companion object { const val TAG = "prepublishing_publish_settings_fragment_tag" fun newInstance() = PrepublishingPublishSettingsFragment() } }
gpl-2.0
danvratil/FBEventSync
app/src/main/java/cz/dvratil/fbeventsync/AllDayReminderPreferenceActivity.kt
1
7041
/* Copyright (C) 2018 Daniel Vrátil <[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 cz.dvratil.fbeventsync import android.content.Context import android.content.SharedPreferences import android.os.Build import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.text.format.DateFormat import android.view.View import android.view.ViewGroup import android.widget.* import android.view.MenuItem class AllDayReminderPreferenceActivity : AppCompatActivity() { class AllDayReminderAdapter(context: AllDayReminderPreferenceActivity, layoutId: Int, textViewId: Int) : ArrayAdapter<FBReminder>(context, layoutId, textViewId) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val view = super.getView(position, convertView, parent) view.findViewById<Button>(R.id.allday_reminder_remove_button).setOnClickListener { val activity = context as AllDayReminderPreferenceActivity var reminders = activity.getReminders().toMutableList() reminders.remove(getItem(position)) activity.setReminders(reminders) } return view } } private lateinit var m_listView: ListView private lateinit var m_viewAdapter: AllDayReminderAdapter private lateinit var m_calendarType: FBCalendar.CalendarType override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.pref_allday_reminder_layout) setSupportActionBar(findViewById<View>(R.id.pref_allday_reminder_toolbar) as Toolbar) supportActionBar?.apply { setDisplayShowHomeEnabled(true) setDisplayHomeAsUpEnabled(true) } m_calendarType = when (intent.extras?.getString("calendarType")) { getString(R.string.pref_calendar_attending_allday_reminders) -> FBCalendar.CalendarType.TYPE_ATTENDING getString(R.string.pref_calendar_tentative_allday_reminders) -> FBCalendar.CalendarType.TYPE_MAYBE getString(R.string.pref_calendar_not_responded_allday_reminders) -> FBCalendar.CalendarType.TYPE_NOT_REPLIED getString(R.string.pref_calendar_declined_allday_reminders) -> FBCalendar.CalendarType.TYPE_DECLINED getString(R.string.pref_calendar_birthday_allday_reminders) -> FBCalendar.CalendarType.TYPE_BIRTHDAY else -> throw Exception("Invalid calendar type in intent!") } m_viewAdapter = AllDayReminderAdapter(this, R.layout.allday_reminder_item_layout, R.id.allday_reminder_item_text) m_listView = findViewById<ListView>(R.id.pref_allday_reminders_listView).apply { adapter = m_viewAdapter } findViewById<FloatingActionButton>(R.id.pref_allday_reminders_fab).setOnClickListener { val view = layoutInflater.inflate(R.layout.allday_reminder_dialog, null) val dayPicker = view.findViewById<NumberPicker>(R.id.allday_reminder_day_picker).apply { minValue = 1 // FIXME: Investigate if we can have a reminder on the day of the event value = 1 maxValue = 30 } val timePicker = view.findViewById<TimePicker>(R.id.allday_reminder_time_picker).apply { // TODO: Preselects current time by default, maybe we could round up/down to nearest half-hour? setIs24HourView(DateFormat.is24HourFormat(context)) } AlertDialog.Builder(this) .setView(view) .setPositiveButton(R.string.btn_save) { dialog, _ -> val currentReminders = getReminders().toMutableList() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { currentReminders.add(FBReminder(dayPicker.value, timePicker.hour, timePicker.minute, true)) } else { currentReminders.add(FBReminder(dayPicker.value, timePicker.currentHour, timePicker.currentMinute, true)) } setReminders(currentReminders) dialog.dismiss() } .setNegativeButton(R.string.btn_cancel) { dialog, _ -> dialog.cancel() } .create() .show() } m_viewAdapter.addAll(getReminders()) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item?.itemId == android.R.id.home) { // Workaround an activity stack related crash when navigating back using the // toolbar home button finish() return true } else { return super.onOptionsItemSelected(item) } } private fun getReminders(): List<FBReminder> { var prefs = Preferences(this) return when (m_calendarType) { FBCalendar.CalendarType.TYPE_ATTENDING -> prefs.attendingCalendarAllDayReminders() FBCalendar.CalendarType.TYPE_MAYBE -> prefs.maybeAttendingCalendarAllDayReminders() FBCalendar.CalendarType.TYPE_DECLINED -> prefs.declinedCalendarAllDayReminders() FBCalendar.CalendarType.TYPE_NOT_REPLIED -> prefs.notRespondedCalendarAllDayReminders() FBCalendar.CalendarType.TYPE_BIRTHDAY -> prefs.birthdayCalendarAllDayReminders() } } private fun setReminders(reminders: List<FBReminder>) { var prefs = Preferences(this) when (m_calendarType) { FBCalendar.CalendarType.TYPE_ATTENDING -> prefs.setAttendingCalendarAllDayReminders(reminders) FBCalendar.CalendarType.TYPE_MAYBE -> prefs.setMaybeAttendingCalendarAllDayReminders(reminders) FBCalendar.CalendarType.TYPE_DECLINED -> prefs.setDeclinedCalendarAllDayReminders(reminders) FBCalendar.CalendarType.TYPE_NOT_REPLIED -> prefs.setNotRespondedCalendarAllDayReminders(reminders) FBCalendar.CalendarType.TYPE_BIRTHDAY -> prefs.setBirthdayCalendarAllDayReminders(reminders) } m_viewAdapter.clear() m_viewAdapter.addAll(reminders) } }
gpl-3.0
IgorGanapolsky/cheesesquare
app/src/main/java/com/support/android/designlibdemo/MainActivity.kt
1
4962
/* * Copyright (C) 2015 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.support.android.designlibdemo import android.os.Build import android.os.Bundle import android.support.design.widget.NavigationView import android.support.design.widget.Snackbar import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.support.v4.view.GravityCompat import android.support.v4.view.ViewPager import android.support.v4.widget.DrawerLayout import android.support.v7.app.AppCompatActivity import android.support.v7.app.AppCompatDelegate import android.view.Menu import android.view.MenuItem import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.include_list_viewpager.* import java.util.* class MainActivity : AppCompatActivity() { private var mDrawerLayout: DrawerLayout? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) val ab = supportActionBar ab!!.setHomeAsUpIndicator(R.drawable.ic_menu) ab.setDisplayHomeAsUpEnabled(true) setupDrawerContent(nav_view) setupViewPager(viewpager) fab.setOnClickListener { view -> Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } tabs.setupWithViewPager(viewpager) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.sample_actions, menu) return true } override fun onPrepareOptionsMenu(menu: Menu): Boolean { when (AppCompatDelegate.getDefaultNightMode()) { AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM -> menu.findItem(R.id.menu_night_mode_system).isChecked = true AppCompatDelegate.MODE_NIGHT_AUTO -> menu.findItem(R.id.menu_night_mode_auto).isChecked = true AppCompatDelegate.MODE_NIGHT_YES -> menu.findItem(R.id.menu_night_mode_night).isChecked = true AppCompatDelegate.MODE_NIGHT_NO -> menu.findItem(R.id.menu_night_mode_day).isChecked = true } return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { mDrawerLayout!!.openDrawer(GravityCompat.START) return true } R.id.menu_night_mode_system -> setNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) R.id.menu_night_mode_day -> setNightMode(AppCompatDelegate.MODE_NIGHT_NO) R.id.menu_night_mode_night -> setNightMode(AppCompatDelegate.MODE_NIGHT_YES) R.id.menu_night_mode_auto -> setNightMode(AppCompatDelegate.MODE_NIGHT_AUTO) } return super.onOptionsItemSelected(item) } private fun setNightMode(@AppCompatDelegate.NightMode nightMode: Int) { AppCompatDelegate.setDefaultNightMode(nightMode) if (Build.VERSION.SDK_INT >= 11) { recreate() } } private fun setupViewPager(viewPager: ViewPager) { val adapter = Adapter(supportFragmentManager) adapter.addFragment(CheeseListFragment(), "Category 1") adapter.addFragment(CheeseListFragment(), "Category 2") adapter.addFragment(CheeseListFragment(), "Category 3") viewPager.adapter = adapter } private fun setupDrawerContent(navigationView: NavigationView) { navigationView.setNavigationItemSelectedListener { menuItem -> menuItem.isChecked = true mDrawerLayout!!.closeDrawers() true } } internal class Adapter(fm: FragmentManager) : FragmentPagerAdapter(fm) { private val mFragments = ArrayList<Fragment>() private val mFragmentTitles = ArrayList<String>() fun addFragment(fragment: Fragment, title: String) { mFragments.add(fragment) mFragmentTitles.add(title) } override fun getItem(position: Int): Fragment { return mFragments[position] } override fun getCount(): Int { return mFragments.size } override fun getPageTitle(position: Int): CharSequence { return mFragmentTitles[position] } } }
apache-2.0
kpavlov/jreactive-8583
src/main/kotlin/com/github/kpavlov/jreactive8583/iso/MessageOrigin.kt
1
541
@file:JvmName("MessageOrigin") package com.github.kpavlov.jreactive8583.iso @Suppress("unused") public enum class MessageOrigin(internal val value: Int) { /** * xxx0 Acquirer */ ACQUIRER(0x0000), /** * xxx1 Acquirer repeat */ ACQUIRER_REPEAT(0x0001), /** * xxx2 Issuer */ ISSUER(0x0002), /** * xxx3 Issuer repeat */ ISSUER_REPEAT(0x0003), /** * xxx4 Other */ OTHER(0x0004), /** * xxx5 Other repeat */ OTHER_REPEAT(0x0005); }
apache-2.0
abeemukthees/Arena
spectacle/src/main/java/com/abhi/spectacle/data/poko/ImgurEntities.kt
1
5579
package com.abhi.spectacle.data.poko import com.squareup.moshi.Json data class ImgurEntities( val data: List<ImgurData>, val success: Boolean, val status: Int ) { data class ImgurData( val id: String, val title: String, val description: Any?, val datetime: Int, val cover: String, @Json(name = "cover_width") val coverWidth: Int, @Json(name = "cover_height") val coverHeight: Int, @Json(name = "account_url") val accountUrl: String, @Json(name = "account_id") val accountId: Int, val privacy: String, val layout: String, val views: Int, val link: String, val ups: Int, val downs: Int, val points: Int, val score: Int, @Json(name = "is_album") val isAlbum: Boolean, val vote: Any?, val favorite: Boolean, val nsfw: Boolean, val section: String, @Json(name = "comment_count") val commentCount: Int, @Json(name = "favorite_count") val favoriteCount: Int, val topic: String, @Json(name = "topic_id") val topicId: Int, @Json(name = "images_count") val imagesCount: Int, @Json(name = "in_gallery") val inGallery: Boolean, @Json(name = "is_ad") val isAd: Boolean, val tags: List<Tag>, @Json(name = "ad_type") val adType: Int, @Json(name = "ad_url") val adUrl: String, @Json(name = "in_most_viral") val inMostViral: Boolean, @Json(name = "include_album_ads") val includeAlbumAds: Boolean, val images: List<Image>?, val type: String, val animated: Boolean, val width: Int, val height: Int, val size: Int, val bandwidth: Long, @Json(name = "has_sound") val hasSound: Boolean, val mp4: String, val gifv: String, @Json(name = "mp4_size") val mp4Size: Int, val looping: Boolean, val processing: Processing ) { data class Tag( val name: String, @Json(name = "display_name") val displayName: String, val followers: Int, @Json(name = "total_items") val totalItems: Int, val following: Boolean, @Json(name = "background_hash") val backgroundHash: String, @Json(name = "thumbnail_hash") val thumbnailHash: Any?, val accent: String, @Json(name = "background_is_animated") val backgroundIsAnimated: Boolean, @Json(name = "thumbnail_is_animated") val thumbnailIsAnimated: Boolean, @Json(name = "is_promoted") val isPromoted: Boolean, val description: String, @Json(name = "logo_hash") val logoHash: Any?, @Json(name = "logo_destination_url") val logoDestinationUrl: Any?, @Json(name = "description_annotations") val descriptionAnnotations: DescriptionAnnotations ) { data class DescriptionAnnotations(val id: Any ) } data class Image( val id: String, val title: Any?, val description: String, val datetime: Int, val type: String, val animated: Boolean, val width: Int, val height: Int, val size: Int, val views: Int, val bandwidth: Long, val vote: Any?, val favorite: Boolean, val nsfw: Any?, val section: Any?, @Json(name = "account_url") val accountUrl: Any?, @Json(name = "account_id") val accountId: Any?, @Json(name = "is_ad") val isAd: Boolean, @Json(name = "in_most_viral") val inMostViral: Boolean, @Json(name = "has_sound") val hasSound: Boolean, val tags: List<Any>, @Json(name = "ad_type") val adType: Int, @Json(name = "ad_url") val adUrl: String, @Json(name = "in_gallery") val inGallery: Boolean, val link: String, @Json(name = "mp4_size") val mp4Size: Int, val mp4: String, val gifv: String, val processing: Processing, @Json(name = "comment_count") val commentCount: Any?, @Json(name = "favorite_count") val favoriteCount: Any?, val ups: Any?, val downs: Any?, val points: Any?, val score: Any? ) { data class Processing( val status: String ) } data class Processing( val status: String ) } }
apache-2.0
DiUS/pact-jvm
consumer/groovy/src/main/kotlin/au/com/dius/pact/consumer/groovy/Matchers.kt
1
20286
package au.com.dius.pact.consumer.groovy import au.com.dius.pact.core.matchers.UrlMatcherSupport import au.com.dius.pact.core.model.generators.DateGenerator import au.com.dius.pact.core.model.generators.DateTimeGenerator import au.com.dius.pact.core.model.generators.Generator import au.com.dius.pact.core.model.generators.RandomBooleanGenerator import au.com.dius.pact.core.model.generators.RandomDecimalGenerator import au.com.dius.pact.core.model.generators.RandomHexadecimalGenerator import au.com.dius.pact.core.model.generators.RandomIntGenerator import au.com.dius.pact.core.model.generators.RandomStringGenerator import au.com.dius.pact.core.model.generators.RegexGenerator import au.com.dius.pact.core.model.generators.TimeGenerator import au.com.dius.pact.core.model.generators.UuidGenerator import au.com.dius.pact.core.model.matchingrules.MatchingRule import au.com.dius.pact.core.model.matchingrules.MaxTypeMatcher import au.com.dius.pact.core.model.matchingrules.MinMaxTypeMatcher import au.com.dius.pact.core.model.matchingrules.MinTypeMatcher import au.com.dius.pact.core.model.matchingrules.NumberTypeMatcher import au.com.dius.pact.core.model.matchingrules.RegexMatcher import au.com.dius.pact.core.support.isNotEmpty import com.mifmif.common.regex.Generex import mu.KLogging import org.apache.commons.lang3.time.DateFormatUtils import org.apache.commons.lang3.time.DateUtils import java.text.ParseException import java.time.ZoneId import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import java.time.format.DateTimeParseException import java.util.Date import java.util.regex.Pattern const val HEXADECIMAL = "[0-9a-fA-F]+" const val IP_ADDRESS = "(\\d{1,3}\\.)+\\d{1,3}" const val UUID_REGEX = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" const val TEN = 10 const val TYPE = "type" const val DECIMAL = "decimal" const val DATE_2000 = 949323600000L const val INTEGER = "integer" /** * Exception for handling invalid matchers */ class InvalidMatcherException(message: String) : RuntimeException(message) /** * Marker class for generated values */ data class GeneratedValue(val expression: String, val exampleValue: Any?) /** * Base class for matchers */ open class Matcher @JvmOverloads constructor( open val value: Any? = null, open val matcher: MatchingRule? = null, open val generator: Generator? = null ) /** * Regular Expression Matcher */ class RegexpMatcher @JvmOverloads constructor( val regex: String, value: String? = null ) : Matcher(value, RegexMatcher(regex, value), if (value == null) RegexGenerator(regex) else null) { override val value: Any? get() = super.value ?: Generex(regex).random() } class HexadecimalMatcher @JvmOverloads constructor( value: String? = null ) : Matcher( value ?: "1234a", RegexMatcher(HEXADECIMAL, value), if (value == null) RandomHexadecimalGenerator(10) else null ) /** * Matcher for validating same types */ class TypeMatcher @JvmOverloads constructor( value: Any? = null, val type: String = "type", generator: Generator? = null ) : Matcher( value, when (type) { "integer" -> NumberTypeMatcher(NumberTypeMatcher.NumberType.INTEGER) "decimal" -> NumberTypeMatcher(NumberTypeMatcher.NumberType.DECIMAL) "number" -> NumberTypeMatcher(NumberTypeMatcher.NumberType.NUMBER) else -> au.com.dius.pact.core.model.matchingrules.TypeMatcher }, generator ) class DateTimeMatcher @JvmOverloads constructor( val pattern: String = DateFormatUtils.ISO_DATETIME_FORMAT.pattern, value: String? = null, expression: String? = null ) : Matcher( value, au.com.dius.pact.core.model.matchingrules.TimestampMatcher(pattern), if (value == null) DateTimeGenerator(pattern, expression) else null ) { override val value: Any? get() = super.value ?: DateTimeFormatter.ofPattern(pattern).withZone(ZoneId.systemDefault()).format( Date(DATE_2000).toInstant()) } class TimeMatcher @JvmOverloads constructor( val pattern: String = DateFormatUtils.ISO_TIME_FORMAT.pattern, value: String? = null, expression: String? = null ) : Matcher( value, au.com.dius.pact.core.model.matchingrules.TimeMatcher(pattern), if (value == null) TimeGenerator(pattern, expression) else null ) { override val value: Any? get() = super.value ?: DateFormatUtils.format(Date(DATE_2000), pattern) } class DateMatcher @JvmOverloads constructor( val pattern: String = DateFormatUtils.ISO_DATE_FORMAT.pattern, value: String? = null, expression: String? = null ) : Matcher( value, au.com.dius.pact.core.model.matchingrules.DateMatcher(pattern), if (value == null) DateGenerator(pattern, expression) else null ) { override val value: Any? get() = super.value ?: DateFormatUtils.format(Date(DATE_2000), pattern) } /** * Matcher for universally unique IDs */ class UuidMatcher @JvmOverloads constructor( value: Any? = null ) : Matcher( value ?: "e2490de5-5bd3-43d5-b7c4-526e33f71304", RegexMatcher(UUID_REGEX), if (value == null) UuidGenerator else null ) /** * Base class for like matchers */ open class LikeMatcher @JvmOverloads constructor( value: Any? = null, val numberExamples: Int = 1, matcher: MatchingRule? = null ) : Matcher(value, matcher ?: au.com.dius.pact.core.model.matchingrules.TypeMatcher) /** * Each like matcher for arrays */ class EachLikeMatcher @JvmOverloads constructor( value: Any? = null, numberExamples: Int = 1 ) : LikeMatcher(value, numberExamples) /** * Like matcher with a maximum size */ class MaxLikeMatcher @JvmOverloads constructor( val max: Int, value: Any? = null, numberExamples: Int = 1 ) : LikeMatcher(value, numberExamples, MaxTypeMatcher(max)) /** * Like matcher with a minimum size */ class MinLikeMatcher @JvmOverloads constructor( val min: Int = 1, value: Any? = null, numberExamples: Int = 1 ) : LikeMatcher(value, numberExamples, MinTypeMatcher(min)) /** * Like Matcher with a minimum and maximum size */ class MinMaxLikeMatcher @JvmOverloads constructor( val min: Int, val max: Int, value: Any? = null, numberExamples: Int = 1 ) : LikeMatcher(value, numberExamples, MinMaxTypeMatcher(min, max)) /** * Matcher to match using equality */ class EqualsMatcher(value: Any) : Matcher(value, au.com.dius.pact.core.model.matchingrules.EqualsMatcher) /** * Matcher for string inclusion */ class IncludeMatcher(value: String) : Matcher(value, au.com.dius.pact.core.model.matchingrules.IncludeMatcher(value)) /** * Matcher that matches if any provided matcher matches */ class OrMatcher(example: Any, val matchers: List<Matcher>) : Matcher(example) /** * Matches if all provided matches match */ class AndMatcher(example: Any, val matchers: List<Matcher>) : Matcher(example) /** * Matcher to match null values */ class NullMatcher : Matcher(null, au.com.dius.pact.core.model.matchingrules.NullMatcher) /** * Match a URL by specifying the base and a series of paths. */ class UrlMatcher @JvmOverloads constructor( val basePath: String, val pathFragments: List<Any>, private val urlMatcherSupport: UrlMatcherSupport = UrlMatcherSupport(basePath, pathFragments.map { if (it is RegexpMatcher) it.matcher!! else it }) ) : Matcher(urlMatcherSupport.getExampleValue(), RegexMatcher(urlMatcherSupport.getRegexExpression())) /** * Base class for DSL matcher methods */ open class Matchers { companion object : KLogging() { /** * Match a regular expression * @param re Regular expression pattern * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun regexp(re: Pattern, value: String? = null) = regexp(re.toString(), value) /** * Match a regular expression * @param re Regular expression pattern * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun regexp(regexp: String, value: String? = null): Matcher { if (value != null && !value.matches(Regex(regexp))) { throw InvalidMatcherException("Example \"$value\" does not match regular expression \"$regexp\"") } return RegexpMatcher(regexp, value) } /** * Match a hexadecimal value * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun hexValue(value: String? = null): Matcher { if (value != null && !value.matches(Regex(HEXADECIMAL))) { throw InvalidMatcherException("Example \"$value\" is not a hexadecimal value") } return HexadecimalMatcher(value) } /** * Match a numeric identifier (integer) * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun identifier(value: Any? = null): Matcher { return TypeMatcher(value ?: 12345678, INTEGER, if (value == null) RandomIntGenerator(0, Integer.MAX_VALUE) else null) } /** * Match an IP Address * @param value Example value, if not provided 127.0.0.1 will be generated */ @JvmStatic @JvmOverloads fun ipAddress(value: String? = null): Matcher { if (value != null && !value.matches(Regex(IP_ADDRESS))) { throw InvalidMatcherException("Example \"$value\" is not an ip address") } return RegexpMatcher(IP_ADDRESS, value ?: "127.0.0.1") } /** * Match a numeric value * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun numeric(value: Number? = null): Matcher { return TypeMatcher(value ?: 100, "number", if (value == null) RandomDecimalGenerator(6) else null) } /** * Match a decimal value * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun decimal(value: Number? = null): Matcher { return TypeMatcher(value ?: 100.0, DECIMAL, if (value == null) RandomDecimalGenerator(6) else null) } /** * Match a integer value * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun integer(value: Long? = null): Matcher { return TypeMatcher(value ?: 100, INTEGER, if (value == null) RandomIntGenerator(0, Integer.MAX_VALUE) else null) } /** * Match a timestamp * @param pattern Pattern to use to match. If not provided, an ISO pattern will be used. * @param value Example value, if not provided the current date and time will be used */ @Deprecated("use datetime instead") @JvmStatic @JvmOverloads fun timestamp(pattern: String = DateFormatUtils.ISO_DATETIME_FORMAT.pattern, value: String? = null): Matcher { return datetime(pattern, value) } /** * Match a timestamp generated from an expression * @param pattern Pattern to use to match. If not provided, an ISO pattern will be used. * @param expression Expression to use to generate the timestamp */ @Deprecated("use datetime instead") @JvmStatic @JvmOverloads fun timestampExpression(expression: String, pattern: String = DateFormatUtils.ISO_DATETIME_FORMAT.pattern): Matcher { return datetimeExpression(expression, pattern) } /** * Match a datetime * @param pattern Pattern to use to match. If not provided, an ISO pattern will be used. * @param value Example value, if not provided the current date and time will be used */ @JvmStatic @JvmOverloads fun datetime(pattern: String = DateFormatUtils.ISO_DATETIME_FORMAT.pattern, value: String? = null): Matcher { validateDateTimeValue(value, pattern) return DateTimeMatcher(pattern, value) } /** * Match a datetime generated from an expression * @param pattern Pattern to use to match. If not provided, an ISO pattern will be used. * @param expression Expression to use to generate the datetime */ fun datetimeExpression(expression: String, pattern: String = DateFormatUtils.ISO_DATETIME_FORMAT.pattern): Matcher { return DateTimeMatcher(pattern, null, expression) } private fun validateTimeValue(value: String?, pattern: String?) { if (value.isNotEmpty() && pattern.isNotEmpty()) { try { DateUtils.parseDateStrictly(value, pattern) } catch (e: ParseException) { throw InvalidMatcherException("Example \"$value\" does not match pattern \"$pattern\"") } } } private fun validateDateTimeValue(value: String?, pattern: String?) { if (value.isNotEmpty() && pattern.isNotEmpty()) { try { ZonedDateTime.parse(value, DateTimeFormatter.ofPattern(pattern).withZone(ZoneId.systemDefault())) } catch (e: DateTimeParseException) { logger.error(e) { "Example \"$value\" does not match pattern \"$pattern\"" } throw InvalidMatcherException("Example \"$value\" does not match pattern \"$pattern\"") } } } /** * Match a time * @param pattern Pattern to use to match. If not provided, an ISO pattern will be used. * @param value Example value, if not provided the current time will be used */ @JvmStatic @JvmOverloads fun time(pattern: String = DateFormatUtils.ISO_TIME_FORMAT.pattern, value: String? = null): Matcher { validateTimeValue(value, pattern) return TimeMatcher(pattern, value) } /** * Match a time generated from an expression * @param pattern Pattern to use to match. If not provided, an ISO pattern will be used. * @param expression Expression to use to generate the time */ @JvmStatic @JvmOverloads fun timeExpression(expression: String, pattern: String = DateFormatUtils.ISO_TIME_FORMAT.pattern): Matcher { return TimeMatcher(pattern, null, expression) } /** * Match a date * @param pattern Pattern to use to match. If not provided, an ISO pattern will be used. * @param value Example value, if not provided the current date will be used */ @JvmStatic @JvmOverloads fun date(pattern: String = DateFormatUtils.ISO_DATE_FORMAT.pattern, value: String? = null): Matcher { validateTimeValue(value, pattern) return DateMatcher(pattern, value) } /** * Match a date generated from an expression * @param pattern Pattern to use to match. If not provided, an ISO pattern will be used. * @param expression Expression to use to generate the date */ @JvmStatic @JvmOverloads fun dateExpression(expression: String, pattern: String = DateFormatUtils.ISO_DATE_FORMAT.pattern): Matcher { return DateMatcher(pattern, null, expression) } /** * Match a universally unique identifier (UUID) * @param value optional value to use for examples */ @JvmStatic @JvmOverloads fun uuid(value: String? = null): Matcher { if (value != null && !value.matches(Regex(UUID_REGEX))) { throw InvalidMatcherException("Example \"$value\" is not a UUID") } return UuidMatcher(value) } /** * Match any string value * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun string(value: String? = null): Matcher { return if (value != null) { TypeMatcher(value) } else { TypeMatcher("string", generator = RandomStringGenerator(10)) } } /** * Match any boolean * @param value Example value, if not provided a random one will be generated */ @JvmStatic @JvmOverloads fun bool(value: Boolean? = null): Matcher { return if (value != null) { TypeMatcher(value) } else { TypeMatcher(true, generator = RandomBooleanGenerator) } } /** * Array where each element like the following object * @param numberExamples Optional number of examples to generate. Defaults to 1. */ @JvmStatic @JvmOverloads fun eachLike(numberExamples: Int = 1, arg: Any): Matcher { return EachLikeMatcher(arg, numberExamples) } /** * Array with maximum size and each element like the following object * @param max The maximum size of the array * @param numberExamples Optional number of examples to generate. Defaults to 1. */ @JvmStatic @JvmOverloads fun maxLike(max: Int, numberExamples: Int = 1, arg: Any): Matcher { if (numberExamples > max) { throw InvalidMatcherException("The number of examples you have specified ($numberExamples) is " + "greater than the maximum ($max)") } return MaxLikeMatcher(max, arg, numberExamples) } /** * Array with minimum size and each element like the following object * @param min The minimum size of the array * @param numberExamples Optional number of examples to generate. Defaults to 1. */ @JvmStatic @JvmOverloads fun minLike(min: Int, numberExamples: Int = 1, arg: Any): Matcher { if (numberExamples > 1 && numberExamples < min) { throw InvalidMatcherException("The number of examples you have specified ($numberExamples) is " + "less than the minimum ($min)") } return MinLikeMatcher(min, arg, numberExamples) } /** * Array with minimum and maximum size and each element like the following object * @param min The minimum size of the array * @param max The maximum size of the array * @param numberExamples Optional number of examples to generate. Defaults to 1. */ @JvmStatic @JvmOverloads fun minMaxLike(min: Int, max: Int, numberExamples: Int = 1, arg: Any): Matcher { if (min > max) { throw InvalidMatcherException("The minimum you have specified ($min) is " + "greater than the maximum ($max)") } else if (numberExamples > 1 && numberExamples < min) { throw InvalidMatcherException("The number of examples you have specified ($numberExamples) is " + "less than the minimum ($min)") } else if (numberExamples > 1 && numberExamples > max) { throw InvalidMatcherException("The number of examples you have specified ($numberExamples) is " + "greater than the maximum ($max)") } return MinMaxLikeMatcher(min, max, arg, numberExamples) } /** * Match Equality * @param value Value to match to */ @JvmStatic fun equalTo(value: Any): Matcher { return EqualsMatcher(value) } /** * Matches if the string is included in the value * @param value String value that must be present */ @JvmStatic fun includesStr(value: String): Matcher { return IncludeMatcher(value) } /** * Matches if any of the provided matches match * @param example Example value to use */ @JvmStatic fun or(example: Any, vararg values: Any): Matcher { return OrMatcher(example, values.map { if (it is Matcher) { it } else { EqualsMatcher(it) } }) } /** * Matches if all of the provided matches match * @param example Example value to use */ @JvmStatic fun and(example: Any, vararg values: Any): Matcher { return AndMatcher(example, values.map { if (it is Matcher) { it } else { EqualsMatcher(it) } }) } /** * Matches a null value */ @JvmStatic fun nullValue(): Matcher { return NullMatcher() } /** * Matches a URL composed of a base path and a list of path fragments */ @JvmStatic fun url(basePath: String, vararg pathFragments: Any): Matcher { return UrlMatcher(basePath, pathFragments.toList()) } /** * Array of arrays where each element like the following object * @param numberExamples Optional number of examples to generate. Defaults to 1. */ @JvmStatic @JvmOverloads fun eachArrayLike(numberExamples: Int = 1, arg: Any): Matcher { return EachLikeMatcher(EachLikeMatcher(arg, numberExamples), numberExamples) } } }
apache-2.0
greenspand/kotlin-extensions
kotlin-ext/src/main/java/com/sorinirimies/kotlinx/animUtils.kt
1
3045
@file:JvmName("AnimUtils") package com.sorinirimies.kotlinx import android.support.v4.view.ViewCompat import android.view.View import android.view.animation.AccelerateInterpolator import android.view.animation.Interpolator /** * Extension function for simple view fade in and out animations. * @param duration of the animation * @param scale of the the view * @param alpha visibility of the the view * @param interpolator the Bezier curve animation of the view * @param visibility of the animated view */ fun View.animateScaleAlpha(delay: Long = 0, duration: Long = 300, scale: Float = 0.7f, alpha: Float = 0f, interpolator: Interpolator = AccelerateInterpolator(), visibility: Int = View.GONE) { ViewCompat.animate(this) .setStartDelay(delay) .setDuration(duration) .scaleX(scale) .scaleY(scale) .alpha(alpha) .setInterpolator(interpolator) .withEndAction { this.visibility = visibility } } /** * Animates a view upwards. * @param translateY the vertical vector * @param duration the default duration * @param interpolator the default interpolator */ fun View.animateUp(translateY: Float = 0f, duration: Long = 300, interpolator: Interpolator = AccelerateInterpolator()) { visible() ViewCompat.animate(this) .setDuration(duration) .translationY(translateY) .interpolator = interpolator } /** * Animates a view to a visible state, with an alpha transition. * @param duration the default duration * @param alpha the given opacity level * @param interpolator the default interpolator */ fun View.animateVisible(duration: Long = 300, alpha: Float = 1f) { visible() ViewCompat.animate(this) .setDuration(duration) .alpha(alpha) } /** * Animates a view to gone, with an alpha transition. * @param duration the default duration * @param alpha the given opacity level * @param interpolator the default interpolator */ fun View.animateGone(duration: Long = 300, alpha: Float = 0f, visibility: Int = View.GONE) { ViewCompat.animate(this) .setDuration(duration) .alpha(alpha) .withEndAction { this.visibility = visibility } } /** * Animates a view downwards. * @param translateY the vertical vector * @param duration the default duration * @param interpolator the default interpolator */ fun View.animateDown(translateY: Float = 400f, duration: Long = 300, visibility: Int = View.GONE) { ViewCompat.animate(this) .setDuration(duration) .translationY(translateY) .withEndAction { this.visibility = visibility } }
mit
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/domains/DomainSuggestionsAdapter.kt
1
1011
package org.wordpress.android.ui.domains import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter class DomainSuggestionsAdapter( private val itemSelectionListener: (DomainSuggestionItem?) -> Unit ) : ListAdapter<DomainSuggestionItem, DomainSuggestionsViewHolder>(DomainSuggestionItemDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = DomainSuggestionsViewHolder(parent, itemSelectionListener) override fun onBindViewHolder(holder: DomainSuggestionsViewHolder, position: Int) { holder.bind(getItem(position)) } private class DomainSuggestionItemDiffCallback : DiffUtil.ItemCallback<DomainSuggestionItem>() { override fun areItemsTheSame(old: DomainSuggestionItem, new: DomainSuggestionItem) = old.domainName == new.domainName override fun areContentsTheSame(old: DomainSuggestionItem, new: DomainSuggestionItem) = old == new } }
gpl-2.0
alexander-schmidt/ihh
ihh-server/src/main/kotlin/com/asurasdevelopment/ihh/server/utils/NumberUtils.kt
1
271
package com.asurasdevelopment.ihh.server.utils fun Number.secToMilli() : Long = this.toLong() * 1000 fun Number.minToMilli() : Long = this.secToMilli() * 60 fun Number.hourToMilli() : Long = this.minToMilli() * 60 fun Number.dayToMilli() : Long = this.hourToMilli() * 24
apache-2.0
android/nowinandroid
core/model/src/main/java/com/google/samples/apps/nowinandroid/core/model/data/NewsResource.kt
1
4169
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.core.model.data import com.google.samples.apps.nowinandroid.core.model.data.NewsResourceType.Codelab import com.google.samples.apps.nowinandroid.core.model.data.NewsResourceType.Video import kotlinx.datetime.Instant import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.toInstant /* ktlint-disable max-line-length */ /** * External data layer representation of a fully populated NiA news resource */ data class NewsResource( val id: String, val title: String, val content: String, val url: String, val headerImageUrl: String?, val publishDate: Instant, val type: NewsResourceType, val authors: List<Author>, val topics: List<Topic> ) val previewNewsResources = listOf( NewsResource( id = "1", title = "Android Basics with Compose", content = "We released the first two units of Android Basics with Compose, our first free course that teaches Android Development with Jetpack Compose to anyone; you do not need any prior programming experience other than basic computer literacy to get started. You’ll learn the fundamentals of programming in Kotlin while building Android apps using Jetpack Compose, Android’s modern toolkit that simplifies and accelerates native UI development. These two units are just the beginning; more will be coming soon. Check out Android Basics with Compose to get started on your Android development journey", url = "https://android-developers.googleblog.com/2022/05/new-android-basics-with-compose-course.html", headerImageUrl = "https://developer.android.com/images/hero-assets/android-basics-compose.svg", authors = listOf(previewAuthors[0]), publishDate = LocalDateTime( year = 2022, monthNumber = 5, dayOfMonth = 4, hour = 23, minute = 0, second = 0, nanosecond = 0 ).toInstant(TimeZone.UTC), type = Codelab, topics = listOf(previewTopics[1]) ), NewsResource( id = "2", title = "Thanks for helping us reach 1M YouTube Subscribers", content = "Thank you everyone for following the Now in Android series and everything the " + "Android Developers YouTube channel has to offer. During the Android Developer " + "Summit, our YouTube channel reached 1 million subscribers! Here’s a small video to " + "thank you all.", url = "https://youtu.be/-fJ6poHQrjM", headerImageUrl = "https://i.ytimg.com/vi/-fJ6poHQrjM/maxresdefault.jpg", publishDate = Instant.parse("2021-11-09T00:00:00.000Z"), type = Video, authors = listOf(previewAuthors[1]), topics = listOf(previewTopics[0], previewTopics[1]) ), NewsResource( id = "3", title = "Transformations and customisations in the Paging Library", content = "A demonstration of different operations that can be performed " + "with Paging. Transformations like inserting separators, when to " + "create a new pager, and customisation options for consuming " + "PagingData.", url = "https://youtu.be/ZARz0pjm5YM", headerImageUrl = "https://i.ytimg.com/vi/ZARz0pjm5YM/maxresdefault.jpg", publishDate = Instant.parse("2021-11-01T00:00:00.000Z"), type = Video, authors = listOf(previewAuthors[0], previewAuthors[1]), topics = listOf(previewTopics[2]) ) )
apache-2.0
hermantai/samples
android/andfun-kotlin-mars-real-estate-Step.08-Solution-Adding-a-Filter/app/src/main/java/com/example/android/marsrealestate/network/MarsProperty.kt
1
1523
/* * Copyright 2018, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.example.android.marsrealestate.network import android.os.Parcelable import androidx.lifecycle.LiveData import com.example.android.marsrealestate.overview.MarsApiStatus import com.squareup.moshi.Json import kotlinx.android.parcel.Parcelize /** * Gets Mars real estate property information from the Mars API Retrofit service and updates the * [MarsProperty] and [MarsApiStatus] [LiveData]. The Retrofit service returns a coroutine * Deferred, which we await to get the result of the transaction. * @param filter the [MarsApiFilter] that is sent as part of the web server request */ @Parcelize data class MarsProperty( val id: String, // used to map img_src from the JSON to imgSrcUrl in our class @Json(name = "img_src") val imgSrcUrl: String, val type: String, val price: Double) : Parcelable { val isRental get() = type == "rent" }
apache-2.0
android/nowinandroid
benchmarks/src/main/java/com/google/samples/apps/nowinandroid/Utils.kt
1
1115
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid import com.google.samples.apps.nowinandroid.benchmarks.BuildConfig /** * Convenience parameter to use proper package name with regards to build type and build flavor. */ val PACKAGE_NAME = StringBuilder("com.google.samples.apps.nowinandroid").apply { if (BuildConfig.FLAVOR != "prod") { append(".${BuildConfig.FLAVOR}") } if (BuildConfig.BUILD_TYPE != "release") { append(".${BuildConfig.BUILD_TYPE}") } }.toString()
apache-2.0
hermantai/samples
kotlin/kotlin-and-android-development-featuring-jetpack/abl-api-client/src/main/kotlin/dev/mfazio/abl/api/DateFormats.kt
1
318
package dev.mfazio.abl.api import java.time.format.DateTimeFormatter val dateFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd") val dateTimeHourFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHH") val dateTimeFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
apache-2.0
team401/SnakeSkin
SnakeSkin-Core/src/main/kotlin/org/snakeskin/hid/state/IControlSurfaceState.kt
1
268
package org.snakeskin.hid.state import org.snakeskin.executor.ExceptionHandlingRunnable /** * @author Cameron Earle * @version 12/12/2018 * */ interface IControlSurfaceState { fun update(timestamp: Double): Boolean val action: ExceptionHandlingRunnable }
gpl-3.0
JetBrains/kotlin-spec
grammar/testData/grammar/annotations/nameAsUseSiteTargetPrefix/receiver.kt
1
264
class Foo(@receiver private val field: Int) {} class Foo { @ann @receiver var field: Int = 10 } class Foo(@receiver @ann protected val field: Int) {} class Foo { @ann @receiver var field: Int = 10 } class Foo { @receiver @ann var field: Int = 10 }
apache-2.0
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/quest/usecase/FindQuestsToRemindUseCase.kt
1
526
package io.ipoli.android.quest.usecase import io.ipoli.android.common.UseCase import io.ipoli.android.quest.Quest import io.ipoli.android.quest.data.persistence.QuestRepository import org.threeten.bp.LocalDateTime /** * Created by Polina Zhelyazkova <[email protected]> * on 10/27/17. */ class FindQuestsToRemindUseCase(private val questRepository: QuestRepository) : UseCase<LocalDateTime, List<Quest>> { override fun execute(parameters: LocalDateTime) = questRepository.findQuestsToRemind(parameters) }
gpl-3.0
Turbo87/intellij-emberjs
src/main/kotlin/com/emberjs/patterns/EmberPatterns.kt
1
1604
package com.emberjs.patterns import com.emberjs.resolver.EmberName import com.emberjs.utils.originalVirtualFile import com.intellij.lang.javascript.patterns.JSElementPattern import com.intellij.lang.javascript.patterns.JSPatterns.jsArgument import com.intellij.lang.javascript.psi.JSLiteralExpression import com.intellij.patterns.InitialPatternCondition import com.intellij.patterns.ObjectPattern import com.intellij.psi.PsiElement import com.intellij.util.ProcessingContext object EmberPatterns { fun jsQuotedLiteralExpression(): JSElementPattern.Capture<JSLiteralExpression> { return JSElementPattern.Capture(object : InitialPatternCondition<JSLiteralExpression>( JSLiteralExpression::class.java) { override fun accepts(o: Any?, context: ProcessingContext?): Boolean { return o is JSLiteralExpression && o.isQuotedLiteral } }) } fun jsQuotedArgument(functionName: String, index: Int) = jsQuotedLiteralExpression().and(jsArgument(functionName, index)) fun inEmberFile(vararg types: String): ObjectPattern.Capture<PsiElement> { return ObjectPattern.Capture(object : InitialPatternCondition<PsiElement>(PsiElement::class.java) { override fun accepts(o: Any?, context: ProcessingContext?): Boolean { if (o !is PsiElement) return false val file = o.originalVirtualFile ?: return false val module = EmberName.from(file) ?: return false return module.type in types } }) } }
apache-2.0
florent37/Flutter-AssetsAudioPlayer
android/src/main/kotlin/com/github/florent37/assets_audio_player/stopwhencall/StopWhenCallAudioFocus.kt
1
2781
package com.github.florent37.assets_audio_player.stopwhencall import android.content.Context import android.media.AudioManager import androidx.media.AudioAttributesCompat import androidx.media.AudioFocusRequestCompat import androidx.media.AudioManagerCompat class StopWhenCallAudioFocus(private val context: Context) : StopWhenCall() { private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager private val focusLock = Any() private var request: AudioFocusRequestCompat? = null private fun generateListener() : ((Int) -> Unit) = { focusChange -> when (focusChange) { AudioManager.AUDIOFOCUS_GAIN -> synchronized(focusLock) { pingListeners(AudioState.AUTHORIZED_TO_PLAY) } AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> synchronized(focusLock) { pingListeners(AudioState.REDUCE_VOLUME) } else -> { synchronized(focusLock) { pingListeners(AudioState.FORBIDDEN) } } } } override fun requestAudioFocus(audioFocusStrategy: AudioFocusStrategy) : AudioState { if(audioFocusStrategy is AudioFocusStrategy.None) return AudioState.FORBIDDEN val strategy = audioFocusStrategy as AudioFocusStrategy.Request request?.let { AudioManagerCompat.abandonAudioFocusRequest(audioManager, it) } val requestType = if(strategy.resumeOthersPlayersAfterDone){ AudioManagerCompat.AUDIOFOCUS_GAIN_TRANSIENT } else { AudioManagerCompat.AUDIOFOCUS_GAIN } val listener = generateListener() this.request = AudioFocusRequestCompat.Builder(requestType).also { it.setAudioAttributes(AudioAttributesCompat.Builder().run { setUsage(AudioAttributesCompat.USAGE_MEDIA) setContentType(AudioAttributesCompat.CONTENT_TYPE_MUSIC) build() }) it.setOnAudioFocusChangeListener(listener) }.build() val result: Int = AudioManagerCompat.requestAudioFocus(audioManager, request!!) synchronized(focusLock) { listener(result) } return when(result){ AudioManager.AUDIOFOCUS_GAIN, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT -> AudioState.AUTHORIZED_TO_PLAY AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> AudioState.REDUCE_VOLUME else -> AudioState.FORBIDDEN } } override fun stop() { this.request?.let { AudioManagerCompat.abandonAudioFocusRequest(audioManager, it) } } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/KotlinBuildScriptManipulator.kt
1
28526
// 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.gradleJava.configuration import com.intellij.openapi.module.Module import com.intellij.openapi.roots.DependencyScope import com.intellij.openapi.roots.ExternalLibraryDescriptor import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.idea.base.codeInsight.CliArgumentStringBuilder.buildArgumentString import org.jetbrains.kotlin.idea.base.codeInsight.CliArgumentStringBuilder.replaceLanguageFeature import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.configuration.* import org.jetbrains.kotlin.idea.gradleCodeInsightCommon.* import org.jetbrains.kotlin.idea.projectConfiguration.RepositoryDescription import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType import org.jetbrains.kotlin.resolve.ImportPath import org.jetbrains.kotlin.utils.addToStdlib.cast class KotlinBuildScriptManipulator( override val scriptFile: KtFile, override val preferNewSyntax: Boolean ) : GradleBuildScriptManipulator<KtFile> { override fun isApplicable(file: PsiFile): Boolean = file is KtFile private val gradleVersion = GradleVersionProvider.fetchGradleVersion(scriptFile) override fun isConfiguredWithOldSyntax(kotlinPluginName: String) = runReadAction { scriptFile.containsApplyKotlinPlugin(kotlinPluginName) && scriptFile.containsCompileStdLib() } override fun isConfigured(kotlinPluginExpression: String): Boolean = runReadAction { scriptFile.containsKotlinPluginInPluginsGroup(kotlinPluginExpression) && scriptFile.containsCompileStdLib() } override fun configureProjectBuildScript(kotlinPluginName: String, version: IdeKotlinVersion): Boolean { if (useNewSyntax(kotlinPluginName, gradleVersion)) return false val originalText = scriptFile.text scriptFile.getBuildScriptBlock()?.apply { addDeclarationIfMissing("var $GSK_KOTLIN_VERSION_PROPERTY_NAME: String by extra", true).also { addExpressionAfterIfMissing("$GSK_KOTLIN_VERSION_PROPERTY_NAME = \"$version\"", it) } getRepositoriesBlock()?.apply { addRepositoryIfMissing(version) addMavenCentralIfMissing() } getDependenciesBlock()?.addPluginToClassPathIfMissing() } return originalText != scriptFile.text } override fun configureModuleBuildScript( kotlinPluginName: String, kotlinPluginExpression: String, stdlibArtifactName: String, version: IdeKotlinVersion, jvmTarget: String? ): Boolean { val originalText = scriptFile.text val useNewSyntax = useNewSyntax(kotlinPluginName, gradleVersion) scriptFile.apply { if (useNewSyntax) { createPluginInPluginsGroupIfMissing(kotlinPluginExpression, version) getDependenciesBlock()?.addNoVersionCompileStdlibIfMissing(stdlibArtifactName) getRepositoriesBlock()?.apply { val repository = getRepositoryForVersion(version) if (repository != null) { scriptFile.module?.getBuildScriptSettingsPsiFile()?.let { with(GradleBuildScriptSupport.getManipulator(it)) { addPluginRepository(repository) addMavenCentralPluginRepository() addPluginRepository(DEFAULT_GRADLE_PLUGIN_REPOSITORY) } } } } } else { script?.blockExpression?.addDeclarationIfMissing("val $GSK_KOTLIN_VERSION_PROPERTY_NAME: String by extra", true) getApplyBlock()?.createPluginIfMissing(kotlinPluginName) getDependenciesBlock()?.addCompileStdlibIfMissing(stdlibArtifactName) } getRepositoriesBlock()?.apply { addRepositoryIfMissing(version) addMavenCentralIfMissing() } jvmTarget?.let { changeKotlinTaskParameter("jvmTarget", it, forTests = false) changeKotlinTaskParameter("jvmTarget", it, forTests = true) } } return originalText != scriptFile.text } override fun changeLanguageFeatureConfiguration( feature: LanguageFeature, state: LanguageFeature.State, forTests: Boolean ): PsiElement? = scriptFile.changeLanguageFeatureConfiguration(feature, state, forTests) override fun changeLanguageVersion(version: String, forTests: Boolean): PsiElement? = scriptFile.changeKotlinTaskParameter("languageVersion", version, forTests) override fun changeApiVersion(version: String, forTests: Boolean): PsiElement? = scriptFile.changeKotlinTaskParameter("apiVersion", version, forTests) override fun addKotlinLibraryToModuleBuildScript( targetModule: Module?, scope: DependencyScope, libraryDescriptor: ExternalLibraryDescriptor ) { val dependencyText = getCompileDependencySnippet( libraryDescriptor.libraryGroupId, libraryDescriptor.libraryArtifactId, libraryDescriptor.maxVersion, scope.toGradleCompileScope(scriptFile.module?.buildSystemType == BuildSystemType.AndroidGradle) ) if (targetModule != null && usesNewMultiplatform()) { val findOrCreateTargetSourceSet = scriptFile .getKotlinBlock() ?.getSourceSetsBlock() ?.findOrCreateTargetSourceSet(targetModule.name.takeLastWhile { it != '.' }) val dependenciesBlock = findOrCreateTargetSourceSet?.getDependenciesBlock() dependenciesBlock?.addExpressionIfMissing(dependencyText) } else { scriptFile.getDependenciesBlock()?.addExpressionIfMissing(dependencyText) } } private fun KtBlockExpression.findOrCreateTargetSourceSet(moduleName: String) = findTargetSourceSet(moduleName) ?: createTargetSourceSet(moduleName) private fun KtBlockExpression.findTargetSourceSet(moduleName: String): KtBlockExpression? = statements.find { it.isTargetSourceSetDeclaration(moduleName) }?.getOrCreateBlock() private fun KtExpression.getOrCreateBlock(): KtBlockExpression? = when (this) { is KtCallExpression -> getBlock() ?: addBlock() is KtReferenceExpression -> replace(KtPsiFactory(project).createExpression("$text {\n}")).cast<KtCallExpression>().getBlock() is KtProperty -> delegateExpressionOrInitializer?.getOrCreateBlock() else -> error("Impossible create block for $this") } private fun KtCallExpression.addBlock(): KtBlockExpression? = parent.addAfter( KtPsiFactory(project).createEmptyBody(), this ) as? KtBlockExpression private fun KtBlockExpression.createTargetSourceSet(moduleName: String) = addExpressionIfMissing("getByName(\"$moduleName\") {\n}") .cast<KtCallExpression>() .getBlock() override fun getKotlinStdlibVersion(): String? = scriptFile.getKotlinStdlibVersion() private fun KtBlockExpression.addCompileStdlibIfMissing(stdlibArtifactName: String): KtCallExpression? = findStdLibDependency() ?: addExpressionIfMissing( getCompileDependencySnippet( KOTLIN_GROUP_ID, stdlibArtifactName, version = "\$$GSK_KOTLIN_VERSION_PROPERTY_NAME" ) ) as? KtCallExpression private fun addPluginRepositoryExpression(expression: String) { scriptFile.getPluginManagementBlock()?.findOrCreateBlock("repositories")?.addExpressionIfMissing(expression) } override fun addMavenCentralPluginRepository() { addPluginRepositoryExpression("mavenCentral()") } override fun addPluginRepository(repository: RepositoryDescription) { addPluginRepositoryExpression(repository.toKotlinRepositorySnippet()) } override fun addResolutionStrategy(pluginId: String) { scriptFile .getPluginManagementBlock() ?.findOrCreateBlock("resolutionStrategy") ?.findOrCreateBlock("eachPlugin") ?.addExpressionIfMissing( """ if (requested.id.id == "$pluginId") { useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${'$'}{requested.version}") } """.trimIndent() ) } private fun KtBlockExpression.addNoVersionCompileStdlibIfMissing(stdlibArtifactName: String): KtCallExpression? = findStdLibDependency() ?: addExpressionIfMissing( "implementation(${getKotlinModuleDependencySnippet( stdlibArtifactName, null )})" ) as? KtCallExpression private fun KtFile.containsCompileStdLib(): Boolean = findScriptInitializer("dependencies")?.getBlock()?.findStdLibDependency() != null private fun KtFile.containsApplyKotlinPlugin(pluginName: String): Boolean = findScriptInitializer("apply")?.getBlock()?.findPlugin(pluginName) != null private fun KtFile.containsKotlinPluginInPluginsGroup(pluginName: String): Boolean = findScriptInitializer("plugins")?.getBlock()?.findPluginInPluginsGroup(pluginName) != null private fun KtBlockExpression.findPlugin(pluginName: String): KtCallExpression? { return PsiTreeUtil.getChildrenOfType(this, KtCallExpression::class.java)?.find { it.calleeExpression?.text == "plugin" && it.valueArguments.firstOrNull()?.text == "\"$pluginName\"" } } private fun KtBlockExpression.findClassPathDependencyVersion(pluginName: String): String? { return PsiTreeUtil.getChildrenOfAnyType(this, KtCallExpression::class.java).mapNotNull { if (it?.calleeExpression?.text == "classpath") { val dependencyName = it.valueArguments.firstOrNull()?.text?.removeSurrounding("\"") if (dependencyName?.startsWith(pluginName) == true) dependencyName.substringAfter("$pluginName:") else null } else null }.singleOrNull() } private fun getPluginInfoFromBuildScript( operatorName: String?, pluginVersion: KtExpression?, receiverCalleeExpression: KtCallExpression? ): Pair<String, String>? { val receiverCalleeExpressionText = receiverCalleeExpression?.calleeExpression?.text?.trim() val receivedPluginName = when { receiverCalleeExpressionText == "id" -> receiverCalleeExpression.valueArguments.firstOrNull()?.text?.trim()?.removeSurrounding("\"") operatorName == "version" -> receiverCalleeExpressionText else -> null } val pluginVersionText = pluginVersion?.text?.trim()?.removeSurrounding("\"") ?: return null return receivedPluginName?.to(pluginVersionText) } private fun KtBlockExpression.findPluginVersionInPluginGroup(pluginName: String): String? { val versionsToPluginNames = PsiTreeUtil.getChildrenOfAnyType(this, KtBinaryExpression::class.java, KtDotQualifiedExpression::class.java).mapNotNull { when (it) { is KtBinaryExpression -> getPluginInfoFromBuildScript( it.operationReference.text, it.right, it.left as? KtCallExpression ) is KtDotQualifiedExpression -> (it.selectorExpression as? KtCallExpression)?.run { getPluginInfoFromBuildScript( calleeExpression?.text, valueArguments.firstOrNull()?.getArgumentExpression(), it.receiverExpression as? KtCallExpression ) } else -> null } }.toMap() return versionsToPluginNames.getOrDefault(pluginName, null) } private fun KtBlockExpression.findPluginInPluginsGroup(pluginName: String): KtCallExpression? { return PsiTreeUtil.getChildrenOfAnyType( this, KtCallExpression::class.java, KtBinaryExpression::class.java, KtDotQualifiedExpression::class.java ).mapNotNull { when (it) { is KtCallExpression -> it is KtBinaryExpression -> { if (it.operationReference.text == "version") it.left as? KtCallExpression else null } is KtDotQualifiedExpression -> { if ((it.selectorExpression as? KtCallExpression)?.calleeExpression?.text == "version") { it.receiverExpression as? KtCallExpression } else null } else -> null } }.find { "${it.calleeExpression?.text?.trim() ?: ""}(${it.valueArguments.firstOrNull()?.text ?: ""})" == pluginName } } private fun KtFile.findScriptInitializer(startsWith: String): KtScriptInitializer? = PsiTreeUtil.findChildrenOfType(this, KtScriptInitializer::class.java).find { it.text.startsWith(startsWith) } private fun KtBlockExpression.findBlock(name: String): KtBlockExpression? { return getChildrenOfType<KtCallExpression>().find { it.calleeExpression?.text == name && it.valueArguments.singleOrNull()?.getArgumentExpression() is KtLambdaExpression }?.getBlock() } private fun KtScriptInitializer.getBlock(): KtBlockExpression? = PsiTreeUtil.findChildOfType(this, KtCallExpression::class.java)?.getBlock() private fun KtCallExpression.getBlock(): KtBlockExpression? = (valueArguments.singleOrNull()?.getArgumentExpression() as? KtLambdaExpression)?.bodyExpression ?: lambdaArguments.lastOrNull()?.getLambdaExpression()?.bodyExpression private fun KtFile.getKotlinStdlibVersion(): String? { return findScriptInitializer("dependencies")?.getBlock()?.let { when (val expression = it.findStdLibDependency()?.valueArguments?.firstOrNull()?.getArgumentExpression()) { is KtCallExpression -> expression.valueArguments.getOrNull(1)?.text?.trim('\"') is KtStringTemplateExpression -> expression.text?.trim('\"')?.substringAfterLast(":")?.removePrefix("$") else -> null } } } private fun KtBlockExpression.findStdLibDependency(): KtCallExpression? { return PsiTreeUtil.getChildrenOfType(this, KtCallExpression::class.java)?.find { val calleeText = it.calleeExpression?.text calleeText in SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS && (it.valueArguments.firstOrNull()?.getArgumentExpression()?.isKotlinStdLib() ?: false) } } private fun KtExpression.isKotlinStdLib(): Boolean = when (this) { is KtCallExpression -> { val calleeText = calleeExpression?.text (calleeText == "kotlinModule" || calleeText == "kotlin") && valueArguments.firstOrNull()?.getArgumentExpression()?.text?.startsWith("\"stdlib") ?: false } is KtStringTemplateExpression -> text.startsWith("\"$STDLIB_ARTIFACT_PREFIX") else -> false } private fun KtFile.getPluginManagementBlock(): KtBlockExpression? = findOrCreateScriptInitializer("pluginManagement", true) private fun KtFile.getKotlinBlock(): KtBlockExpression? = findOrCreateScriptInitializer("kotlin") private fun KtBlockExpression.getSourceSetsBlock(): KtBlockExpression? = findOrCreateBlock("sourceSets") private fun KtFile.getRepositoriesBlock(): KtBlockExpression? = findOrCreateScriptInitializer("repositories") private fun KtFile.getDependenciesBlock(): KtBlockExpression? = findOrCreateScriptInitializer("dependencies") private fun KtFile.getPluginsBlock(): KtBlockExpression? = findOrCreateScriptInitializer("plugins", true) private fun KtFile.createPluginInPluginsGroupIfMissing(pluginName: String, version: IdeKotlinVersion): KtCallExpression? = getPluginsBlock()?.let { it.findPluginInPluginsGroup(pluginName) ?: it.addExpressionIfMissing("$pluginName version \"${version.artifactVersion}\"") as? KtCallExpression } private fun KtFile.createApplyBlock(): KtBlockExpression? { val apply = psiFactory.createScriptInitializer("apply {\n}") val plugins = findScriptInitializer("plugins") val addedElement = plugins?.addSibling(apply) ?: addToScriptBlock(apply) addedElement?.addNewLinesIfNeeded() return (addedElement as? KtScriptInitializer)?.getBlock() } private fun KtFile.getApplyBlock(): KtBlockExpression? = findScriptInitializer("apply")?.getBlock() ?: createApplyBlock() private fun KtBlockExpression.createPluginIfMissing(pluginName: String): KtCallExpression? = findPlugin(pluginName) ?: addExpressionIfMissing("plugin(\"$pluginName\")") as? KtCallExpression private fun KtFile.changeCoroutineConfiguration(coroutineOption: String): PsiElement? { val snippet = "experimental.coroutines = Coroutines.${coroutineOption.toUpperCase()}" val kotlinBlock = getKotlinBlock() ?: return null addImportIfMissing("org.jetbrains.kotlin.gradle.dsl.Coroutines") val statement = kotlinBlock.statements.find { it.text.startsWith("experimental.coroutines") } return if (statement != null) { statement.replace(psiFactory.createExpression(snippet)) } else { kotlinBlock.add(psiFactory.createExpression(snippet)).apply { addNewLinesIfNeeded() } } } private fun KtFile.changeLanguageFeatureConfiguration( feature: LanguageFeature, state: LanguageFeature.State, forTests: Boolean ): PsiElement? { if (usesNewMultiplatform()) { state.assertApplicableInMultiplatform() return getKotlinBlock() ?.findOrCreateBlock("sourceSets") ?.findOrCreateBlock("all") ?.addExpressionIfMissing("languageSettings.enableLanguageFeature(\"${feature.name}\")") } val pluginsBlock = findScriptInitializer("plugins")?.getBlock() val rawKotlinVersion = pluginsBlock?.findPluginVersionInPluginGroup("kotlin") ?: pluginsBlock?.findPluginVersionInPluginGroup("org.jetbrains.kotlin.jvm") ?: findScriptInitializer("buildscript")?.getBlock()?.findBlock("dependencies")?.findClassPathDependencyVersion("org.jetbrains.kotlin:kotlin-gradle-plugin") val kotlinVersion = rawKotlinVersion?.let(IdeKotlinVersion::opt) val featureArgumentString = feature.buildArgumentString(state, kotlinVersion) val parameterName = "freeCompilerArgs" return addOrReplaceKotlinTaskParameter( parameterName, "listOf(\"$featureArgumentString\")", forTests ) { val newText = text.replaceLanguageFeature( feature, state, kotlinVersion, prefix = "$parameterName = listOf(", postfix = ")" ) replace(psiFactory.createExpression(newText)) } } private fun KtFile.addOrReplaceKotlinTaskParameter( parameterName: String, defaultValue: String, forTests: Boolean, replaceIt: KtExpression.() -> PsiElement ): PsiElement? { val taskName = if (forTests) "compileTestKotlin" else "compileKotlin" val optionsBlock = findScriptInitializer("$taskName.kotlinOptions")?.getBlock() return if (optionsBlock != null) { val assignment = optionsBlock.statements.find { (it as? KtBinaryExpression)?.left?.text == parameterName } assignment?.replaceIt() ?: optionsBlock.addExpressionIfMissing("$parameterName = $defaultValue") } else { addImportIfMissing("org.jetbrains.kotlin.gradle.tasks.KotlinCompile") script?.blockExpression?.addDeclarationIfMissing("val $taskName: KotlinCompile by tasks") addTopLevelBlock("$taskName.kotlinOptions")?.addExpressionIfMissing("$parameterName = $defaultValue") } } private fun KtFile.changeKotlinTaskParameter(parameterName: String, parameterValue: String, forTests: Boolean): PsiElement? { return addOrReplaceKotlinTaskParameter(parameterName, "\"$parameterValue\"", forTests) { replace(psiFactory.createExpression("$parameterName = \"$parameterValue\"")) } } private fun KtBlockExpression.getRepositorySnippet(version: IdeKotlinVersion): String? { val repository = getRepositoryForVersion(version) return when { repository != null -> repository.toKotlinRepositorySnippet() !isRepositoryConfigured(text) -> MAVEN_CENTRAL else -> null } } private fun KtFile.getBuildScriptBlock(): KtBlockExpression? = findOrCreateScriptInitializer("buildscript", true) private fun KtFile.findOrCreateScriptInitializer(name: String, first: Boolean = false): KtBlockExpression? = findScriptInitializer(name)?.getBlock() ?: addTopLevelBlock(name, first) private fun KtBlockExpression.getRepositoriesBlock(): KtBlockExpression? = findOrCreateBlock("repositories") private fun KtBlockExpression.getDependenciesBlock(): KtBlockExpression? = findOrCreateBlock("dependencies") private fun KtBlockExpression.addRepositoryIfMissing(version: IdeKotlinVersion): KtCallExpression? { val snippet = getRepositorySnippet(version) ?: return null return addExpressionIfMissing(snippet) as? KtCallExpression } private fun KtBlockExpression.addMavenCentralIfMissing(): KtCallExpression? = if (!isRepositoryConfigured(text)) addExpressionIfMissing(MAVEN_CENTRAL) as? KtCallExpression else null private fun KtBlockExpression.findOrCreateBlock(name: String, first: Boolean = false) = findBlock(name) ?: addBlock(name, first) private fun KtBlockExpression.addPluginToClassPathIfMissing(): KtCallExpression? = addExpressionIfMissing(getKotlinGradlePluginClassPathSnippet()) as? KtCallExpression private fun KtBlockExpression.addBlock(name: String, first: Boolean = false): KtBlockExpression? { return psiFactory.createExpression("$name {\n}") .let { if (first) addAfter(it, null) else add(it) } ?.apply { addNewLinesIfNeeded() } ?.cast<KtCallExpression>() ?.getBlock() } private fun KtFile.addTopLevelBlock(name: String, first: Boolean = false): KtBlockExpression? { val scriptInitializer = psiFactory.createScriptInitializer("$name {\n}") val addedElement = addToScriptBlock(scriptInitializer, first) as? KtScriptInitializer addedElement?.addNewLinesIfNeeded() return addedElement?.getBlock() } private fun PsiElement.addSibling(element: PsiElement): PsiElement = parent.addAfter(element, this) private fun PsiElement.addNewLineBefore(lineBreaks: Int = 1) { parent.addBefore(psiFactory.createNewLine(lineBreaks), this) } private fun PsiElement.addNewLineAfter(lineBreaks: Int = 1) { parent.addAfter(psiFactory.createNewLine(lineBreaks), this) } private fun PsiElement.addNewLinesIfNeeded(lineBreaks: Int = 1) { if (prevSibling != null && prevSibling.text.isNotBlank()) { addNewLineBefore(lineBreaks) } if (nextSibling != null && nextSibling.text.isNotBlank()) { addNewLineAfter(lineBreaks) } } private fun KtFile.addToScriptBlock(element: PsiElement, first: Boolean = false): PsiElement? = if (first) script?.blockExpression?.addAfter(element, null) else script?.blockExpression?.add(element) private fun KtFile.addImportIfMissing(path: String): KtImportDirective = importDirectives.find { it.importPath?.pathStr == path } ?: importList?.add( psiFactory.createImportDirective( ImportPath.fromString( path ) ) ) as KtImportDirective private fun KtBlockExpression.addExpressionAfterIfMissing(text: String, after: PsiElement): KtExpression = addStatementIfMissing(text) { addAfter(psiFactory.createExpression(it), after) } private fun KtBlockExpression.addExpressionIfMissing(text: String, first: Boolean = false): KtExpression = addStatementIfMissing(text) { psiFactory.createExpression(it).let { created -> if (first) addAfter(created, null) else add(created) } } private fun KtBlockExpression.addDeclarationIfMissing(text: String, first: Boolean = false): KtDeclaration = addStatementIfMissing(text) { psiFactory.createDeclaration<KtDeclaration>(it).let { created -> if (first) addAfter(created, null) else add(created) } } private inline fun <reified T : PsiElement> KtBlockExpression.addStatementIfMissing( text: String, crossinline factory: (String) -> PsiElement ): T { statements.find { StringUtil.equalsIgnoreWhitespaces(it.text, text) }?.let { return it as T } return factory(text).apply { addNewLinesIfNeeded() } as T } private fun KtPsiFactory.createScriptInitializer(text: String): KtScriptInitializer = createFile("dummy.kts", text).script?.blockExpression?.firstChild as KtScriptInitializer private val PsiElement.psiFactory: KtPsiFactory get() = KtPsiFactory(this) private fun getCompileDependencySnippet( groupId: String, artifactId: String, version: String?, compileScope: String = "implementation" ): String { if (groupId != KOTLIN_GROUP_ID) { return "$compileScope(\"$groupId:$artifactId:$version\")" } val kotlinPluginName = if (scriptFile.module?.buildSystemType == BuildSystemType.AndroidGradle) { "kotlin-android" } else { KotlinGradleModuleConfigurator.KOTLIN } if (useNewSyntax(kotlinPluginName, gradleVersion)) { return "$compileScope(${getKotlinModuleDependencySnippet(artifactId)})" } val libraryVersion = if (version == GSK_KOTLIN_VERSION_PROPERTY_NAME) "\$$version" else version return "$compileScope(${getKotlinModuleDependencySnippet(artifactId, libraryVersion)})" } companion object { private const val STDLIB_ARTIFACT_PREFIX = "org.jetbrains.kotlin:kotlin-stdlib" const val GSK_KOTLIN_VERSION_PROPERTY_NAME = "kotlin_version" fun getKotlinGradlePluginClassPathSnippet(): String = "classpath(${getKotlinModuleDependencySnippet("gradle-plugin", "\$$GSK_KOTLIN_VERSION_PROPERTY_NAME")})" fun getKotlinModuleDependencySnippet(artifactId: String, version: String? = null): String { val moduleName = artifactId.removePrefix("kotlin-") return when (version) { null -> "kotlin(\"$moduleName\")" "\$$GSK_KOTLIN_VERSION_PROPERTY_NAME" -> "kotlinModule(\"$moduleName\", $GSK_KOTLIN_VERSION_PROPERTY_NAME)" else -> "kotlinModule(\"$moduleName\", ${"\"$version\""})" } } } } private fun KtExpression.isTargetSourceSetDeclaration(moduleName: String): Boolean = with(text) { when (this@isTargetSourceSetDeclaration) { is KtProperty -> startsWith("val $moduleName by") || initializer?.isTargetSourceSetDeclaration(moduleName) == true is KtCallExpression -> startsWith("getByName(\"$moduleName\")") else -> false } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/multiplatform/nativeStdlib/common/common.kt
3
85
// !DIAGNOSTICS: -UNUSED_VARIABLE package mpp fun some() { } fun commonFun() { }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createFunction/invoke/invokeWithExplicitParamNamesOnUserType.kt
4
147
// "Create member function 'A.invoke'" "true" class A<T>(val n: T) fun test() { val a: A<Int> = A(1)<caret>(abc = 1, ghi = A(2), def = "s") }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/hints/KotlinVcsCodeVisionContext.kt
8
1697
// 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.codeInsight.hints import com.intellij.codeInsight.hints.VcsCodeVisionLanguageContext import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import java.awt.event.MouseEvent class KotlinVcsCodeVisionContext : VcsCodeVisionLanguageContext { override fun isAccepted(element: PsiElement): Boolean { return when (element) { is KtClassOrObject -> isAcceptedClassOrObject(element) is KtNamedFunction -> element.isTopLevel || isAcceptedClassOrObject(element.containingClassOrObject) is KtSecondaryConstructor -> true is KtClassInitializer -> true is KtProperty -> element.accessors.isNotEmpty() else -> false } } private fun isAcceptedClassOrObject(element: KtClassOrObject?): Boolean = when (element) { is KtClass -> element !is KtEnumEntry is KtObjectDeclaration -> !element.isObjectLiteral() else -> false } override fun handleClick(mouseEvent: MouseEvent, editor: Editor, element: PsiElement) { val project = element.project val location = if (element is KtClassOrObject) KotlinCodeVisionUsagesCollector.CLASS_LOCATION else KotlinCodeVisionUsagesCollector.FUNCTION_LOCATION KotlinCodeVisionUsagesCollector.logCodeAuthorClicked(project, location) } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/navigation/gotoSuper/multiModule/actualProperty/jvm/jvm.kt
13
156
package test actual class Expected { actual fun foo() = 42 actual val <caret>bar = "Hello" } // REF: [testModule_Common] (in test.Expected).bar
apache-2.0
GunoH/intellij-community
plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/contributors/keywords/OverrideKeywordHandler.kt
1
7689
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion.contributors.keywords import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.lookup.LookupElement import com.intellij.icons.AllIcons import com.intellij.openapi.project.Project import com.intellij.ui.RowIcon import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.idea.completion.* import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext import org.jetbrains.kotlin.idea.completion.keywords.CompletionKeywordHandler import org.jetbrains.kotlin.idea.core.overrideImplement.* import org.jetbrains.kotlin.idea.core.overrideImplement.KtClassMember import org.jetbrains.kotlin.idea.core.overrideImplement.KtGenerateMembersHandler import org.jetbrains.kotlin.idea.core.overrideImplement.KtOverrideMembersHandler import org.jetbrains.kotlin.idea.core.overrideImplement.generateMember import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithModality import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.idea.KtIconProvider.getIcon import org.jetbrains.kotlin.analysis.api.symbols.markers.KtNamedSymbol import org.jetbrains.kotlin.analysis.api.symbols.nameOrAnonymous import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer import com.intellij.openapi.application.runWriteAction internal class OverrideKeywordHandler( private val basicContext: FirBasicCompletionContext ) : CompletionKeywordHandler<KtAnalysisSession>(KtTokens.OVERRIDE_KEYWORD) { @OptIn(ExperimentalStdlibApi::class) override fun KtAnalysisSession.createLookups( parameters: CompletionParameters, expression: KtExpression?, lookup: LookupElement, project: Project ): Collection<LookupElement> { val result = mutableListOf(lookup) val position = parameters.position val isConstructorParameter = position.getNonStrictParentOfType<KtPrimaryConstructor>() != null val classOrObject = position.getNonStrictParentOfType<KtClassOrObject>() ?: return result val members = collectMembers(classOrObject, isConstructorParameter) for (member in members) { result += createLookupElementToGenerateSingleOverrideMember(member, classOrObject, isConstructorParameter, project) } return result } private fun KtAnalysisSession.collectMembers(classOrObject: KtClassOrObject, isConstructorParameter: Boolean): List<KtClassMember> { val allMembers = KtOverrideMembersHandler().collectMembersToGenerate(classOrObject) return if (isConstructorParameter) { allMembers.mapNotNull { member -> if (member.memberInfo.isProperty) { member.copy(bodyType = BodyType.FromTemplate, preferConstructorParameter = true) } else null } } else allMembers.toList() } @OptIn(KtAllowAnalysisOnEdt::class) private fun KtAnalysisSession.createLookupElementToGenerateSingleOverrideMember( member: KtClassMember, classOrObject: KtClassOrObject, isConstructorParameter: Boolean, project: Project ): OverridesCompletionLookupElementDecorator { val memberSymbol = member.symbol check(memberSymbol is KtNamedSymbol) val text = getSymbolTextForLookupElement(memberSymbol) val baseIcon = getIcon(memberSymbol) val isImplement = (memberSymbol as? KtSymbolWithModality)?.modality == Modality.ABSTRACT val additionalIcon = if (isImplement) AllIcons.Gutter.ImplementingMethod else AllIcons.Gutter.OverridingMethod val icon = RowIcon(baseIcon, additionalIcon) val baseClass = classOrObject.getClassOrObjectSymbol() val baseClassIcon = getIcon(baseClass) val isSuspendFunction = (memberSymbol as? KtFunctionSymbol)?.isSuspend == true val baseClassName = baseClass.nameOrAnonymous.asString() val memberPointer = memberSymbol.createPointer() val baseLookupElement = with(basicContext.lookupElementFactory) { createLookupElement(memberSymbol, basicContext.importStrategyDetector) } ?: error("Lookup element should be available for override completion") return OverridesCompletionLookupElementDecorator( baseLookupElement, declaration = null, text, isImplement, icon, baseClassName, baseClassIcon, isConstructorParameter, isSuspendFunction, generateMember = { generateMemberInNewAnalysisSession(classOrObject, memberPointer, member, project) }, shortenReferences = { element -> val shortenings = allowAnalysisOnEdt { analyze(classOrObject) { collectPossibleReferenceShortenings(element.containingKtFile, element.textRange) } } runWriteAction { shortenings.invokeShortening() } } ) } private fun KtAnalysisSession.getSymbolTextForLookupElement(memberSymbol: KtCallableSymbol): String = buildString { append(KtTokens.OVERRIDE_KEYWORD.value) .append(" ") .append(memberSymbol.render(renderingOptionsForLookupElementRendering)) if (memberSymbol is KtFunctionSymbol) { append(" {...}") } } @OptIn(KtAllowAnalysisOnEdt::class) private fun generateMemberInNewAnalysisSession( classOrObject: KtClassOrObject, memberPointer: KtSymbolPointer<KtCallableSymbol>, member: KtClassMember, project: Project ) = allowAnalysisOnEdt { analyze(classOrObject) { val memberInCorrectAnalysisSession = createCopyInCurrentAnalysisSession(memberPointer, member) generateMember( project, memberInCorrectAnalysisSession, classOrObject, copyDoc = false, mode = MemberGenerateMode.OVERRIDE ) } } //todo temporary hack until KtSymbolPointer is properly implemented private fun KtAnalysisSession.createCopyInCurrentAnalysisSession( memberPointer: KtSymbolPointer<KtCallableSymbol>, member: KtClassMember ) = KtClassMember( KtClassMemberInfo( memberPointer.restoreSymbol() ?: error("Cannot restore symbol from $memberPointer"), member.memberInfo.memberText, member.memberInfo.memberIcon, member.memberInfo.containingSymbolText, member.memberInfo.containingSymbolIcon, ), member.bodyType, member.preferConstructorParameter, ) companion object { private val renderingOptionsForLookupElementRendering = KtGenerateMembersHandler.renderOption.copy( renderUnitReturnType = false, renderDeclarationHeader = true ) } }
apache-2.0
NiciDieNase/chaosflix
touch/src/main/java/de/nicidienase/chaosflix/touch/favoritesimport/FavoritesImportActivity.kt
1
707
package de.nicidienase.chaosflix.touch.favoritesimport import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import de.nicidienase.chaosflix.touch.R class FavoritesImportActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_favorites_import) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) supportActionBar?.title = getString(R.string.import_activity_label) } companion object { private val TAG = FavoritesImportActivity::class.java.simpleName } }
mit
NiciDieNase/chaosflix
touch/src/main/java/de/nicidienase/chaosflix/touch/SplashActivity.kt
1
2486
package de.nicidienase.chaosflix.touch import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Conference import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Event import de.nicidienase.chaosflix.common.viewmodel.SplashViewModel import de.nicidienase.chaosflix.common.viewmodel.ViewModelFactory import de.nicidienase.chaosflix.touch.browse.BrowseActivity import de.nicidienase.chaosflix.touch.browse.eventslist.EventsListActivity import de.nicidienase.chaosflix.touch.eventdetails.EventDetailsActivity class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) when (intent.action) { Intent.ACTION_VIEW -> { setContentView(R.layout.activity_splash) handleViewAction(intent.data) } else -> { goToOverview() } } } private fun handleViewAction(data: Uri?) { val viewModel = ViewModelProviders.of( this, ViewModelFactory.getInstance(this) )[SplashViewModel::class.java] viewModel.state.observe(this, Observer { when (it.state) { SplashViewModel.State.FOUND -> { when (val item = it.data) { is Event -> goToEvent(item) is Conference -> goToConference(item) else -> goToOverview() } } SplashViewModel.State.NOT_FOUND -> { goToOverview() } } }) if (data != null) { when (data.pathSegments[0]) { "v" -> viewModel.findEventForUri(data) "c" -> viewModel.findConferenceForUri(data) } } else { goToOverview() } } private fun goToOverview() { BrowseActivity.launch(this) finish() } private fun goToEvent(event: Event) { EventDetailsActivity.launch(this, event) finish() } private fun goToConference(conference: Conference) { EventsListActivity.start(this, conference) finish() } }
mit
abertschi/ad-free
app/src/main/java/ch/abertschi/adfree/detector/NotificationBundleAndroidTextDetector.kt
1
1820
/* * Ad Free * Copyright (c) 2017 by abertschi, www.abertschi.ch * See the file "LICENSE" for the full license governing this code. */ package ch.abertschi.adfree.detector import android.app.Notification import android.os.Bundle import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.warn /** * Created by abertschi on 17.04.17. */ class NotificationBundleAndroidTextDetector : AbstractSpStatusBarDetector(), AnkoLogger { override fun canHandle(payload: AdPayload): Boolean = super.canHandle(payload) && payload?.statusbarNotification?.notification != null override fun flagAsAdvertisement(payload: AdPayload): Boolean { try { val bundle = getNotificationBundle(payload!!.statusbarNotification!!.notification) var flagAsAd = false bundle.let { val androidText: CharSequence? = bundle?.get("android.text") as CharSequence? flagAsAd = androidText == null && payload!!.statusbarNotification!!.notification!! .tickerText?.isNotEmpty() ?: false } return flagAsAd } catch (e: Exception) { warn(e) } return false } private fun getNotificationBundle(notification: Notification): Bundle? { try { //NoSuchFieldException val f = notification.javaClass.getDeclaredField("extras") f.isAccessible = true return f.get(notification) as Bundle } catch (e: Exception) { error("Can not access notification bundle with reflection, $e") } } override fun getMeta(): AdDetectorMeta = AdDetectorMeta( "Notification bundle", "spotify generic inspection of notification bundle", category = "Spotify" ) }
apache-2.0
ktorio/ktor
ktor-utils/common/src/io/ktor/util/pipeline/DebugPipelineContext.kt
1
2311
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.pipeline import io.ktor.util.* import kotlin.coroutines.* /** * Represents running execution of a pipeline * @param context object representing context in which pipeline executes * @param interceptors list of interceptors to execute * @param subject object representing subject that goes along the pipeline */ @KtorDsl internal class DebugPipelineContext<TSubject : Any, TContext : Any> constructor( context: TContext, private val interceptors: List<PipelineInterceptorFunction<TSubject, TContext>>, subject: TSubject, override val coroutineContext: CoroutineContext ) : PipelineContext<TSubject, TContext>(context) { /** * Subject of this pipeline execution */ override var subject: TSubject = subject private var index = 0 /** * Finishes current pipeline execution */ override fun finish() { index = -1 } /** * Continues execution of the pipeline with the given subject */ override suspend fun proceedWith(subject: TSubject): TSubject { this.subject = subject return proceed() } /** * Continues execution of the pipeline with the same subject */ override suspend fun proceed(): TSubject { val index = index if (index < 0) return subject if (index >= interceptors.size) { finish() return subject } return proceedLoop() } override suspend fun execute(initial: TSubject): TSubject { index = 0 subject = initial return proceed() } private suspend fun proceedLoop(): TSubject { do { val index = index if (index == -1) { break } val interceptors = interceptors if (index >= interceptors.size) { finish() break } val executeInterceptor = interceptors[index] this.index = index + 1 @Suppress("UNCHECKED_CAST") (executeInterceptor as PipelineInterceptor<TSubject, TContext>).invoke(this, subject) } while (true) return subject } }
apache-2.0
airbnb/lottie-android
sample/src/main/kotlin/com/airbnb/lottie/samples/DynamicTextActivity.kt
1
1103
package com.airbnb.lottie.samples import android.os.Bundle import android.text.Editable import android.text.TextWatcher import androidx.appcompat.app.AppCompatActivity import com.airbnb.lottie.TextDelegate import com.airbnb.lottie.samples.databinding.DynamicTextActivityBinding import com.airbnb.lottie.samples.utils.viewBinding class DynamicTextActivity : AppCompatActivity() { private val binding: DynamicTextActivityBinding by viewBinding() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val textDelegate = TextDelegate(binding.dynamicTextView) binding.nameEditText.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { textDelegate.setText("NAME", s.toString()) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} }) binding.dynamicTextView.setTextDelegate(textDelegate) } }
apache-2.0
code-disaster/lwjgl3
modules/lwjgl/openxr/src/templates/kotlin/openxr/templates/HTC_vive_cosmos_controller_interaction.kt
3
1011
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package openxr.templates import org.lwjgl.generator.* import openxr.* val HTC_vive_cosmos_controller_interaction = "HTCViveCosmosControllerInteraction".nativeClassXR("HTC_vive_cosmos_controller_interaction", type = "instance", postfix = "HTC") { documentation = """ The <a href="https://registry.khronos.org/OpenXR/specs/1.0/html/xrspec.html\#XR_HTC_vive_cosmos_controller_interaction">XR_HTC_vive_cosmos_controller_interaction</a> extension. This extension defines a new interaction profile for the VIVE Cosmos Controller. """ IntConstant( "The extension specification version.", "HTC_vive_cosmos_controller_interaction_SPEC_VERSION".."1" ) StringConstant( "The extension name.", "HTC_VIVE_COSMOS_CONTROLLER_INTERACTION_EXTENSION_NAME".."XR_HTC_vive_cosmos_controller_interaction" ) }
bsd-3-clause
code-disaster/lwjgl3
modules/lwjgl/openal/src/templates/kotlin/openal/templates/ALC11.kt
4
3233
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package openal.templates import org.lwjgl.generator.* import openal.* val ALC11 = "ALC11".nativeClassALC("ALC11") { extends = ALC10 documentation = "Native bindings to ALC 1.1 functionality." IntConstant( "Context creation attributes.", "MONO_SOURCES"..0x1010, "STEREO_SOURCES"..0x1011 ) IntConstant( "String queries.", "DEFAULT_ALL_DEVICES_SPECIFIER"..0x1012, "ALL_DEVICES_SPECIFIER"..0x1013, "CAPTURE_DEVICE_SPECIFIER"..0x310, "CAPTURE_DEFAULT_DEVICE_SPECIFIER"..0x311 ) IntConstant( "Integer queries.", "CAPTURE_SAMPLES"..0x312 ) ALCdevice.p( "CaptureOpenDevice", """ Allows the application to connect to a capture device. The {@code deviceName} argument is a null terminated string that requests a certain device or device configuration. If #NULL is specified, the implementation will provide an implementation specific default. """, nullable..ALCcharUTF8.const.p("deviceName", "the device or device configuration"), ALCuint("frequency", "the audio frequency"), ALCenum("format", "the audio format"), ALCsizei("samples", "the number of sample frames to buffer in the AL") ) ALCboolean( "CaptureCloseDevice", "Allows the application to disconnect from a capture device.", ALCdevice.p("device", "the capture device to close") ) ALCvoid( "CaptureStart", """ Starts recording audio on the specific capture device. Once started, the device will record audio to an internal ring buffer, the size of which was specified when opening the device. The application may query the capture device to discover how much data is currently available via the alcGetInteger with the ALC_CAPTURE_SAMPLES token. This will report the number of sample frames currently available. """, ALCdevice.p("device", "the capture device") ) ALCvoid( "CaptureStop", """ Halts audio capturing without closing the capture device. The implementation is encouraged to optimize for this case. The amount of audio samples available after restarting a stopped capture device is reset to zero. The application does not need to stop the capture device to read from it. """, ALCdevice.p("device", "the capture device") ) ALCvoid( "CaptureSamples", """ Obtains captured audio samples from the AL. The implementation may defer conversion and resampling until this point. Requesting more sample frames than are currently available is an error. """, ALCdevice.p("device", "the capture device"), Unsafe..MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT )..ALCvoid.p("buffer", "the buffer that will receive the samples. It must be big enough to contain at least {@code samples} sample frames."), ALCsizei("samples", "the number of sample frames to obtain") ) }
bsd-3-clause
code-disaster/lwjgl3
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/GLX_ARB_create_context.kt
4
3901
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* import core.linux.* val GLX_ARB_create_context = "GLXARBCreateContext".nativeClassGLX("GLX_ARB_create_context", ARB) { documentation = """ Native bindings to the $registryLink extension. With the advent of new versions of OpenGL which deprecate features and/or break backward compatibility with older versions, there is a need and desire to indicate at context creation which interface will be used. These extensions add a new context creation routine with attributes specifying the GL version and context properties requested for the context, and additionally add an attribute specifying the GL profile requested for a context of OpenGL 3.2 or later. It also allows making an OpenGL 3.0 or later context current without providing a default framebuffer. Requires ${GLX14.glx}. """ IntConstant( "Accepted as an attribute name in {@code attrib_list}.", "CONTEXT_MAJOR_VERSION_ARB"..0x2091, "CONTEXT_MINOR_VERSION_ARB"..0x2092, "CONTEXT_FLAGS_ARB"..0x2094 ) IntConstant( "Accepted as bits in the attribute value for #CONTEXT_FLAGS_ARB in {@code attrib_list}.", "CONTEXT_DEBUG_BIT_ARB"..0x0001, "CONTEXT_FORWARD_COMPATIBLE_BIT_ARB"..0x0002 ) GLXContext( "CreateContextAttribsARB", """ Creates an OpenGL rendering context. If {@code glXCreateContextAttribsARB} succeeds, it initializes the context to the initial state defined by the OpenGL specification, and returns a handle to it. This handle can be used to render to any GLX surface (window, pixmap, or pbuffer) compatible with {@code config}, subject to constraints imposed by the OpenGL API version of the context. If {@code share_context} is not #NULL, then all shareable data (excluding OpenGL texture objects named 0) will be shared by {@code share_context}, all other contexts {@code share_context} already shares with, and the newly created context. An arbitrary number of {@code GLXContexts} can share data in this fashion. The server context state for all sharing contexts must exist in a single address space. """, DISPLAY, GLXFBConfig("config", "the {@code GLXFBConfig}"), nullable..GLXContext( "share_context", """ if not #NULL, then all shareable data (excluding OpenGL texture objects named 0) will be shared by {@code share_context}, all other contexts {@code share_context} already shares with, and the newly created context. An arbitrary number of GLXContexts can share data in this fashion. The server context state for all sharing contexts must exist in a single address space. """ ), Bool( "direct", """ direct rendering is requested if {@code direct} is {@code True}, and indirect rendering if {@code direct} is {@code False}. If {@code direct} is {@code True}, the implementation may nonetheless create an indirect rendering context if any of the following conditions hold: ${ul( "The implementation does not support direct rendering.", "{@code display} is not a local X server.", "Implementation-dependent limits on the number of direct rendering contexts that can be supported simultaneously are exceeded." )} Use #IsDirect() to determine whether or not a request for a direct rendering context succeeded. """ ), nullable..NullTerminated..int.const.p("attrib_list", "an optional list of attributes for the context, terminated with {@code None}") ) }
bsd-3-clause
google/android-fhir
datacapture/src/main/java/com/google/android/fhir/datacapture/utilities/MoreLocalTimes.kt
1
1220
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.datacapture.utilities import android.content.Context import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime // ICU on Android does not observe the user's 24h/12h time format setting (obtained from // DateFormat.is24HourFormat()). In order to observe the setting, we are using DateFormat as // suggested in the docs. See // https://developer.android.com/guide/topics/resources/internationalization#24h-setting for // details. internal fun LocalTime.toLocalizedString(context: Context) = LocalDateTime.of(LocalDate.now(), this).toLocalizedTimeString(context)
apache-2.0
dhis2/dhis2-android-sdk
core/src/androidTest/java/org/hisp/dhis/android/core/settings/internal/AnalyticsTeiDataElementStoreIntegrationShould.kt
1
2561
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.settings.internal import org.hisp.dhis.android.core.data.database.ObjectStoreAbstractIntegrationShould import org.hisp.dhis.android.core.data.settings.AnalyticsSettingsSamples import org.hisp.dhis.android.core.settings.AnalyticsTeiDataElement import org.hisp.dhis.android.core.settings.AnalyticsTeiDataElementTableInfo import org.hisp.dhis.android.core.utils.integration.mock.TestDatabaseAdapterFactory import org.hisp.dhis.android.core.utils.runner.D2JunitRunner import org.junit.runner.RunWith @RunWith(D2JunitRunner::class) class AnalyticsTeiDataElementStoreIntegrationShould : ObjectStoreAbstractIntegrationShould<AnalyticsTeiDataElement>( AnalyticsTeiDataElementStore.create(TestDatabaseAdapterFactory.get()), AnalyticsTeiDataElementTableInfo.TABLE_INFO, TestDatabaseAdapterFactory.get() ) { override fun buildObject(): AnalyticsTeiDataElement { return AnalyticsSettingsSamples.analyticsTeiDataElementSample } }
bsd-3-clause
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/depend/DependPlugin.kt
1
1269
/* * Copyright (C) 2016-Present The MoonLake ([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.mcmoonlake.api.depend import org.bukkit.plugin.Plugin /** * ## DependPlugin (依赖插件) * * @see [Depend] * @see [DependPluginInfo] * @see [DependPluginAbstract] * @author lgou2w * @since 2.0 */ interface DependPlugin : Depend, DependPluginInfo { /** * * Get this plugin dependent plugin object. * * 获取此依赖插件的插件对象. */ val plugin: Plugin /** * * Get this plugin dependent plugin name. * * 获取此依赖插件的插件名称. */ val name: String }
gpl-3.0
kunny/RxBinding
rxbinding-appcompat-v7-kotlin/src/main/kotlin/com/jakewharton/rxbinding/support/v7/widget/RxSearchView.kt
1
1344
package com.jakewharton.rxbinding.support.v7.widget import android.support.v7.widget.SearchView import rx.Observable import rx.functions.Action1 /** * Create an observable of {@linkplain SearchViewQueryTextEvent query text events} on {@code * view}. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Note:* A value will be emitted immediately on subscribe. */ public inline fun SearchView.queryTextChangeEvents(): Observable<SearchViewQueryTextEvent> = RxSearchView.queryTextChangeEvents(this) /** * Create an observable of character sequences for query text changes on `view`. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * *Note:* A value will be emitted immediately on subscribe. */ public inline fun SearchView.queryTextChanges(): Observable<CharSequence> = RxSearchView.queryTextChanges(this) /** * An action which sets the query property of `view` with character sequences. * * *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe * to free this reference. * * @param submit weather to submit query right after updating query text */ public inline fun SearchView.query(submit: Boolean): Action1<in CharSequence> = RxSearchView.query(this, submit)
apache-2.0
StPatrck/edac
app/src/main/java/com/phapps/elitedangerous/companion/EdacApp.kt
1
1636
package com.phapps.elitedangerous.companion import android.app.Activity import android.app.Application import com.phapps.elitedangerous.companion.di.AppInjector import com.phapps.elitedangerous.edsm.EdsmClient import com.squareup.leakcanary.LeakCanary import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.HasActivityInjector import timber.log.Timber import javax.inject.Inject class EdacApp : Application(), HasActivityInjector { @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity> override fun onCreate() { super.onCreate() if (LeakCanary.isInAnalyzerProcess(this)) { // This process is dedicated to LeakCanary for heap analysis. // You should not init your app in this process. return } Timber.plant(Timber.DebugTree()) Timber.tag("EdacApp") AppInjector.init(this) instance = this LeakCanary.install(this) EdsmClient.init(this) EdsmClient.getInstance().setLoggingEnabled(BuildConfig.DEBUG) EdsmClient.getInstance().setServer(EdsmClient.Server.Production) // FIXME: Should be converted to a bg service like the sync service. // newer Android SDK versions do not allow the job to be created if the app is in the bg. //JobManager.create(this).addJobCreator(EdsmJobCreator(commanderRepo)) } override fun activityInjector(): AndroidInjector<Activity> { return dispatchingAndroidInjector } companion object { lateinit var instance: EdacApp } }
gpl-3.0
Frederikam/FredBoat
FredBoat/src/main/java/fredboat/main/Launcher.kt
1
9699
package fredboat.main import com.sedmelluq.discord.lavaplayer.tools.PlayerLibrary import fredboat.agent.* import fredboat.commandmeta.CommandRegistry import fredboat.config.property.ConfigPropertiesProvider import fredboat.feature.I18n import fredboat.util.AppInfo import fredboat.util.GitRepoState import org.json.JSONObject import org.slf4j.LoggerFactory import org.springframework.boot.ApplicationArguments import org.springframework.boot.ApplicationRunner import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration import org.springframework.boot.context.event.ApplicationFailedEvent import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware import org.springframework.context.ApplicationListener import org.springframework.context.annotation.Bean import org.springframework.context.annotation.ComponentScan import org.springframework.context.support.AbstractApplicationContext import java.io.IOException import java.util.concurrent.ExecutorService import java.util.function.Supplier /** * The class responsible for launching FredBoat */ @SpringBootApplication(exclude = [ // Excluded because we manage these already DataSourceAutoConfiguration::class, DataSourceTransactionManagerAutoConfiguration::class, HibernateJpaAutoConfiguration::class, FlywayAutoConfiguration::class]) @ComponentScan(basePackages = ["fredboat"]) class Launcher( botController: BotController, private val configProvider: ConfigPropertiesProvider, private val executor: ExecutorService, private val statsAgent: StatsAgent, private val invalidationAgent: GuildCacheInvalidationAgent, private val voiceChannelCleanupAgent: VoiceChannelCleanupAgent, private val carbonitexAgent: CarbonitexAgent ) : ApplicationRunner, ApplicationContextAware { init { Launcher.botController = botController } @Throws(InterruptedException::class) override fun run(args: ApplicationArguments) { I18n.start() log.info("Loaded commands, registry size is " + CommandRegistry.getTotalSize()) if (!configProvider.appConfig.isPatronDistribution) { log.info("Starting VoiceChannelCleanupAgent.") FredBoatAgent.start(voiceChannelCleanupAgent) } else { log.info("Skipped setting up the VoiceChannelCleanupAgent") } //Check imgur creds executor.submit{ this.hasValidImgurCredentials() } FredBoatAgent.start(statsAgent) FredBoatAgent.start(invalidationAgent) val carbonKey = configProvider.credentials.carbonKey if (configProvider.appConfig.isMusicDistribution && !carbonKey.isEmpty()) FredBoatAgent.start(carbonitexAgent) //force a count once all shards are up, this speeds up the stats availability on small boats while (areThereNotConnectedShards()) { Thread.sleep(1000) } statsAgent.run() } // ################################################################################ // ## Login / credential tests // ################################################################################ private fun hasValidImgurCredentials(): Boolean { val imgurClientId = configProvider.credentials.imgurClientId if (imgurClientId.isEmpty()) { log.info("Imgur credentials not found. Commands relying on Imgur will not work properly.") return false } val request = BotController.HTTP.get("https://api.imgur.com/3/credits") .auth("Client-ID $imgurClientId") try { request.execute().use { response -> val content = response.body()!!.string() if (response.isSuccessful) { val data = JSONObject(content).getJSONObject("data") //https://api.imgur.com/#limits //at the time of the introduction of this code imgur offers daily 12500 and hourly 500 GET requests for open source software //hitting the daily limit 5 times in a month will blacklist the app for the rest of the month //we use 3 requests per hour (and per restart of the bot), so there should be no problems with imgur's rate limit val hourlyLimit = data.getInt("UserLimit") val hourlyLeft = data.getInt("UserRemaining") val seconds = data.getLong("UserReset") - System.currentTimeMillis() / 1000 val timeTillReset = String.format("%d:%02d:%02d", seconds / 3600, seconds % 3600 / 60, seconds % 60) val dailyLimit = data.getInt("ClientLimit") val dailyLeft = data.getInt("ClientRemaining") log.info("Imgur credentials are valid. " + hourlyLeft + "/" + hourlyLimit + " requests remaining this hour, resetting in " + timeTillReset + ", " + dailyLeft + "/" + dailyLimit + " requests remaining today.") return true } else { log.warn("Imgur login failed with {}\n{}", response.toString(), content) } } } catch (e: IOException) { log.warn("Imgur login failed, it seems to be down.", e) } return false } //returns true if all registered shards are reporting back as CONNECTED, false otherwise private fun areThereNotConnectedShards(): Boolean { return true //TODO //return shardProvider.streamShards() // .anyMatch(shard -> shard.getStatus() != JDA.Status.CONNECTED); } override fun setApplicationContext(applicationContext: ApplicationContext) { springContext = applicationContext as AbstractApplicationContext // Make the launcher available for integration testing instance = this } companion object { lateinit var springContext: AbstractApplicationContext private val log = LoggerFactory.getLogger(Launcher::class.java) val START_TIME = System.currentTimeMillis() lateinit var botController: BotController private set //temporary hack access to the bot context var instance: Launcher? = null private set @Bean fun springContextSupplier() = Supplier { this.springContext as ApplicationContext } @Throws(IllegalArgumentException::class) @JvmStatic fun main(args: Array<String>) { //just post the info to the console if (args.isNotEmpty() && (args[0].equals("-v", ignoreCase = true) || args[0].equals("--version", ignoreCase = true) || args[0].equals("-version", ignoreCase = true))) { println("Version flag detected. Printing version info, then exiting.") println(versionInfo) println("Version info printed, exiting.") return } log.info(versionInfo) val javaVersionMajor = Runtime.version().feature() if (javaVersionMajor != 11) { log.warn("\n\t\t __ ___ ___ _ _ ___ _ _ ___ \n" + "\t\t \\ \\ / /_\\ | _ \\ \\| |_ _| \\| |/ __|\n" + "\t\t \\ \\/\\/ / _ \\| / .` || || .` | (_ |\n" + "\t\t \\_/\\_/_/ \\_\\_|_\\_|\\_|___|_|\\_|\\___|\n" + "\t\t ") log.warn("FredBoat only officially supports Java 11. You are running Java {}", Runtime.version()) } System.setProperty("spring.config.name", "fredboat") System.setProperty("spring.http.converters.preferred-json-mapper", "gson") val app = SpringApplication(Launcher::class.java) app.addListeners(ApplicationListener { event: ApplicationFailedEvent -> log.error("Application failed", event.exception) }) app.run(*args) } private val versionInfo: String get() = ("\n\n" + " ______ _ ____ _ \n" + " | ____| | | _ \\ | | \n" + " | |__ _ __ ___ __| | |_) | ___ __ _| |_ \n" + " | __| '__/ _ \\/ _` | _ < / _ \\ / _` | __|\n" + " | | | | | __/ (_| | |_) | (_) | (_| | |_ \n" + " |_| |_| \\___|\\__,_|____/ \\___/ \\__,_|\\__|\n\n" + "\n\tVersion: " + AppInfo.getAppInfo().VERSION + "\n\tBuild: " + AppInfo.getAppInfo().BUILD_NUMBER + "\n\tCommit: " + GitRepoState.getGitRepositoryState().commitIdAbbrev + " (" + GitRepoState.getGitRepositoryState().branch + ")" + "\n\tCommit time: " + GitRepoState.getGitRepositoryState().commitTime + "\n\tJVM: " + System.getProperty("java.version") + "\n\tLavaplayer " + PlayerLibrary.VERSION + "\n") } } fun getBotController(): BotController = Launcher.botController
mit
dahlstrom-g/intellij-community
plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/gradle/ui/LegacyIsResolveModulePerSourceSetNotification.kt
1
6425
// 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.gradle.ui import com.intellij.notification.* import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.* import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder import com.intellij.openapi.externalSystem.util.ExternalSystemUtil import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.util.PlatformUtils import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.util.KotlinPlatformUtils import org.jetbrains.kotlin.idea.configuration.GRADLE_SYSTEM_ID import org.jetbrains.plugins.gradle.settings.GradleProjectSettings import org.jetbrains.plugins.gradle.settings.GradleSettings import java.lang.ref.WeakReference private var previouslyShownNotification = WeakReference<Notification>(null) fun notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded(projectPath: String) { notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded( ProjectManager.getInstance().openProjects.firstOrNull { it.basePath == projectPath } ?: return ) } fun notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded(project: Project) { notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded( project = project, notificationSuppressState = SuppressResolveModulePerSourceSetNotificationState.default(project), isResolveModulePerSourceSetSetting = IsResolveModulePerSourceSetSetting.default(project), ) } fun notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded( project: Project, notificationSuppressState: SuppressResolveModulePerSourceSetNotificationState, isResolveModulePerSourceSetSetting: IsResolveModulePerSourceSetSetting ) { if (KotlinPlatformUtils.isAndroidStudio || PlatformUtils.isMobileIde() || PlatformUtils.isAppCode()) return if (notificationSuppressState.isSuppressed) return if (isResolveModulePerSourceSetSetting.isResolveModulePerSourceSet) return if (previouslyShownNotification.get()?.isExpired == false) return val notification = createNotification(notificationSuppressState, isResolveModulePerSourceSetSetting) notification.notify(project) previouslyShownNotification = WeakReference(notification) } private fun createNotification( notificationSuppressState: SuppressResolveModulePerSourceSetNotificationState, isResolveModulePerSourceSetSetting: IsResolveModulePerSourceSetSetting ): Notification { NotificationsConfiguration.getNotificationsConfiguration().register( KOTLIN_UPDATE_IS_RESOLVE_MODULE_PER_SOURCE_SET_GROUP_ID, NotificationDisplayType.STICKY_BALLOON, true ) return Notification( KOTLIN_UPDATE_IS_RESOLVE_MODULE_PER_SOURCE_SET_GROUP_ID, KotlinBundle.message("configuration.is.resolve.module.per.source.set"), KotlinBundle.htmlMessage("configuration.update.is.resolve.module.per.source.set"), NotificationType.WARNING ).apply { isSuggestionType = true addAction(createUpdateGradleProjectSettingsAction(isResolveModulePerSourceSetSetting)) addAction(createSuppressNotificationAction(notificationSuppressState)) isImportant = true } } private fun createUpdateGradleProjectSettingsAction( isResolveModulePerSourceSetSetting: IsResolveModulePerSourceSetSetting ) = NotificationAction.create( KotlinBundle.message("configuration.apply.is.resolve.module.per.source.set"), ) { event: AnActionEvent, notification: Notification -> notification.expire() val project = event.project ?: return@create if (project.isDisposed) return@create runWriteAction { isResolveModulePerSourceSetSetting.isResolveModulePerSourceSet = true ExternalSystemUtil.refreshProjects(ImportSpecBuilder(project, GRADLE_SYSTEM_ID)) } } private fun createSuppressNotificationAction( notificationSuppressState: SuppressResolveModulePerSourceSetNotificationState ) = NotificationAction.create( KotlinBundle.message("configuration.do.not.suggest.update.is.resolve.module.per.source.set") ) { event: AnActionEvent, notification: Notification -> notification.expire() val project = event.project ?: return@create if (project.isDisposed) return@create runWriteAction { notificationSuppressState.isSuppressed = true } } private val Project.gradleProjectSettings: List<GradleProjectSettings> get() = GradleSettings.getInstance(this).linkedProjectsSettings.toList() /* Accessing "isResolveModulePerSourceSet" setting */ interface IsResolveModulePerSourceSetSetting { var isResolveModulePerSourceSet: Boolean companion object { fun default(project: Project): IsResolveModulePerSourceSetSetting = ProjectIsResolveModulePerSourceSetSetting(project) } } private class ProjectIsResolveModulePerSourceSetSetting(private val project: Project) : IsResolveModulePerSourceSetSetting { override var isResolveModulePerSourceSet: Boolean get() = project.gradleProjectSettings.all { it.isResolveModulePerSourceSet } set(value) = project.gradleProjectSettings.forEach { it.isResolveModulePerSourceSet = value } } /* Storing State about Notification Suppress */ interface SuppressResolveModulePerSourceSetNotificationState { var isSuppressed: Boolean companion object { fun default(project: Project): SuppressResolveModulePerSourceSetNotificationState = IdeResolveModulePerSourceSetComponent.getInstance(project).state } } private class IdeSuppressResolveModulePerSourceSetNotificationState : BaseState(), SuppressResolveModulePerSourceSetNotificationState { override var isSuppressed: Boolean by property(false) } @Service @State(name = "SuppressResolveModulePerSourceSetNotification") private class IdeResolveModulePerSourceSetComponent : SimplePersistentStateComponent<IdeSuppressResolveModulePerSourceSetNotificationState>( IdeSuppressResolveModulePerSourceSetNotificationState() ) { companion object { fun getInstance(project: Project): IdeResolveModulePerSourceSetComponent = project.service() } } const val KOTLIN_UPDATE_IS_RESOLVE_MODULE_PER_SOURCE_SET_GROUP_ID = "Update isResolveModulePerSourceSet setting"
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/fun/genericWithTypeVariables/FunGenericParam.kt
10
35
package test fun <T> f(): Int = 1
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/kdoc/resolve/AmbiguousReferenceTypeParameter.kt
13
138
class C { class TT { } /** * The [T<caret>T] references a type parameter. */ class D<TT> { } } // REF: TT
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/repl/src/org/jetbrains/kotlin/console/gutter/ReplIcons.kt
5
2032
// 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.console.gutter import com.intellij.icons.AllIcons import com.intellij.openapi.util.NlsContexts import org.jetbrains.kotlin.KotlinIdeaReplBundle import org.jetbrains.kotlin.idea.KotlinIcons import javax.swing.Icon data class IconWithTooltip(val icon: Icon, @NlsContexts.Tooltip val tooltip: String?) object ReplIcons { val BUILD_WARNING_INDICATOR: IconWithTooltip = IconWithTooltip(AllIcons.General.Warning, null) val HISTORY_INDICATOR: IconWithTooltip = IconWithTooltip( AllIcons.Vcs.History, KotlinIdeaReplBundle.message("icon.tool.tip.history.of.executed.commands") ) val EDITOR_INDICATOR: IconWithTooltip = IconWithTooltip( KotlinIcons.LAUNCH, KotlinIdeaReplBundle.message("icon.tool.tip.write.your.commands.here") ) val EDITOR_READLINE_INDICATOR: IconWithTooltip = IconWithTooltip( AllIcons.General.Balloon, KotlinIdeaReplBundle.message("icon.tool.tip.waiting.for.input") ) val COMMAND_MARKER: IconWithTooltip = IconWithTooltip( AllIcons.RunConfigurations.TestState.Run, KotlinIdeaReplBundle.message("icon.tool.tip.executed.command") ) val READLINE_MARKER: IconWithTooltip = IconWithTooltip( AllIcons.Debugger.PromptInput, KotlinIdeaReplBundle.message("icon.tool.tip.input.line") ) // command result icons val SYSTEM_HELP: IconWithTooltip = IconWithTooltip(AllIcons.Actions.Help, KotlinIdeaReplBundle.message("icon.tool.tip.system.help")) val RESULT: IconWithTooltip = IconWithTooltip(AllIcons.Vcs.Equal, KotlinIdeaReplBundle.message("icon.tool.tip.result")) val COMPILER_ERROR: Icon = AllIcons.General.Error val RUNTIME_EXCEPTION: IconWithTooltip = IconWithTooltip( AllIcons.General.BalloonWarning, KotlinIdeaReplBundle.message("icon.tool.tip.runtime.exception") ) }
apache-2.0
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/util/Lists.kt
1
1706
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.jonathanxd.kores.util inline fun <T> List<T>.bothMatches(other: List<T>, predicate: (T, T) -> Boolean): Boolean { if (this.size != other.size) return false return this.indices.all { predicate(this[it], other[it]) } }
mit
mikepenz/FastAdapter
app/src/main/java/com/mikepenz/fastadapter/app/view/RecyclerViewBackgroundDrawable.kt
1
1447
package com.mikepenz.fastadapter.app.view import android.graphics.Canvas import android.graphics.ColorFilter import android.graphics.Paint import android.graphics.PixelFormat import android.graphics.drawable.Drawable import androidx.recyclerview.widget.RecyclerView // Based on https://stackoverflow.com/a/49825927/1800174 class RecyclerViewBackgroundDrawable internal constructor(private val color: Int) : Drawable() { private var recyclerView: RecyclerView? = null private val paint: Paint = Paint().apply { color = [email protected] } fun attachTo(recyclerView: RecyclerView?) { this.recyclerView = recyclerView recyclerView?.background = this } override fun draw(canvas: Canvas) { val recyclerView = recyclerView ?: return if (recyclerView.childCount == 0) { return } var bottom = recyclerView.getChildAt(recyclerView.childCount - 1).bottom if (bottom >= recyclerView.bottom) { bottom = recyclerView.bottom } canvas.drawRect( recyclerView.left.toFloat(), recyclerView.top.toFloat(), recyclerView.right.toFloat(), bottom.toFloat(), paint ) } override fun setAlpha(alpha: Int) = Unit override fun setColorFilter(colorFilter: ColorFilter?) = Unit override fun getOpacity(): Int = PixelFormat.OPAQUE }
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/modifiers/nestedSealedClass.kt
12
232
// "Add 'inner' modifier" "false" // ACTION: Convert to enum class // ACTION: Create test // ACTION: Implement sealed class // ERROR: Class is not allowed here class A() { inner class B() { sealed class <caret>C } }
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/LookupCancelWatcher.kt
8
986
// 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.completion import com.intellij.codeInsight.lookup.Lookup import com.intellij.codeInsight.lookup.LookupManagerListener import com.intellij.openapi.editor.event.EditorFactoryEvent import com.intellij.openapi.editor.event.EditorFactoryListener class LookupCancelWatcher : EditorFactoryListener { override fun editorReleased(event: EditorFactoryEvent) { val editor = event.editor val project = editor.project ?: return LookupCancelService.getServiceIfCreated(project)?.disposeLastReminiscence(editor) } } class LookupCancelWatcherListener : LookupManagerListener { override fun activeLookupChanged(oldLookup: Lookup?, newLookup: Lookup?) { if (newLookup == null) return newLookup.addLookupListener(LookupCancelService.getInstance(newLookup.project).lookupCancelListener) } }
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/autoImports/importAliasPropertyAlreadyExists.before.Main.kt
7
175
// "Import" "true" // ERROR: Unresolved reference: importedValA import editor.completion.apx.importedValA as valA fun context() { <caret>importedValA() } /* IGNORE_FIR */
apache-2.0
dahlstrom-g/intellij-community
platform/markdown-utils/src/com/intellij/markdown/utils/lang/CodeBlockHtmlSyntaxHighlighter.kt
9
969
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.markdown.utils.lang import com.intellij.lang.Language import com.intellij.markdown.utils.lang.HtmlSyntaxHighlighter.Companion.colorHtmlChunk import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.HtmlChunk class CodeBlockHtmlSyntaxHighlighter( private val project: Project? ) : HtmlSyntaxHighlighter { override fun color(language: String?, @NlsSafe rawContent: String): HtmlChunk { return findRegisteredLanguage(language)?.let { colorHtmlChunk(project, it, rawContent).wrapWith("pre") } ?: HtmlChunk.text(rawContent) } private fun findRegisteredLanguage(language: String?): Language? = Language.getRegisteredLanguages() .singleOrNull { registeredLanguage -> registeredLanguage.id.lowercase() == language?.lowercase() } }
apache-2.0
phylame/jem
commons/src/main/kotlin/jclp/vdm/VdmSpec.kt
1
3025
/* * Copyright 2015-2017 Peng Wan <[email protected]> * * This file is part of Jem. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jclp.vdm import jclp.KeyedService import jclp.ServiceManager import jclp.VariantMap import jclp.io.Flob import jclp.text.Text import java.io.Closeable import java.io.InputStream import java.io.OutputStream import java.nio.charset.Charset interface VdmEntry { val name: String val comment: String? val lastModified: Long val isDirectory: Boolean } interface VdmReader : Closeable { val name: String val comment: String? fun getEntry(name: String): VdmEntry? fun getInputStream(entry: VdmEntry): InputStream val entries: Iterator<VdmEntry> val size: Int } fun VdmReader.openStream(name: String) = getEntry(name)?.let { getInputStream(it) } fun VdmReader.readBytes(name: String, estimatedSize: Int = DEFAULT_BUFFER_SIZE): ByteArray? = openStream(name)?.use { it.readBytes(estimatedSize) } fun VdmReader.readText(name: String, charset: Charset = Charsets.UTF_8): String? = openStream(name)?.use { it.reader(charset).readText() } interface VdmWriter : Closeable { fun setComment(comment: String) fun newEntry(name: String): VdmEntry fun putEntry(entry: VdmEntry): OutputStream fun closeEntry(entry: VdmEntry) } inline fun <R> VdmWriter.useStream(name: String, block: (OutputStream) -> R): R { return with(newEntry(name)) { val stream = putEntry(this) try { block(stream) } finally { closeEntry(this) } } } fun VdmWriter.writeBytes(name: String, data: ByteArray) = useStream(name) { it.write(data) } fun VdmWriter.writeFlob(name: String, flob: Flob) = useStream(name) { flob.writeTo(it) it.flush() } fun VdmWriter.writeText(name: String, text: Text, charset: Charset = Charsets.UTF_8) = useStream(name) { with(it.writer(charset)) { text.writeTo(this) flush() } } interface VdmFactory : KeyedService { fun getReader(input: Any, props: VariantMap): VdmReader fun getWriter(output: Any, props: VariantMap): VdmWriter } object VdmManager : ServiceManager<VdmFactory>(VdmFactory::class.java) { fun openReader(name: String, input: Any, props: VariantMap = emptyMap()): VdmReader? = get(name)?.getReader(input, props) fun openWriter(name: String, output: Any, props: VariantMap = emptyMap()): VdmWriter? = get(name)?.getWriter(output, props) }
apache-2.0
openium/auvergne-webcams-droid
app/src/debug/java/fr/openium/auvergnewebcams/di/DebugModules.kt
1
4315
package fr.openium.auvergnewebcams.di import android.content.Context import com.google.gson.ExclusionStrategy import com.google.gson.FieldAttributes import com.google.gson.GsonBuilder import fr.openium.auvergnewebcams.model.AWClient import fr.openium.auvergnewebcams.rest.AWApi import fr.openium.auvergnewebcams.rest.MockApi import fr.openium.auvergnewebcams.rest.model.SectionList import io.reactivex.Single import io.reactivex.schedulers.Schedulers import okhttp3.HttpUrl import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.kodein.di.Kodein import org.kodein.di.generic.bind import org.kodein.di.generic.instance import org.kodein.di.generic.provider import org.kodein.di.generic.singleton import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.mock.Calls import retrofit2.mock.MockRetrofit import retrofit2.mock.NetworkBehavior import java.io.InputStreamReader import java.util.concurrent.TimeUnit /** * Created by Openium on 19/02/2019. */ object DebugModules { const val mock = false val configModule = Kodein.Module("Config module") { } val serviceModule = Kodein.Module("Service module") { } val databaseService = Kodein.Module("Database Module") { bind<AWClient>(overrides = true) with provider { AWClient.getInstance(instance()) } } val restModule = Kodein.Module("REST module") { bind<OkHttpClient>(overrides = true) with provider { OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) .cache(instance()) .build() } bind<Retrofit>(overrides = true) with singleton { Retrofit.Builder() .baseUrl(instance<HttpUrl>()).client(instance()) .addConverterFactory(GsonConverterFactory.create(instance())) .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io())) .build() } bind<AWApi>(overrides = true) with provider { if (mock) { val networkBehaviour = NetworkBehavior.create() networkBehaviour.setDelay(0, TimeUnit.MILLISECONDS) networkBehaviour.setFailurePercent(0) networkBehaviour.setVariancePercent(0) val apiMock = object : MockApi() { override fun getSections(): Single<SectionList> { val thisValue = instance<Context>().assets.open("aw-config.json") val reader = InputStreamReader(thisValue) val sObjectMapper = GsonBuilder() .setExclusionStrategies(object : ExclusionStrategy { override fun shouldSkipClass(clazz: Class<*>?): Boolean { return false } override fun shouldSkipField(f: FieldAttributes): Boolean { return f.declaredClass == SectionList::class.java } }) .serializeNulls() .create() val listLoaded = sObjectMapper.fromJson(reader, SectionList::class.java) as SectionList return delegate.returning(Calls.response(listLoaded)).getSections() } } apiMock.delegate = MockRetrofit.Builder( Retrofit.Builder() .baseUrl(instance<HttpUrl>()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() ) .networkBehavior(networkBehaviour) .build().create(AWApi::class.java) apiMock } else { instance<Retrofit>().create(AWApi::class.java) } } } val repositoryModule = Kodein.Module("Repository Module") { } }
mit
tateisu/SubwayTooter
app/src/main/java/jp/juggler/util/PrimitiveUtils.kt
1
2774
package jp.juggler.util //////////////////////////////////////////////////////////////////// // Comparable fun <T : Comparable<T>> clipRange(min: T, max: T, src: T) = if (src < min) min else if (src > max) max else src //////////////////////////////////////////////////////////////////// // usage: number.notZero() ?: fallback // equivalent: if(this != 0 ) this else null fun Int.notZero(): Int? = if (this != 0) this else null fun Long.notZero(): Long? = if (this != 0L) this else null fun Float.notZero(): Float? = if (this != 0f) this else null fun Double.notZero(): Double? = if (this != .0) this else null // usage: boolean.truth() ?: fallback() // equivalent: if(this != 0 ) this else null // fun Boolean.truth() : Boolean? = if(this) this else null //////////////////////////////////////////////////////////////////// // long //////////////////////////////////////////////////////////////////// // float fun Float.abs(): Float = kotlin.math.abs(this) //@SuppressLint("DefaultLocale") //fun Long.formatTimeDuration() : String { // var t = this // val sb = StringBuilder() // var n : Long // // day // n = t / 86400000L // if(n > 0) { // sb.append(String.format(Locale.JAPAN, "%dd", n)) // t -= n * 86400000L // } // // h // n = t / 3600000L // if(n > 0 || sb.isNotEmpty()) { // sb.append(String.format(Locale.JAPAN, "%dh", n)) // t -= n * 3600000L // } // // m // n = t / 60000L // if(n > 0 || sb.isNotEmpty()) { // sb.append(String.format(Locale.JAPAN, "%dm", n)) // t -= n * 60000L // } // // s // val f = t / 1000f // sb.append(String.format(Locale.JAPAN, "%.03fs", f)) // // return sb.toString() //} //private val bytesSizeFormat = DecimalFormat("#,###") //fun Long.formatBytesSize() = Utils.bytesSizeFormat.format(this) // StringBuilder sb = new StringBuilder(); // long n; // // giga // n = t / 1000000000L; // if( n > 0 ){ // sb.append( String.format( Locale.JAPAN, "%dg", n ) ); // t -= n * 1000000000L; // } // // Mega // n = t / 1000000L; // if( sb.length() > 0 ){ // sb.append( String.format( Locale.JAPAN, "%03dm", n ) ); // t -= n * 1000000L; // }else if( n > 0 ){ // sb.append( String.format( Locale.JAPAN, "%dm", n ) ); // t -= n * 1000000L; // } // // kilo // n = t / 1000L; // if( sb.length() > 0 ){ // sb.append( String.format( Locale.JAPAN, "%03dk", n ) ); // t -= n * 1000L; // }else if( n > 0 ){ // sb.append( String.format( Locale.JAPAN, "%dk", n ) ); // t -= n * 1000L; // } // // length // if( sb.length() > 0 ){ // sb.append( String.format( Locale.JAPAN, "%03d", t ) ); // }else if( n > 0 ){ // sb.append( String.format( Locale.JAPAN, "%d", t ) ); // } // // return sb.toString();
apache-2.0
TechzoneMC/SonarPet
api/src/main/kotlin/com/dsh105/echopet/compat/api/entity/type/pet/IGuardianPet.kt
1
160
package com.dsh105.echopet.compat.api.entity.type.pet import com.dsh105.echopet.compat.api.entity.IPet interface IGuardianPet: IPet { var elder: Boolean }
gpl-3.0
mapzen/android
samples/mapzen-sample/src/test/java/mapzen/com/sdksampleapp/models/SearchSampleListTest.kt
1
324
package mapzen.com.sdksampleapp.models import mapzen.com.sdksampleapp.models.SearchSampleList.Companion.SEARCH_SAMPLES import org.assertj.core.api.Assertions.assertThat import org.junit.Test class SearchSampleListTest { @Test fun searchSamplesContainsCorrectSamples() { assertThat(SEARCH_SAMPLES).isEmpty() } }
apache-2.0
TheMrMilchmann/lwjgl3
modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/AMD_texture_gather_bias_lod.kt
1
5096
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package vulkan.templates import org.lwjgl.generator.* import vulkan.* val AMD_texture_gather_bias_lod = "AMDTextureGatherBiasLod".nativeClassVK("AMD_texture_gather_bias_lod", type = "device", postfix = "AMD") { documentation = """ This extension adds two related features. Firstly, support for the following SPIR-V extension in Vulkan is added: <ul> <li>{@code SPV_AMD_texture_gather_bias_lod}</li> </ul> Secondly, the extension allows the application to query which formats can be used together with the new function prototypes introduced by the SPIR-V extension. <h5>Examples</h5> <pre><code> ￿struct VkTextureLODGatherFormatPropertiesAMD ￿{ ￿ VkStructureType sType; ￿ const void* pNext; ￿ VkBool32 supportsTextureGatherLODBiasAMD; ￿}; ￿ ￿// ---------------------------------------------------------------------------------------- ￿// How to detect if an image format can be used with the new function prototypes. ￿VkPhysicalDeviceImageFormatInfo2 formatInfo; ￿VkImageFormatProperties2 formatProps; ￿VkTextureLODGatherFormatPropertiesAMD textureLODGatherSupport; ￿ ￿textureLODGatherSupport.sType = VK_STRUCTURE_TYPE_TEXTURE_LOD_GATHER_FORMAT_PROPERTIES_AMD; ￿textureLODGatherSupport.pNext = nullptr; ￿ ￿formatInfo.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2; ￿formatInfo.pNext = nullptr; ￿formatInfo.format = ...; ￿formatInfo.type = ...; ￿formatInfo.tiling = ...; ￿formatInfo.usage = ...; ￿formatInfo.flags = ...; ￿ ￿formatProps.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2; ￿formatProps.pNext = &amp;textureLODGatherSupport; ￿ ￿vkGetPhysicalDeviceImageFormatProperties2(physical_device, &amp;formatInfo, &amp;formatProps); ￿ ￿if (textureLODGatherSupport.supportsTextureGatherLODBiasAMD == VK_TRUE) ￿{ ￿ // physical device supports SPV_AMD_texture_gather_bias_lod for the specified ￿ // format configuration. ￿} ￿else ￿{ ￿ // physical device does not support SPV_AMD_texture_gather_bias_lod for the ￿ // specified format configuration. ￿}</code></pre> <h5>VK_AMD_texture_gather_bias_lod</h5> <dl> <dt><b>Name String</b></dt> <dd>{@code VK_AMD_texture_gather_bias_lod}</dd> <dt><b>Extension Type</b></dt> <dd>Device extension</dd> <dt><b>Registered Extension Number</b></dt> <dd>42</dd> <dt><b>Revision</b></dt> <dd>1</dd> <dt><b>Extension and Version Dependencies</b></dt> <dd><ul> <li>Requires support for Vulkan 1.0</li> <li>Requires {@link KHRGetPhysicalDeviceProperties2 VK_KHR_get_physical_device_properties2} to be enabled for any device-level functionality</li> </ul></dd> <dt><b>Contact</b></dt> <dd><ul> <li>Rex Xu <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_AMD_texture_gather_bias_lod]%20@amdrexu%250A%3C%3CHere%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_AMD_texture_gather_bias_lod%20extension%3E%3E">amdrexu</a></li> </ul></dd> </dl> <h5>Other Extension Metadata</h5> <dl> <dt><b>Last Modified Date</b></dt> <dd>2017-03-21</dd> <dt><b>IP Status</b></dt> <dd>No known IP claims.</dd> <dt><b>Interactions and External Dependencies</b></dt> <dd><ul> <li>This extension requires <a target="_blank" href="https://htmlpreview.github.io/?https://github.com/KhronosGroup/SPIRV-Registry/blob/master/extensions/AMD/SPV_AMD_texture_gather_bias_lod.html">{@code SPV_AMD_texture_gather_bias_lod}</a></li> <li>This extension provides API support for <a target="_blank" href="https://www.khronos.org/registry/OpenGL/extensions/AMD/AMD_texture_gather_bias_lod.txt">{@code GL_AMD_texture_gather_bias_lod}</a></li> </ul></dd> <dt><b>Contributors</b></dt> <dd><ul> <li>Dominik Witczak, AMD</li> <li>Daniel Rakos, AMD</li> <li>Graham Sellers, AMD</li> <li>Matthaeus G. Chajdas, AMD</li> <li>Qun Lin, AMD</li> <li>Rex Xu, AMD</li> <li>Timothy Lottes, AMD</li> </ul></dd> </dl> """ IntConstant( "The extension specification version.", "AMD_TEXTURE_GATHER_BIAS_LOD_SPEC_VERSION".."1" ) StringConstant( "The extension name.", "AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME".."VK_AMD_texture_gather_bias_lod" ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_TEXTURE_LOD_GATHER_FORMAT_PROPERTIES_AMD".."1000041000" ) }
bsd-3-clause
audit4j/audit4j-demo
audit4j-kotlin-demo-springboot/src/test/kotlin/org/springframework/samples/petclinic/owner/VisitControllerTests.kt
1
2619
package org.springframework.samples.petclinic.owner import org.mockito.BDDMockito.given; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.samples.petclinic.owner.Pet; import org.springframework.samples.petclinic.owner.PetRepository; import org.springframework.samples.petclinic.owner.VisitController; import org.springframework.samples.petclinic.visit.VisitRepository; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; /** * Test class for {@link VisitController} * * @author Colin But */ @RunWith(SpringRunner::class) @WebMvcTest(VisitController::class) class VisitControllerTests { companion object { const val TEST_PET_ID = 1 } @Autowired lateinit private var mockMvc : MockMvc @MockBean lateinit private var visits: VisitRepository @MockBean lateinit private var pets: PetRepository @Before fun init() { given(pets.findById(TEST_PET_ID)).willReturn(Pet()) } @Test fun testInitNewVisitForm() { mockMvc.perform(get("/owners/*/pets/{petId}/visits/new", TEST_PET_ID)) .andExpect(status().isOk()) .andExpect(view().name("pets/createOrUpdateVisitForm")); } @Test fun testProcessNewVisitFormSuccess() { mockMvc.perform(post("/owners/*/pets/{petId}/visits/new", TEST_PET_ID) .param("name", "George") .param("description", "Visit Description") ) .andExpect(status().is3xxRedirection()) .andExpect(view().name("redirect:/owners/{ownerId}")); } @Test fun testProcessNewVisitFormHasErrors() { mockMvc.perform(post("/owners/*/pets/{petId}/visits/new", TEST_PET_ID) .param("name", "George") ) .andExpect(model().attributeHasErrors("visit")) .andExpect(status().isOk()) .andExpect(view().name("pets/createOrUpdateVisitForm")); } }
apache-2.0
opst-miyatay/LightCalendarView
library/src/main/kotlin/jp/co/recruit_mp/android/lightcalendarview/CellLayout.kt
2
4213
/* * Copyright (C) 2016 RECRUIT MARKETING PARTNERS CO., LTD. * * 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 jp.co.recruit_mp.android.lightcalendarview import android.content.Context import android.support.v4.view.ViewCompat import android.view.View import android.view.ViewGroup /** * 子ビューをグリッド状に配置する {@link ViewGroup} * Created by masayuki-recruit on 8/19/16. */ abstract class CellLayout(context: Context, protected val settings: CalendarSettings) : ViewGroup(context) { abstract val rowNum: Int abstract val colNum: Int override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val (specWidthSize, specWidthMode) = Measure.createFromSpec(widthMeasureSpec) val (specHeightSize, specHeightMode) = Measure.createFromSpec(heightMeasureSpec) // 自分の大きさを確定 val minSide = when { specWidthMode == MeasureSpec.UNSPECIFIED && specHeightMode == MeasureSpec.UNSPECIFIED -> throw IllegalStateException("CellLayout can never be left to determine its size") specWidthMode == MeasureSpec.UNSPECIFIED -> specHeightSize / rowNum specHeightMode == MeasureSpec.UNSPECIFIED -> specWidthSize / colNum else -> Math.min(specWidthSize / colNum, specHeightSize / rowNum) } val minWidth = minSide * colNum val minHeight = minSide * rowNum val selfMeasuredWidth = when (specWidthMode) { MeasureSpec.EXACTLY -> specWidthSize MeasureSpec.AT_MOST -> Math.min(minWidth, specWidthSize) MeasureSpec.UNSPECIFIED -> minWidth else -> specWidthSize } val selfMeasuredHeight = when (specHeightMode) { MeasureSpec.EXACTLY -> specHeightSize MeasureSpec.AT_MOST -> Math.min(minHeight, specHeightSize) MeasureSpec.UNSPECIFIED -> minHeight else -> specHeightSize } setMeasuredDimension(selfMeasuredWidth, selfMeasuredHeight) // 子ビューを measure val childMeasuredWidth = selfMeasuredWidth / colNum val childMeasuredHeight = selfMeasuredHeight / rowNum val childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childMeasuredWidth, MeasureSpec.AT_MOST) val childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childMeasuredHeight, MeasureSpec.AT_MOST) childList.forEach { it.measure(childWidthMeasureSpec, childHeightMeasureSpec) } } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { // セルを中央に配置する為に、上下左右のマージンを計算 val offsetTop: Int = (measuredHeight % rowNum) / 2 val offsetStart: Int = (measuredWidth % colNum) / 2 val parentTop: Int = paddingTop val parentStart: Int = ViewCompat.getPaddingStart(this) // RTL かどうか判定 val isRtl: Boolean = (layoutDirection == View.LAYOUT_DIRECTION_RTL) // 各セルを配置 childList.forEachIndexed { i, child -> val x: Int = i % colNum val y: Int = i / colNum val childWidth: Int = child.measuredWidth val childHeight: Int = child.measuredHeight val childTop: Int = parentTop + offsetTop + (y * childHeight) val childStart: Int = parentStart + offsetStart + (x * childWidth) val childLeft: Int = if (isRtl) { r - childStart - childWidth } else { childStart } child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight) } } }
apache-2.0
gmariotti/kotlin-koans
lesson1/task6/src/Task.kt
2
116
val month = "(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)" fun getPattern(): String = """\d{2} $month \d{4}"""
mit
paplorinc/intellij-community
platform/platform-tests/testSrc/com/intellij/openapi/editor/colors/EditorColorSchemeTest.kt
1
2604
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.editor.colors import com.intellij.configurationStore.schemeManager.SchemeManagerFactoryBase import com.intellij.ide.ui.UISettings import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager import com.intellij.openapi.editor.colors.impl.AbstractColorsScheme import com.intellij.openapi.editor.colors.impl.EditorColorsManagerImpl import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.assertions.Assertions.assertThat import com.intellij.testFramework.rules.InMemoryFsRule import com.intellij.util.io.readText import com.intellij.util.io.write import org.junit.ClassRule import org.junit.Rule import org.junit.Test class EditorColorSchemeTest { companion object { @JvmField @ClassRule val projectRule = ProjectRule() } @JvmField @Rule val fsRule = InMemoryFsRule() @Test fun loadSchemes() { val schemeFile = fsRule.fs.getPath("colors/Foo.icls") val schemeData = """ <scheme name="Foo" version="142" parent_scheme="Default"> <option name="EDITOR_FONT_SIZE" value="12" /> <option name="EDITOR_FONT_NAME" value="Menlo" /> <option name="JAVA_NUMBER" baseAttributes="DEFAULT_NUMBER" /> </scheme>""".trimIndent() schemeFile.write(schemeData) val schemeManagerFactory = SchemeManagerFactoryBase.TestSchemeManagerFactory(fsRule.fs.getPath("")) val manager = EditorColorsManagerImpl(DefaultColorSchemesManager.getInstance(), schemeManagerFactory) val scheme = manager.getScheme("Foo") assertThat(scheme.name).isEqualTo("Foo") (scheme as AbstractColorsScheme).setSaveNeeded(true) schemeManagerFactory.save() // JAVA_NUMBER is removed - see isParentOverwritingInheritance assertThat(removeSchemeMetaInfo(schemeFile.readText())).isEqualTo(""" <scheme name="Foo" version="142" parent_scheme="Default"> <option name="FONT_SCALE" value="${UISettings.defFontScale}" /> <option name="LINE_SPACING" value="1.2" /> <option name="EDITOR_FONT_SIZE" value="12" /> <option name="EDITOR_FONT_NAME" value="${scheme.editorFontName}" /> </scheme>""".trimIndent()) assertThat(schemeFile.parent).hasChildren("Foo.icls") // test reload val schemeNamesBeforeReload = manager.schemeManager.allSchemes.map { it.name } schemeManagerFactory.process { it.reload() } assertThat(manager.schemeManager.allSchemes.map { it.name }).isEqualTo(schemeNamesBeforeReload) } }
apache-2.0
jstuyts/kotlin-multiplatform-recipes
common/src/main/kotlin/mp/MultiPlatformCloseableInterfaceHeader.kt
1
155
package mp /** * An interface that is multi-platform, i.e. the implementation differs per platform. */ expect interface MpCloseable { fun close() }
mit
apoi/quickbeer-next
app/src/main/java/quickbeer/android/domain/idlist/store/IdListEntity.kt
2
625
package quickbeer.android.domain.idlist.store import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.TypeConverters import org.threeten.bp.ZonedDateTime import quickbeer.android.data.room.converter.IntListConverter import quickbeer.android.data.room.converter.ZonedDateTimeConverter @Entity(tableName = "lists") @TypeConverters(value = [IntListConverter::class, ZonedDateTimeConverter::class]) class IdListEntity( @PrimaryKey val id: String, @ColumnInfo(name = "values") val values: List<Int>, @ColumnInfo(name = "updated") val updated: ZonedDateTime )
gpl-3.0
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/UniqueMapper.kt
1
2808
package org.runestar.client.updater.mapper import kotlin.reflect.KClass abstract class UniqueMapper<T> : Mapper<T>(), InstructionResolver<T> { abstract val method: Method2 override fun match(jar: Jar2): T { return method.instructions.filter(predicate).mapTo(HashSet()) { resolve(it) }.single() } abstract val predicate: Predicate<Instruction2> abstract class InMethod<T>(val methodMapper: KClass<out Mapper<Method2>>) : UniqueMapper<T>() { override val method get() = context.methods.getValue(methodMapper) abstract class Class( methodMapper: KClass<out Mapper<Method2>> ) : InMethod<Class2>(methodMapper), ElementMatcher.Class, InstructionResolver.Class abstract class Field( methodMapper: KClass<out Mapper<Method2>> ) : InMethod<Field2>(methodMapper), ElementMatcher.Field, InstructionResolver.Field abstract class Method( methodMapper: KClass<out Mapper<Method2>> ) : InMethod<Method2>(methodMapper), ElementMatcher.Method, InstructionResolver.Method } abstract class InConstructor<T>(val classMapper: KClass<out Mapper<Class2>>) : UniqueMapper<T>() { override val method: Method2 get() { return context.classes.getValue(classMapper).constructors.single(constructorPredicate) } open val constructorPredicate = predicateOf<Method2> { true } abstract class Class( classMapper: KClass<out Mapper<Class2>> ) : InConstructor<Class2>(classMapper), ElementMatcher.Class, InstructionResolver.Class abstract class Field( classMapper: KClass<out Mapper<Class2>> ) : InConstructor<Field2>(classMapper), ElementMatcher.Field, InstructionResolver.Field abstract class Method( classMapper: KClass<out Mapper<Class2>> ) : InConstructor<Method2>(classMapper), ElementMatcher.Method, InstructionResolver.Method } abstract class InClassInitializer<T>(val classMapper: KClass<out Mapper<Class2>>) : UniqueMapper<T>() { override val method: Method2 get() { return context.classes.getValue(classMapper).classInitializer!! } abstract class Class( classMapper: KClass<out Mapper<Class2>> ) : InClassInitializer<Class2>(classMapper), ElementMatcher.Class, InstructionResolver.Class abstract class Field( classMapper: KClass<out Mapper<Class2>> ) : InClassInitializer<Field2>(classMapper), ElementMatcher.Field, InstructionResolver.Field abstract class Method( classMapper: KClass<out Mapper<Class2>> ) : InClassInitializer<Method2>(classMapper), ElementMatcher.Method, InstructionResolver.Method } }
mit
google/intellij-community
plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/findUsages/KotlinFindUsagesSupport.kt
2
3272
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.findUsages import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.psi.PsiConstructorCall import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.Processor import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtObjectDeclaration import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType interface KotlinFindUsagesSupport { companion object { fun getInstance(project: Project): KotlinFindUsagesSupport = project.service() val KtParameter.isDataClassComponentFunction: Boolean get() = getInstance(project).isDataClassComponentFunction(this) fun processCompanionObjectInternalReferences( companionObject: KtObjectDeclaration, referenceProcessor: Processor<PsiReference> ): Boolean = getInstance(companionObject.project).processCompanionObjectInternalReferences(companionObject, referenceProcessor) fun getTopMostOverriddenElementsToHighlight(target: PsiElement): List<PsiElement> = getInstance(target.project).getTopMostOverriddenElementsToHighlight(target) fun tryRenderDeclarationCompactStyle(declaration: KtDeclaration): String? = getInstance(declaration.project).tryRenderDeclarationCompactStyle(declaration) fun PsiReference.isConstructorUsage(ktClassOrObject: KtClassOrObject): Boolean { fun isJavaConstructorUsage(): Boolean { val call = element.getNonStrictParentOfType<PsiConstructorCall>() return call == element.parent && call?.resolveConstructor()?.containingClass?.navigationElement == ktClassOrObject } return isJavaConstructorUsage() || getInstance(ktClassOrObject.project).isKotlinConstructorUsage(this, ktClassOrObject) } fun getSuperMethods(declaration: KtDeclaration, ignore: Collection<PsiElement>?) : List<PsiElement> = getInstance(declaration.project).getSuperMethods(declaration, ignore) fun sourcesAndLibraries(delegate: GlobalSearchScope, project: Project): GlobalSearchScope = getInstance(project).sourcesAndLibraries(delegate, project) } fun processCompanionObjectInternalReferences(companionObject: KtObjectDeclaration, referenceProcessor: Processor<PsiReference>): Boolean fun isDataClassComponentFunction(element: KtParameter): Boolean fun getTopMostOverriddenElementsToHighlight(target: PsiElement): List<PsiElement> fun tryRenderDeclarationCompactStyle(declaration: KtDeclaration): String? fun isKotlinConstructorUsage(psiReference: PsiReference, ktClassOrObject: KtClassOrObject): Boolean fun getSuperMethods(declaration: KtDeclaration, ignore: Collection<PsiElement>?) : List<PsiElement> fun sourcesAndLibraries(delegate: GlobalSearchScope, project: Project): GlobalSearchScope }
apache-2.0
vhromada/Catalog
core/src/main/kotlin/com/github/vhromada/catalog/entity/Song.kt
1
601
package com.github.vhromada.catalog.entity import com.github.vhromada.catalog.common.entity.Time /** * A class represents song. * * @author Vladimir Hromada */ data class Song( /** * UUID */ val uuid: String, /** * Name */ val name: String, /** * Length */ val length: Int, /** * Note */ val note: String? ) { /** * Returns formatted length. * * @return formatted length */ @Suppress("unused") fun getFormattedLength(): String { return Time(length = length).toString() } }
mit
JetBrains/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/service/execution/GradleExecutionAware.kt
1
768
// 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 org.jetbrains.plugins.gradle.service.execution import com.intellij.openapi.externalSystem.service.execution.ExternalSystemExecutionAware import com.intellij.openapi.project.Project import org.jetbrains.annotations.ApiStatus @ApiStatus.Experimental @JvmDefaultWithCompatibility interface GradleExecutionAware : ExternalSystemExecutionAware { fun getBuildLayoutParameters(project: Project, projectPath: String): BuildLayoutParameters? = null fun getDefaultBuildLayoutParameters(project: Project): BuildLayoutParameters? = null fun isGradleInstallationHomeDir(project: Project, homePath: String): Boolean = false }
apache-2.0
JetBrains/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/overrideImplement/functionWithTypeParameters.kt
1
164
interface Interface { fun <A, B : Runnable, E : Map.Entry<A, B>> foo() where B : Cloneable, B : Comparable<B> } class InterfaceImpl : Interface { <caret> }
apache-2.0
JetBrains/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/enumValuesSoftDeprecate/forLoop.kt
1
204
// COMPILER_ARGUMENTS: -XXLanguage:+EnumEntries -opt-in=kotlin.ExperimentalStdlibApi // WITH_STDLIB enum class EnumClass @ExperimentalStdlibApi fun foo() { for (el in EnumClass.values<caret>()) { } }
apache-2.0
google/iosched
shared/src/main/java/com/google/samples/apps/iosched/shared/data/session/json/DeserializerUtils.kt
4
857
/* * Copyright 2019 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.shared.data.session.json import com.google.gson.JsonObject internal fun getListFromJsonArray(obj: JsonObject, key: String): List<String> { val array = obj.get(key).asJsonArray return array.map { it.asString } }
apache-2.0
StepicOrg/stepik-android
app/src/main/java/org/stepic/droid/adaptive/listeners/AnswerListener.kt
2
159
package org.stepic.droid.adaptive.listeners interface AnswerListener { fun onCorrectAnswer(submissionId: Long) fun onWrongAnswer(submissionId: Long) }
apache-2.0
exercism/xkotlin
exercises/practice/accumulate/.meta/src/reference/kotlin/Accumulate.kt
2
258
object Accumulate { fun <T, R> accumulate(collection: List<T>, function: (T) -> R): List<R> { val retVal = mutableListOf<R>() for(item in collection) { retVal.add(function.invoke(item)) } return retVal } }
mit
Hexworks/snap
src/main/kotlin/org/codetome/snap/adapter/parser/MarkdownEndpointSegmentParser.kt
1
645
package org.codetome.snap.adapter.parser import com.vladsch.flexmark.ast.Node import org.codetome.snap.service.parser.* class MarkdownEndpointSegmentParser( segmentTypeAnalyzer: SegmentTypeAnalyzer<Node>, headerSegmentParser: HeaderSegmentParser<Node>, descriptionSegmentParser: DescriptionSegmentParser<Node>, schemaSegmentParser: SchemaSegmentParser<Node>, restMethodSegmentParser: RestMethodSegmentParser<Node>) : EndpointSegmentParser<Node>( segmentTypeAnalyzer, headerSegmentParser, descriptionSegmentParser, schemaSegmentParser, restMethodSegmentParser)
agpl-3.0
ursjoss/sipamato
core/core-web/src/test/kotlin/ch/difty/scipamato/core/web/newsletter/NewsletterProviderTest.kt
2
4540
package ch.difty.scipamato.core.web.newsletter import ch.difty.scipamato.common.persistence.paging.matchPaginationContext import ch.difty.scipamato.core.entity.newsletter.Newsletter import ch.difty.scipamato.core.entity.newsletter.NewsletterFilter import ch.difty.scipamato.core.web.AbstractWicketTest import io.mockk.confirmVerified import io.mockk.every import io.mockk.verify import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeFalse import org.amshove.kluent.shouldBeTrue import org.amshove.kluent.shouldNotBeEqualTo import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder import org.apache.wicket.util.tester.WicketTester import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test @Suppress("SpellCheckingInspection") internal class NewsletterProviderTest : AbstractWicketTest() { private lateinit var provider: NewsletterProvider private val filterDummy = NewsletterFilter().apply { issueMask = "foo" } private val entityDummy = Newsletter() private val entities = listOf(entityDummy, entityDummy, entityDummy) @BeforeEach fun setUp() { WicketTester(application) provider = NewsletterProvider(filterDummy) provider.setService(newsletterServiceMock) } @AfterEach fun tearDown() { confirmVerified(newsletterServiceMock) } @Test fun defaultFilterIsNewNewsletterFilter() { provider = NewsletterProvider() provider.filterState shouldBeEqualTo NewsletterFilter() } @Test fun nullFilterResultsInNewNewsletterFilter() { val p = NewsletterProvider(null) p.filterState shouldBeEqualTo NewsletterFilter() } @Test fun size() { val size = 5 every { newsletterServiceMock.countByFilter(filterDummy) } returns size provider.size() shouldBeEqualTo size.toLong() verify { newsletterServiceMock.countByFilter(filterDummy) } } @Test fun gettingModel_wrapsEntity() { val model = provider.model(entityDummy) model.getObject() shouldBeEqualTo entityDummy } @Test fun gettingFilterState_returnsFilter() { provider.filterState shouldBeEqualTo filterDummy } @Test fun settingFilterState() { provider = NewsletterProvider() provider.filterState shouldNotBeEqualTo filterDummy provider.filterState = filterDummy provider.filterState shouldBeEqualTo filterDummy } @Test fun iterating_withNoRecords_returnsNoRecords() { every { newsletterServiceMock.findPageByFilter(filterDummy, any()) } returns emptyList() val it = provider.iterator(0, 3) it.hasNext().shouldBeFalse() verify { newsletterServiceMock.findPageByFilter(filterDummy, matchPaginationContext(0, 3, "issue: DESC")) } } @Test fun iterating_throughFirst() { every { newsletterServiceMock.findPageByFilter(filterDummy, any()) } returns entities val it = provider.iterator(0, 3) assertRecordsIn(it) verify { newsletterServiceMock.findPageByFilter(filterDummy, matchPaginationContext(0, 3, "issue: DESC")) } } private fun assertRecordsIn(it: Iterator<Newsletter>) { repeat(3) { _ -> it.hasNext().shouldBeTrue() it.next() } it.hasNext().shouldBeFalse() } @Test fun iterating_throughSecondPage() { every { newsletterServiceMock.findPageByFilter(filterDummy, any()) } returns entities val it = provider.iterator(3, 3) assertRecordsIn(it) verify { newsletterServiceMock.findPageByFilter(filterDummy, matchPaginationContext(3, 3, "issue: DESC")) } } @Test fun iterating_throughThirdPage() { provider.setSort("title", SortOrder.DESCENDING) every { newsletterServiceMock.findPageByFilter(filterDummy, any()) } returns entities val it = provider.iterator(6, 3) assertRecordsIn(it) verify { newsletterServiceMock.findPageByFilter(filterDummy, matchPaginationContext(6, 3, "title: DESC")) } } @Test fun iterating_throughThirdPage_ascendingly() { provider.setSort("title", SortOrder.ASCENDING) every { newsletterServiceMock.findPageByFilter(filterDummy, any()) } returns entities val it = provider.iterator(6, 3) assertRecordsIn(it) verify { newsletterServiceMock.findPageByFilter(filterDummy, matchPaginationContext(6, 3, "title: ASC")) } } }
gpl-3.0
fluidsonic/fluid-json
coding/sources-jvm/implementations/AbstractJsonDecoderCodec.kt
1
1291
package io.fluidsonic.json import java.lang.reflect.* import kotlin.reflect.* public abstract class AbstractJsonDecoderCodec<Value : Any, in Context : JsonCodingContext>( private val additionalProviders: List<JsonCodecProvider<Context>> = emptyList(), decodableType: JsonCodingType<Value>? = null ) : JsonDecoderCodec<Value, Context> { @Suppress("UNCHECKED_CAST") final override val decodableType: JsonCodingType<Value> = decodableType ?: JsonCodingType.of((this::class.java.genericSuperclass as ParameterizedType).actualTypeArguments[0]) as JsonCodingType<Value> override fun <ActualValue : Any> decoderCodecForType(decodableType: JsonCodingType<ActualValue>): JsonDecoderCodec<ActualValue, Context>? { var codec = super.decoderCodecForType(decodableType) if (codec != null) { return codec } for (provider in additionalProviders) { codec = provider.decoderCodecForType(decodableType) if (codec != null) { return codec } } return null } override fun <ActualValue : Any> encoderCodecForClass(encodableClass: KClass<ActualValue>): JsonEncoderCodec<ActualValue, Context>? { for (provider in additionalProviders) { val codec = provider.encoderCodecForClass(encodableClass) if (codec != null) { return codec } } return null } }
apache-2.0
allotria/intellij-community
platform/lang-api/src/com/intellij/codeInsight/hints/settings/InlayProviderSettingsModel.kt
3
1895
// 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.codeInsight.hints.settings import com.intellij.codeInsight.hints.ChangeListener import com.intellij.codeInsight.hints.ImmediateConfigurable import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.NlsContexts import com.intellij.psi.PsiFile import org.jetbrains.annotations.Nls import javax.swing.JComponent /** * Model of settings of single language hints provider (Preferences | Editor | Inlay Hints) * @param isEnabled language is enabled in terms of InlayHintsSettings.hintsEnabled */ abstract class InlayProviderSettingsModel(var isEnabled: Boolean, val id: String) { /** * Listener must be notified if any settings of inlay provider was changed */ var onChangeListener: ChangeListener? = null /** * Name of provider to be displayed in list */ abstract val name: @Nls String /** * Arbitrary component to be displayed in */ abstract val component: JComponent /** * Called, when it is required to update inlay hints for file in preview * Invariant: if previewText == null, this method is not invoked */ abstract fun collectAndApply(editor: Editor, file: PsiFile) /** * Text of hints preview. If null, won't be shown. */ abstract val previewText: String? /** * Saves changed settings */ abstract fun apply() /** * Checks, whether settings are different from stored ones */ abstract fun isModified(): Boolean /** * Loads stored settings and replaces current ones */ abstract fun reset() @get:NlsContexts.Checkbox abstract val mainCheckBoxLabel: String /** * List of cases, if main check check box is disabled, these checkboxes are also disabled */ abstract val cases: List<ImmediateConfigurable.Case> }
apache-2.0
allotria/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/GuiRobotHolder.kt
10
937
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testGuiFramework.impl import org.fest.swing.core.Robot import org.fest.swing.core.SmartWaitRobot object GuiRobotHolder { @Volatile private var myRobot: Robot? = null val robot: Robot get() { if(myRobot == null) synchronized(this) { if(myRobot == null) initializeRobot() } return myRobot ?: throw IllegalStateException("Cannot initialize the robot") } private fun initializeRobot() { if (myRobot != null) releaseRobot() myRobot = SmartWaitRobot() // acquires ScreenLock } fun releaseRobot() { if(myRobot != null) { synchronized(this){ if (myRobot != null){ myRobot!!.cleanUpWithoutDisposingWindows() // releases ScreenLock myRobot = null } } } } }
apache-2.0
allotria/intellij-community
platform/statistics/envTests/test/com/intellij/internal/statistic/envTest/config/EventLogExternalSettingsServiceTest.kt
2
3786
// 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.internal.statistic.envTest.config import com.intellij.internal.statistic.envTest.StatisticsServiceBaseTest import com.intellij.internal.statistic.envTest.upload.RECORDER_ID import com.intellij.internal.statistic.envTest.upload.TestEventLogApplicationInfo import com.intellij.internal.statistic.eventLog.EventLogConfigOptionsService.* import com.intellij.internal.statistic.eventLog.connection.EventLogUploadSettingsService import junit.framework.TestCase import java.util.concurrent.TimeUnit internal class EventLogExternalSettingsServiceTest : StatisticsServiceBaseTest() { fun `test load and cache external settings`() { val settings = configureDynamicConfig(TimeUnit.HOURS.toMillis(1)) val metadata = loadMetadata(settings.metadataProductUrl) Thread.sleep(1000) assertMetadata(settings.metadataProductUrl, metadata) Thread.sleep(1000) assertMetadata(settings.metadataProductUrl, metadata) } fun `test cached external settings are invalidated`() { val settings = configureDynamicConfig(10) var metadata = loadMetadata(settings.metadataProductUrl) Thread.sleep(1000) metadata = assertNewMetadata(settings.metadataProductUrl, metadata) Thread.sleep(1000) assertNewMetadata(settings.metadataProductUrl, metadata) } fun `test load options from external settings`() { val settings = configureDynamicConfig(TimeUnit.HOURS.toMillis(1)) TestCase.assertEquals(settings.getOptionValue("dataThreshold"), "16000") TestCase.assertEquals(settings.getOptionValue("groupDataThreshold"), "8000") TestCase.assertEquals(settings.getOptionValue("groupAlertThreshold"), "4000") } fun `test load salt and id revisions from external settings`() { val settings = configureDynamicConfig(TimeUnit.HOURS.toMillis(1)) TestCase.assertEquals(settings.getOptionValue(MACHINE_ID_SALT), "test_salt") TestCase.assertEquals(settings.getOptionValue(MACHINE_ID_SALT_REVISION), "1") } private fun configureDynamicConfig(configCacheTimeoutMs: Long): EventLogUploadSettingsService { val applicationInfo = TestEventLogApplicationInfo(RECORDER_ID, container.getBaseUrl("config/dynamic_config.php").toString()) return EventLogUploadSettingsService(RECORDER_ID, applicationInfo, configCacheTimeoutMs) } private fun loadMetadata(metadata: String?): String { TestCase.assertNotNull("Cannot retrieve metadata url", metadata) return metadata!! } private fun assertNewMetadata(metadata: String?, previous: String?): String { TestCase.assertNotNull("Cannot retrieve metadata url", metadata) previous?.let { val newMetadata = parseMetadata(metadata) val oldMetadata = parseMetadata(previous) TestCase.assertTrue("Metadata did not change: $it", newMetadata != oldMetadata) } return metadata!! } private fun assertMetadata(metadata: String?, previous: String?) { TestCase.assertNotNull("Cannot retrieve metadata url", metadata) previous?.let { val newMetadata = parseMetadata(metadata) val oldMetadata = parseMetadata(previous) TestCase.assertEquals("Metadata changed but should stay the same", oldMetadata, newMetadata) } } private fun parseMetadata(metadataUrl: String?): String { TestCase.assertTrue("Wrong format of the metadata url: $metadataUrl", metadataUrl!!.contains("metadata/")) val start = metadataUrl.indexOf("metadata/") + "metadata/".length val end = metadataUrl.lastIndexOf("/") TestCase.assertTrue("Wrong format of the metadata url: $metadataUrl", end >= 0 && start >= 0 && end > start) return metadataUrl.substring(start, end) } }
apache-2.0
75py/TextCounter
app/src/main/java/com/nagopy/android/textcounter/TextBackup.kt
1
975
/* * Copyright 2018 75py * * 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.nagopy.android.textcounter import android.content.SharedPreferences import timber.log.Timber class TextBackup(val sp: SharedPreferences) { fun backup(text: String) { Timber.d("backup: %s", text) sp.edit().putString("backup", text).apply() } fun restore(): String { Timber.d("restore") return sp.getString("backup", "") } }
apache-2.0
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/jvm/src/internal/SystemProps.kt
1
531
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:JvmName("SystemPropsKt") @file:JvmMultifileClass package kotlinx.coroutines.internal // number of processors at startup for consistent prop initialization internal val AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors() internal actual fun systemProp( propertyName: String ): String? = try { System.getProperty(propertyName) } catch (e: SecurityException) { null }
apache-2.0
stefanosiano/PowerfulImageView
sample/src/androidTest/java/com/stefanosiano/powerful_libraries/imageviewsample/MainUiTest.kt
1
840
package com.stefanosiano.powerful_libraries.imageviewsample import android.graphics.Bitmap import androidx.test.core.app.ActivityScenario import androidx.test.core.app.launchActivity import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.runner.RunWith import kotlin.test.BeforeTest @RunWith(AndroidJUnit4::class) class MainUiTest : BaseUiTest() { private lateinit var normalBitmap: Bitmap // private lateinit var piv: PowerfulImageView private lateinit var mainActivityScenario: ActivityScenario<MainActivity> @BeforeTest fun setup() { val d = context.resources.getDrawable(R.drawable.sf1) normalBitmap = d.createBitmap() mainActivityScenario = launchActivity<MainActivity>() mainActivityScenario.onActivity { // piv = it.binding.blurImage } } }
mit
intellij-purescript/intellij-purescript
src/main/kotlin/org/purescript/highlighting/PSSyntaxHighlighterFactory.kt
1
480
package org.purescript.highlighting import com.intellij.openapi.fileTypes.SyntaxHighlighter import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile class PSSyntaxHighlighterFactory : SyntaxHighlighterFactory() { override fun getSyntaxHighlighter( project: Project?, virtualFile: VirtualFile? ): SyntaxHighlighter { return PSSyntaxHighlighter() } }
bsd-3-clause
mrbublos/vkm
app/src/main/java/vkm/vkm/PagerActivity.kt
1
5984
package vkm.vkm import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Bundle import android.os.IBinder import android.view.View import android.widget.BaseAdapter import android.widget.ListView import android.widget.SeekBar import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter import androidx.lifecycle.Observer import kotlinx.android.synthetic.main.pager_activity.* import kotlinx.android.synthetic.main.pager_activity.view.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import vkm.vkm.utils.Composition import vkm.vkm.utils.HttpUtils import vkm.vkm.utils.db.Db class PagerActivity : AppCompatActivity(), ServiceConnection { var musicPlayer: MusicPlayService? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) HttpUtils.loadProxies(Db.instance(applicationContext).proxyDao()) DownloadManager.initialize(Db.instance(applicationContext).tracksDao()) savedInstanceState?.let { State.currentSearchTab = it.getInt("currentSearchTab") State.currentHistoryTab = it.getString("currentHistoryTab") ?: "" } setContentView(R.layout.pager_activity) pager.adapter = PagerAdapter(supportFragmentManager) pager.currentItem = 0 bindService(Intent(applicationContext, MusicPlayService::class.java), this, Context.BIND_AUTO_CREATE) } override fun onSaveInstanceState(outState: Bundle?) { super.onSaveInstanceState(outState) outState?.putInt("currentSearchTab", State.currentSearchTab) outState?.putString("currentHistoryTab", State.currentHistoryTab) HttpUtils.storeProxies(Db.instance(applicationContext).proxyDao()) } override fun onDestroy() { super.onDestroy() HttpUtils.storeProxies(Db.instance(applicationContext).proxyDao()) unbindService(this) } override fun onServiceConnected(name: ComponentName?, service: IBinder?) { musicPlayer = (service as MusicPlayService.MusicPlayerController).getService() setupMusicService() } private fun setupMusicService() { nextTrack.setOnClickListener { musicPlayer?.next() } pause.setOnClickListener { if (musicPlayer?.isPlaying() == true) { musicPlayer?.pause() } else { musicPlayer?.play(musicPlayer?.displayedComposition?.value) } } trackPlayingProgress.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { if (!fromUser) { return } val duration = musicPlayer?.trackLength ?: 0 musicPlayer?.skipTo((progress * duration / 100).toInt()) } override fun onStartTrackingTouch(seekBar: SeekBar?) {} override fun onStopTrackingTouch(seekBar: SeekBar?) {} }) musicPlayer?.state?.observe(this, Observer { state -> when (state) { "playing" -> onPlayerPlay() "stopped" -> onPlayerStop() "paused" -> onPlayerPause() else -> refreshList() } }) musicPlayer?.progress?.observe(this, Observer { GlobalScope.launch(Dispatchers.Main) { currentTrackPlaying.trackPlayingProgress.progress = it.toInt() } }) musicPlayer?.displayedComposition?.observe(this, Observer { GlobalScope.launch(Dispatchers.Main) { currentTrackPlaying?.name?.text = it.name currentTrackPlaying?.name?.isSelected = true currentTrackPlaying?.artist?.text = it.artist currentTrackPlaying?.artist?.isSelected = true } }) } private fun refreshList() { GlobalScope.launch(Dispatchers.Main) { ((findViewById<ListView>(R.id.resultList))?.adapter as BaseAdapter?)?.notifyDataSetChanged() } } private val onPlayerPlay: () -> Unit = { GlobalScope.launch(Dispatchers.Main) { currentTrackPlaying.visibility = View.VISIBLE pause.setImageDrawable(applicationContext.getDrawable(R.drawable.ic_pause_player)) refreshList() } } private val onPlayerStop: () -> Unit = { GlobalScope.launch(Dispatchers.Main) { currentTrackPlaying.visibility = View.VISIBLE pause.setImageDrawable(applicationContext.getDrawable(R.drawable.ic_play_player)) refreshList() } } private val onPlayerPause: () -> Unit = { GlobalScope.launch(Dispatchers.Main) { currentTrackPlaying.visibility = View.VISIBLE pause.setImageDrawable(applicationContext.getDrawable(R.drawable.ic_play_player)) refreshList() } } fun playNewTrack(list: List<Composition>, track: Composition) { musicPlayer?.stop() val newPlayList = mutableListOf<Composition>() newPlayList.addAll(list) musicPlayer?.playList = newPlayList musicPlayer?.play(track) refreshList() } override fun onServiceDisconnected(name: ComponentName?) { musicPlayer = null } } class PagerAdapter(fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) { // Order: Search, History, Settings override fun getItem(position: Int): Fragment { return when (position % 3) { 1 -> HistoryFragment() 2 -> SettingsFragment() else -> SearchFragment() } } override fun getCount(): Int = 3 }
gpl-3.0
faceofcat/Tesla-Core-Lib
src/main/kotlin/net/ndrei/teslacorelib/utils/miscextensions.kt
1
265
package net.ndrei.teslacorelib.utils import java.awt.Color /** * Created by CF on 2017-07-15. */ fun Color.withAlpha(alpha: Float) = this.withAlpha((alpha * 255.0f + 0.5f).toInt()) fun Color.withAlpha(alpha: Int) = Color(this.red, this.green, this.blue, alpha)
mit
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/traits/kt1936_1.kt
5
223
interface MyTrait { var property : String fun foo() = property } open class B(param : String) : MyTrait { override var property : String = param override fun foo() = super.foo() } fun box()= B("OK").foo()
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/safeDelete/deleteValueParameter/kotlinValueParameter/dataClassComponent.kt
13
131
package test data public class RemData(val remo<caret>vable: Int) fun usage(data: RemData): Int { return data.component1() }
apache-2.0