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
JetBrains/intellij-community
plugins/gradle/testSources/org/jetbrains/plugins/gradle/testFramework/GradleProjectTestCase.kt
1
1677
// 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.plugins.gradle.testFramework import com.intellij.openapi.externalSystem.util.* import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDocumentManager import org.gradle.util.GradleVersion import org.jetbrains.plugins.gradle.frameworkSupport.buildscript.isGradleAtLeast import org.jetbrains.plugins.gradle.frameworkSupport.buildscript.isGradleOlderThan abstract class GradleProjectTestCase : GradleProjectBaseTestCase() { @get:JvmName("myProject") val project: Project get() = gradleFixture.project val projectRoot: VirtualFile get() = gradleFixture.fileFixture.root val projectPath: String get() = projectRoot.path val gradleVersion: GradleVersion get() = gradleFixture.gradleVersion fun isGradleAtLeast(version: String): Boolean = gradleVersion.isGradleAtLeast(version) fun isGradleOlderThan(version: String): Boolean = gradleVersion.isGradleOlderThan(version) fun findOrCreateFile(relativePath: String, text: String): VirtualFile { gradleFixture.fileFixture.snapshot(relativePath) return runWriteActionAndGet { val file = projectRoot.findOrCreateFile(relativePath) file.text = text FileDocumentManager.getInstance().getDocument(file)?.let { PsiDocumentManager.getInstance(project).commitDocument(it) } file } } fun getFile(relativePath: String): VirtualFile { return runReadAction { projectRoot.getFile(relativePath) } } }
apache-2.0
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/presentation/course_purchase/CoursePurchaseViewModel.kt
1
502
package org.stepik.android.presentation.course_purchase import ru.nobird.app.presentation.redux.container.ReduxViewContainer import ru.nobird.android.view.redux.viewmodel.ReduxViewModel class CoursePurchaseViewModel( reduxViewContainer: ReduxViewContainer<CoursePurchaseFeature.State, CoursePurchaseFeature.Message, CoursePurchaseFeature.Action.ViewAction> ) : ReduxViewModel<CoursePurchaseFeature.State, CoursePurchaseFeature.Message, CoursePurchaseFeature.Action.ViewAction>(reduxViewContainer)
apache-2.0
Hexworks/snap
src/main/kotlin/org/codetome/snap/service/parser/EndpointSegmentParser.kt
1
3056
package org.codetome.snap.service.parser import org.codetome.snap.model.ConfigSegmentType.REST_ENDPOINT import org.codetome.snap.model.ConfigSegmentType.REST_METHOD import org.codetome.snap.model.ParseContext import org.codetome.snap.model.rest.MethodType import org.codetome.snap.model.rest.Path import org.codetome.snap.model.rest.RestEndpoint import org.codetome.snap.model.rest.RestMethod import org.codetome.snap.util.SubstringRanges abstract class EndpointSegmentParser<N>( private val segmentTypeAnalyzer: SegmentTypeAnalyzer<N>, private val headerSegmentParser: HeaderSegmentParser<N>, private val descriptionSegmentParser: DescriptionSegmentParser<N>, private val schemaSegmentParser: SchemaSegmentParser<N>, private val restMethodSegmentParser: RestMethodSegmentParser<N>) : SegmentParser<N, RestEndpoint> { override fun parseSegment(nodes: List<N>, context: ParseContext): Pair<RestEndpoint, List<N>> { if (nodes.size < 3) { throw IllegalArgumentException("An Endpoint declaration must contain at least a description, a schema declaration and a method!") } if (REST_ENDPOINT != segmentTypeAnalyzer.determineSegmentType(nodes.first())) { throw IllegalArgumentException("An Endpoint declaration must start with an Endpoint header!") } val (header, rest0) = headerSegmentParser.parseSegment(nodes, context) val (description, rest1) = descriptionSegmentParser.parseSegment(rest0, context) val (schema, rest2) = schemaSegmentParser.parseSegment(rest1, context) context.declaredSchemas.put(schema.name, schema) if (rest2.isEmpty()) { throw IllegalArgumentException("An Endpoint declaration must contain at least a single Rest Method!") } var remaining = rest2 val restMethods = mutableMapOf<MethodType, RestMethod>() while (hasRemainingRestMethods(remaining)) { val (restMethod, tempRemaining) = restMethodSegmentParser.parseSegment(remaining, context) remaining = tempRemaining restMethods.put(restMethod.method, restMethod) } return Pair(RestEndpoint( name = header.name, description = description, path = Path( pathStr = header.linkContent, paramToSchemaPropertyMapping = parsePathParams(header.linkContent) // TODO: fill this properly in next version! ), schema = schema, restMethods = restMethods ), remaining) } private fun parsePathParams(pathStr: String): Map<String, String> { return SubstringRanges.rangesDelimitedByPairInString(Pair('{', '}'), pathStr) .subStrings .map { Pair(it, it) } .toMap() } private fun hasRemainingRestMethods(remaining: List<N>) = remaining.isNotEmpty() && REST_METHOD == segmentTypeAnalyzer.determineSegmentType(remaining.first()) }
agpl-3.0
theunknownxy/mcdocs
src/main/kotlin/de/theunknownxy/mcdocs/CommonProxy.kt
1
93
package de.theunknownxy.mcdocs public open class CommonProxy { open fun setupKeys() {} }
mit
theunknownxy/mcdocs
src/main/kotlin/de/theunknownxy/mcdocs/docs/loader/FileDocumentationLoader.kt
1
3352
package de.theunknownxy.mcdocs.docs.loader import de.theunknownxy.mcdocs.docs.* import de.theunknownxy.mcdocs.docs.loader.xml.XMLParserHandler import java.io.File import java.nio.file.Path import java.util.ArrayList import javax.xml.parsers.SAXParserFactory public class FileDocumentationLoader(private val root_path: Path) : DocumentationLoader { private val extension = ".xml" private fun get_nodepath(ref: DocumentationNodeRef): Path { var filepath: Path = root_path.resolve(ref.path) // Check whether the path is valid if (!filepath.startsWith(root_path)) { throw IllegalArgumentException("The path '$filepath' is not within '$root_path'") } return filepath } private fun should_show_entry(p: File): Boolean { return p.getName() != "index.xml" && (p.isDirectory() || p.extension.equalsIgnoreCase("xml")) } private fun collect_childs(p: Path): MutableList<DocumentationNodeRef> { var childs: MutableList<DocumentationNodeRef> = ArrayList() if (p.toFile().isDirectory()) { val files = p.toFile().list() files.sort() for (child in files) { if (should_show_entry(File(p.toFile(), child))) { val childpath = p.resolve(child.replace(".xml", "")) childs.add(DocumentationNodeRef(root_path.relativize(childpath).toString())) } } } return childs } private fun get_filepath(p: Path): Path { // Construct the real filesystem path if (p.toFile().isDirectory()) { // The actual content is within the folder return p.resolve("index" + extension) } else { // Append the .xml suffix if it's a file return p.getParent().resolve((p.getFileName().toString() + extension)) } } private fun parse_file(filepath: Path): Pair<String, Content> { // Read and parse the file var title: String var content: Content try { val spf = SAXParserFactory.newInstance() val parser = spf.newSAXParser() val handler = XMLParserHandler() parser.parse(filepath.toFile(), handler) title = handler.document.title content = handler.document.content } catch(e: Exception) { title = "Invalid" // Create a page with the error content = Content() val p: ParagraphBlock = ParagraphBlock(ParagraphElement()) p.value.childs.add(TextElement("Invalid document($filepath): $e")) content.blocks.add(p) } return Pair(title, content) } override fun load(ref: DocumentationNodeRef): DocumentationNode { val nodepath: Path = get_nodepath(ref) val childs = collect_childs(nodepath) val filepath = get_filepath(nodepath) if (!filepath.toFile().exists()) { val node = DocumentationNode(ref, "FIXME", null) node.children = childs return node } var (title: String, content: Content) = parse_file(filepath) val node = DocumentationNode(ref, title, content) node.children = childs node.parent = ref.parent() return node } }
mit
Homes-MinecraftServerMod/Homes
src/main/kotlin/com/masahirosaito/spigot/homes/datas/strings/commands/ListCommandStringData.kt
1
502
package com.masahirosaito.spigot.homes.datas.strings.commands data class ListCommandStringData( val DESCRIPTION_PLAYER_COMMAND: String = "Display the list of your homes", val DESCRIPTION_CONSOLE_COMMAND: String = "Display the list of player homes", val USAGE_CONSOLE_COMMAND_LIST: String = "Display the list of players", val USAGE_PLAYER_COMMAND_LIST: String = "Display the list of homes", val USAGE_LIST_PLAYER: String = "Display the list of player's homes" )
apache-2.0
fluidsonic/fluid-json
coding/sources-jvm/implementations/StandardCodingSerializer.kt
1
463
package io.fluidsonic.json internal class StandardCodingSerializer<out Context : JsonCodingContext>( private val context: Context, private val encoderFactory: (destination: JsonWriter, context: Context) -> JsonEncoder<Context> ) : JsonCodingSerializer { override fun serializeValue(value: Any?, destination: JsonWriter, withTermination: Boolean) { encoderFactory(destination, context) .withTermination(withTermination) { writeValueOrNull(value) } } }
apache-2.0
cortinico/myo-emg-visualizer
app/src/test/java/it/ncorti/emgvisualizer/ui/export/ExportPresenterTest.kt
1
4561
package it.ncorti.emgvisualizer.ui.export import com.ncorti.myonnaise.Myo import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import io.reactivex.Flowable import it.ncorti.emgvisualizer.dagger.DeviceManager import it.ncorti.emgvisualizer.ui.testutil.TestSchedulerRule import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.ArgumentMatchers import org.mockito.ArgumentMatchers.anyInt class ExportPresenterTest { @get:Rule val testSchedulerRule = TestSchedulerRule() private lateinit var mockedView: ExportContract.View private lateinit var mockedDeviceManager: DeviceManager private lateinit var mockedMyo: Myo private lateinit var testPresenter: ExportPresenter @Before fun setUp() { mockedView = mock {} mockedMyo = mock {} mockedDeviceManager = mock { on(mock.myo) doReturn mockedMyo } testPresenter = ExportPresenter(mockedView, mockedDeviceManager) } @Test fun onStart_collectedPointsAreShown() { testPresenter.start() verify(mockedView).showCollectedPoints(anyInt()) } @Test fun onStart_withStreamingDevice_enableCollection() { whenever(mockedDeviceManager.myo?.isStreaming()).thenReturn(true) testPresenter.start() verify(mockedView).enableStartCollectingButton() } @Test fun onStart_withNotStreamingDevice_disableCollection() { whenever(mockedDeviceManager.myo?.isStreaming()).thenReturn(false) testPresenter.start() verify(mockedView).disableStartCollectingButton() } @Test fun onCollectionTogglePressed_withNotStreamingDevice_showErrorMessage() { testPresenter.onCollectionTogglePressed() verify(mockedView).showNotStreamingErrorMessage() } @Test fun onCollectionTogglePressed_withStreamingDeviceAndNotSubscribed_showCollectedPoints() { whenever(mockedDeviceManager.myo?.isStreaming()).thenReturn(true) whenever(mockedDeviceManager.myo?.dataFlowable()) .thenReturn( Flowable.just( floatArrayOf(1.0f), floatArrayOf(2.0f), floatArrayOf(3.0f) ) ) testPresenter.dataSubscription = null testPresenter.onCollectionTogglePressed() assertNotNull(testPresenter.dataSubscription) verify(mockedView).showCollectionStarted() verify(mockedView).disableResetButton() verify(mockedView).showCollectedPoints(1) verify(mockedView).showCollectedPoints(2) verify(mockedView).showCollectedPoints(3) } @Test fun onCollectionTogglePressed_withStreamingDevice_showCollectedPoints() { whenever(mockedDeviceManager.myo?.isStreaming()).thenReturn(true) // We simulate that we are subscribed to a flowable testPresenter.dataSubscription = mock {} testPresenter.onCollectionTogglePressed() verify(testPresenter.dataSubscription)?.dispose() verify(mockedView).enableResetButton() verify(mockedView).showSaveArea() verify(mockedView).showCollectionStopped() } @Test fun onResetPressed_resetTheView() { testPresenter.onResetPressed() verify(mockedView).showCollectedPoints(0) verify(mockedView).hideSaveArea() verify(mockedView).disableResetButton() } @Test fun onSavePressed_askViewToSave() { testPresenter.onSavePressed() verify(mockedView).saveCsvFile(ArgumentMatchers.anyString()) } @Test fun onSharePressed_askViewToShare() { testPresenter.onSharePressed() verify(mockedView).sharePlainText(ArgumentMatchers.anyString()) } @Test fun createCsv_withEmptyBuffer_EmptyList() { assertEquals("", testPresenter.createCsv(arrayListOf())) } @Test fun createCsv_withSingleLine_OneLineCsv() { val buffer = arrayListOf(floatArrayOf(1f, 2f, 3f)) assertEquals("1.0;2.0;3.0;\n", testPresenter.createCsv(buffer)) } @Test fun createCsv_withMultipleLine_MultipleLineCsv() { val buffer = arrayListOf( floatArrayOf(1f, 2f, 3f), floatArrayOf(4f, 5f, 6f) ) assertEquals("1.0;2.0;3.0;\n4.0;5.0;6.0;\n", testPresenter.createCsv(buffer)) } }
mit
F43nd1r/acra-backend
acrarium/src/main/kotlin/com/faendir/acra/security/SecurityUtils.kt
1
2958
/* * (C) Copyright 2018 Lukas Morawietz (https://github.com/F43nd1r) * * 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.faendir.acra.security import com.faendir.acra.model.App import com.faendir.acra.model.Permission import com.faendir.acra.model.User import com.vaadin.flow.server.HandlerHelper.RequestType import com.vaadin.flow.shared.ApplicationConstants import org.springframework.core.annotation.AnnotationUtils import org.springframework.security.authentication.AnonymousAuthenticationToken import org.springframework.security.core.context.SecurityContextHolder import javax.servlet.http.HttpServletRequest object SecurityUtils { @JvmStatic fun isLoggedIn(): Boolean = SecurityContextHolder.getContext().authentication?.takeIf { it !is AnonymousAuthenticationToken }?.isAuthenticated ?: false @JvmStatic fun hasRole(role: User.Role): Boolean = SecurityContextHolder.getContext().authentication?.authorities?.any { it.authority == role.authority } ?: false @JvmStatic fun getUsername(): String = SecurityContextHolder.getContext().authentication?.name ?: "" @JvmStatic fun hasPermission(app: App, level: Permission.Level): Boolean = SecurityContextHolder.getContext().authentication?.let { getPermission(app, it.authorities.filterIsInstance<Permission>()) { hasRole(User.Role.ADMIN) }.ordinal >= level.ordinal } ?: false @JvmStatic fun hasAccess(getApp: () -> App, target: Class<*>): Boolean { return AnnotationUtils.findAnnotation(target, RequiresRole::class.java)?.let { hasRole(it.value) } ?: true && AnnotationUtils.findAnnotation(target, RequiresPermission::class.java)?.let { hasPermission(getApp(), it.value) } ?: true } @JvmStatic fun getPermission(app: App, user: User): Permission.Level = getPermission(app, user.permissions) { user.roles.contains(User.Role.ADMIN) } private fun getPermission(app: App, permissionStream: Collection<Permission>, isAdmin: () -> Boolean): Permission.Level = permissionStream.firstOrNull { it.app == app }?.level ?: if (isAdmin()) Permission.Level.ADMIN else Permission.Level.NONE @JvmStatic fun isFrameworkInternalRequest(request: HttpServletRequest): Boolean { val parameterValue = request.getParameter(ApplicationConstants.REQUEST_TYPE_PARAMETER) return (parameterValue != null && RequestType.values().any { it.identifier == parameterValue }) } }
apache-2.0
ylemoigne/ReactKT
sampleprojects/demo-material/src/main/kotlin/fr/javatic/reactktSample/material/App.kt
1
1038
package fr.javatic.reactktSample.material import fr.javatic.reactkt.core.Component import fr.javatic.reactkt.core.ReactElement import fr.javatic.reactkt.core.ktx import fr.javatic.reactkt.material.components.* import fr.javatic.reactkt.material.components.LayoutFixedDrawer import fr.javatic.reactkt.material.components.data.NavLink class App : Component<Any,AppState>() { init { this.state = AppState(Step.Input, "") } override fun render(): ReactElement { val content = when(this.state.display){ Step.Input -> ktx { component(::InputStep, InputStepProp(state.input)) } else -> ktx { div("className" to "mdl-cell mdl-cell--12-col") {+"Something need to be done"} } } return ktx { component(::LayoutFixedDrawer, LayoutDrawerProps("I'm the title", NavLink("a", "A"),NavLink("b", "B"),NavLink("c", "C"),NavLink("d", "D"))) { div("className" to "mdl-grid") { +content } } } } }
apache-2.0
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/main/kotlin/com/vrem/wifianalyzer/wifi/timegraph/DataManager.kt
1
3024
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.wifianalyzer.wifi.timegraph import com.jjoe64.graphview.series.LineGraphSeries import com.vrem.annotation.OpenClass import com.vrem.wifianalyzer.wifi.graphutils.* import com.vrem.wifianalyzer.wifi.model.WiFiDetail @OpenClass internal class DataManager(private val timeGraphCache: TimeGraphCache = TimeGraphCache()) { var scanCount: Int = 0 var xValue = 0 fun addSeriesData(graphViewWrapper: GraphViewWrapper, wiFiDetails: List<WiFiDetail>, levelMax: Int): Set<WiFiDetail> { val inOrder: Set<WiFiDetail> = wiFiDetails.toSet() inOrder.forEach { addData(graphViewWrapper, it, levelMax) } adjustData(graphViewWrapper, inOrder) xValue++ if (scanCount < MAX_SCAN_COUNT) { scanCount++ } if (scanCount == 2) { graphViewWrapper.setHorizontalLabelsVisible(true) } return newSeries(inOrder) } fun adjustData(graphViewWrapper: GraphViewWrapper, wiFiDetails: Set<WiFiDetail>) { graphViewWrapper.differenceSeries(wiFiDetails).forEach { val dataPoint = GraphDataPoint(xValue, MIN_Y + MIN_Y_OFFSET) val drawBackground = it.wiFiAdditional.wiFiConnection.connected graphViewWrapper.appendToSeries(it, dataPoint, scanCount, drawBackground) timeGraphCache.add(it) } timeGraphCache.clear() } fun newSeries(wiFiDetails: Set<WiFiDetail>): Set<WiFiDetail> = wiFiDetails.plus(timeGraphCache.active()) fun addData(graphViewWrapper: GraphViewWrapper, wiFiDetail: WiFiDetail, levelMax: Int) { val drawBackground = wiFiDetail.wiFiAdditional.wiFiConnection.connected val level = wiFiDetail.wiFiSignal.level.coerceAtMost(levelMax) if (graphViewWrapper.newSeries(wiFiDetail)) { val dataPoint = GraphDataPoint(xValue, (if (scanCount > 0) MIN_Y + MIN_Y_OFFSET else level)) val series = LineGraphSeries(arrayOf(dataPoint)) graphViewWrapper.addSeries(wiFiDetail, series, drawBackground) } else { val dataPoint = GraphDataPoint(xValue, level) graphViewWrapper.appendToSeries(wiFiDetail, dataPoint, scanCount, drawBackground) } timeGraphCache.reset(wiFiDetail) } }
gpl-3.0
Raizlabs/DBFlow
core/src/main/kotlin/com/dbflow5/converter/TypeConverters.kt
1
4117
package com.dbflow5.converter import java.math.BigDecimal import java.math.BigInteger import java.sql.Time import java.sql.Timestamp import java.util.* /** * Author: andrewgrosner * Description: This class is responsible for converting the stored database value into the field value in * a Model. */ @com.dbflow5.annotation.TypeConverter abstract class TypeConverter<DataClass, ModelClass> { /** * Converts the ModelClass into a DataClass * * @param model this will be called upon syncing * @return The DataClass value that converts into a SQLite type */ abstract fun getDBValue(model: ModelClass?): DataClass? /** * Converts a DataClass from the DB into a ModelClass * * @param data This will be called when the model is loaded from the DB * @return The ModelClass value that gets set in a Model that holds the data class. */ abstract fun getModelValue(data: DataClass?): ModelClass? } /** * Description: Defines how we store and retrieve a [java.math.BigDecimal] */ @com.dbflow5.annotation.TypeConverter class BigDecimalConverter : TypeConverter<String, BigDecimal>() { override fun getDBValue(model: BigDecimal?): String? = model?.toString() override fun getModelValue(data: String?): BigDecimal? = if (data == null) null else BigDecimal(data) } /** * Description: Defines how we store and retrieve a [java.math.BigInteger] */ @com.dbflow5.annotation.TypeConverter class BigIntegerConverter : TypeConverter<String, BigInteger>() { override fun getDBValue(model: BigInteger?): String? = model?.toString() override fun getModelValue(data: String?): BigInteger? = if (data == null) null else BigInteger(data) } /** * Description: Converts a boolean object into an Integer for database storage. */ @com.dbflow5.annotation.TypeConverter class BooleanConverter : TypeConverter<Int, Boolean>() { override fun getDBValue(model: Boolean?): Int? = if (model == null) null else if (model) 1 else 0 override fun getModelValue(data: Int?): Boolean? = if (data == null) null else data == 1 } /** * Description: Defines how we store and retrieve a [java.util.Calendar] */ @com.dbflow5.annotation.TypeConverter(allowedSubtypes = [(GregorianCalendar::class)]) class CalendarConverter : TypeConverter<Long, Calendar>() { override fun getDBValue(model: Calendar?): Long? = model?.timeInMillis override fun getModelValue(data: Long?): Calendar? = if (data != null) Calendar.getInstance().apply { timeInMillis = data } else null } /** * Description: Converts a [Character] into a [String] for database storage. */ @com.dbflow5.annotation.TypeConverter class CharConverter : TypeConverter<String, Char>() { override fun getDBValue(model: Char?): String? = if (model != null) String(charArrayOf(model)) else null override fun getModelValue(data: String?): Char? = if (data != null) data[0] else null } /** * Description: Defines how we store and retrieve a [java.util.Date] */ @com.dbflow5.annotation.TypeConverter class DateConverter : TypeConverter<Long, Date>() { override fun getDBValue(model: Date?): Long? = model?.time override fun getModelValue(data: Long?): Date? = if (data == null) null else Date(data) } /** * Description: Defines how we store and retrieve a [java.sql.Date] */ @com.dbflow5.annotation.TypeConverter(allowedSubtypes = [(Time::class), (Timestamp::class)]) class SqlDateConverter : TypeConverter<Long, java.sql.Date>() { override fun getDBValue(model: java.sql.Date?): Long? = model?.time override fun getModelValue(data: Long?): java.sql.Date? = if (data == null) null else java.sql.Date(data) } /** * Description: Responsible for converting a [UUID] to a [String]. * * @author Andrew Grosner (fuzz) */ @com.dbflow5.annotation.TypeConverter class UUIDConverter : TypeConverter<String, UUID>() { override fun getDBValue(model: UUID?): String? = model?.toString() override fun getModelValue(data: String?): UUID? { return if (data == null) { null } else UUID.fromString(data) } }
mit
nobuoka/vc-oauth-java
ktor-twitter-login/src/test/kotlin/info/vividcode/ktor/twitter/login/TwitterLoginInterceptorsTest.kt
1
5941
package info.vividcode.ktor.twitter.login import info.vividcode.ktor.twitter.login.application.TemporaryCredentialNotFoundException import info.vividcode.ktor.twitter.login.application.TestServerTwitter import info.vividcode.ktor.twitter.login.application.TwitterCallFailedException import info.vividcode.ktor.twitter.login.application.responseBuilder import info.vividcode.ktor.twitter.login.test.TestCallFactory import info.vividcode.ktor.twitter.login.test.TestTemporaryCredentialStore import info.vividcode.oauth.OAuth import io.ktor.application.Application import io.ktor.application.call import io.ktor.http.HttpMethod import io.ktor.http.HttpStatusCode import io.ktor.response.respondText import io.ktor.routing.get import io.ktor.routing.post import io.ktor.routing.routing import io.ktor.server.testing.handleRequest import io.ktor.server.testing.withTestApplication import kotlinx.coroutines.newSingleThreadContext import kotlinx.coroutines.runBlocking import okhttp3.Call import okhttp3.MediaType import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.ResponseBody import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import java.time.Clock import java.time.Instant import java.time.ZoneId import kotlin.coroutines.CoroutineContext internal class TwitterLoginInterceptorsTest { private val testServer = TestServerTwitter() private val testTemporaryCredentialStore = TestTemporaryCredentialStore() private val twitterLoginInterceptors = TwitterLoginInterceptors( ClientCredential("test-identifier", "test-secret"), "http://test.com/callback", object : Env { override val oauth: OAuth = OAuth(object : OAuth.Env { override val clock: Clock = Clock.fixed(Instant.parse("2015-01-01T00:00:00Z"), ZoneId.systemDefault()) override val nextInt: (Int) -> Int = { (it - 1) / 2 } }) override val httpClient: Call.Factory = TestCallFactory(testServer) override val httpCallContext: CoroutineContext = newSingleThreadContext("TestHttpCall") override val temporaryCredentialStore: TemporaryCredentialStore = testTemporaryCredentialStore }, object : OutputPort { override val success: OutputInterceptor<TwitterToken> = { call.respondText("test success") } override val twitterCallFailed: OutputInterceptor<TwitterCallFailedException> = { call.respondText("test twitter call failed") } override val temporaryCredentialNotFound: OutputInterceptor<TemporaryCredentialNotFoundException> = { call.respondText("test temporary credential not found (identifier : ${it.temporaryCredentialIdentifier})") } } ) private val testableModule: Application.() -> Unit = { routing { post("/start", twitterLoginInterceptors.startTwitterLogin) get("/callback", twitterLoginInterceptors.finishTwitterLogin) } } @Test fun testRequest() = withTestApplication(testableModule) { testServer.responseBuilders.add(responseBuilder { code(200).message("OK") body( ResponseBody.create( "application/x-www-form-urlencoded".toMediaTypeOrNull(), "oauth_token=test-temporary-token&oauth_token_secret=test-token-secret" ) ) }) handleRequest(HttpMethod.Post, "/start").run { assertEquals(HttpStatusCode.Found, response.status()) assertEquals( "https://api.twitter.com/oauth/authenticate?oauth_token=test-temporary-token", response.headers["Location"] ) } testServer.responseBuilders.add(responseBuilder { code(200).message("OK") body( ResponseBody.create( "application/x-www-form-urlencoded".toMediaTypeOrNull(), "oauth_token=test-access-token&oauth_token_secret=test-token-secret&user_id=101&screen_name=foo" ) ) }) handleRequest(HttpMethod.Get, "/callback?oauth_token=test-temporary-token&verifier=test-verifier").run { assertEquals(HttpStatusCode.OK, response.status()) assertEquals("test success", response.content) } } @Test fun redirect_twitterServerError() = withTestApplication(testableModule) { testServer.responseBuilders.add(responseBuilder { code(500).message("Internal Server Error") }) handleRequest(HttpMethod.Post, "/start").run { assertEquals(HttpStatusCode.OK, response.status()) assertEquals("test twitter call failed", response.content) } } @Test fun accessToken_twitterServerError() = withTestApplication(testableModule) { runBlocking { testTemporaryCredentialStore.saveTemporaryCredential( TemporaryCredential("test-temporary-token", "test-secret") ) } testServer.responseBuilders.add(responseBuilder { code(500).message("Internal Server Error") }) handleRequest(HttpMethod.Get, "/callback?oauth_token=test-temporary-token&verifier=test-verifier").run { assertEquals(HttpStatusCode.OK, response.status()) assertEquals("test twitter call failed", response.content) } } @Test fun accessToken_tokenNotFound() = withTestApplication(testableModule) { handleRequest(HttpMethod.Get, "/callback?oauth_token=test-temporary-token&verifier=test-verifier").run { assertEquals(HttpStatusCode.OK, response.status()) assertEquals("test temporary credential not found (identifier : test-temporary-token)", response.content) } } }
apache-2.0
Raizlabs/DBFlow
lib/src/main/kotlin/com/dbflow5/query/Operator.kt
1
23769
@file:Suppress("UNCHECKED_CAST") package com.dbflow5.query import com.dbflow5.annotation.Collate import com.dbflow5.appendOptional import com.dbflow5.config.FlowLog import com.dbflow5.config.FlowManager import com.dbflow5.converter.TypeConverter import com.dbflow5.query.property.Property import com.dbflow5.query.property.TypeConvertedProperty import com.dbflow5.sql.Query /** * Description: The class that contains a column name, Operator<T>, and value. * This class is mostly reserved for internal use at this point. Using this class directly should be avoided * and use the generated [Property] instead. </T> */ class Operator<T : Any?> internal constructor(nameAlias: NameAlias?, private val table: Class<*>? = null, private val getter: TypeConvertedProperty.TypeConverterGetter? = null, private val convertToDB: Boolean) : BaseOperator(nameAlias), IOperator<T> { private val typeConverter: TypeConverter<*, *>? by lazy { table?.let { table -> getter?.getTypeConverter(table) } } private var convertToString = true override val query: String get() = appendToQuery() internal constructor(operator: Operator<*>) : this(operator.nameAlias, operator.table, operator.getter, operator.convertToDB) { this.value = operator.value } override fun appendConditionToQuery(queryBuilder: StringBuilder) { queryBuilder.append(columnName()).append(operation()) // Do not use value for certain operators // If is raw, we do not want to convert the value to a string. if (isValueSet) { queryBuilder.append(if (convertToString) convertObjectToString(value(), true) else value()) } postArgument()?.let { queryBuilder.append(" $it") } } override fun isNull() = apply { operation = " ${Operation.IS_NULL} " } override fun isNotNull() = apply { operation = " ${Operation.IS_NOT_NULL} " } override fun `is`(value: T?): Operator<T> { operation = Operation.EQUALS return value(value) } override fun eq(value: T?): Operator<T> = `is`(value) override fun isNot(value: T?): Operator<T> { operation = Operation.NOT_EQUALS return value(value) } override fun notEq(value: T?): Operator<T> = isNot(value) /** * Uses the LIKE operation. Case insensitive comparisons. * * @param value Uses sqlite LIKE regex to match rows. * It must be a string to escape it properly. * There are two wildcards: % and _ * % represents [0,many) numbers or characters. * The _ represents a single number or character. * @return This condition */ override fun like(value: String): Operator<T> { operation = " ${Operation.LIKE} " return value(value) } /** * Uses the MATCH operation. Faster than [like], using an FTS4 Table. * * . If the WHERE clause of the SELECT statement contains a sub-clause of the form "<column> MATCH ?", * FTS is able to use the built-in full-text index to restrict the search to those documents * that match the full-text query string specified as the right-hand operand of the MATCH clause. * * @param value a simple string to match. */ override fun match(value: String): Operator<T> { operation = " ${Operation.MATCH} " return value(value) } /** * Uses the NOT LIKE operation. Case insensitive comparisons. * * @param value Uses sqlite LIKE regex to inversely match rows. * It must be a string to escape it properly. * There are two wildcards: % and _ * % represents [0,many) numbers or characters. * The _ represents a single number or character. * */ override fun notLike(value: String): Operator<T> { operation = " ${Operation.NOT_LIKE} " return value(value) } /** * Uses the GLOB operation. Similar to LIKE except it uses case sensitive comparisons. * * @param value Uses sqlite GLOB regex to match rows. * It must be a string to escape it properly. * There are two wildcards: * and ? * * represents [0,many) numbers or characters. * The ? represents a single number or character * */ override fun glob(value: String): Operator<T> { operation = " ${Operation.GLOB} " return value(value) } /** * The value of the parameter * * @param value The value of the column in the DB * */ fun value(value: Any?) = apply { this.value = value isValueSet = true } override fun greaterThan(value: T): Operator<T> { operation = Operation.GREATER_THAN return value(value) } override fun greaterThanOrEq(value: T): Operator<T> { operation = Operation.GREATER_THAN_OR_EQUALS return value(value) } override fun lessThan(value: T): Operator<T> { operation = Operation.LESS_THAN return value(value) } override fun lessThanOrEq(value: T): Operator<T> { operation = Operation.LESS_THAN_OR_EQUALS return value(value) } override fun plus(value: T): Operator<T> = assignValueOp(value, Operation.PLUS) override fun minus(value: T): Operator<T> = assignValueOp(value, Operation.MINUS) override fun div(value: T): Operator<T> = assignValueOp(value, Operation.DIVISION) override fun times(value: T): Operator<T> = assignValueOp(value, Operation.MULTIPLY) override fun rem(value: T): Operator<T> = assignValueOp(value, Operation.MOD) /** * Add a custom operation to this argument * * @param operation The SQLite operator * */ fun operation(operation: String) = apply { this.operation = operation } /** * Adds a COLLATE to the end of this condition * * @param collation The SQLite collate function * . */ infix fun collate(collation: String) = apply { postArg = "COLLATE $collation" } /** * Adds a COLLATE to the end of this condition using the [Collate] enum. * * @param collation The SQLite collate function * . */ infix fun collate(collation: Collate) = apply { if (collation == Collate.NONE) { postArg = null } else { collate(collation.name) } } /** * Appends an optional SQL string to the end of this condition */ infix fun postfix(postfix: String) = apply { postArg = postfix } /** * Optional separator when chaining this Operator within a [OperatorGroup] * * @param separator The separator to use * @return This instance */ override fun separator(separator: String) = apply { this.separator = separator } override fun `is`(conditional: IConditional): Operator<*> = assignValueOp(conditional, Operation.EQUALS) override fun eq(conditional: IConditional): Operator<*> = assignValueOp(conditional, Operation.EQUALS) override fun isNot(conditional: IConditional): Operator<*> = assignValueOp(conditional, Operation.NOT_EQUALS) override fun notEq(conditional: IConditional): Operator<*> = assignValueOp(conditional, Operation.NOT_EQUALS) override fun like(conditional: IConditional): Operator<T> = like(conditional.query) override fun glob(conditional: IConditional): Operator<T> = glob(conditional.query) override fun greaterThan(conditional: IConditional): Operator<T> = assignValueOp(conditional, Operation.GREATER_THAN) override fun greaterThanOrEq(conditional: IConditional): Operator<T> = assignValueOp(conditional, Operation.GREATER_THAN_OR_EQUALS) override fun lessThan(conditional: IConditional): Operator<T> = assignValueOp(conditional, Operation.LESS_THAN) override fun lessThanOrEq(conditional: IConditional): Operator<T> = assignValueOp(conditional, Operation.LESS_THAN_OR_EQUALS) override fun between(conditional: IConditional): Between<*> = Between(this as Operator<Any>, conditional) override fun `in`(firstConditional: IConditional, vararg conditionals: IConditional): In<*> = In(this as Operator<Any>, firstConditional, true, *conditionals) override fun notIn(firstConditional: IConditional, vararg conditionals: IConditional): In<*> = In(this as Operator<Any>, firstConditional, false, *conditionals) override fun notIn(firstBaseModelQueriable: BaseModelQueriable<*>, vararg baseModelQueriables: BaseModelQueriable<*>): In<*> = In(this as Operator<Any>, firstBaseModelQueriable, false, *baseModelQueriables) override fun `is`(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = assignValueOp(baseModelQueriable, Operation.EQUALS) override fun eq(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = assignValueOp(baseModelQueriable, Operation.EQUALS) override fun isNot(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = assignValueOp(baseModelQueriable, Operation.NOT_EQUALS) override fun notEq(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = assignValueOp(baseModelQueriable, Operation.NOT_EQUALS) override fun like(baseModelQueriable: BaseModelQueriable<*>): Operator<T> = assignValueOp(baseModelQueriable, Operation.LIKE) override fun notLike(conditional: IConditional): Operator<*> = assignValueOp(conditional, Operation.NOT_LIKE) override fun notLike(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = assignValueOp(baseModelQueriable, Operation.NOT_LIKE) override fun glob(baseModelQueriable: BaseModelQueriable<*>): Operator<T> = assignValueOp(baseModelQueriable, Operation.GLOB) override fun greaterThan(baseModelQueriable: BaseModelQueriable<*>): Operator<T> = assignValueOp(baseModelQueriable, Operation.GREATER_THAN) override fun greaterThanOrEq(baseModelQueriable: BaseModelQueriable<*>): Operator<T> = assignValueOp(baseModelQueriable, Operation.GREATER_THAN_OR_EQUALS) override fun lessThan(baseModelQueriable: BaseModelQueriable<*>): Operator<T> = assignValueOp(baseModelQueriable, Operation.LESS_THAN) override fun lessThanOrEq(baseModelQueriable: BaseModelQueriable<*>): Operator<T> = assignValueOp(baseModelQueriable, Operation.LESS_THAN_OR_EQUALS) operator fun plus(value: IConditional): Operator<*> = assignValueOp(value, Operation.PLUS) operator fun minus(value: IConditional): Operator<*> = assignValueOp(value, Operation.MINUS) operator fun div(value: IConditional): Operator<*> = assignValueOp(value, Operation.DIVISION) operator fun times(value: IConditional): Operator<*> = assignValueOp(value, Operation.MULTIPLY) operator fun rem(value: IConditional): Operator<*> = assignValueOp(value, Operation.MOD) override fun plus(value: BaseModelQueriable<*>): Operator<*> = assignValueOp(value, Operation.PLUS) override fun minus(value: BaseModelQueriable<*>): Operator<*> = assignValueOp(value, Operation.MINUS) override fun div(value: BaseModelQueriable<*>): Operator<*> = assignValueOp(value, Operation.DIVISION) override fun times(value: BaseModelQueriable<*>): Operator<*> = assignValueOp(value, Operation.MULTIPLY) override fun rem(value: BaseModelQueriable<*>): Operator<*> = assignValueOp(value, Operation.MOD) override fun between(baseModelQueriable: BaseModelQueriable<*>): Between<*> = Between(this as Operator<Any>, baseModelQueriable) override fun `in`(firstBaseModelQueriable: BaseModelQueriable<*>, vararg baseModelQueriables: BaseModelQueriable<*>): In<*> = In(this as Operator<Any>, firstBaseModelQueriable, true, *baseModelQueriables) override fun concatenate(value: Any?): Operator<T> { var _value = value operation = "${Operation.EQUALS}${columnName()}" var typeConverter: TypeConverter<*, Any>? = this.typeConverter as TypeConverter<*, Any>? if (typeConverter == null && _value != null) { typeConverter = FlowManager.getTypeConverterForClass(_value.javaClass) as TypeConverter<*, Any>? } if (typeConverter != null && convertToDB) { _value = typeConverter.getDBValue(_value) } operation = when (_value) { is String, is IOperator<*>, is Char -> "$operation ${Operation.CONCATENATE} " is Number -> "$operation ${Operation.PLUS} " else -> throw IllegalArgumentException( "Cannot concatenate the ${if (_value != null) _value.javaClass else "null"}") } this.value = _value isValueSet = true return this } override fun concatenate(conditional: IConditional): Operator<T> = concatenate(conditional as Any) /** * Turns this condition into a SQL BETWEEN operation * * @param value The value of the first argument of the BETWEEN clause * @return Between operator */ override fun between(value: T): Between<T> = Between(this, value) @SafeVarargs override fun `in`(firstValue: T, vararg values: T): In<T> = In(this, firstValue, true, *values) @SafeVarargs override fun notIn(firstValue: T, vararg values: T): In<T> = In(this, firstValue, false, *values) override fun `in`(values: Collection<T>): In<T> = In(this, values, true) override fun notIn(values: Collection<T>): In<T> = In(this, values, false) override fun convertObjectToString(obj: Any?, appendInnerParenthesis: Boolean): String = (typeConverter as? TypeConverter<*, Any>?)?.let { typeConverter -> var converted = obj try { converted = if (convertToDB) typeConverter.getDBValue(obj) else obj } catch (c: ClassCastException) { // if object type is not valid converted type, just use type as is here. // if object type is not valid converted type, just use type as is here. FlowLog.log(FlowLog.Level.I, "Value passed to operation is not valid type" + " for TypeConverter in the column. Preserving value $obj to be used as is.") } convertValueToString(converted, appendInnerParenthesis, false) } ?: super.convertObjectToString(obj, appendInnerParenthesis) private fun assignValueOp(value: Any?, operation: String): Operator<T> { return if (!isValueSet) { this.operation = operation value(value) } else { convertToString = false // convert value to a string value because of conversion. value(convertValueToString(this.value) + operation + convertValueToString(value)) } } /** * Static constants that define condition operations */ object Operation { /** * Equals comparison */ const val EQUALS = "=" /** * Not-equals comparison */ const val NOT_EQUALS = "!=" /** * String concatenation */ const val CONCATENATE = "||" /** * Number addition */ const val PLUS = "+" /** * Number subtraction */ const val MINUS = "-" const val DIVISION = "/" const val MULTIPLY = "*" const val MOD = "%" /** * If something is LIKE another (a case insensitive search). * There are two wildcards: % and _ * % represents [0,many) numbers or characters. * The _ represents a single number or character. */ const val LIKE = "LIKE" /** * If the WHERE clause of the SELECT statement contains a sub-clause of the form "<column> MATCH ?", * FTS is able to use the built-in full-text index to restrict the search to those documents * that match the full-text query string specified as the right-hand operand of the MATCH clause. */ const val MATCH = "MATCH" /** * If something is NOT LIKE another (a case insensitive search). * There are two wildcards: % and _ * % represents [0,many) numbers or characters. * The _ represents a single number or character. */ const val NOT_LIKE = "NOT LIKE" /** * If something is case sensitive like another. * It must be a string to escape it properly. * There are two wildcards: * and ? * * represents [0,many) numbers or characters. * The ? represents a single number or character */ const val GLOB = "GLOB" /** * Greater than some value comparison */ const val GREATER_THAN = ">" /** * Greater than or equals to some value comparison */ const val GREATER_THAN_OR_EQUALS = ">=" /** * Less than some value comparison */ const val LESS_THAN = "<" /** * Less than or equals to some value comparison */ const val LESS_THAN_OR_EQUALS = "<=" /** * Between comparison. A simplification of X&lt;Y AND Y&lt;Z to Y BETWEEN X AND Z */ const val BETWEEN = "BETWEEN" /** * AND comparison separator */ const val AND = "AND" /** * OR comparison separator */ const val OR = "OR" /** * An empty value for the condition. */ @Deprecated(replaceWith = ReplaceWith( expression = "Property.WILDCARD", imports = ["com.dbflow5.query.Property"] ), message = "Deprecated. This will translate to '?' in the query as it get's SQL-escaped. " + "Use the Property.WILDCARD instead to get desired ? behavior.") const val EMPTY_PARAM = "?" /** * Special operation that specify if the column is not null for a specified row. Use of this as * an operator will ignore the value of the [Operator] for it. */ const val IS_NOT_NULL = "IS NOT NULL" /** * Special operation that specify if the column is null for a specified row. Use of this as * an operator will ignore the value of the [Operator] for it. */ const val IS_NULL = "IS NULL" /** * The SQLite IN command that will select rows that are contained in a list of values. * EX: SELECT * from Table where column IN ('first', 'second', etc) */ const val IN = "IN" /** * The reverse of the [.IN] command that selects rows that are not contained * in a list of values specified. */ const val NOT_IN = "NOT IN" } /** * The SQL BETWEEN operator that contains two values instead of the normal 1. */ class Between<T> /** * Creates a new instance * * @param operator * @param value The value of the first argument of the BETWEEN clause */ internal constructor(operator: Operator<T>, value: T) : BaseOperator(operator.nameAlias), Query { private var secondValue: T? = null override val query: String get() = appendToQuery() init { this.operation = " ${Operation.BETWEEN} " this.value = value isValueSet = true this.postArg = operator.postArgument() } infix fun and(secondValue: T?) = apply { this.secondValue = secondValue } fun secondValue(): T? = secondValue override fun appendConditionToQuery(queryBuilder: StringBuilder) { queryBuilder.append(columnName()).append(operation()) .append(convertObjectToString(value(), true)) .append(" ${Operation.AND} ") .append(convertObjectToString(secondValue(), true)) .append(" ") .appendOptional(postArgument()) } } /** * The SQL IN and NOT IN operator that specifies a list of values to SELECT rows from. * EX: SELECT * FROM myTable WHERE columnName IN ('column1','column2','etc') */ class In<T> : BaseOperator, Query { private val inArguments = arrayListOf<T?>() override val query: String get() = appendToQuery() /** * Creates a new instance * * @param operator The operator object to pass in. We only use the column name here. * @param firstArgument The first value in the IN query as one is required. * @param isIn if this is an [Operator.Operation.IN] * statement or a [Operator.Operation.NOT_IN] */ @SafeVarargs internal constructor(operator: Operator<T>, firstArgument: T?, isIn: Boolean, vararg arguments: T?) : super(operator.columnAlias()) { inArguments.add(firstArgument) inArguments.addAll(arguments) operation = " ${if (isIn) Operation.IN else Operation.NOT_IN} " } internal constructor(operator: Operator<T>, args: Collection<T>, isIn: Boolean) : super(operator.columnAlias()) { inArguments.addAll(args) operation = " ${if (isIn) Operation.IN else Operation.NOT_IN} " } /** * Appends another value to this In statement * * @param argument The non-type converted value of the object. The value will be converted * in a [OperatorGroup]. * @return */ infix fun and(argument: T?): In<T> { inArguments.add(argument) return this } override fun appendConditionToQuery(queryBuilder: StringBuilder) { queryBuilder.append(columnName()) .append(operation()) .append("(") .append(joinArguments(",", inArguments, this)) .append(")") } } companion object { @JvmStatic fun convertValueToString(value: Any?): String? = convertValueToString(value, false) @JvmStatic fun <T> op(column: NameAlias): Operator<T> = Operator(column, convertToDB = false) @JvmStatic fun <T> op(alias: NameAlias, table: Class<*>, getter: TypeConvertedProperty.TypeConverterGetter, convertToDB: Boolean): Operator<T> = Operator(alias, table, getter, convertToDB) } } fun <T : Any> NameAlias.op() = Operator.op<T>(this) fun <T : Any> String.op(): Operator<T> = nameAlias.op() infix fun <T : Any> Operator<T>.and(sqlOperator: SQLOperator): OperatorGroup = OperatorGroup.clause(this).and(sqlOperator) infix fun <T : Any> Operator<T>.or(sqlOperator: SQLOperator): OperatorGroup = OperatorGroup.clause(this).or(sqlOperator) infix fun <T : Any> Operator<T>.andAll(sqlOperator: Collection<SQLOperator>): OperatorGroup = OperatorGroup.clause(this).andAll(sqlOperator) infix fun <T : Any> Operator<T>.orAll(sqlOperator: Collection<SQLOperator>): OperatorGroup = OperatorGroup.clause(this).orAll(sqlOperator) infix fun <T : Any> Operator<T>.`in`(values: Array<T>): Operator.In<T> = when (values.size) { 1 -> `in`(values[0]) else -> this.`in`(values[0], *values.sliceArray(IntRange(1, values.size))) } infix fun <T : Any> Operator<T>.notIn(values: Array<T>): Operator.In<T> = when (values.size) { 1 -> notIn(values[0]) else -> this.notIn(values[0], *values.sliceArray(IntRange(1, values.size))) }
mit
code-helix/slatekit
src/lib/kotlin/slatekit-tests/src/test/kotlin/test/entities/Data_04_Database_Procs.kt
1
1195
package test.entities import org.junit.Assert import org.junit.Test import org.threeten.bp.LocalDate import org.threeten.bp.LocalDateTime import org.threeten.bp.LocalTime import slatekit.common.DateTimes import slatekit.common.data.* import slatekit.common.ids.ULIDs import slatekit.db.Db import test.setup.TestSupport import java.util.* /** * DONE: * 1. connect : Db.of() // config, con, etc * 2. prepare : db.update("sql..", listOf(...) ) * 3. methodX : db.... * * * 4. ddl : db.createTable, createColumn, createKey, createIndex ( just for models ) * 4. Sqlite : SqliteProvider .... * 5. Postgres: PostgresProvider .... */ class Data_04_Database_Procs : TestSupport { private val table = "sample_entity" @Test fun can_execute_proc() { val db = db() val result = db.callQuery("dbtests_get_max_id", { rs -> rs.getLong(1) }) Assert.assertTrue(result!! > 0L) } @Test fun can_execute_proc_update() { val db = db() val result = db.callUpdate("dbtests_update_by_id", listOf(Value("", DataType.DTInt, 6))) Assert.assertTrue(result!! >= 1) } fun db(): IDb { return EntitySetup.db() } }
apache-2.0
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/boxInline/nonLocalReturns/deparenthesize/bracket.kt
5
669
// FILE: 1.kt package test public inline fun <R> doCall(block: ()-> R) : R { return block() } // FILE: 2.kt import test.* fun test1(b: Boolean): String { val localResult = doCall ((local@ { if (b) { return@local "local" } else { return "nonLocal" } })) return "result=" + localResult; } fun test2(nonLocal: String): String { val localResult = doCall { return nonLocal } } fun box(): String { val test1 = test1(true) if (test1 != "result=local") return "test1: ${test1}" val test2 = test1(false) if (test2 != "nonLocal") return "test2: ${test2}" return "OK" }
apache-2.0
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/evaluate/parenthesized.kt
2
1314
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME @Retention(AnnotationRetention.RUNTIME) annotation class Ann( val p1: Byte, val p2: Short, val p3: Int, val p4: Long, val p5: Double, val p6: Float ) val prop1: Byte = (1 + 2) * 2 val prop2: Short = (1 + 2) * 2 val prop3: Int = (1 + 2) * 2 val prop4: Long = (1 + 2) * 2 val prop5: Double = (1.0 + 2) * 2 val prop6: Float = (1.toFloat() + 2) * 2 @Ann((1 + 2) * 2, (1 + 2) * 2, (1 + 2) * 2, (1 + 2) * 2, (1.0 + 2) * 2, (1.toFloat() + 2) * 2) class MyClass fun box(): String { val annotation = MyClass::class.java.getAnnotation(Ann::class.java)!! if (annotation.p1 != prop1) return "fail 1, expected = ${prop1}, actual = ${annotation.p1}" if (annotation.p2 != prop2) return "fail 2, expected = ${prop2}, actual = ${annotation.p2}" if (annotation.p3 != prop3) return "fail 3, expected = ${prop3}, actual = ${annotation.p3}" if (annotation.p4 != prop4) return "fail 4, expected = ${prop4}, actual = ${annotation.p4}" if (annotation.p5 != prop5) return "fail 5, expected = ${prop5}, actual = ${annotation.p5}" if (annotation.p6 != prop6) return "fail 6, expected = ${prop6}, actual = ${annotation.p6}" return "OK" }
apache-2.0
room-15/ChatSE
app/src/main/java/com/tristanwiley/chatse/about/pokos/AboutIconPoko.kt
1
285
package com.tristanwiley.chatse.about.pokos import android.view.View /** * Created by mauker on 31/08/17. * Class that represents an icon, it carries a click listener. */ data class AboutIconPoko(val iconResource: Int, val message: String, val clickListener: View.OnClickListener)
apache-2.0
InventiDevelopment/AndroidSkeleton
app/src/main/java/cz/inventi/inventiskeleton/presentation/common/BaseView.kt
1
582
package cz.inventi.inventiskeleton.presentation.common import android.app.Activity import android.support.design.widget.Snackbar import android.view.ViewGroup import com.hannesdorfmann.mosby3.mvp.MvpView /** * Created by tomas.valenta on 5/11/2017. */ interface BaseView : MvpView { fun getParentActivity(): Activity? fun showError(errorText: String) { val content: ViewGroup? = getParentActivity()?.findViewById(android.R.id.content) content?.getChildAt(0)?.let { Snackbar.make(it, errorText, Snackbar.LENGTH_LONG).show() } } }
apache-2.0
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/ranges/forInUntil/forInUntilLong.kt
3
853
// WITH_RUNTIME import kotlin.test.assertEquals fun testLongInLongUntilLong() { var sum = 0 for (i in 1L until 5L) { sum = sum * 10 + i.toInt() } assertEquals(1234, sum) } fun testLongInLongUntilInt() { var sum = 0 for (i in 1L until 5.toInt()) { sum = sum * 10 + i.toInt() } assertEquals(1234, sum) } fun testLongInIntUntilLong() { var sum = 0 for (i in 1.toInt() until 5L) { sum = sum * 10 + i.toInt() } assertEquals(1234, sum) } fun testNullableLongInIntUntilLong() { var sum = 0 for (i: Long? in 1.toInt() until 5L) { sum = sum * 10 + (i?.toInt() ?: break) } assertEquals(1234, sum) } fun box(): String { testLongInLongUntilLong() testLongInIntUntilLong() testLongInLongUntilInt() testNullableLongInIntUntilLong() return "OK" }
apache-2.0
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/boxInline/defaultValues/maskElimination/kt19679.kt
2
269
// FILE: 1.kt package test inline fun build(func: () -> Unit, noinline pathFunc: (() -> String)? = null) { func() pathFunc?.invoke() } // FILE: 2.kt import test.* fun box(): String { var result = "fail" build({ result = "OK" }) return result }
apache-2.0
Pozo/threejs-kotlin
threejs-dsl/src/main/kotlin/three/dsl/CoreDsl.kt
1
3014
package three import three.core.Object3D import three.lights.DirectionalLight import three.materials.Material import three.materials.MaterialColors import three.materials.basic.MeshBasicMaterial import three.materials.basic.MeshBasicMaterialParam import three.materials.phong.MeshPhongMaterial import three.materials.phong.MeshPhongMaterialParam import three.math.Color import three.objects.Mesh import three.scenes.Scene @DslMarker annotation class ThreejsDSL interface Object3DBuilder { fun build(): Object3D } @ThreejsDSL class MeshBuilder : Object3DBuilder { val objects = mutableListOf<Object3D>() var geometry: dynamic = null var material: dynamic = null var x: Double? = null var y: Double? = null var rotationX: Double? = null override fun build(): Object3D { val mesh = Mesh(geometry, material) x?.apply { mesh.position.x = x as Double } y?.apply { mesh.position.y = y as Double } rotationX?.apply { mesh.rotation.x = rotationX as Double } for (`object` in objects) { mesh.add(`object`) } return mesh } fun mesh(setup: MeshBuilder.() -> Unit = {}) { val meshBuilder = MeshBuilder() meshBuilder.setup() objects += meshBuilder.build() } } @ThreejsDSL class SceneBuilder { val objects = mutableListOf<Object3D>() var background: Int = 0 operator fun Object3D.unaryPlus() { objects += this } fun build(): Scene { val scene = Scene() scene.background = Color(background) for (`object` in objects) { scene.add(`object`) } return scene } @Suppress("UNUSED_PARAMETER") @Deprecated(level = DeprecationLevel.ERROR, message = "Scene can't be nested.") fun scene(param: () -> Unit = {}) { } fun mesh(setup: MeshBuilder.() -> Unit = {}) { val meshBuilder = MeshBuilder() meshBuilder.setup() objects += meshBuilder.build() } fun directionalLight(setup: DirectionalLightBuilder.() -> Unit = {}) { val meshBuilder = DirectionalLightBuilder() meshBuilder.setup() objects += meshBuilder.build() } } @ThreejsDSL class DirectionalLightBuilder : Object3DBuilder { var color: Int? = null var intensity: Float? = null var x: Float = 0f var y: Float = 0f var z: Float = 0f override fun build(): Object3D { val mesh = DirectionalLight() color?.apply { mesh.color = Color(color as Int) } intensity?.apply { mesh.intensity = intensity as Float } mesh.position.set(x, y, z) return mesh } @Suppress("UNUSED_PARAMETER") @Deprecated(level = DeprecationLevel.ERROR, message = "Directional Light can't be nested.") fun directionalLight(param: () -> Unit = {}) { } } fun scene(setup: SceneBuilder.() -> Unit): Scene { val sectionBuilder = SceneBuilder() sectionBuilder.setup() return sectionBuilder.build() }
mit
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/enums/ViewPrivacyType.kt
1
1251
package com.vimeo.networking2.enums /** * Privacy values that can be set for viewing a video. */ enum class ViewPrivacyType(override val value: String?) : StringValue { /** * Anyone can view the user's videos. */ ANYBODY("anybody"), /** * This is a stock video and may have limited access restrictions. */ STOCK("stock"), /** * This is an on-demand video that is limited to buyers of the video. */ TVOD("ptv"), /** * Only contacts can view the user's videos. */ CONTACTS("contacts"), /** * Views are disabled for the user's videos. */ DISABLE("disable"), /** * The videos don't appear on Vimeo, but they can be embedded elsewhere. */ EMBED_ONLY("embed_only"), /** * No one except the user can view the user's videos. */ NOBODY("nobody"), /** * Only those with the password can view the user's videos. */ PASSWORD("password"), /** * Anybody can view the user's videos if they have a link. */ UNLISTED("unlisted"), /** * Only other Vimeo members can view the user's videos. */ USERS("users"), /** * Unknown privacy value. */ UNKNOWN(null) }
mit
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/usageHighlighter/importAliasFromStdLibPropertyFromObject.kt
9
146
// WITH_STDLIB import kotlin.Int.Companion.MAX_VALUE as <info descr="null">~maxValue</info> fun main() { <info descr="null">maxValue</info> }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/coroutines/DirectUseOfResultTypeInspection.kt
3
4331
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.coroutines import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.types.KotlinType class DirectUseOfResultTypeInspection : AbstractIsResultInspection( typeShortName = SHORT_NAME, typeFullName = "kotlin.Result", allowedSuffix = CATCHING, allowedNames = setOf("success", "failure", "runCatching"), suggestedFunctionNameToCall = "getOrThrow" ) { private fun MemberScope.hasCorrespondingNonCatchingFunction( nameWithoutCatching: String, valueParameters: List<ValueParameterDescriptor>, returnType: KotlinType?, extensionReceiverType: KotlinType? ): Boolean { val nonCatchingFunctions = getContributedFunctions(Name.identifier(nameWithoutCatching), NoLookupLocation.FROM_IDE) return nonCatchingFunctions.any { nonCatchingFun -> nonCatchingFun.valueParameters.size == valueParameters.size && nonCatchingFun.returnType == returnType && nonCatchingFun.extensionReceiverParameter?.type == extensionReceiverType } } private fun FunctionDescriptor.hasCorrespondingNonCatchingFunction(returnType: KotlinType, nameWithoutCatching: String): Boolean? { val containingDescriptor = containingDeclaration val scope = when (containingDescriptor) { is ClassDescriptor -> containingDescriptor.unsubstitutedMemberScope is PackageFragmentDescriptor -> containingDescriptor.getMemberScope() else -> return null } val returnTypeArgument = returnType.arguments.firstOrNull()?.type val extensionReceiverType = extensionReceiverParameter?.type if (scope.hasCorrespondingNonCatchingFunction(nameWithoutCatching, valueParameters, returnTypeArgument, extensionReceiverType)) { return true } if (extensionReceiverType != null) { val extensionClassDescriptor = extensionReceiverType.constructor.declarationDescriptor as? ClassDescriptor if (extensionClassDescriptor != null) { val extensionClassScope = extensionClassDescriptor.unsubstitutedMemberScope if (extensionClassScope.hasCorrespondingNonCatchingFunction( nameWithoutCatching, valueParameters, returnTypeArgument, extensionReceiverType = null ) ) { return true } } } return false } override fun analyzeFunctionWithAllowedSuffix( name: String, descriptor: FunctionDescriptor, toReport: PsiElement, holder: ProblemsHolder ) { val returnType = descriptor.returnType ?: return val nameWithoutCatching = name.substringBeforeLast(CATCHING) if (descriptor.hasCorrespondingNonCatchingFunction(returnType, nameWithoutCatching) == false) { val returnTypeArgument = returnType.arguments.firstOrNull()?.type val typeName = returnTypeArgument?.constructor?.declarationDescriptor?.name?.asString() ?: "T" holder.registerProblem( toReport, KotlinBundle.message( "function.0.returning.1.without.the.corresponding", name, "$SHORT_NAME<$typeName>", nameWithoutCatching, typeName ), ProblemHighlightType.GENERIC_ERROR_OR_WARNING ) } } } private const val SHORT_NAME = "Result" private const val CATCHING = "Catching"
apache-2.0
LouisCAD/Splitties
modules/views-dsl-material/src/androidMain/kotlin/splitties/views/dsl/material/TextInputLayout.kt
1
974
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.views.dsl.material import androidx.annotation.IdRes import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputLayout import splitties.views.dsl.core.add import splitties.views.dsl.core.matchParent import splitties.views.dsl.core.view import splitties.views.dsl.core.wrapContent import kotlin.contracts.InvocationKind import kotlin.contracts.contract import android.widget.LinearLayout.LayoutParams as LP inline fun TextInputLayout.addInput( @IdRes id: Int, initView: TextInputEditText.() -> Unit = {} ): TextInputEditText { contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) } return add( view( createView = ::TextInputEditText, id = id, initView = initView ), LP(matchParent, wrapContent) ) }
apache-2.0
smmribeiro/intellij-community
uast/uast-common/src/org/jetbrains/uast/kinds/UastClassKind.kt
19
1175
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast /** * Kinds of [UClass]. */ open class UastClassKind(val text: String) { companion object { @JvmField val CLASS: UastClassKind = UastClassKind("class") @JvmField val INTERFACE: UastClassKind = UastClassKind("interface") @JvmField val ANNOTATION: UastClassKind = UastClassKind("annotation") @JvmField val ENUM: UastClassKind = UastClassKind("enum") @JvmField val OBJECT: UastClassKind = UastClassKind("object") } override fun toString(): String { return "UastClassKind(text='$text')" } }
apache-2.0
smmribeiro/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/google/authorization/GoogleCredentials.kt
7
767
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.google.authorization import com.intellij.collaboration.auth.credentials.CredentialsWithRefresh import java.util.* class GoogleCredentials( override val accessToken: String, override val refreshToken: String, override val expiresIn: Long, val tokenType: String, val scope: String, val expirationTime: Date) : CredentialsWithRefresh { /** * @return true if the token has not expired yet; * false if the token has already expired. */ override fun isAccessTokenValid(): Boolean = Date(System.currentTimeMillis()).before(expirationTime) }
apache-2.0
smmribeiro/intellij-community
platform/platform-tests/testSrc/com/intellij/ide/plugins/DynamicPluginsTest.kt
1
26719
// 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. @file:Suppress("UsePropertyAccessSyntax") package com.intellij.ide.plugins import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.impl.config.IntentionManagerImpl import com.intellij.codeInspection.GlobalInspectionTool import com.intellij.codeInspection.InspectionEP import com.intellij.codeInspection.ex.InspectionToolRegistrar import com.intellij.ide.plugins.cl.PluginClassLoader import com.intellij.ide.startup.impl.StartupManagerImpl import com.intellij.ide.ui.UISettings import com.intellij.ide.ui.UISettingsListener import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.extensions.InternalIgnoreDependencyViolation import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.module.ModuleConfigurationEditor import com.intellij.openapi.options.Configurable import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ui.configuration.ModuleConfigurationEditorProvider import com.intellij.openapi.roots.ui.configuration.ModuleConfigurationState import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.use import com.intellij.psi.PsiFile import com.intellij.testFramework.EdtRule import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.RunsInEdt import com.intellij.testFramework.assertions.Assertions.assertThat import com.intellij.testFramework.rules.InMemoryFsRule import com.intellij.ui.switcher.ShowQuickActionPopupAction import com.intellij.util.KeyedLazyInstanceEP import com.intellij.util.io.Ksuid import com.intellij.util.ui.UIUtil import com.intellij.util.xmlb.annotations.Attribute import org.junit.Rule import org.junit.Test import java.nio.file.Files import java.util.concurrent.atomic.AtomicInteger @RunsInEdt class DynamicPluginsTest { companion object { val receivedNotifications = mutableListOf<UISettings>() val receivedNotifications2 = mutableListOf<UISettings>() } // per test @Rule @JvmField val projectRule = ProjectRule() @Rule @JvmField val inMemoryFs = InMemoryFsRule() @Rule @JvmField val runInEdt = EdtRule() private fun loadPluginWithText(pluginBuilder: PluginBuilder): Disposable { return loadPluginWithText(pluginBuilder, inMemoryFs.fs) } @Test fun testLoadListeners() { receivedNotifications.clear() val app = ApplicationManager.getApplication() app.messageBus.syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(UISettings()) val path = inMemoryFs.fs.getPath("/plugin") PluginBuilder().name("testLoadListeners").applicationListeners(""" <listener class="${MyUISettingsListener::class.java.name}" topic="com.intellij.ide.ui.UISettingsListener"/> """.trimIndent()).build(path) val descriptor = loadDescriptorInTest(path) setPluginClassLoaderForMainAndSubPlugins(descriptor, DynamicPlugins::class.java.classLoader) DynamicPlugins.loadPlugin(descriptor) app.messageBus.syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(UISettings()) assertThat(receivedNotifications).hasSize(1) DynamicPlugins.unloadAndUninstallPlugin(descriptor) app.messageBus.syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(UISettings()) assertThat(receivedNotifications).hasSize(1) } @Test fun testClassloaderAfterReload() { val path = inMemoryFs.fs.getPath("/plugin") val builder = PluginBuilder().randomId("bar").also { it.build(path) } val descriptor = loadDescriptorInTest(path) assertThat(descriptor).isNotNull DynamicPlugins.loadPlugin(descriptor) DisabledPluginsState.saveDisabledPlugins(PathManager.getConfigDir(), builder.id) DynamicPlugins.unloadAndUninstallPlugin(descriptor) assertThat(PluginManagerCore.getPlugin(descriptor.pluginId)?.pluginClassLoader as? PluginClassLoader).isNull() DisabledPluginsState.saveDisabledPlugins(PathManager.getConfigDir()) val newDescriptor = loadDescriptorInTest(path) ClassLoaderConfigurator(PluginManagerCore.getPluginSet().enablePlugin(newDescriptor)).configureModule(newDescriptor) DynamicPlugins.loadPlugin(newDescriptor) try { assertThat(PluginManagerCore.getPlugin(descriptor.pluginId)?.pluginClassLoader as? PluginClassLoader).isNotNull() } finally { DynamicPlugins.unloadAndUninstallPlugin(newDescriptor) } } @Test fun testSaveSettingsOnPluginUnload() { val data = System.currentTimeMillis().toString() val extensionTag = "<applicationService serviceImplementation=\"${MyPersistentComponent::class.java.name}\"/>" val disposable = loadExtensionWithText(extensionTag) val service = ApplicationManager.getApplication().getService(MyPersistentComponent::class.java) service.myState.stateData = data Disposer.dispose(disposable) val disposable2 = loadExtensionWithText(extensionTag) val service2 = ApplicationManager.getApplication().getService(MyPersistentComponent::class.java) assertThat(service2.myState.stateData).isEqualTo(data) Disposer.dispose(disposable2) } @Test fun unloadActionReference() { val disposable = loadPluginWithText(PluginBuilder().actions(""" <reference ref="QuickActionPopup"> <add-to-group group-id="ListActions" anchor="last"/> </reference>""")) val group = ActionManager.getInstance().getAction("ListActions") as DefaultActionGroup assertThat(group.getChildren(null).any { it is ShowQuickActionPopupAction }).isTrue() Disposer.dispose(disposable) assertThat(group.getChildren(null).any { it is ShowQuickActionPopupAction }).isFalse() } @Test fun unloadGroupWithActions() { val disposable = loadPluginWithText(PluginBuilder().actions(""" <group id="Foo"> <action id="foo.bar" class="${MyAction::class.java.name}"/> </group>""")) assertThat(ActionManager.getInstance().getAction("foo.bar")).isNotNull() Disposer.dispose(disposable) assertThat(ActionManager.getInstance().getAction("foo.bar")).isNull() } @Test fun unloadGroupWithActionReferences() { ActionManager.getInstance() val disposable = loadPluginWithText(PluginBuilder().actions(""" <action id="foo.bar" class="${MyAction::class.java.name}"/> <action id="foo.bar2" class="${MyAction2::class.java.name}"/> <group id="Foo"> <reference ref="foo.bar"/> <reference ref="foo.bar2"/> </group>""")) assertThat(ActionManager.getInstance().getAction("foo.bar")).isNotNull() Disposer.dispose(disposable) assertThat(ActionManager.getInstance().getAction("foo.bar")).isNull() } @Test fun unloadNestedGroupWithActions() { val disposable = loadPluginWithText(PluginBuilder().actions(""" <group id="Foo"> <group id="Bar"> <action id="foo.bar" class="${MyAction::class.java.name}"/> </group> </group>""")) assertThat(ActionManager.getInstance().getAction("foo.bar")).isNotNull() Disposer.dispose(disposable) assertThat(ActionManager.getInstance().getAction("foo.bar")).isNull() } @Test fun loadNonDynamicEP() { val epName = "one.foo" val pluginBuilder = PluginBuilder() .randomId("nonDynamic") .extensionPoints("""<extensionPoint qualifiedName="$epName" interface="java.lang.Runnable"/>""") .extensions("""<foo implementation="${MyRunnable::class.java.name}"/>""", "one") val descriptor = loadDescriptorInTest( pluginBuilder, Files.createTempDirectory(inMemoryFs.fs.getPath("/"), null), ) assertThat(DynamicPlugins.checkCanUnloadWithoutRestart(descriptor)) .isEqualTo("Plugin ${descriptor.pluginId} is not unload-safe because of extension to non-dynamic EP $epName") } @Test fun loadOptionalDependency() { // match production - on plugin load/unload ActionManager is already initialized val actionManager = ActionManager.getInstance() runAndCheckThatNoNewPlugins { val dependency = PluginBuilder().randomId("dependency").packagePrefix("org.dependency") val dependent = PluginBuilder() .randomId("dependent") .packagePrefix("org.dependent") .module( "org.dependent", PluginBuilder().actions("""<group id="FooBarGroup"></group>""").packagePrefix("org.dependent.sub").pluginDependency(dependency.id) ) loadPluginWithText(dependent).use { assertThat(actionManager.getAction("FooBarGroup")).isNull() runAndCheckThatNoNewPlugins { loadPluginWithText(dependency).use { assertThat(actionManager.getAction("FooBarGroup")).isNotNull() } } assertThat(actionManager.getAction("FooBarGroup")).isNull() } } } @Test fun loadOptionalDependencyDuplicateNotification() { InspectionToolRegistrar.getInstance().createTools() val barBuilder = PluginBuilder().randomId("bar") val barDisposable = loadPluginWithText(barBuilder) val fooDisposable = loadPluginWithOptionalDependency( PluginBuilder().extensions("""<globalInspection implementationClass="${MyInspectionTool::class.java.name}"/>"""), PluginBuilder().extensions("""<globalInspection implementationClass="${MyInspectionTool2::class.java.name}"/>"""), barBuilder ) assertThat(InspectionEP.GLOBAL_INSPECTION.extensions.count { it.implementationClass == MyInspectionTool::class.java.name || it.implementationClass == MyInspectionTool2::class.java.name }).isEqualTo(2) Disposer.dispose(fooDisposable) Disposer.dispose(barDisposable) } @Test fun loadOptionalDependencyExtension() { val pluginTwoBuilder = PluginBuilder() .randomId("optionalDependencyExtension-two") .packagePrefix("org.foo.two") .extensionPoints( """<extensionPoint qualifiedName="bar.barExtension" beanClass="com.intellij.util.KeyedLazyInstanceEP" dynamic="true"/>""") val plugin1Disposable = loadPluginWithText( PluginBuilder() .randomId("optionalDependencyExtension-one") .packagePrefix("org.foo.one") .noDepends() .module( moduleName = "intellij.foo.one.module1", moduleDescriptor = PluginBuilder() .extensions("""<barExtension key="foo" implementationClass="y"/>""", "bar") .dependency(pluginTwoBuilder.id) .packagePrefix("org.foo"), ) ) try { val plugin2Disposable = loadPluginWithText(pluginTwoBuilder) val extensionArea = ApplicationManager.getApplication().extensionArea try { val ep = extensionArea.getExtensionPointIfRegistered<KeyedLazyInstanceEP<*>>("bar.barExtension") assertThat(ep).isNotNull() val extensions = ep!!.extensionList assertThat(extensions).hasSize(1) assertThat(extensions.single().key).isEqualTo("foo") } finally { Disposer.dispose(plugin2Disposable) } assertThat(extensionArea.hasExtensionPoint("bar.barExtension")).isFalse() } finally { Disposer.dispose(plugin1Disposable) } } @Test fun loadOptionalDependencyOwnExtension() { val barBuilder = PluginBuilder().randomId("bar").packagePrefix("bar") val fooBuilder = PluginBuilder().randomId("foo").packagePrefix("foo") .extensionPoints( """<extensionPoint qualifiedName="foo.barExtension" beanClass="com.intellij.util.KeyedLazyInstanceEP" dynamic="true"/>""") .module("intellij.foo.sub", PluginBuilder() .extensions("""<barExtension key="foo" implementationClass="y"/>""", "foo") .packagePrefix("foo1") .pluginDependency(barBuilder.id) ) loadPluginWithText(fooBuilder).use { val ep = ApplicationManager.getApplication().extensionArea.getExtensionPointIfRegistered<KeyedLazyInstanceEP<*>>("foo.barExtension") assertThat(ep).isNotNull() loadPluginWithText(barBuilder).use { val extension = ep!!.extensionList.single() assertThat(extension.key).isEqualTo("foo") assertThat(extension.pluginDescriptor) .isEqualTo(PluginManagerCore.getPluginSet().findEnabledModule("intellij.foo.sub")!!) } assertThat(ep!!.extensionList).isEmpty() } } @Test fun loadOptionalDependencyDescriptor() { val pluginOneBuilder = PluginBuilder().randomId("optionalDependencyDescriptor-one") val app = ApplicationManager.getApplication() loadPluginWithText(pluginOneBuilder).use { assertThat(app.getService(MyPersistentComponent::class.java)).isNull() val pluginTwoId = "optionalDependencyDescriptor-two_${Ksuid.generate()}" loadPluginWithOptionalDependency( PluginBuilder().id(pluginTwoId), PluginBuilder().extensions("""<applicationService serviceImplementation="${MyPersistentComponent::class.java.name}"/>"""), pluginOneBuilder ).use { assertThat(app.getService(MyPersistentComponent::class.java)).isNotNull() } assertThat(PluginManagerCore.getPlugin(PluginId.getId(pluginTwoId))).isNull() assertThat(app.getService(MyPersistentComponent::class.java)).isNull() } } @Test fun loadOptionalDependencyListener() { receivedNotifications.clear() receivedNotifications2.clear() val pluginTwoBuilder = PluginBuilder().randomId("optionalDependencyListener-two").packagePrefix("optionalDependencyListener-two") val pluginDescriptor = PluginBuilder().randomId("optionalDependencyListener-one").packagePrefix("optionalDependencyListener-one") .applicationListeners( """<listener class="${MyUISettingsListener::class.java.name}" topic="com.intellij.ide.ui.UISettingsListener"/>""") .packagePrefix("org.foo.one") .module( "intellij.org.foo", PluginBuilder() .applicationListeners( """<listener class="${MyUISettingsListener2::class.java.name}" topic="com.intellij.ide.ui.UISettingsListener"/>""") .packagePrefix("org.foo") .pluginDependency(pluginTwoBuilder.id), ) loadPluginWithText(pluginDescriptor).use { val app = ApplicationManager.getApplication() app.messageBus.syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(UISettings()) assertThat(receivedNotifications).hasSize(1) loadPluginWithText(pluginTwoBuilder).use { app.messageBus.syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(UISettings()) assertThat(receivedNotifications).hasSize(2) assertThat(receivedNotifications2).hasSize(1) } app.messageBus.syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(UISettings()) assertThat(receivedNotifications).hasSize(3) assertThat(receivedNotifications2).hasSize(1) } } @Test fun loadOptionalDependencyEP() { val pluginTwoBuilder = PluginBuilder().randomId("optionalDependencyListener-two") val pluginTwoDisposable = loadPluginWithText(pluginTwoBuilder) try { val pluginOneDisposable = loadPluginWithOptionalDependency( PluginBuilder().randomId("optionalDependencyListener-one"), PluginBuilder() .extensionPoints("""<extensionPoint qualifiedName="one.foo" interface="java.lang.Runnable" dynamic="true"/>""") .extensions("""<foo implementation="${MyRunnable::class.java.name}"/>""", "one"), pluginTwoBuilder ) Disposer.dispose(pluginOneDisposable) } finally { Disposer.dispose(pluginTwoDisposable) } } @Test fun loadOptionalDependencyEPAdjacentDescriptor() { val pluginTwoBuilder = PluginBuilder().randomId("optionalDependencyListener-two") val pluginThreeBuilder = PluginBuilder().randomId("optionalDependencyListener-three") val pluginTwoDisposable = loadPluginWithText(pluginTwoBuilder) val pluginThreeDisposable = loadPluginWithText(pluginThreeBuilder) try { val pluginDescriptor = PluginBuilder().randomId("optionalDependencyListener-one") pluginDescriptor.depends( pluginTwoBuilder.id, PluginBuilder().extensionPoints("""<extensionPoint qualifiedName="one.foo" interface="java.lang.Runnable" dynamic="true"/>""")) pluginDescriptor.depends( pluginThreeBuilder.id, PluginBuilder().extensions("""<foo implementation="${MyRunnable::class.java.name}"/>""", "one") ) val pluginOneDisposable = loadPluginWithText(pluginDescriptor) Disposer.dispose(pluginOneDisposable) } finally { Disposer.dispose(pluginTwoDisposable) Disposer.dispose(pluginThreeDisposable) } } @Test fun testProjectService() { val project = projectRule.project loadPluginWithText(PluginBuilder().extensions(""" <projectService serviceImplementation="${MyProjectService::class.java.name}"/> """), inMemoryFs.fs).use { assertThat(project.getService(MyProjectService::class.java)).isNotNull() } } @Test fun extensionOnServiceDependency() { val project = projectRule.project StartupManagerImpl.addActivityEpListener(project) loadExtensionWithText(""" <postStartupActivity implementation="${MyStartupActivity::class.java.name}"/> <projectService serviceImplementation="${MyProjectService::class.java.name}"/> """).use { assertThat(project.service<MyProjectService>().executed).isTrue() } } @Test fun unloadEPWithDefaultAttributes() { loadExtensionWithText( "<globalInspection implementationClass=\"${MyInspectionTool::class.java.name}\" cleanupTool=\"false\"/>").use { assertThat(InspectionEP.GLOBAL_INSPECTION.extensionList.any { it.implementationClass == MyInspectionTool::class.java.name }).isTrue() } assertThat(InspectionEP.GLOBAL_INSPECTION.extensionList.any { it.implementationClass == MyInspectionTool::class.java.name }).isFalse() } @Test fun unloadEPWithTags() { val disposable = loadExtensionWithText( """ <intentionAction> <bundleName>messages.CommonBundle</bundleName> <categoryKey>button.add</categoryKey> <className>${MyIntentionAction::class.java.name}</className> </intentionAction>""") try { val intention = IntentionManagerImpl.EP_INTENTION_ACTIONS.extensionList.find { it.className == MyIntentionAction::class.java.name } assertThat(intention).isNotNull intention!!.categories } finally { Disposer.dispose(disposable) } assertThat(IntentionManagerImpl.EP_INTENTION_ACTIONS.extensionList).allMatch { it.className != MyIntentionAction::class.java.name } } @Test fun unloadEPCollection() { val project = projectRule.project assertThat(Configurable.PROJECT_CONFIGURABLE.getExtensions(project).any { it.instanceClass == MyConfigurable::class.java.name }).isFalse() val listenerDisposable = Disposer.newDisposable() val checked = AtomicInteger() Configurable.PROJECT_CONFIGURABLE.addChangeListener(project, Runnable { checked.incrementAndGet() }, listenerDisposable) val disposable = loadExtensionWithText("<projectConfigurable instance=\"${MyConfigurable::class.java.name}\" displayName=\"foo\"/>") try { assertThat(checked.get()).isEqualTo(1) assertThat( Configurable.PROJECT_CONFIGURABLE.getExtensions(project).any { it.instanceClass == MyConfigurable::class.java.name }).isTrue() } finally { Disposer.dispose(disposable) Disposer.dispose(listenerDisposable) } assertThat(checked.get()).isEqualTo(2) assertThat( Configurable.PROJECT_CONFIGURABLE.getExtensions(project).any { it.instanceClass == MyConfigurable::class.java.name }).isFalse() } @Test fun unloadModuleEP() { val disposable = loadExtensionWithText( """<moduleConfigurationEditorProvider implementation="${MyModuleConfigurationEditorProvider::class.java.name}"/>""") Disposer.dispose(disposable) } @Test fun loadExistingFileTypeModification() { @Suppress("SpellCheckingInspection") val textToLoad = "<fileType name=\"PLAIN_TEXT\" language=\"PLAIN_TEXT\" fileNames=\".texttest\"/>" var disposable = loadExtensionWithText(textToLoad) Disposer.dispose(disposable) UIUtil.dispatchAllInvocationEvents() disposable = loadExtensionWithText(textToLoad) Disposer.dispose(disposable) } @Test fun disableWithoutRestart() { val pluginBuilder = PluginBuilder() .randomId("disableWithoutRestart") .extensions("""<applicationService serviceImplementation="${MyPersistentComponent::class.java.name}"/>""") val disposable = loadPluginWithText(pluginBuilder) val app = ApplicationManager.getApplication() assertThat(app.getService(MyPersistentComponent::class.java)).isNotNull() try { val pluginDescriptor = PluginManagerCore.getPlugin(PluginId.getId(pluginBuilder.id))!! val disabled = PluginEnabler.getInstance().disable(listOf(pluginDescriptor)) assertThat(disabled).isTrue() assertThat(pluginDescriptor.isEnabled).isFalse() assertThat(app.getService(MyPersistentComponent::class.java)).isNull() val enabled = PluginEnabler.getInstance().enable(listOf(pluginDescriptor)) assertThat(enabled).isTrue() assertThat(pluginDescriptor.isEnabled).isTrue() assertThat(app.getService(MyPersistentComponent::class.java)).isNotNull() } finally { Disposer.dispose(disposable) } } @Test fun canUnloadNestedOptionalDependency() { val barBuilder = PluginBuilder().randomId("bar") .extensionPoints( """<extensionPoint qualifiedName="foo.barExtension" beanClass="com.intellij.util.KeyedLazyInstanceEP"/>""") val quuxBuilder = PluginBuilder().randomId("quux") val quuxDependencyDescriptor = PluginBuilder().extensions("""<barExtension key="foo" implementationClass="y"/>""", "foo") val barDependencyDescriptor = PluginBuilder().depends(quuxBuilder.id, quuxDependencyDescriptor) val mainDescriptor = PluginBuilder().randomId("main").depends(barBuilder.id, barDependencyDescriptor) loadPluginWithText(barBuilder).use { loadPluginWithText(quuxBuilder).use { val descriptor = loadDescriptorInTest( mainDescriptor, Files.createTempDirectory(inMemoryFs.fs.getPath("/"), null), ) setPluginClassLoaderForMainAndSubPlugins(descriptor, DynamicPluginsTest::class.java.classLoader) assertThat(DynamicPlugins.checkCanUnloadWithoutRestart(descriptor)).isEqualTo( "Plugin ${mainDescriptor.id} is not unload-safe because of extension to non-dynamic EP foo.barExtension in optional dependency on ${quuxBuilder.id} in optional dependency on ${barBuilder.id}") } } } private fun loadPluginWithOptionalDependency(pluginDescriptor: PluginBuilder, optionalDependencyDescriptor: PluginBuilder, dependsOn: PluginBuilder): Disposable { pluginDescriptor.depends(dependsOn.id, optionalDependencyDescriptor) return loadPluginWithText(pluginDescriptor) } } private class MyUISettingsListener : UISettingsListener { override fun uiSettingsChanged(uiSettings: UISettings) { DynamicPluginsTest.receivedNotifications.add(uiSettings) } } private class MyUISettingsListener2 : UISettingsListener { override fun uiSettingsChanged(uiSettings: UISettings) { DynamicPluginsTest.receivedNotifications2.add(uiSettings) } } private data class MyPersistentState(@Attribute var stateData: String? = "") @State(name = "MyTestState", storages = [Storage("other.xml")], allowLoadInTests = true) private class MyPersistentComponent : PersistentStateComponent<MyPersistentState> { var myState = MyPersistentState("") override fun getState() = myState override fun loadState(state: MyPersistentState) { myState = state } } @InternalIgnoreDependencyViolation private class MyStartupActivity : StartupActivity.DumbAware { override fun runActivity(project: Project) { val service = project.getService(MyProjectService::class.java) if (service != null) { service.executed = true } } } @InternalIgnoreDependencyViolation private class MyProjectService { companion object { val LOG = logger<MyProjectService>() } init { LOG.info("MyProjectService initialized") } var executed = false } private class MyInspectionTool : GlobalInspectionTool() private class MyInspectionTool2 : GlobalInspectionTool() private class MyConfigurable : Configurable { override fun isModified(): Boolean = TODO() override fun getDisplayName(): String = TODO() override fun apply() {} override fun createComponent() = TODO() } private class MyAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { } } private class MyAction2 : AnAction() { override fun actionPerformed(e: AnActionEvent) { } } @Suppress("DialogTitleCapitalization") private class MyIntentionAction : IntentionAction { override fun startInWriteAction() = false override fun getFamilyName() = "foo" override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = false override fun getText(): String = "foo" override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { } } private class MyRunnable : Runnable { override fun run() { } } private class MyModuleConfigurationEditorProvider : ModuleConfigurationEditorProvider { override fun createEditors(state: ModuleConfigurationState?): Array<ModuleConfigurationEditor> = arrayOf() } private inline fun runAndCheckThatNoNewPlugins(block: () -> Unit) { val expectedPluginIds = lexicographicallySortedPluginIds() block() assertThat(lexicographicallySortedPluginIds()).isEqualTo(expectedPluginIds) } private fun lexicographicallySortedPluginIds() = PluginManagerCore.getLoadedPlugins() .toSortedSet(compareBy { it.pluginId })
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/AnnotationClassConversion.kt
1
3001
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.nj2k.conversions import org.jetbrains.kotlin.j2k.ast.Nullability import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.toExpression import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.types.JKJavaArrayType import org.jetbrains.kotlin.nj2k.types.isArrayType import org.jetbrains.kotlin.nj2k.types.replaceJavaClassWithKotlinClassType import org.jetbrains.kotlin.nj2k.types.updateNullabilityRecursively class AnnotationClassConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKClass) return recurse(element) if (element.classKind != JKClass.ClassKind.ANNOTATION) return recurse(element) val javaAnnotationMethods = element.classBody.declarations .filterIsInstance<JKJavaAnnotationMethod>() val constructor = JKKtPrimaryConstructor( JKNameIdentifier(""), javaAnnotationMethods.map { it.asKotlinAnnotationParameter() }, JKStubExpression(), JKAnnotationList(), emptyList(), JKVisibilityModifierElement(Visibility.PUBLIC), JKModalityModifierElement(Modality.FINAL) ) element.modality = Modality.FINAL element.classBody.declarations += constructor element.classBody.declarations -= javaAnnotationMethods return recurse(element) } private fun JKJavaAnnotationMethod.asKotlinAnnotationParameter(): JKParameter { val type = returnType.type .updateNullabilityRecursively(Nullability.NotNull) .replaceJavaClassWithKotlinClassType(symbolProvider) val initializer = this::defaultValue.detached().toExpression(symbolProvider) val isVarArgs = type is JKJavaArrayType && name.value == "value" return JKParameter( JKTypeElement( if (!isVarArgs) type else (type as JKJavaArrayType).type ), JKNameIdentifier(name.value), isVarArgs = isVarArgs, initializer = if (type.isArrayType() && initializer !is JKKtAnnotationArrayInitializerExpression && initializer !is JKStubExpression ) { JKKtAnnotationArrayInitializerExpression(initializer) } else initializer, annotationList = this::annotationList.detached(), ).also { parameter -> if (trailingComments.any { it is JKComment }) { parameter.trailingComments += trailingComments } if (leadingComments.any { it is JKComment }) { parameter.leadingComments += leadingComments } } } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/changeSignature/addFunctionParameterForReferencedArgument5.kt
13
194
// "Add parameter to function 'foo'" "true" // DISABLE-ERRORS fun foo() {} class Test { val x: String = "" get() { foo(field<caret>) return field } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/configuration/libraryUtils.kt
5
1302
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.configuration import com.intellij.openapi.roots.libraries.Library class ExternalLibraryInfo( val artifactId: String, val version: String ) fun parseExternalLibraryName(library: Library): ExternalLibraryInfo? { val libName = library.name ?: return null val versionWithKind = libName.substringAfterLastNullable(":") ?: return null val version = versionWithKind.substringBefore("@") val artifactId = libName.substringBeforeLastNullable(":")?.substringAfterLastNullable(":") ?: return null if (version.isBlank() || artifactId.isBlank()) return null return ExternalLibraryInfo(artifactId, version) } private fun String.substringBeforeLastNullable(delimiter: String, missingDelimiterValue: String? = null): String? { val index = lastIndexOf(delimiter) return if (index == -1) missingDelimiterValue else substring(0, index) } private fun String.substringAfterLastNullable(delimiter: String, missingDelimiterValue: String? = null): String? { val index = lastIndexOf(delimiter) return if (index == -1) missingDelimiterValue else substring(index + 1, length) }
apache-2.0
WillowChat/Kale
src/test/kotlin/chat/willow/kale/irc/message/utility/RawMessageTests.kt
2
1012
package chat.willow.kale.irc.message.utility import chat.willow.kale.core.message.IrcMessage import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test class RawMessageTests { private lateinit var messageSerialiser: RawMessage.Line.Serialiser @Before fun setUp() { messageSerialiser = RawMessage.Line.Serialiser } @Test fun test_serialise_WellFormedLine() { val message = messageSerialiser.serialise(RawMessage.Line(line = ":prefix 123 1 :2 3")) assertEquals(IrcMessage(command = "123", prefix = "prefix", parameters = listOf("1", "2 3")), message) } @Test fun test_serialise_BadlyFormedLine_Empty() { val message = messageSerialiser.serialise(RawMessage.Line(line = "")) assertNull(message) } @Test fun test_serialise_BadlyFormedLine_Garbage() { val message = messageSerialiser.serialise(RawMessage.Line(line = ": :1 :2 :3")) assertNull(message) } }
isc
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCall/filterNotNullMap.kt
9
109
// WITH_STDLIB // PROBLEM: none fun test(map: Map<String?, String?>) { map.<caret>filter { it != null } }
apache-2.0
Flank/flank
flank-scripts/src/main/kotlin/flank/scripts/cli/assemble/ios/TestPlansExample.kt
1
669
package flank.scripts.cli.assemble.ios import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.options.flag import com.github.ajalt.clikt.parameters.options.option import flank.scripts.ops.assemble.ios.buildTestPlansExample object TestPlansExample : CliktCommand( name = "test_plans", help = "Build ios test plans example app" ) { private val generate: Boolean? by option(help = "Make build") .flag("-g", default = true) private val copy: Boolean? by option(help = "Copy output files to tmp") .flag("-c", default = true) override fun run() { buildTestPlansExample(generate, copy) } }
apache-2.0
serssp/reakt
todo/src/main/kotlin/todo/components/MainSection.kt
3
1299
package todo.components import com.github.andrewoma.react.* import todo.actions.TodoActions import todo.stores.Todo import todo.stores.areAllCompleted data class MainSectionProperties(val todos: Collection<Todo>) class MainSection : ComponentSpec<MainSectionProperties, Unit>() { companion object { val factory = react.createFactory(MainSection()) } override fun Component.render() { log.debug("MainSection.render", props) if (props.todos.size < 1) return section({ id = "main" }) { input({ id = "toggle-all" `type` = "checkbox" onChange = { onToggleCompleteAll() } checked = if ( props.todos.areAllCompleted() ) "checked" else "" }) label({ htmlFor = "toggle-all" }) { text("Mark all as complete") } ul({ id = "todo-list" }) { for (todo in props.todos) { todoItem(TodoItemProperties(key = todo.id, todo = todo)) } } } } fun onToggleCompleteAll() { TodoActions.toggleCompleteAll(null) } } fun Component.todoMainSection(props: MainSectionProperties): Component { return constructAndInsert(Component({ MainSection.factory(Ref(props)) })) }
mit
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/blocks/GetLightDirectionFromFragPos.kt
1
1086
package de.fabmax.kool.modules.ksl.blocks import de.fabmax.kool.modules.ksl.lang.* import de.fabmax.kool.scene.Light class GetLightDirectionFromFragPos(parentScope: KslScopeBuilder) : KslFunction<KslTypeFloat3>(FUNC_NAME, KslTypeFloat3, parentScope.parentStage) { init { val fragPos = paramFloat3("fragPos") val encLightPos = paramFloat4("encLightPos") body { val dir = float3Var() `if` (encLightPos.w eq Light.Type.DIRECTIONAL.encoded.const) { dir set encLightPos.xyz * -(1f.const) }.`else` { dir set encLightPos.xyz - fragPos } return@body dir } } companion object { const val FUNC_NAME = "getLightDirectionFromFragPos" } } fun KslScopeBuilder.getLightDirectionFromFragPos( fragPos: KslExprFloat3, encodedLightPos: KslExprFloat4 ): KslExprFloat3 { val func = parentStage.getOrCreateFunction(GetLightDirectionFromFragPos.FUNC_NAME) { GetLightDirectionFromFragPos(this) } return func(fragPos, encodedLightPos) }
apache-2.0
kohesive/kohesive-iac
model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredAmazonCloudFormation.kt
1
1353
package uy.kohesive.iac.model.aws.clients import com.amazonaws.services.cloudformation.AbstractAmazonCloudFormation import com.amazonaws.services.cloudformation.AmazonCloudFormation import com.amazonaws.services.cloudformation.model.* import uy.kohesive.iac.model.aws.IacContext import uy.kohesive.iac.model.aws.proxy.makeProxy open class BaseDeferredAmazonCloudFormation(val context: IacContext) : AbstractAmazonCloudFormation(), AmazonCloudFormation { override fun createChangeSet(request: CreateChangeSetRequest): CreateChangeSetResult { return with (context) { request.registerWithAutoName() makeProxy<CreateChangeSetRequest, CreateChangeSetResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun createStack(request: CreateStackRequest): CreateStackResult { return with (context) { request.registerWithAutoName() makeProxy<CreateStackRequest, CreateStackResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } } class DeferredAmazonCloudFormation(context: IacContext) : BaseDeferredAmazonCloudFormation(context)
mit
Pattonville-App-Development-Team/Android-App
app/src/main/java/org/pattonvillecs/pattonvilleapp/view/ui/calendar/IFlexibleHasStartDate.kt
1
1276
/* * Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District * * 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 org.pattonvillecs.pattonvilleapp.view.ui.calendar import android.support.v7.widget.RecyclerView import eu.davidea.flexibleadapter.items.IFlexible import org.pattonvillecs.pattonvilleapp.service.model.calendar.event.HasStartDate /** * This interface serves to provide a concrete type of something that implements [IFlexible] and [HasStartDate] * * @author Mitchell Skaggs * @since 1.2.0 */ interface IFlexibleHasStartDate<VH : RecyclerView.ViewHolder> : IFlexible<VH>, HasStartDate
gpl-3.0
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt
1
10660
package info.nightscout.androidaps.dependencyInjection import dagger.Binds import dagger.Module import dagger.multibindings.IntKey import dagger.multibindings.IntoMap import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin import info.nightscout.androidaps.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.danar.DanaRPlugin import info.nightscout.androidaps.danars.DanaRSPlugin import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.constraints.dstHelper.DstHelperPlugin import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin import info.nightscout.androidaps.plugins.constraints.signatureVerifier.SignatureVerifierPlugin import info.nightscout.androidaps.plugins.constraints.storage.StorageConstraintPlugin import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerPlugin import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin import info.nightscout.androidaps.plugins.general.dataBroadcaster.DataBroadcastPlugin import info.nightscout.androidaps.plugins.general.food.FoodPlugin import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin import info.nightscout.androidaps.plugins.general.openhumans.OpenHumansUploader import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin import info.nightscout.androidaps.plugins.general.persistentNotification.PersistentNotificationPlugin import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin import info.nightscout.androidaps.plugins.general.wear.WearPlugin import info.nightscout.androidaps.plugins.general.xdripStatusline.StatusLinePlugin import info.nightscout.androidaps.plugins.insulin.InsulinLyumjevPlugin import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin import info.nightscout.androidaps.plugins.insulin.InsulinOrefUltraRapidActingPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin import info.nightscout.androidaps.plugins.pump.mdi.MDIPlugin import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin import info.nightscout.androidaps.plugins.pump.omnipod.OmnipodPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin import info.nightscout.androidaps.plugins.source.* import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import javax.inject.Qualifier @Module abstract class PluginsModule { @Binds @AllConfigs @IntoMap @IntKey(0) abstract fun bindOverviewPlugin(plugin: OverviewPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(10) abstract fun bindIobCobCalculatorPlugin(plugin: IobCobCalculatorPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(20) abstract fun bindActionsPlugin(plugin: ActionsPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(30) abstract fun bindInsulinOrefRapidActingPlugin(plugin: InsulinOrefRapidActingPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(40) abstract fun bindInsulinOrefUltraRapidActingPlugin(plugin: InsulinOrefUltraRapidActingPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(42) abstract fun bindInsulinLyumjevPlugin(plugin: InsulinLyumjevPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(50) abstract fun bindInsulinOrefFreePeakPlugin(plugin: InsulinOrefFreePeakPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(60) abstract fun bindSensitivityAAPSPlugin(plugin: SensitivityAAPSPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(70) abstract fun bindSensitivityWeightedAveragePlugin(plugin: SensitivityWeightedAveragePlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(80) abstract fun bindSensitivityOref1Plugin(plugin: SensitivityOref1Plugin): PluginBase @Binds @PumpDriver @IntoMap @IntKey(90) abstract fun bindDanaRPlugin(plugin: DanaRPlugin): PluginBase @Binds @PumpDriver @IntoMap @IntKey(100) abstract fun bindDanaRKoreanPlugin(plugin: DanaRKoreanPlugin): PluginBase @Binds @PumpDriver @IntoMap @IntKey(110) abstract fun bindDanaRv2Plugin(plugin: DanaRv2Plugin): PluginBase @Binds @PumpDriver @IntoMap @IntKey(120) abstract fun bindDanaRSPlugin(plugin: DanaRSPlugin): PluginBase @Binds @PumpDriver @IntoMap @IntKey(130) abstract fun bindLocalInsightPlugin(plugin: LocalInsightPlugin): PluginBase @Binds @PumpDriver @IntoMap @IntKey(140) abstract fun bindComboPlugin(plugin: ComboPlugin): PluginBase @Binds @PumpDriver @IntoMap @IntKey(150) abstract fun bindMedtronicPumpPlugin(plugin: MedtronicPumpPlugin): PluginBase @Binds @PumpDriver @IntoMap @IntKey(155) abstract fun bindOmnipodPumpPlugin(plugin: OmnipodPumpPlugin): PluginBase @Binds @NotNSClient @IntoMap @IntKey(160) abstract fun bindMDIPlugin(plugin: MDIPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(170) abstract fun bindVirtualPumpPlugin(plugin: VirtualPumpPlugin): PluginBase @Binds @APS @IntoMap @IntKey(190) abstract fun bindLoopPlugin(plugin: LoopPlugin): PluginBase @Binds @APS @IntoMap @IntKey(210) abstract fun bindOpenAPSAMAPlugin(plugin: OpenAPSAMAPlugin): PluginBase @Binds @APS @IntoMap @IntKey(220) abstract fun bindOpenAPSSMBPlugin(plugin: OpenAPSSMBPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(230) abstract fun bindNSProfilePlugin(plugin: NSProfilePlugin): PluginBase @Binds @NotNSClient @IntoMap @IntKey(240) abstract fun bindLocalProfilePlugin(plugin: LocalProfilePlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(250) abstract fun bindAutomationPlugin(plugin: AutomationPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(260) abstract fun bindTreatmentsPlugin(plugin: TreatmentsPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(265) abstract fun bindSafetyPlugin(plugin: SafetyPlugin): PluginBase @Binds @NotNSClient @IntoMap @IntKey(270) abstract fun bindVersionCheckerPlugin(plugin: VersionCheckerPlugin): PluginBase @Binds @NotNSClient @IntoMap @IntKey(280) abstract fun bindSmsCommunicatorPlugin(plugin: SmsCommunicatorPlugin): PluginBase @Binds @APS @IntoMap @IntKey(290) abstract fun bindStorageConstraintPlugin(plugin: StorageConstraintPlugin): PluginBase @Binds @APS @IntoMap @IntKey(300) abstract fun bindSignatureVerifierPlugin(plugin: SignatureVerifierPlugin): PluginBase @Binds @APS @IntoMap @IntKey(310) abstract fun bindObjectivesPlugin(plugin: ObjectivesPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(320) abstract fun bindFoodPlugin(plugin: FoodPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(330) abstract fun bindWearPlugin(plugin: WearPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(340) abstract fun bindStatusLinePlugin(plugin: StatusLinePlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(350) abstract fun bindPersistentNotificationPlugin(plugin: PersistentNotificationPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(360) abstract fun bindNSClientPlugin(plugin: NSClientPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(370) abstract fun bindMaintenancePlugin(plugin: MaintenancePlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(380) abstract fun bindDstHelperPlugin(plugin: DstHelperPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(390) abstract fun bindDataBroadcastPlugin(plugin: DataBroadcastPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(400) abstract fun bindXdripPlugin(plugin: XdripPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(410) abstract fun bindNSClientSourcePlugin(plugin: NSClientSourcePlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(420) abstract fun bindMM640gPlugin(plugin: MM640gPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(430) abstract fun bindGlimpPlugin(plugin: GlimpPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(440) abstract fun bindDexcomPlugin(plugin: DexcomPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(450) abstract fun bindPoctechPlugin(plugin: PoctechPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(460) abstract fun bindTomatoPlugin(plugin: TomatoPlugin): PluginBase @Binds @AllConfigs @IntoMap @IntKey(470) abstract fun bindRandomBgPlugin(plugin: RandomBgPlugin): PluginBase @Binds @NotNSClient @IntoMap @IntKey(480) abstract fun bindOpenHumansPlugin(plugin: OpenHumansUploader): PluginBase @Binds @AllConfigs @IntoMap @IntKey(490) abstract fun bindConfigBuilderPlugin(plugin: ConfigBuilderPlugin): PluginBase @Qualifier annotation class AllConfigs @Qualifier annotation class PumpDriver @Qualifier annotation class NotNSClient @Qualifier annotation class APS }
agpl-3.0
Flank/flank
test_runner/src/main/kotlin/ftl/presentation/cli/firebase/test/refresh/HandleRefreshRunState.kt
1
667
package ftl.presentation.cli.firebase.test.refresh import ftl.config.FtlConstants import ftl.domain.RefreshLastRunState internal fun handleRefreshLastRunState(state: RefreshLastRunState): String = when (state) { is RefreshLastRunState.LoadingRun -> "Loading run ${state.lastRun}" is RefreshLastRunState.RefreshMatrices -> "${FtlConstants.indent}Refreshing ${state.matrixCount}x matrices" RefreshLastRunState.RefreshMatricesStarted -> "RefreshMatrices" is RefreshLastRunState.RefreshMatrix -> "${FtlConstants.indent} ${state.matrixState} ${state.matrixId}" RefreshLastRunState.UpdatingMatrixFile -> "${FtlConstants.indent}Updating matrix file" }
apache-2.0
kohesive/kohesive-iac
cloudtrail-tool/src/test/kotlin/uy/kohesive/iac/model/aws/cloudtrail/SmokeTest.kt
1
1776
package uy.kohesive.iac.model.aws.cloudtrail import uy.kohesive.iac.model.aws.codegen.AWSModelProvider import uy.kohesive.iac.model.aws.codegen.TemplateDescriptor import java.io.File fun main(args: Array<String>) { val packageName = "uy.kohesive.iac.model.aws.cloudtrail.test4" val outputDir = File("/Users/eliseyev/TMP/codegen/runners/", packageName.replace('.', '/')).apply { mkdirs() } val awsModelProvider = AWSModelProvider() var counter = 0 FileSystemEventsProcessor( // eventsDir = File("/Users/eliseyev/Downloads/CloudTrail2/us-east-1/2017/02/16/"), // eventsDir = File("/Users/eliseyev/Downloads/CloudTrail/"), eventsDir = File("/Users/eliseyev/TMP/cloudtrail/"), // eventsDir = File("/Users/eliseyev/Downloads/BadCloudTrail/"), oneEventPerFile = true, gzipped = false ).process { event -> if (listOf("Create", "Put", "Attach", "Run", "Set").any { event.eventName.startsWith(it) }) { val serviceName = event.eventSource.split('.').first() val awsModel = try { awsModelProvider.getModel(serviceName, event.apiVersion) } catch (t: Throwable) { throw RuntimeException("Can't obtain an AWS model for $event", t) } val className = "${event.eventName}Runner_${counter++}" val classContent = AWSApiCallBuilder( intermediateModel = awsModel, event = event, packageName = packageName, className = className ).build(TemplateDescriptor.RequestRunner) File(outputDir, "$className.kt").writeText(classContent) } }.forEach { } }
mit
Flank/flank
test_runner/src/main/kotlin/ftl/adapter/google/SummaryAdapter.kt
1
494
package ftl.adapter.google import ftl.api.TestMatrix import ftl.client.google.BillableMinutes import ftl.client.google.TestOutcome fun Pair<BillableMinutes, List<TestOutcome>>.toApiModel(): TestMatrix.Summary { val (billableMinutes, outcomes) = this return TestMatrix.Summary( billableMinutes = billableMinutes.toApiModel(), axes = outcomes.map(TestOutcome::toApiModel) ) } private fun BillableMinutes.toApiModel() = TestMatrix.BillableMinutes(virtual, physical)
apache-2.0
ingokegel/intellij-community
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/inference/nullability/NullabilityConstraintsCollector.kt
2
3523
// 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.j2k.post.processing.inference.nullability import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.* import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.collectors.ConstraintsCollector import org.jetbrains.kotlin.psi.* class NullabilityConstraintsCollector : ConstraintsCollector() { override fun ConstraintBuilder.collectConstraints( element: KtElement, boundTypeCalculator: BoundTypeCalculator, inferenceContext: InferenceContext, resolutionFacade: ResolutionFacade ) { when { element is KtBinaryExpression && (element.left?.isNullExpression() == true || element.right?.isNullExpression() == true) -> { val notNullOperand = if (element.left?.isNullExpression() == true) element.right else element.left notNullOperand?.isTheSameTypeAs(org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.UPPER, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.COMPARE_WITH_NULL) } element is KtQualifiedExpression -> { element.receiverExpression.isTheSameTypeAs(org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER) } element is KtForExpression -> { element.loopRange?.isTheSameTypeAs(org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER) } element is KtWhileExpressionBase -> { element.condition?.isTheSameTypeAs(org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER) } element is KtIfExpression -> { element.condition?.isTheSameTypeAs(org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER) } element is KtValueArgument && element.isSpread -> { element.getArgumentExpression()?.isTheSameTypeAs( org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER) } element is KtBinaryExpression && !KtPsiUtil.isAssignment(element) -> { element.left?.isTheSameTypeAs(org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER) element.right?.isTheSameTypeAs(org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER) } } } }
apache-2.0
leafclick/intellij-community
plugins/gradle/java/src/service/resolve/GradleMiscContributor.kt
1
5658
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.service.resolve import com.intellij.patterns.PsiJavaPatterns.psiElement import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.ResolveState import com.intellij.psi.scope.PsiScopeProcessor import groovy.lang.Closure import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.* import org.jetbrains.plugins.groovy.lang.psi.GroovyFile import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder import org.jetbrains.plugins.groovy.lang.psi.patterns.GroovyClosurePattern import org.jetbrains.plugins.groovy.lang.psi.patterns.groovyClosure import org.jetbrains.plugins.groovy.lang.psi.patterns.psiMethod import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_CLOSURE import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DELEGATES_TO_TYPE_KEY import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DelegatesToInfo /** * @author Vladislav.Soroka */ class GradleMiscContributor : GradleMethodContextContributor { companion object { val useJUnitClosure: GroovyClosurePattern = groovyClosure().inMethod(psiMethod(GRADLE_API_TASKS_TESTING_TEST, "useJUnit")) val testLoggingClosure: GroovyClosurePattern = groovyClosure().inMethod(psiMethod(GRADLE_API_TASKS_TESTING_TEST, "testLogging")) val downloadClosure: GroovyClosurePattern = groovyClosure().inMethod(psiMethod(GRADLE_API_PROJECT, "download")) val domainCollectionWithTypeClosure: GroovyClosurePattern = groovyClosure().inMethod(psiMethod(GRADLE_API_DOMAIN_OBJECT_COLLECTION, "withType")) val manifestClosure: GroovyClosurePattern = groovyClosure().inMethod(psiMethod(GRADLE_JVM_TASKS_JAR, "manifest")) // val publicationsClosure = groovyClosure().inMethod(psiMethod("org.gradle.api.publish.PublishingExtension", "publications")) const val downloadSpecFqn: String = "de.undercouch.gradle.tasks.download.DownloadSpec" const val pluginDependenciesSpecFqn: String = "org.gradle.plugin.use.PluginDependenciesSpec" } override fun getDelegatesToInfo(closure: GrClosableBlock): DelegatesToInfo? { if (useJUnitClosure.accepts(closure)) { return DelegatesToInfo(createType(GRADLE_API_JUNIT_OPTIONS, closure), Closure.DELEGATE_FIRST) } if (testLoggingClosure.accepts(closure)) { return DelegatesToInfo(createType(GRADLE_API_TEST_LOGGING_CONTAINER, closure), Closure.DELEGATE_FIRST) } if (downloadClosure.accepts(closure)) { return DelegatesToInfo(createType(downloadSpecFqn, closure), Closure.DELEGATE_FIRST) } if (manifestClosure.accepts(closure)) { return DelegatesToInfo(createType(GRADLE_API_JAVA_ARCHIVES_MANIFEST, closure), Closure.DELEGATE_FIRST) } // if (publicationsClosure.accepts(closure)) { // return DelegatesToInfo(TypesUtil.createType("org.gradle.api.publish.PublicationContainer", closure), Closure.DELEGATE_FIRST) // } val parent = closure.parent if (domainCollectionWithTypeClosure.accepts(closure)) { if (parent is GrMethodCallExpression) { val psiElement = parent.argumentList.allArguments.singleOrNull()?.reference?.resolve() if (psiElement is PsiClass) { return DelegatesToInfo(createType(psiElement.qualifiedName, closure), Closure.DELEGATE_FIRST) } } } // resolve closure type to delegate based on return method type, e.g. // FlatDirectoryArtifactRepository flatDir(Closure configureClosure) if (parent is GrMethodCall) { parent.resolveMethod()?.returnType?.let { type -> return DelegatesToInfo(type, Closure.DELEGATE_FIRST) } } return null } override fun process(methodCallInfo: MutableList<String>, processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { val classHint = processor.getHint(com.intellij.psi.scope.ElementClassHint.KEY) val shouldProcessMethods = ResolveUtil.shouldProcessMethods(classHint) val groovyPsiManager = GroovyPsiManager.getInstance(place.project) val resolveScope = place.resolveScope if (shouldProcessMethods && place.parent?.parent is GroovyFile && place.text == "plugins") { val pluginsDependenciesClass = JavaPsiFacade.getInstance(place.project).findClass(pluginDependenciesSpecFqn, resolveScope) ?: return true val returnClass = groovyPsiManager.createTypeByFQClassName(pluginDependenciesSpecFqn, resolveScope) ?: return true val methodBuilder = GrLightMethodBuilder(place.manager, "plugins").apply { containingClass = pluginsDependenciesClass returnType = returnClass } methodBuilder.addAndGetParameter("configuration", GROOVY_LANG_CLOSURE).putUserData(DELEGATES_TO_TYPE_KEY, pluginDependenciesSpecFqn) if (!processor.execute(methodBuilder, state)) return false } if (psiElement().inside(domainCollectionWithTypeClosure).accepts(place)) { } return true } }
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/sortedLast2.kt
2
87
// API_VERSION: 1.4 // WITH_RUNTIME val x: Int = listOf(1, 3, 2).<caret>sorted().last()
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/intentions/simplifyBooleanWithConstants/notReduceableBinary.kt
4
84
fun test() { foo(<caret>false || !true) ?: return } fun foo(v: Boolean): Int = 1
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/indentationOnNewline/emptyParameters/EmptyParameterInDestructuringDeclaration3.after.kt
6
103
fun a() { a.forEach { ( <caret> )} } // SET_FALSE: ALIGN_MULTILINE_METHOD_BRACKETS
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/editor/enterHandler/multilineString/spaces/dontAddMarginWhenItIsUnused.kt
4
198
val a = """ blah blah blah blah blah blah blah blah blah<caret> """.trimMargin() //----- val a = """ blah blah blah blah blah blah blah blah blah <caret> """.trimMargin()
apache-2.0
taskworld/KxAndroid
kxandroid/src/main/kotlin/com/taskworld/kxandroid/StringBuilders.kt
1
520
package com.taskworld.kxandroid import android.text.SpannableStringBuilder import android.text.Spanned import android.text.style.CharacterStyle fun StringBuilder.plus(add: String?): StringBuilder { if (add != null) { append(add) } return this } fun SpannableStringBuilder.append(word: String, span: CharacterStyle): SpannableStringBuilder { val start = length val end = start + word.length append(word) setSpan(span, start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE) return this }
mit
JetBrains/kotlin-native
backend.native/tests/codegen/delegatedProperty/lazy.kt
4
355
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package codegen.delegatedProperty.lazy import kotlin.test.* val lazyValue: String by lazy { println("computed!") "Hello" } @Test fun runTest() { println(lazyValue) println(lazyValue) }
apache-2.0
josecefe/Rueda
src/es/um/josecefe/rueda/util/Combinatoria.kt
1
1643
/* * Copyright (c) 2016-2017. Jose Ceferino Ortega Carretero * * 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 es.um.josecefe.rueda.util import java.util.* tailrec fun factorial(n: Long, a: Long = 1): Long = if (n <= 1) a else factorial(n - 1, a * n) fun permutations(n: Long, r: Long): Long = factorial(n) / factorial(n - r) fun combinations(n: Long, r: Long): Long = permutations(n, r) / factorial(r) fun <T> cartesianProduct(lists: List<List<T>>): List<List<T>> { val resultLists = ArrayList<List<T>>() if (lists.isEmpty()) { resultLists.add(emptyList()) return resultLists } else { val firstList = lists[0] val remainingLists = cartesianProduct(lists.subList(1, lists.size)) for (condition in firstList) { for (remainingList in remainingLists) { val resultList = ArrayList<T>() resultList.add(condition) resultList.addAll(remainingList) resultLists.add(resultList) } } } return resultLists }
gpl-3.0
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/generate/equalsWithHashCode/interface.kt
13
57
// NOT_APPLICABLE interface A {<caret> val foo: Int }
apache-2.0
allotria/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/SimpleToolWindowWithTwoToolbarsPanel.kt
1
2740
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels import com.intellij.openapi.actionSystem.ActionToolbar import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.DataProvider import com.intellij.ui.JBColor import com.intellij.ui.switcher.QuickActionProvider import com.intellij.util.ui.UIUtil import java.awt.BorderLayout import java.awt.Container import java.awt.Graphics import java.awt.event.ContainerAdapter import java.awt.event.ContainerEvent import javax.swing.JComponent import javax.swing.JPanel import org.jetbrains.annotations.NonNls class SimpleToolWindowWithTwoToolbarsPanel( val leftToolbar: JComponent, val topToolbar: JComponent, val content: JComponent ) : JPanel(), QuickActionProvider, DataProvider { private var myProvideQuickActions: Boolean = false init { layout = BorderLayout(1, 1) myProvideQuickActions = true addContainerListener(object : ContainerAdapter() { override fun componentAdded(e: ContainerEvent?) { val child = e!!.child if (child is Container) { child.addContainerListener(this) } } override fun componentRemoved(e: ContainerEvent?) { val child = e!!.child if (child is Container) { child.removeContainerListener(this) } } }) add(leftToolbar, BorderLayout.WEST) add(JPanel(BorderLayout()).apply { add(topToolbar, BorderLayout.NORTH) add(content, BorderLayout.CENTER) }, BorderLayout.CENTER) revalidate() repaint() } override fun getData(@NonNls dataId: String) = when { QuickActionProvider.KEY.`is`(dataId) && myProvideQuickActions -> this else -> null } override fun getActions(originalProvider: Boolean): List<AnAction> { val actions = ArrayList<AnAction>() actions.addAll(extractActions(topToolbar)) actions.addAll(extractActions(leftToolbar)) return actions } override fun getComponent(): JComponent? { return this } override fun paintComponent(g: Graphics) { super.paintComponent(g) val x = leftToolbar.bounds.maxX.toInt() val y = topToolbar.bounds.maxY.toInt() g.apply { color = JBColor.border() drawLine(0, y, width, y) drawLine(x, 0, x, height) } } fun extractActions(c: JComponent): List<AnAction> = UIUtil.uiTraverser(c) .traverse() .filter(ActionToolbar::class.java) .flatten { toolbar -> toolbar.actions } .toList() }
apache-2.0
androidx/androidx
core/core-remoteviews/src/androidTest/java/androidx/core/widget/RemoteViewsCompatTest.kt
3
16973
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.widget import android.Manifest.permission import android.app.PendingIntent import android.app.UiAutomation import android.appwidget.AppWidgetHostView import android.appwidget.AppWidgetManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Build import android.os.Parcel import android.view.View import android.view.ViewGroup import android.view.ViewTreeObserver.OnDrawListener import android.widget.Adapter import android.widget.ListView import android.widget.RemoteViews import android.widget.TextView import androidx.core.remoteviews.test.R import androidx.core.widget.RemoteViewsCompat.RemoteCollectionItems import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import androidx.test.platform.app.InstrumentationRegistry import com.google.common.truth.Truth.assertThat import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import kotlin.test.assertFailsWith import kotlin.test.fail @SdkSuppress(minSdkVersion = 29) @MediumTest public class RemoteViewsCompatTest { private val mUsingBackport = Build.VERSION.SDK_INT <= Build.VERSION_CODES.S private val mContext = ApplicationProvider.getApplicationContext<Context>() private val mPackageName = mContext.packageName private val mAppWidgetManager = AppWidgetManager.getInstance(mContext) @Rule @JvmField public val mActivityTestRule: ActivityScenarioRule<AppWidgetHostTestActivity> = ActivityScenarioRule(AppWidgetHostTestActivity::class.java) private lateinit var mRemoteViews: RemoteViews private lateinit var mHostView: AppWidgetHostView private var mAppWidgetId = 0 private val mUiAutomation: UiAutomation get() = InstrumentationRegistry.getInstrumentation().uiAutomation private val mListView: ListView get() = mHostView.getChildAt(0) as ListView @Before public fun setUp() { mUiAutomation.adoptShellPermissionIdentity(permission.BIND_APPWIDGET) mActivityTestRule.scenario.onActivity { activity -> mHostView = activity.bindAppWidget() } mAppWidgetId = mHostView.appWidgetId mRemoteViews = RemoteViews(mPackageName, R.layout.remote_views_list) mAppWidgetManager.updateAppWidget(mAppWidgetId, mRemoteViews) // Wait until the remote views has been added to the host view. observeDrawUntil { mHostView.childCount > 0 } } @After public fun tearDown() { mUiAutomation.dropShellPermissionIdentity() } @Test public fun testParcelingAndUnparceling() { val items = RemoteCollectionItems.Builder() .setHasStableIds(true) .setViewTypeCount(10) .addItem(id = 3, RemoteViews(mPackageName, R.layout.list_view_row)) .addItem(id = 5, RemoteViews(mPackageName, R.layout.list_view_row2)) .build() val parcel = Parcel.obtain() val unparceled = try { items.writeToParcel(parcel, /* flags= */ 0) parcel.setDataPosition(0) RemoteCollectionItems(parcel) } finally { parcel.recycle() } assertThat(unparceled.itemCount).isEqualTo(2) assertThat(unparceled.getItemId(0)).isEqualTo(3) assertThat(unparceled.getItemId(1)).isEqualTo(5) assertThat(unparceled.getItemView(0).layoutId).isEqualTo(R.layout.list_view_row) assertThat(unparceled.getItemView(1).layoutId).isEqualTo(R.layout.list_view_row2) assertThat(unparceled.hasStableIds()).isTrue() assertThat(unparceled.viewTypeCount).isEqualTo(10) } @Test public fun testBuilder_empty() { val items = RemoteCollectionItems.Builder().build() assertThat(items.itemCount).isEqualTo(0) assertThat(items.viewTypeCount).isEqualTo(1) assertThat(items.hasStableIds()).isFalse() } @Test public fun testBuilder_viewTypeCountUnspecified() { val firstItem = RemoteViews(mPackageName, R.layout.list_view_row) val secondItem = RemoteViews(mPackageName, R.layout.list_view_row2) val items = RemoteCollectionItems.Builder() .setHasStableIds(true) .addItem(id = 3, firstItem) .addItem(id = 5, secondItem) .build() assertThat(items.itemCount).isEqualTo(2) assertThat(items.getItemId(0)).isEqualTo(3) assertThat(items.getItemId(1)).isEqualTo(5) assertThat(items.getItemView(0).layoutId).isEqualTo(R.layout.list_view_row) assertThat(items.getItemView(1).layoutId).isEqualTo(R.layout.list_view_row2) assertThat(items.hasStableIds()).isTrue() // The view type count should be derived from the number of different layout ids if // unspecified. assertThat(items.viewTypeCount).isEqualTo(2) } @Test public fun testBuilder_viewTypeCountSpecified() { val firstItem = RemoteViews(mPackageName, R.layout.list_view_row) val secondItem = RemoteViews(mPackageName, R.layout.list_view_row2) val items = RemoteCollectionItems.Builder() .addItem(id = 3, firstItem) .addItem(id = 5, secondItem) .setViewTypeCount(15) .build() assertThat(items.viewTypeCount).isEqualTo(15) } @Test public fun testBuilder_repeatedIdsAndLayouts() { val firstItem = RemoteViews(mPackageName, R.layout.list_view_row) val secondItem = RemoteViews(mPackageName, R.layout.list_view_row) val thirdItem = RemoteViews(mPackageName, R.layout.list_view_row) val items = RemoteCollectionItems.Builder() .setHasStableIds(false) .addItem(id = 42, firstItem) .addItem(id = 42, secondItem) .addItem(id = 42, thirdItem) .build() assertThat(items.itemCount).isEqualTo(3) assertThat(items.getItemId(0)).isEqualTo(42) assertThat(items.getItemId(1)).isEqualTo(42) assertThat(items.getItemId(2)).isEqualTo(42) assertThat(items.getItemView(0)).isSameInstanceAs(firstItem) assertThat(items.getItemView(1)).isSameInstanceAs(secondItem) assertThat(items.getItemView(2)).isSameInstanceAs(thirdItem) assertThat(items.hasStableIds()).isFalse() assertThat(items.viewTypeCount).isEqualTo(1) } @Test public fun testBuilder_viewTypeCountLowerThanLayoutCount() { assertFailsWith(IllegalArgumentException::class) { RemoteCollectionItems.Builder() .setHasStableIds(true) .setViewTypeCount(1) .addItem(3, RemoteViews(mPackageName, R.layout.list_view_row)) .addItem(5, RemoteViews(mPackageName, R.layout.list_view_row2)) .build() } } @Test public fun testServiceIntent_hasSameUriForSameIds() { val intent1 = RemoteViewsCompatService.createIntent(mContext, appWidgetId = 1, viewId = 42) val intent2 = RemoteViewsCompatService.createIntent(mContext, appWidgetId = 1, viewId = 42) assertThat(intent1.data).isEqualTo(intent2.data) } @Test public fun testServiceIntent_hasDifferentUriForDifferentWidgetIds() { val intent1 = RemoteViewsCompatService.createIntent(mContext, appWidgetId = 1, viewId = 42) val intent2 = RemoteViewsCompatService.createIntent(mContext, appWidgetId = 2, viewId = 42) assertThat(intent1.data).isNotEqualTo(intent2.data) } @Test public fun testServiceIntent_hasDifferentUriForDifferentViewIds() { val intent1 = RemoteViewsCompatService.createIntent(mContext, appWidgetId = 1, viewId = 42) val intent2 = RemoteViewsCompatService.createIntent(mContext, appWidgetId = 1, viewId = 43) assertThat(intent1.data).isNotEqualTo(intent2.data) } @Test public fun testSetRemoteAdapter_emptyCollection() { val items = RemoteCollectionItems.Builder().build() RemoteViewsCompat.setRemoteAdapter( mContext, mRemoteViews, mAppWidgetId, R.id.list_view, items ) mAppWidgetManager.updateAppWidget(mAppWidgetId, mRemoteViews) observeDrawUntil { mListView.adapter != null } assertThat(mListView.childCount).isEqualTo(0) assertThat(mListView.adapter.count).isEqualTo(0) assertThat(mListView.adapter.viewTypeCount).isAtLeast(1) assertThat(mListView.adapter.hasStableIds()).isFalse() } @Test public fun testSetRemoteAdapter_withItems() { val items = RemoteCollectionItems.Builder() .setHasStableIds(true) .addItem(id = 10, createTextRow("Hello")) .addItem(id = 11, createTextRow("World")) .build() RemoteViewsCompat.setRemoteAdapter( mContext, mRemoteViews, mAppWidgetId, R.id.list_view, items ) mAppWidgetManager.updateAppWidget(mAppWidgetId, mRemoteViews) observeDrawUntil { mListView.adapter != null && mListView.childCount == 2 } val adapter = mListView.adapter assertThat(adapter.count).isEqualTo(2) assertThat(adapter.getItemViewType(1)).isEqualTo(adapter.getItemViewType(0)) assertThat(adapter.getItemId(0)).isEqualTo(10) assertThat(adapter.getItemId(1)).isEqualTo(11) assertThat(mListView.adapter.hasStableIds()).isTrue() assertThat(mListView.childCount).isEqualTo(2) assertThat(getListChildAt<TextView>(0).text.toString()).isEqualTo("Hello") assertThat(getListChildAt<TextView>(1).text.toString()).isEqualTo("World") } @Test public fun testSetRemoteAdapter_clickListener() { val action = "my-action" val receiver = TestBroadcastReceiver() mContext.registerReceiver(receiver, IntentFilter(action)) val pendingIntent = PendingIntent.getBroadcast( mContext, 0, Intent(action).setPackage(mPackageName), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE ) mRemoteViews.setPendingIntentTemplate(R.id.list_view, pendingIntent) val item2 = RemoteViews(mPackageName, R.layout.list_view_row2) item2.setTextViewText(R.id.text, "Clickable") item2.setOnClickFillInIntent(R.id.text, Intent().putExtra("my-extra", 42)) val items = RemoteCollectionItems.Builder() .setHasStableIds(true) .addItem(id = 10, createTextRow("Hello")) .addItem(id = 11, createTextRow("World")) .addItem(id = 12, createTextRow("Mundo")) .addItem(id = 13, item2) .build() RemoteViewsCompat.setRemoteAdapter( mContext, mRemoteViews, mAppWidgetId, R.id.list_view, items ) mAppWidgetManager.updateAppWidget(mAppWidgetId, mRemoteViews) observeDrawUntil { mListView.adapter != null && mListView.childCount == 4 } val adapter: Adapter = mListView.adapter assertThat(adapter.count).isEqualTo(4) assertThat(adapter.getItemViewType(0)).isEqualTo(adapter.getItemViewType(1)) assertThat(adapter.getItemViewType(0)).isEqualTo(adapter.getItemViewType(2)) assertThat(adapter.getItemViewType(0)).isNotEqualTo(adapter.getItemViewType(3)) assertThat(adapter.getItemId(0)).isEqualTo(10) assertThat(adapter.getItemId(1)).isEqualTo(11) assertThat(adapter.getItemId(2)).isEqualTo(12) assertThat(adapter.getItemId(3)).isEqualTo(13) assertThat(adapter.hasStableIds()).isTrue() assertThat(mListView.childCount).isEqualTo(4) val textView2 = getListChildAt<ViewGroup>(3).getChildAt(0) as TextView assertThat(getListChildAt<TextView>(0).text.toString()).isEqualTo("Hello") assertThat(getListChildAt<TextView>(1).text.toString()).isEqualTo("World") assertThat(getListChildAt<TextView>(2).text.toString()).isEqualTo("Mundo") assertThat(textView2.text.toString()).isEqualTo("Clickable") // View being clicked should launch the intent. val receiverIntent = receiver.runAndAwaitIntentReceived { textView2.performClick() } assertThat(receiverIntent.getIntExtra("my-extra", 0)).isEqualTo(42) mContext.unregisterReceiver(receiver) } @Test public fun testSetRemoteAdapter_multipleCalls() { var items = RemoteCollectionItems.Builder() .setHasStableIds(true) .addItem(id = 10, createTextRow("Hello")) .addItem(id = 11, createTextRow("World")) .build() RemoteViewsCompat.setRemoteAdapter( mContext, mRemoteViews, mAppWidgetId, R.id.list_view, items ) mAppWidgetManager.updateAppWidget(mAppWidgetId, mRemoteViews) observeDrawUntil { mListView.adapter != null && mListView.childCount == 2 } items = RemoteCollectionItems.Builder() .setHasStableIds(true) .addItem(id = 20, createTextRow("Bonjour")) .addItem(id = 21, createTextRow("le")) .addItem(id = 22, createTextRow("monde")) .build() RemoteViewsCompat.setRemoteAdapter( mContext, mRemoteViews, mAppWidgetId, R.id.list_view, items ) mAppWidgetManager.updateAppWidget(mAppWidgetId, mRemoteViews) observeDrawUntil { mListView.childCount == 3 } val adapter: Adapter = mListView.adapter assertThat(adapter.count).isEqualTo(3) assertThat(adapter.getItemId(0)).isEqualTo(20) assertThat(adapter.getItemId(1)).isEqualTo(21) assertThat(adapter.getItemId(2)).isEqualTo(22) assertThat(mListView.childCount).isEqualTo(3) assertThat(getListChildAt<TextView>(0).text.toString()).isEqualTo("Bonjour") assertThat(getListChildAt<TextView>(1).text.toString()).isEqualTo("le") assertThat(getListChildAt<TextView>(2).text.toString()).isEqualTo("monde") } private fun createTextRow(text: String): RemoteViews { return RemoteViews(mPackageName, R.layout.list_view_row) .also { it.setTextViewText(R.id.text, text) } } private fun observeDrawUntil(test: () -> Boolean) { val latch = CountDownLatch(1) val onDrawListener = OnDrawListener { if (test()) latch.countDown() } mActivityTestRule.scenario.onActivity { mHostView.viewTreeObserver.addOnDrawListener(onDrawListener) } val countedDown = latch.await(5, TimeUnit.SECONDS) mActivityTestRule.scenario.onActivity { mHostView.viewTreeObserver.removeOnDrawListener(onDrawListener) } if (!countedDown && !test()) { fail("Expected condition to be met within 5 seconds") } } @Suppress("UNCHECKED_CAST") private fun <V : View> getListChildAt(position: Int): V { return if (mUsingBackport) { // When using RemoteViewsAdapter, an extra wrapper FrameLayout is added. (mListView.getChildAt(position) as ViewGroup).getChildAt(0) as V } else { mListView.getChildAt(position) as V } } private inner class TestBroadcastReceiver : BroadcastReceiver() { private lateinit var mCountDownLatch: CountDownLatch private var mIntent: Intent? = null override fun onReceive(context: Context, intent: Intent) { mIntent = intent mCountDownLatch.countDown() } fun runAndAwaitIntentReceived(runnable: () -> Unit): Intent { mCountDownLatch = CountDownLatch(1) mActivityTestRule.scenario.onActivity { runnable() } mCountDownLatch.await(5, TimeUnit.SECONDS) return mIntent ?: fail("Expected intent to be received within five seconds") } } }
apache-2.0
androidx/androidx
glance/glance/src/androidMain/kotlin/androidx/glance/layout/Padding.kt
3
8609
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.glance.layout import android.content.res.Resources import androidx.annotation.DimenRes import androidx.annotation.RestrictTo import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.glance.GlanceModifier /** * Apply additional space along each edge of the content in [Dp]: [start], [top], [end] and * [bottom]. The start and end edges will be determined by layout direction of the current locale. * Padding is applied before content measurement and takes precedence; content may only be as large * as the remaining space. * * If any value is not defined, it will be [0.dp] or whatever value was defined by an earlier * modifier. */ fun GlanceModifier.padding( start: Dp = 0.dp, top: Dp = 0.dp, end: Dp = 0.dp, bottom: Dp = 0.dp, ): GlanceModifier = this.then( PaddingModifier( start = start.toPadding(), top = top.toPadding(), end = end.toPadding(), bottom = bottom.toPadding(), ) ) /** * Apply additional space along each edge of the content in [Dp]: [start], [top], [end] and * [bottom]. The start and end edges will be determined by layout direction of the current locale. * Padding is applied before content measurement and takes precedence; content may only be as large * as the remaining space. * * If any value is not defined, it will be [0.dp] or whatever value was defined by an earlier * modifier. */ fun GlanceModifier.padding( @DimenRes start: Int = 0, @DimenRes top: Int = 0, @DimenRes end: Int = 0, @DimenRes bottom: Int = 0 ): GlanceModifier = this.then( PaddingModifier( start = start.toPadding(), top = top.toPadding(), end = end.toPadding(), bottom = bottom.toPadding(), ) ) /** * Apply [horizontal] dp space along the left and right edges of the content, and [vertical] dp * space along the top and bottom edges. * * If any value is not defined, it will be [0.dp] or whatever value was defined by an earlier * modifier. */ fun GlanceModifier.padding( horizontal: Dp = 0.dp, vertical: Dp = 0.dp, ): GlanceModifier = this.then( PaddingModifier( start = horizontal.toPadding(), top = vertical.toPadding(), end = horizontal.toPadding(), bottom = vertical.toPadding(), ) ) /** * Apply [horizontal] dp space along the left and right edges of the content, and [vertical] dp * space along the top and bottom edges. * * If any value is not defined, it will be [0.dp] or whatever value was defined by an earlier * modifier. */ fun GlanceModifier.padding( @DimenRes horizontal: Int = 0, @DimenRes vertical: Int = 0 ): GlanceModifier = this.then( PaddingModifier( start = horizontal.toPadding(), top = vertical.toPadding(), end = horizontal.toPadding(), bottom = vertical.toPadding(), ) ) /** * Apply [all] dp of additional space along each edge of the content, left, top, right and bottom. */ fun GlanceModifier.padding(all: Dp): GlanceModifier { val allDp = all.toPadding() return this.then( PaddingModifier( start = allDp, top = allDp, end = allDp, bottom = allDp, ) ) } /** * Apply [all] dp of additional space along each edge of the content, left, top, right and bottom. */ fun GlanceModifier.padding(@DimenRes all: Int): GlanceModifier { val allDp = all.toPadding() return this.then( PaddingModifier( start = allDp, top = allDp, end = allDp, bottom = allDp, ) ) } /** * Apply additional space along each edge of the content in [Dp]: [left], [top], [right] and * [bottom], ignoring the current locale's layout direction. */ fun GlanceModifier.absolutePadding( left: Dp = 0.dp, top: Dp = 0.dp, right: Dp = 0.dp, bottom: Dp = 0.dp, ): GlanceModifier = this.then( PaddingModifier( left = left.toPadding(), top = top.toPadding(), right = right.toPadding(), bottom = bottom.toPadding(), ) ) /** * Apply additional space along each edge of the content in [Dp]: [left], [top], [right] and * [bottom], ignoring the current locale's layout direction. */ fun GlanceModifier.absolutePadding( @DimenRes left: Int = 0, @DimenRes top: Int = 0, @DimenRes right: Int = 0, @DimenRes bottom: Int = 0 ): GlanceModifier = this.then( PaddingModifier( left = left.toPadding(), top = top.toPadding(), right = right.toPadding(), bottom = bottom.toPadding(), ) ) private fun Dp.toPadding() = PaddingDimension(dp = this) private fun Int.toPadding() = if (this == 0) PaddingDimension() else PaddingDimension(this) /** @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun GlanceModifier.collectPadding(): PaddingModifier? = foldIn<PaddingModifier?>(null) { acc, modifier -> if (modifier is PaddingModifier) { (acc ?: PaddingModifier()) + modifier } else { acc } } /** @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun GlanceModifier.collectPaddingInDp(resources: Resources) = collectPadding()?.toDp(resources) private fun List<Int>.toDp(resources: Resources) = fold(0.dp) { acc, res -> acc + (resources.getDimension(res) / resources.displayMetrics.density).dp } /** @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class PaddingModifier( val left: PaddingDimension = PaddingDimension(), val start: PaddingDimension = PaddingDimension(), val top: PaddingDimension = PaddingDimension(), val right: PaddingDimension = PaddingDimension(), val end: PaddingDimension = PaddingDimension(), val bottom: PaddingDimension = PaddingDimension(), ) : GlanceModifier.Element { operator fun plus(other: PaddingModifier) = PaddingModifier( left = left + other.left, start = start + other.start, top = top + other.top, right = right + other.right, end = end + other.end, bottom = bottom + other.bottom, ) fun toDp(resources: Resources): PaddingInDp = PaddingInDp( left = left.dp + left.resourceIds.toDp(resources), start = start.dp + start.resourceIds.toDp(resources), top = top.dp + top.resourceIds.toDp(resources), right = right.dp + right.resourceIds.toDp(resources), end = end.dp + end.resourceIds.toDp(resources), bottom = bottom.dp + bottom.resourceIds.toDp(resources), ) } /** @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class PaddingDimension( val dp: Dp = 0.dp, val resourceIds: List<Int> = emptyList(), ) { constructor(@DimenRes resource: Int) : this(resourceIds = listOf(resource)) operator fun plus(other: PaddingDimension) = PaddingDimension( dp = dp + other.dp, resourceIds = resourceIds + other.resourceIds, ) companion object { val Zero = PaddingDimension() } } /** @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class PaddingInDp( val left: Dp = 0.dp, val start: Dp = 0.dp, val top: Dp = 0.dp, val right: Dp = 0.dp, val end: Dp = 0.dp, val bottom: Dp = 0.dp, ) { /** Transfer [start] / [end] to [left] / [right] depending on [isRtl]. */ fun toAbsolute(isRtl: Boolean) = PaddingInDp( left = left + if (isRtl) end else start, top = top, right = right + if (isRtl) start else end, bottom = bottom, ) /** Transfer [left] / [right] to [start] / [end] depending on [isRtl]. */ fun toRelative(isRtl: Boolean) = PaddingInDp( start = start + if (isRtl) right else left, top = top, end = end + if (isRtl) left else right, bottom = bottom ) }
apache-2.0
kamerok/Orny
app/src/main/kotlin/com/kamer/orny/presentation/settings/errors/WrongBudgetFormatException.kt
1
123
package com.kamer.orny.presentation.settings.errors class WrongBudgetFormatException(message: String): Exception(message)
apache-2.0
androidx/androidx
compose/ui/ui-text/src/androidAndroidTest/kotlin/androidx/compose/ui/text/TextPainterTest.kt
3
16146
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalTextApi::class) package androidx.compose.ui.text import android.graphics.Bitmap import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.drawscope.CanvasDrawScope import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Fill import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.createFontFamilyResolver import androidx.compose.ui.text.font.toFontFamily import androidx.compose.ui.text.matchers.assertThat import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.sp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.test.platform.app.InstrumentationRegistry import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @MediumTest class TextPainterTest { private val fontFamilyMeasureFont = FontTestData.BASIC_MEASURE_FONT.toFontFamily() private val context = InstrumentationRegistry.getInstrumentation().context private val fontFamilyResolver = createFontFamilyResolver(context) private var defaultDensity = Density(density = 1f) private var layoutDirection = LayoutDirection.Ltr private val longText = AnnotatedString( "Lorem ipsum dolor sit amet, consectetur " + "adipiscing elit. Curabitur augue leo, finibus vitae felis ac, pretium condimentum " + "augue. Nullam non libero sed lectus aliquet venenatis non at purus. Fusce id arcu " + "eu mauris pulvinar laoreet." ) @Test fun drawTextWithMeasurer_shouldBeEqualTo_drawTextLayoutResult() { val measurer = textMeasurer() val textLayoutResult = measurer.measure( text = longText, style = TextStyle(fontFamily = fontFamilyMeasureFont, fontSize = 20.sp), constraints = Constraints(maxWidth = 400, maxHeight = 400) ) val bitmap = draw { drawText(textLayoutResult) } val bitmap2 = draw { drawText( measurer, text = longText, style = TextStyle(fontFamily = fontFamilyMeasureFont, fontSize = 20.sp), maxSize = IntSize(400, 400) ) } assertThat(bitmap).isEqualToBitmap(bitmap2) } @Test fun textMeasurerCache_shouldNotAffectTheResult_forColor() { val measurer = textMeasurer(cacheSize = 8) val bitmap = draw { drawText( textMeasurer = measurer, text = longText, style = TextStyle( color = Color.Red, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), maxSize = IntSize(400, 400) ) } val bitmap2 = draw { drawText( textMeasurer = measurer, text = longText, style = TextStyle( color = Color.Blue, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), maxSize = IntSize(400, 400) ) } assertThat(bitmap).isNotEqualToBitmap(bitmap2) } @Test fun textMeasurerCache_shouldNotAffectTheResult_forFontSize() { val measurer = textMeasurer(cacheSize = 8) val bitmap = draw { drawText( textMeasurer = measurer, text = longText, style = TextStyle(fontFamily = fontFamilyMeasureFont, fontSize = 20.sp), maxSize = IntSize(400, 400) ) } val bitmap2 = draw { drawText( textMeasurer = measurer, text = longText, style = TextStyle(fontFamily = fontFamilyMeasureFont, fontSize = 24.sp), maxSize = IntSize(400, 400) ) } assertThat(bitmap).isNotEqualToBitmap(bitmap2) } @Test fun drawTextLayout_shouldChangeColor() { val measurer = textMeasurer() val textLayoutResultRed = measurer.measure( text = longText, style = TextStyle( color = Color.Red, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(400, 400) ) val textLayoutResultBlue = measurer.measure( text = longText, style = TextStyle( color = Color.Blue, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(400, 400) ) val bitmap = draw { drawText(textLayoutResultRed, color = Color.Blue) } val bitmap2 = draw { drawText(textLayoutResultBlue) } assertThat(bitmap).isEqualToBitmap(bitmap2) } @Test fun drawTextLayout_shouldChangeAlphaColor() { val measurer = textMeasurer() val textLayoutResultOpaque = measurer.measure( text = longText, style = TextStyle( color = Color.Red, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(400, 400) ) val textLayoutResultHalfOpaque = measurer.measure( text = longText, style = TextStyle( color = Color.Red.copy(alpha = 0.5f), fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(400, 400) ) val bitmap = draw { drawText(textLayoutResultOpaque, alpha = 0.5f) } val bitmap2 = draw { drawText(textLayoutResultHalfOpaque) } assertThat(bitmap).isEqualToBitmap(bitmap2) } @Test fun drawTextLayout_shouldChangeBrush() { val rbBrush = Brush.radialGradient(listOf(Color.Red, Color.Blue)) val gyBrush = Brush.radialGradient(listOf(Color.Green, Color.Yellow)) val measurer = textMeasurer() val textLayoutResultRB = measurer.measure( text = longText, style = TextStyle( brush = rbBrush, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(400, 400) ) val textLayoutResultGY = measurer.measure( text = longText, style = TextStyle( brush = gyBrush, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(400, 400) ) val bitmap = draw { drawText(textLayoutResultRB, brush = gyBrush) } val bitmap2 = draw { drawText(textLayoutResultGY) } assertThat(bitmap).isEqualToBitmap(bitmap2) } @Test fun drawTextLayout_shouldChangeAlphaForBrush() { val rbBrush = Brush.radialGradient(listOf(Color.Red, Color.Blue)) val measurer = textMeasurer() val textLayoutResultOpaque = measurer.measure( text = longText, style = TextStyle( brush = rbBrush, alpha = 1f, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(400, 400) ) val textLayoutResultHalfOpaque = measurer.measure( text = longText, style = TextStyle( brush = rbBrush, alpha = 0.5f, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(400, 400) ) val bitmap = draw { drawText(textLayoutResultOpaque, alpha = 0.5f) } val bitmap2 = draw { drawText(textLayoutResultHalfOpaque) } assertThat(bitmap).isEqualToBitmap(bitmap2) } @Test fun drawTextLayout_shouldChangeDrawStyle() { val fillDrawStyle = Fill val strokeDrawStyle = Stroke(8f, cap = StrokeCap.Round) val measurer = textMeasurer() val textLayoutResultFill = measurer.measure( text = longText, style = TextStyle( drawStyle = fillDrawStyle, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints(maxWidth = 400, maxHeight = 400) ) val textLayoutResultStroke = measurer.measure( text = longText, style = TextStyle( drawStyle = strokeDrawStyle, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints(maxWidth = 400, maxHeight = 400) ) val bitmap = draw { drawText(textLayoutResultFill, drawStyle = strokeDrawStyle) } val bitmap2 = draw { drawText(textLayoutResultStroke) } assertThat(bitmap).isEqualToBitmap(bitmap2) } @Test fun textMeasurerDraw_isConstrainedTo_canvasSizeByDefault() { val measurer = textMeasurer() // constrain the width, height is ignored val textLayoutResult = measurer.measure( text = longText, style = TextStyle( fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(200, 4000) ) val bitmap = draw(200f, 4000f) { drawText(textLayoutResult) } val bitmap2 = draw(200f, 4000f) { drawText(measurer, longText, style = TextStyle( fontFamily = fontFamilyMeasureFont, fontSize = 20.sp )) } assertThat(bitmap).isEqualToBitmap(bitmap2) } @Test fun textMeasurerDraw_usesCanvasDensity_ByDefault() { val measurer = textMeasurer() // constrain the width, height is ignored val textLayoutResult = measurer.measure( text = longText, style = TextStyle( fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), density = Density(4f), constraints = Constraints.fixed(1000, 1000) ) val bitmap = draw { drawText(textLayoutResult) } defaultDensity = Density(4f) val bitmap2 = draw { drawText(measurer, longText, style = TextStyle( fontFamily = fontFamilyMeasureFont, fontSize = 20.sp )) } assertThat(bitmap).isEqualToBitmap(bitmap2) } @Test fun drawTextClipsTheContent_ifOverflowIsClip() { val measurer = textMeasurer() // constrain the width, height is ignored val textLayoutResult = measurer.measure( text = longText, style = TextStyle( fontFamily = fontFamilyMeasureFont, fontSize = 14.sp ), softWrap = false, overflow = TextOverflow.Clip, constraints = Constraints.fixed(200, 200) ) val bitmap = draw(400f, 200f) { drawText(textLayoutResult) } val croppedBitmap = Bitmap.createBitmap(bitmap, 200, 0, 200, 200) // cropped part should be empty assertThat(croppedBitmap).isEqualToBitmap(Bitmap.createBitmap( 200, 200, Bitmap.Config.ARGB_8888)) } @Test fun drawTextClipsTheContent_ifOverflowIsEllipsis_ifLessThanOneLineFits() { val measurer = textMeasurer() with(defaultDensity) { val fontSize = 20.sp val height = fontSize.toPx().ceilToInt() / 2 val textLayoutResult = measurer.measure( text = longText, style = TextStyle( fontFamily = fontFamilyMeasureFont, fontSize = fontSize ), softWrap = false, overflow = TextOverflow.Ellipsis, constraints = Constraints.fixed(200, height) ) val bitmap = draw(200f, 200f) { drawText(textLayoutResult) } val croppedBitmap = Bitmap.createBitmap(bitmap, 0, height, 200, 200 - height) // cropped part should be empty assertThat(croppedBitmap).isEqualToBitmap( Bitmap.createBitmap( 200, 200 - height, Bitmap.Config.ARGB_8888 ) ) } } @Test fun drawTextDoesNotClipTheContent_ifOverflowIsVisible() { val measurer = textMeasurer() // constrain the width, height is ignored val textLayoutResult = measurer.measure( text = longText, style = TextStyle( fontFamily = fontFamilyMeasureFont, fontSize = 14.sp ), softWrap = false, overflow = TextOverflow.Clip, constraints = Constraints.fixed(400, 200) ) val textLayoutResultNoClip = measurer.measure( text = longText, style = TextStyle( fontFamily = fontFamilyMeasureFont, fontSize = 14.sp ), softWrap = false, overflow = TextOverflow.Visible, constraints = Constraints.fixed(200, 200) ) val bitmap = draw(400f, 200f) { drawText(textLayoutResult) } val bitmapNoClip = draw(400f, 200f) { drawText(textLayoutResultNoClip) } // cropped part should be empty assertThat(bitmap).isEqualToBitmap(bitmapNoClip) } private fun textMeasurer( fontFamilyResolver: FontFamily.Resolver = this.fontFamilyResolver, density: Density = this.defaultDensity, layoutDirection: LayoutDirection = this.layoutDirection, cacheSize: Int = 0 ): TextMeasurer = TextMeasurer( fontFamilyResolver, density, layoutDirection, cacheSize ) fun draw( width: Float = 1000f, height: Float = 1000f, block: DrawScope.() -> Unit ): Bitmap { val size = Size(width, height) val bitmap = Bitmap.createBitmap( size.width.toIntPx(), size.height.toIntPx(), Bitmap.Config.ARGB_8888 ) val canvas = Canvas(bitmap.asImageBitmap()) val drawScope = CanvasDrawScope() drawScope.draw( defaultDensity, layoutDirection, canvas, size, block ) return bitmap } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/replacePutWithAssignment/putOnThis.kt
9
116
// WITH_STDLIB class MyMap() : HashMap<String, String>() { init { this.<caret>put("foo", "bar") } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/replaceWithSafeCallForScopeFunction/applyWithoutThisMethodCall.kt
9
142
// "Replace scope function with safe (?.) call" "true" // WITH_STDLIB fun foo(a: String?) { a.apply { <caret>toLowerCase() } }
apache-2.0
GunoH/intellij-community
python/src/com/jetbrains/python/sdk/add/wizardUIUtil.kt
9
2802
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.jetbrains.python.sdk.add import com.intellij.openapi.project.Project import com.intellij.openapi.util.SystemInfoRt import com.intellij.ui.JBCardLayout import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.messages.showProcessExecutionErrorDialog import com.intellij.util.ui.GridBag import com.intellij.util.ui.JBInsets import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.jetbrains.python.packaging.PyExecutionException import java.awt.* import javax.swing.BorderFactory import javax.swing.Box import javax.swing.JButton import javax.swing.JPanel internal fun doCreateSouthPanel(leftButtons: List<JButton>, rightButtons: List<JButton>): JPanel { val panel = JPanel(BorderLayout()) //noinspection UseDPIAwareInsets val insets = if (SystemInfoRt.isMac) if (UIUtil.isUnderIntelliJLaF()) JBUI.insets(0, 8) else JBInsets.emptyInsets() else if (UIUtil.isUnderWin10LookAndFeel()) JBInsets.emptyInsets() else Insets(8, 0, 0, 0) //don't wrap to JBInsets val bag = GridBag().setDefaultInsets(insets) val lrButtonsPanel = NonOpaquePanel(GridBagLayout()) val leftButtonsPanel = createButtonsPanel(leftButtons) leftButtonsPanel.border = BorderFactory.createEmptyBorder(0, 0, 0, 20) // leave some space between button groups lrButtonsPanel.add(leftButtonsPanel, bag.next()) lrButtonsPanel.add(Box.createHorizontalGlue(), bag.next().weightx(1.0).fillCellHorizontally()) // left strut val buttonsPanel = createButtonsPanel(rightButtons) lrButtonsPanel.add(buttonsPanel, bag.next()) panel.add(lrButtonsPanel, BorderLayout.CENTER) panel.border = JBUI.Borders.emptyTop(8) return panel } private fun createButtonsPanel(buttons: List<JButton>): JPanel { val hgap = if (SystemInfoRt.isMac) if (UIUtil.isUnderIntelliJLaF()) 8 else 0 else 5 val buttonsPanel = NonOpaquePanel(GridLayout(1, buttons.size, hgap, 0)) buttons.forEach { buttonsPanel.add(it) } return buttonsPanel } internal fun swipe(panel: JPanel, stepContent: Component, swipeDirection: JBCardLayout.SwipeDirection) { val stepContentName = stepContent.hashCode().toString() panel.add(stepContentName, stepContent) (panel.layout as JBCardLayout).swipe(panel, stepContentName, swipeDirection) } internal fun show(panel: JPanel, stepContent: Component) { val stepContentName = stepContent.hashCode().toString() panel.add(stepContentName, stepContent) (panel.layout as CardLayout).show(panel, stepContentName) } fun showProcessExecutionErrorDialog(project: Project?, e: PyExecutionException) = showProcessExecutionErrorDialog(project, e.localizedMessage.orEmpty(), e.command, e.stdout, e.stderr, e.exitCode)
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/javaClassOnCompanion/replaceWithClassJava/simple.kt
9
102
// "Replace with '::class.java'" "true" // WITH_STDLIB fun main() { val c = Int.javaClass<caret> }
apache-2.0
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderPresenter.kt
1
17162
package eu.kanade.tachiyomi.ui.reader import android.os.Bundle import eu.kanade.tachiyomi.data.cache.ChapterCache import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.History import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.database.models.MangaSync import eu.kanade.tachiyomi.data.download.DownloadManager import eu.kanade.tachiyomi.data.mangasync.MangaSyncManager import eu.kanade.tachiyomi.data.mangasync.UpdateMangaSyncService import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.source.SourceManager import eu.kanade.tachiyomi.data.source.model.Page import eu.kanade.tachiyomi.data.source.online.OnlineSource import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter import eu.kanade.tachiyomi.util.RetryWithDelay import eu.kanade.tachiyomi.util.SharedData import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import timber.log.Timber import uy.kohesive.injekt.injectLazy import java.io.File import java.util.* /** * Presenter of [ReaderActivity]. */ class ReaderPresenter : BasePresenter<ReaderActivity>() { /** * Preferences. */ val prefs: PreferencesHelper by injectLazy() /** * Database. */ val db: DatabaseHelper by injectLazy() /** * Download manager. */ val downloadManager: DownloadManager by injectLazy() /** * Sync manager. */ val syncManager: MangaSyncManager by injectLazy() /** * Source manager. */ val sourceManager: SourceManager by injectLazy() /** * Chapter cache. */ val chapterCache: ChapterCache by injectLazy() /** * Manga being read. */ lateinit var manga: Manga private set /** * Active chapter. */ lateinit var chapter: ReaderChapter private set /** * Previous chapter of the active. */ private var prevChapter: ReaderChapter? = null /** * Next chapter of the active. */ private var nextChapter: ReaderChapter? = null /** * Source of the manga. */ private val source by lazy { sourceManager.get(manga.source)!! } /** * Chapter list for the active manga. It's retrieved lazily and should be accessed for the first * time in a background thread to avoid blocking the UI. */ private val chapterList by lazy { val dbChapters = db.getChapters(manga).executeAsBlocking().map { it.toModel() } val sortFunction: (Chapter, Chapter) -> Int = when (manga.sorting) { Manga.SORTING_SOURCE -> { c1, c2 -> c2.source_order.compareTo(c1.source_order) } Manga.SORTING_NUMBER -> { c1, c2 -> c1.chapter_number.compareTo(c2.chapter_number) } else -> throw NotImplementedError("Unknown sorting method") } dbChapters.sortedWith(Comparator<Chapter> { c1, c2 -> sortFunction(c1, c2) }) } /** * Map of chapters that have been loaded in the reader. */ private val loadedChapters = hashMapOf<Long?, ReaderChapter>() /** * List of manga services linked to the active manga, or null if auto syncing is not enabled. */ private var mangaSyncList: List<MangaSync>? = null /** * Chapter loader whose job is to obtain the chapter list and initialize every page. */ private val loader by lazy { ChapterLoader(downloadManager, manga, source) } /** * Subscription for appending a chapter to the reader (seamless mode). */ private var appenderSubscription: Subscription? = null /** * Subscription for retrieving the adjacent chapters to the current one. */ private var adjacentChaptersSubscription: Subscription? = null companion object { /** * Id of the restartable that loads the active chapter. */ private const val LOAD_ACTIVE_CHAPTER = 1 } override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) if (savedState == null) { val event = SharedData.get(ReaderEvent::class.java) ?: return manga = event.manga chapter = event.chapter.toModel() } else { manga = savedState.getSerializable(ReaderPresenter::manga.name) as Manga chapter = savedState.getSerializable(ReaderPresenter::chapter.name) as ReaderChapter } // Send the active manga to the view to initialize the reader. Observable.just(manga) .subscribeLatestCache({ view, manga -> view.onMangaOpen(manga) }) // Retrieve the sync list if auto syncing is enabled. if (prefs.autoUpdateMangaSync()) { add(db.getMangasSync(manga).asRxSingle() .subscribe({ mangaSyncList = it })) } restartableLatestCache(LOAD_ACTIVE_CHAPTER, { loadChapterObservable(chapter) }, { view, chapter -> view.onChapterReady(this.chapter) }, { view, error -> view.onChapterError(error) }) if (savedState == null) { loadChapter(chapter) } } override fun onSave(state: Bundle) { chapter.requestedPage = chapter.last_page_read state.putSerializable(ReaderPresenter::manga.name, manga) state.putSerializable(ReaderPresenter::chapter.name, chapter) super.onSave(state) } override fun onDestroy() { loader.cleanup() onChapterLeft() super.onDestroy() } /** * Converts a chapter to a [ReaderChapter] if needed. */ private fun Chapter.toModel(): ReaderChapter { if (this is ReaderChapter) return this return ReaderChapter(this) } /** * Returns an observable that loads the given chapter, discarding any previous work. * * @param chapter the now active chapter. */ private fun loadChapterObservable(chapter: ReaderChapter): Observable<ReaderChapter> { loader.restart() return loader.loadChapter(chapter) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } /** * Obtains the adjacent chapters of the given one in a background thread, and notifies the view * when they are known. * * @param chapter the current active chapter. */ private fun getAdjacentChapters(chapter: ReaderChapter) { // Keep only one subscription adjacentChaptersSubscription?.let { remove(it) } adjacentChaptersSubscription = Observable .fromCallable { getAdjacentChaptersStrategy(chapter) } .doOnNext { pair -> prevChapter = loadedChapters.getOrElse(pair.first?.id) { pair.first } nextChapter = loadedChapters.getOrElse(pair.second?.id) { pair.second } } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeLatestCache({ view, pair -> view.onAdjacentChapters(pair.first, pair.second) }) } /** * Returns the previous and next chapters of the given one in a [Pair] according to the sorting * strategy set for the manga. * * @param chapter the current active chapter. * @param previousChapterAmount the desired number of chapters preceding the current active chapter (Default: 1). * @param nextChapterAmount the desired number of chapters succeeding the current active chapter (Default: 1). */ private fun getAdjacentChaptersStrategy(chapter: ReaderChapter, previousChapterAmount: Int = 1, nextChapterAmount: Int = 1) = when (manga.sorting) { Manga.SORTING_SOURCE -> { val currChapterIndex = chapterList.indexOfFirst { chapter.id == it.id } val nextChapter = chapterList.getOrNull(currChapterIndex + nextChapterAmount) val prevChapter = chapterList.getOrNull(currChapterIndex - previousChapterAmount) Pair(prevChapter, nextChapter) } Manga.SORTING_NUMBER -> { val currChapterIndex = chapterList.indexOfFirst { chapter.id == it.id } val chapterNumber = chapter.chapter_number var prevChapter: ReaderChapter? = null for (i in (currChapterIndex - previousChapterAmount) downTo 0) { val c = chapterList[i] if (c.chapter_number < chapterNumber && c.chapter_number >= chapterNumber - previousChapterAmount) { prevChapter = c break } } var nextChapter: ReaderChapter? = null for (i in (currChapterIndex + nextChapterAmount) until chapterList.size) { val c = chapterList[i] if (c.chapter_number > chapterNumber && c.chapter_number <= chapterNumber + nextChapterAmount) { nextChapter = c break } } Pair(prevChapter, nextChapter) } else -> throw NotImplementedError("Unknown sorting method") } /** * Loads the given chapter and sets it as the active one. This method also accepts a requested * page, which will be set as active when it's displayed in the view. * * @param chapter the chapter to load. * @param requestedPage the requested page from the view. */ private fun loadChapter(chapter: ReaderChapter, requestedPage: Int = 0) { // Cleanup any append. appenderSubscription?.let { remove(it) } this.chapter = loadedChapters.getOrPut(chapter.id) { chapter } // If the chapter is partially read, set the starting page to the last the user read // otherwise use the requested page. chapter.requestedPage = if (!chapter.read) chapter.last_page_read else requestedPage // Reset next and previous chapter. They have to be fetched again nextChapter = null prevChapter = null start(LOAD_ACTIVE_CHAPTER) getAdjacentChapters(chapter) } /** * Changes the active chapter, but doesn't load anything. Called when changing chapters from * the reader with the seamless mode. * * @param chapter the chapter to set as active. */ fun setActiveChapter(chapter: ReaderChapter) { onChapterLeft() this.chapter = chapter nextChapter = null prevChapter = null getAdjacentChapters(chapter) } /** * Appends the next chapter to the reader, if possible. */ fun appendNextChapter() { appenderSubscription?.let { remove(it) } val nextChapter = nextChapter ?: return val chapterToLoad = loadedChapters.getOrPut(nextChapter.id) { nextChapter } appenderSubscription = loader.loadChapter(chapterToLoad) .subscribeOn(Schedulers.io()) .retryWhen(RetryWithDelay(1, { 3000 })) .observeOn(AndroidSchedulers.mainThread()) .subscribeLatestCache({ view, chapter -> view.onAppendChapter(chapter) }, { view, error -> view.onChapterAppendError() }) } /** * Retries a page that failed to load due to network error or corruption. * * @param page the page that failed. */ fun retryPage(page: Page?) { if (page != null && source is OnlineSource) { page.status = Page.QUEUE if (page.imagePath != null) { val file = File(page.imagePath) chapterCache.removeFileFromCache(file.name) } loader.retryPage(page) } } /** * Called before loading another chapter or leaving the reader. It allows to do operations * over the chapter read like saving progress */ fun onChapterLeft() { // Reference these locally because they are needed later from another thread. val chapter = chapter val pages = chapter.pages ?: return Observable.fromCallable { // Chapters with 1 page don't trigger page changes, so mark them as read. if (pages.size == 1) { chapter.read = true } // Cache current page list progress for online chapters to allow a faster reopen if (!chapter.isDownloaded) { source.let { if (it is OnlineSource) it.savePageList(chapter, pages) } } if (chapter.read) { val removeAfterReadSlots = prefs.removeAfterReadSlots() when (removeAfterReadSlots) { // Setting disabled -1 -> { /**Empty function**/ } // Remove current read chapter 0 -> deleteChapter(chapter, manga) // Remove previous chapter specified by user in settings. else -> getAdjacentChaptersStrategy(chapter, removeAfterReadSlots) .first?.let { deleteChapter(it, manga) } } } db.updateChapterProgress(chapter).executeAsBlocking() try { val history = History.create(chapter).apply { last_read = Date().time } db.updateHistoryLastRead(history).executeAsBlocking() } catch (error: Exception) { // TODO find out why it crashes Timber.e(error) } } .subscribeOn(Schedulers.io()) .subscribe() } /** * Called when the active page changes in the reader. * * @param page the active page */ fun onPageChanged(page: Page) { val chapter = page.chapter chapter.last_page_read = page.pageNumber if (chapter.pages!!.last() === page) { chapter.read = true } if (!chapter.isDownloaded && page.status == Page.QUEUE) { loader.loadPriorizedPage(page) } } /** * Delete selected chapter * * @param chapter chapter that is selected * @param manga manga that belongs to chapter */ fun deleteChapter(chapter: ReaderChapter, manga: Manga) { chapter.isDownloaded = false chapter.pages?.forEach { it.status == Page.QUEUE } downloadManager.deleteChapter(source, manga, chapter) } /** * Returns the chapter to be marked as last read in sync services or 0 if no update required. */ fun getMangaSyncChapterToUpdate(): Int { val mangaSyncList = mangaSyncList if (chapter.pages == null || mangaSyncList == null || mangaSyncList.isEmpty()) return 0 val prevChapter = prevChapter // Get the last chapter read from the reader. val lastChapterRead = if (chapter.read) Math.floor(chapter.chapter_number.toDouble()).toInt() else if (prevChapter != null && prevChapter.read) Math.floor(prevChapter.chapter_number.toDouble()).toInt() else 0 mangaSyncList.forEach { sync -> if (lastChapterRead > sync.last_chapter_read) { sync.last_chapter_read = lastChapterRead sync.update = true } } return if (mangaSyncList.any { it.update }) lastChapterRead else 0 } /** * Starts the service that updates the last chapter read in sync services */ fun updateMangaSyncLastChapterRead() { mangaSyncList?.forEach { sync -> val service = syncManager.getService(sync.sync_id) if (service != null && service.isLogged && sync.update) { UpdateMangaSyncService.start(context, sync) } } } /** * Loads the next chapter. * * @return true if the next chapter is being loaded, false if there is no next chapter. */ fun loadNextChapter(): Boolean { nextChapter?.let { onChapterLeft() loadChapter(it, 0) return true } return false } /** * Loads the next chapter. * * @return true if the previous chapter is being loaded, false if there is no previous chapter. */ fun loadPreviousChapter(): Boolean { prevChapter?.let { onChapterLeft() loadChapter(it, if (it.read) -1 else 0) return true } return false } /** * Returns true if there's a next chapter. */ fun hasNextChapter(): Boolean { return nextChapter != null } /** * Returns true if there's a previous chapter. */ fun hasPreviousChapter(): Boolean { return prevChapter != null } /** * Updates the viewer for this manga. * * @param viewer the id of the viewer to set. */ fun updateMangaViewer(viewer: Int) { manga.viewer = viewer db.insertManga(manga).executeAsBlocking() } }
gpl-3.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceJavaStaticMethodWithKotlinAnalog/collections/deepHashCode.kt
4
123
// WITH_RUNTIME import java.util.Arrays fun test() { val a = arrayOf(1) val hash = Arrays.<caret>deepHashCode(a) }
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/intentions/removeBraces/elseInDotQualifiedExpression.kt
4
151
// WITH_RUNTIME fun test(b: Boolean) { val list1 = mutableListOf(1) val list2 = mutableListOf(2) if (b) list1 else <caret>{list2}.add(3) }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/search/KotlinSSPropertyTest.kt
5
8356
// 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.structuralsearch.search import org.jetbrains.kotlin.idea.structuralsearch.KotlinStructuralSearchTest import org.jetbrains.kotlin.idea.structuralsearch.KotlinStructuralSearchProfile import org.jetbrains.kotlin.idea.structuralsearch.filters.AlsoMatchValModifier import org.jetbrains.kotlin.idea.structuralsearch.filters.AlsoMatchVarModifier import org.jetbrains.kotlin.idea.structuralsearch.filters.OneStateFilter class KotlinSSPropertyTest : KotlinStructuralSearchTest() { fun testVar() { doTest(pattern = "var '_", highlighting = """ fun main() { val foo = 1 <warning descr="SSR">var bar = 1</warning> print(foo + bar) } """.trimIndent()) } fun testVal() { doTest(pattern = "val '_", highlighting = """ fun main() { <warning descr="SSR">val foo = 1</warning> var bar: Int = 1 print(foo + bar) } """.trimIndent()) } fun testValType() { doTest(pattern = "val '_ : Int", highlighting = """ class A { val foo1 = Int() <warning descr="SSR">val foo2 : A.Int = Int()</warning> class Int } fun main(): String { val bar = "1" <warning descr="SSR">val bar1: Int = 1</warning> <warning descr="SSR">val bar2: kotlin.Int = 1</warning> return "${"$"}bar + ${"$"}bar1 + ${"$"}bar2" } """.trimIndent()) } fun testValFqType() { doTest(pattern = "val '_ : Foo.Int", highlighting = """ class Foo { val foo = Int() <warning descr="SSR">val bar : Foo.Int</warning> init {bar = Int()} class Int } fun main() { val foo2: Int = 1 print(foo2) } """.trimIndent()) } fun testValComplexFqType() { doTest(pattern = "val '_ : '_<'_<'_, (Foo.Int) -> Int>>", highlighting = """ class Foo { class Int } <warning descr="SSR">val foo1: List<Pair<String, (Foo.Int) -> kotlin.Int>> = listOf()</warning> val foo2 = listOf("foo" to { _: Foo.Int -> 2 }) val bar1: List<Pair<String, (Int) -> Int>> = listOf() val bar2 = listOf("bar" to { _: Int -> 2 }) """.trimIndent()) } fun testValInitializer() { doTest(pattern = "val '_ = 1", highlighting = """ fun main() { <warning descr="SSR">val foo = 1</warning> val foo2: Int var bar: Int = 1 foo2 = 1 <warning descr="SSR">val bar2: Int = 1</warning> <warning descr="SSR">val bar3: Int = (1)</warning> <warning descr="SSR">val bar4: Int = (((1)))</warning> print(foo + foo2 + bar + bar2 + bar3 + bar4) } """.trimIndent()) } fun testValReceiverType() { doTest(pattern = "val '_ : ('_T) -> '_U = '_", highlighting = """ <warning descr="SSR">val foo: (Int) -> String? = { "${"$"}it" }</warning> val bar: String = "bar" val bar2: (Int, Int) -> String? = TODO() """.trimIndent()) } fun testVarTypeProjection() { doTest(pattern = "var '_ : Comparable<'_T>", highlighting = """ <warning descr="SSR">var foo: Comparable<Int> = TODO()</warning> var bar: List<Int> = TODO() """.trimIndent()) } fun testVarStringAssign() { doTest(pattern = "var '_ = \"Hello world\"", highlighting = """ <warning descr="SSR">var a = "Hello world"</warning> <warning descr="SSR">var b = ("Hello world")</warning> <warning descr="SSR">var c = (("Hello world"))</warning> """.trimIndent()) } fun testVarStringAssignPar() { doTest(pattern = "var '_ = (\"Hello world\")", highlighting = """ var a = "Hello world" <warning descr="SSR">var b = ("Hello world")</warning> var c = (("Hello world")) """.trimIndent()) } fun testVarRefAssign() { doTest(pattern = "var '_ = a", highlighting = """ val a = "Hello World" <warning descr="SSR">var b = a</warning> <warning descr="SSR">var c = (a)</warning> <warning descr="SSR">var d = ((a))</warning> """.trimIndent()) } fun testVarNoInitializer() { doTest(pattern = "var '_ = '_{0,0}", highlighting = """ class MyClass() abstract class MyAbstractClass { var a = MyClass() <warning descr="SSR">abstract var b: MyClass</warning> <warning descr="SSR">lateinit var c: MyAbstractClass</warning> } """.trimIndent()) } fun testVarGetterModifier() { doTest(pattern = """ var '_Field = '_ @'_Ann get() = '_ """.trimIndent(), highlighting = """ annotation class MyAnn <warning descr="SSR">var tlProp: Int = 1 @MyAnn get() { return field * 3 }</warning> class A { <warning descr="SSR">var myProp: Int = 1 @MyAnn get() = field * 3</warning> var myPropTwo = 2 get() = field * 2 } """.trimIndent(), KotlinStructuralSearchProfile.PROPERTY_CONTEXT) } fun testVarSetterModifier() { doTest(pattern = """ var '_Field = '_ private set('_x) { '_* } """.trimIndent(), highlighting = """ class A { <warning descr="SSR">var myProp: Int = 1 private set(value) { field = value * 3 }</warning> var myPropTwo = 2 set(value) { field = value * 3 } } """.trimIndent(), KotlinStructuralSearchProfile.PROPERTY_CONTEXT) } fun testFunctionType() { doTest(pattern = "val '_ : ('_{2,2}) -> Unit", highlighting = """ class MyClass { <warning descr="SSR">val fooThree: (Int, String) -> Unit = { i: Int, s: String -> }</warning> val fooTwo: (String) -> Unit = {} val fooOne: () -> Unit = {} } """.trimIndent()) } fun testFunctionTypeNamedParameter() { doTest(pattern = "val '_ : ('_) -> '_", highlighting = """ class MyClass { <warning descr="SSR">val funTwo: (s: String) -> Unit = {}</warning> <warning descr="SSR">val funOne: (String) -> Unit = {}</warning> } """.trimIndent()) } fun testReturnTypeReference() { doTest(pattern = "val '_ : ('_) -> Unit", highlighting = """ class MyClass { val funOne: (String) -> String = { it } <warning descr="SSR">val funTwo: (String) -> Unit = { print(it) }</warning> } """.trimIndent()) } fun testNullableFunctionType() { doTest(pattern = "val '_ : '_ ?", highlighting = """ class ClassOne { <warning descr="SSR">val valOne: (() -> Unit)? = {}</warning> <warning descr="SSR">val valTwo: ClassOne? = null</warning> } """.trimIndent()) } fun testReceiverTypeReference() { doTest(pattern = "val Int.'_ : '_", highlighting = """ val String.foo: Int get() = 1 <warning descr="SSR">val Int.foo: Int get() = 1</warning> """.trimIndent()) } fun testReceiverFqTypeReference() { doTest(pattern = "val kotlin.Int.'_ : '_", highlighting = """ val String.foo: Int get() = 1 val Int.foo: Int get() = 1 <warning descr="SSR">val kotlin.Int.bar: Int get() = 1</warning> class A { class Int val Int.foo: kotlin.Int get() = 1 } """.trimIndent()) } fun testAlsoMatchValModifier() { doTest(pattern = "var '_:[_${AlsoMatchValModifier.CONSTRAINT_NAME}(${OneStateFilter.ENABLED})]", """ fun main() { <warning descr="SSR">var x = 1</warning> <warning descr="SSR">val y = 1</warning> print(x + y) } """.trimIndent()) } fun testAlsoMatchVarModifier() { doTest(pattern = "val '_:[_${AlsoMatchVarModifier.CONSTRAINT_NAME}(${OneStateFilter.ENABLED})]", """ fun main() { <warning descr="SSR">var x = 1</warning> <warning descr="SSR">val y = 1</warning> print(x + y) } """.trimIndent()) } }
apache-2.0
GunoH/intellij-community
java/idea-ui/src/com/intellij/ide/starters/shared/ui/LibrariesSearchTextField.kt
3
2501
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.starters.shared.ui import com.intellij.ide.starters.JavaStartersBundle import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonShortcuts import com.intellij.ui.JBColor import com.intellij.ui.SearchTextField import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBUI import org.jetbrains.annotations.ApiStatus import java.awt.Dimension import java.awt.event.KeyEvent import javax.swing.JComponent @ApiStatus.Internal class LibrariesSearchTextField : SearchTextField() { var list: JComponent? = null init { textEditor.putClientProperty("JTextField.Search.Gap", JBUIScale.scale(6)) textEditor.putClientProperty("JTextField.Search.GapEmptyText", JBUIScale.scale(-1)) textEditor.border = JBUI.Borders.empty() textEditor.emptyText.text = JavaStartersBundle.message("hint.library.search") border = JBUI.Borders.customLine(JBColor.border(), 1, 1, 0, 1) } override fun preprocessEventForTextField(event: KeyEvent): Boolean { val keyCode: Int = event.keyCode val id: Int = event.id if ((keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_ENTER) && id == KeyEvent.KEY_PRESSED && handleListEvents(event)) { return true } return super.preprocessEventForTextField(event) } private fun handleListEvents(event: KeyEvent): Boolean { val selectionTracker = list if (selectionTracker != null) { selectionTracker.dispatchEvent(event) return true } return false } override fun getPreferredSize(): Dimension { val size = super.getPreferredSize() size.height = JBUIScale.scale(30) return size } override fun toClearTextOnEscape(): Boolean { object : AnAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabled = text.isNotEmpty() } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun actionPerformed(e: AnActionEvent) { text = "" } init { isEnabledInModalContext = true } }.registerCustomShortcutSet(CommonShortcuts.ESCAPE, this) return false } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/editor/enterHandler/SmartEnterWithTabsOnConstructorParametersWithInvertedAlignWhenMultiline.after.kt
7
125
// SET_TRUE: SMART_TABS // SET_TRUE: USE_TAB_CHARACTER // SET_TRUE: ALIGN_MULTILINE_PARAMETERS class A( a: Int, <caret> )
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/filter/filterIndexed_merge4.kt
9
393
// WITH_STDLIB // INTENTION_TEXT: "Replace with 'filterIndexed{}.firstOrNull()'" // INTENTION_TEXT_2: "Replace with 'asSequence().filterIndexed{}.firstOrNull()'" fun foo(list: List<String>): String? { var index2 = 0 <caret>for ((index1, s) in list.withIndex()) { if (s.length > index1) continue if (s.length < index2++) continue return s } return null }
apache-2.0
GunoH/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaULambdaExpression.kt
7
3051
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.psi.* import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* @ApiStatus.Internal class JavaULambdaExpression( override val sourcePsi: PsiLambdaExpression, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), ULambdaExpression { override val functionalInterfaceType: PsiType? get() = sourcePsi.functionalInterfaceType override val valueParameters: List<UParameter> by lz { sourcePsi.parameterList.parameters.map { JavaUParameter(it, this) } } override val body: UExpression by lz { when (val b = sourcePsi.body) { is PsiCodeBlock -> JavaConverter.convertBlock(b, this) is PsiExpression -> wrapLambdaBody(this, b) else -> UastEmptyExpression(this) } } } private fun wrapLambdaBody(parent: JavaULambdaExpression, b: PsiExpression): UBlockExpression = JavaImplicitUBlockExpression(parent).apply { expressions = listOf(JavaImplicitUReturnExpression(this).apply { returnExpression = JavaConverter.convertOrEmpty(b, this) }) } private class JavaImplicitUReturnExpression(givenParent: UElement?) : JavaAbstractUExpression(givenParent), UReturnExpression { override val label: String? get() = null override val jumpTarget: UElement? = getParentOfType(ULambdaExpression::class.java, strict = true) override val sourcePsi: PsiElement? get() = null override val psi: PsiElement? get() = null override lateinit var returnExpression: UExpression internal set override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as JavaImplicitUReturnExpression val b = returnExpression != other.returnExpression if (b) return false return true } override fun hashCode(): Int = 31 + returnExpression.hashCode() } private class JavaImplicitUBlockExpression(givenParent: UElement?) : JavaAbstractUExpression(givenParent), UBlockExpression { override val sourcePsi: PsiElement? get() = null override lateinit var expressions: List<UExpression> internal set override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as JavaImplicitUBlockExpression if (expressions != other.expressions) return false return true } override fun hashCode(): Int = 31 + expressions.hashCode() }
apache-2.0
GunoH/intellij-community
plugins/ide-features-trainer/src/training/featuresSuggester/suggesters/ReplaceCompletionSuggester.kt
2
5180
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package training.featuresSuggester.suggesters import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.refactoring.suggested.startOffset import training.featuresSuggester.* import training.featuresSuggester.actions.* class ReplaceCompletionSuggester : AbstractFeatureSuggester() { override val id: String = "Completion with replace" override val suggestingActionDisplayName: String = FeatureSuggesterBundle.message("replace.completion.name") override val message = FeatureSuggesterBundle.message("replace.completion.message") override val suggestingActionId = "EditorChooseLookupItemReplace" override val suggestingDocUrl = "https://www.jetbrains.com/help/idea/auto-completing-code.html#accept" override val minSuggestingIntervalDays = 14 override val languages = listOf("JAVA", "kotlin", "Python", "JavaScript", "ECMAScript 6") private data class EditedStatementData(val dotOffset: Int) { var isCompletionStarted: Boolean = false var textToDelete: String = "" var deletedText: String = "" var addedExprEndOffset: Int = -1 val isCompletionFinished: Boolean get() = textToDelete != "" fun isAroundDot(offset: Int): Boolean { return offset in dotOffset..(dotOffset + 7) } fun isIdentifierNameDeleted(caretOffset: Int, newDeletedText: String): Boolean { return isCaretInRangeOfExprToDelete(caretOffset, newDeletedText) && (deletedText.contains(textToDelete) || deletedText.contains(textToDelete.reversed())) } private fun isCaretInRangeOfExprToDelete(caretOffset: Int, newDeletedText: String): Boolean { return caretOffset in (addedExprEndOffset - 2)..(addedExprEndOffset + newDeletedText.length) } fun isDeletedTooMuch(): Boolean { return deletedText.length >= textToDelete.length * 2 } } private var editedStatementData: EditedStatementData? = null override fun getSuggestion(action: Action): Suggestion { val language = action.language ?: return NoSuggestion val langSupport = SuggesterSupport.getForLanguage(language) ?: return NoSuggestion when (action) { is BeforeEditorTextRemovedAction -> { if (action.textFragment.text == ".") { editedStatementData = langSupport.createEditedStatementData(action, action.caretOffset) } } is BeforeEditorTextInsertedAction -> { if (editedStatementData != null && action.text == "." && action.caretOffset == editedStatementData!!.dotOffset ) { editedStatementData!!.isCompletionStarted = true } } is EditorCodeCompletionAction -> { val caretOffset = action.caretOffset if (caretOffset == 0) return NoSuggestion if (action.document.getText(TextRange(caretOffset - 1, caretOffset)) == ".") { editedStatementData = langSupport.createEditedStatementData(action, action.caretOffset)?.apply { isCompletionStarted = true } } } is BeforeCompletionChooseItemAction -> { if (editedStatementData == null || editedStatementData?.isAroundDot(action.caretOffset) != true) { return NoSuggestion } val curElement = action.psiFile?.findElementAt(action.caretOffset) ?: return NoSuggestion if (langSupport.isIdentifier(curElement)) { // remove characters that user typed before completion editedStatementData!!.textToDelete = curElement.text.substring(action.caretOffset - curElement.startOffset) } } is CompletionChooseItemAction -> { editedStatementData?.addedExprEndOffset = action.caretOffset } is EditorTextInsertedAction -> { if (editedStatementData?.isCompletionFinished != true) return NoSuggestion if (action.caretOffset < editedStatementData!!.addedExprEndOffset) { editedStatementData!!.addedExprEndOffset += action.text.length } } is EditorTextRemovedAction -> { if (editedStatementData?.isCompletionFinished != true) return NoSuggestion editedStatementData!!.deletedText += action.textFragment.text if (editedStatementData!!.isDeletedTooMuch()) { editedStatementData = null } else if (editedStatementData!!.isIdentifierNameDeleted( action.caretOffset, action.textFragment.text ) ) { editedStatementData = null return createSuggestion() } } is EditorEscapeAction -> { editedStatementData = null } } return NoSuggestion } private fun SuggesterSupport.createEditedStatementData(action: EditorAction, offset: Int): EditedStatementData? { val curElement = action.psiFile?.findElementAt(offset) ?: return null return if (curElement.getParentByPredicate(::isLiteralExpression) == null && curElement.getParentOfType<PsiComment>() == null ) { EditedStatementData(offset) } else { null } } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/members/javaMethodSyntheticIsSet/KotlinUsageSynthetic.kt
9
58
fun kotlinUsageSynthetic() { Kotlin().isSmth = false }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/intentions/declarations/convertMemberToExtension/valWithGetter.kt
13
53
class Owner { val <caret>p: Int get() = 1 }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/typeAddition/propertyWithSetterWithoutType.kt
5
161
// "Specify type explicitly" "true" class My { var yy = 0 var <caret>y get() = yy set(arg: Int) { yy = arg + 1 } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/rename/labeledLambdaByLabel/before/test.kt
13
89
fun <R> foo(f: () -> R) = f() fun test() { foo /*rename*/bar@ { return@bar false } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/map/mapVar.kt
9
298
// WITH_STDLIB // INTENTION_TEXT: "Replace with 'map{}.firstOrNull{}'" // INTENTION_TEXT_2: "Replace with 'asSequence().map{}.firstOrNull{}'" fun foo(list: List<String>): Int? { <caret>for (s in list) { var length = s.length if (length > 0) return length } return null }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/rename/renameKotlinValPropertyInCompanionObject/before/RenameKotlinValPropertyInCompanionObject.kt
13
91
package testing.rename class Foo { companion object { val FIRST = 111 } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/nameConflict.kt
12
105
fun onc<caret>e(p: Int): Int { val v = p + 1 return v } fun callShadow() { val v = once(1) }
apache-2.0
smmribeiro/intellij-community
plugins/devkit/devkit-core/src/inspections/missingApi/MissingRecentApiInspection.kt
10
5895
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.devkit.inspections.missingApi import com.intellij.codeInspection.InspectionProfileEntry import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.apiUsage.ApiUsageUastVisitor import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.roots.TestSourcesFilter import com.intellij.openapi.util.BuildNumber import com.intellij.psi.PsiElementVisitor import com.intellij.psi.xml.XmlFile import com.intellij.ui.components.JBLabel import com.intellij.util.ui.FormBuilder import org.jetbrains.idea.devkit.DevKitBundle import org.jetbrains.idea.devkit.actions.DevkitActionsUtil import org.jetbrains.idea.devkit.module.PluginModuleType import org.jetbrains.idea.devkit.util.DescriptorUtil import org.jetbrains.idea.devkit.util.PsiUtil import java.awt.BorderLayout import javax.swing.JComponent import javax.swing.JPanel /** * Inspection that warns plugin authors if they use IntelliJ Platform's APIs that aren't available * in some IDE versions specified as compatible with the plugin via the "since-until" constraints. * * Suppose a plugin specifies `183.1; 181.9` as compatibility range, but some IntelliJ Platform's API * in use appeared only in `183.5`. Then the plugin won't work in `[181.1, 181.5)` * and this inspection's goal is to prevent it. * * *Implementation details*. * Info on when APIs were first introduced is obtained from "available since" artifacts. * They are are built on the build server for each IDE build and uploaded to * [IntelliJ artifacts repository](https://www.jetbrains.com/intellij-repository/releases/), * containing external annotations [org.jetbrains.annotations.ApiStatus.AvailableSince] * where APIs' introduction versions are specified. */ class MissingRecentApiInspection : LocalInspectionTool() { companion object { val INSPECTION_SHORT_NAME = InspectionProfileEntry.getShortName(MissingRecentApiInspection::class.java.simpleName) } /** * Actual "since" build constraint of the plugin under development. * * Along with [untilBuildString] it may be set manually if values in plugin.xml * differ from the actual values. For example, it is the case for gradle-intellij-plugin, * which allows to override "since" and "until" values during plugin build. */ var sinceBuildString: String? = null /** * Actual "until" build constraint of the plugin under development. */ var untilBuildString: String? = null private val sinceBuild: BuildNumber? get() = sinceBuildString?.let { BuildNumber.fromStringOrNull(it) } private val untilBuild: BuildNumber? get() = untilBuildString?.let { BuildNumber.fromStringOrNull(it) } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { val project = holder.project val virtualFile = holder.file.virtualFile if (PsiUtil.isIdeaProject(project) || virtualFile != null && TestSourcesFilter.isTestSources(virtualFile, project)) { return PsiElementVisitor.EMPTY_VISITOR } val module = ModuleUtil.findModuleForPsiElement(holder.file) ?: return PsiElementVisitor.EMPTY_VISITOR val targetedSinceUntilRanges = getTargetedSinceUntilRanges(module) if (targetedSinceUntilRanges.isEmpty()) { return PsiElementVisitor.EMPTY_VISITOR } return ApiUsageUastVisitor.createPsiElementVisitor( MissingRecentApiUsageProcessor(holder, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, targetedSinceUntilRanges) ) } override fun createOptionsPanel(): JComponent { val emptyBuildNumber = BuildNumber.fromString("1.0")!! val sinceField = BuildNumberField("since", emptyBuildNumber) sinceBuild?.also { sinceField.value = it } sinceField.emptyText.text = DevKitBundle.message("inspections.missing.recent.api.settings.since.empty.text") sinceField.valueEditor.addListener { value -> sinceBuildString = value.takeIf { it != emptyBuildNumber }?.asString() } val untilField = BuildNumberField("until", untilBuild ?: emptyBuildNumber) untilField.emptyText.text = DevKitBundle.message("inspections.missing.recent.api.settings.until.empty.text") untilBuild?.also { untilField.value = it } untilField.valueEditor.addListener { value -> untilBuildString = value.takeIf { it != emptyBuildNumber }?.asString() } val formBuilder = FormBuilder.createFormBuilder() .addComponent(JBLabel(DevKitBundle.message("inspections.missing.recent.api.settings.range"))) .addLabeledComponent(DevKitBundle.message("inspections.missing.recent.api.settings.since"), sinceField) .addLabeledComponent(DevKitBundle.message("inspections.missing.recent.api.settings.until"), untilField) val container = JPanel(BorderLayout()) container.add(formBuilder.panel, BorderLayout.NORTH) return container } private fun getTargetedSinceUntilRanges(module: Module): List<SinceUntilRange> { if (sinceBuild == null && untilBuild == null) { return DevkitActionsUtil.getCandidatePluginModules(module) .mapNotNull { PluginModuleType.getPluginXml(it) } .mapNotNull { getSinceUntilRange(it) } .filterNot { it.sinceBuild == null } } return listOf(SinceUntilRange(sinceBuild, untilBuild)) } private fun getSinceUntilRange(pluginXml: XmlFile): SinceUntilRange? { val ideaPlugin = DescriptorUtil.getIdeaPlugin(pluginXml) ?: return null val ideaVersion = ideaPlugin.ideaVersion val sinceBuild = ideaVersion.sinceBuild.value val untilBuild = ideaVersion.untilBuild.value return SinceUntilRange(sinceBuild, untilBuild) } }
apache-2.0
mjdev/libaums
libaums/src/main/java/me/jahnen/libaums/core/ErrNo.kt
2
782
package me.jahnen.libaums.core import android.util.Log /** * Created by magnusja on 5/19/17. */ object ErrNo { private val TAG = "ErrNo" private var isInited = true val errno: Int get() = if (isInited) { errnoNative } else { 1337 } val errstr: String get() = if (isInited) { errstrNative } else { "errno-lib could not be loaded!" } private val errnoNative: Int external get private val errstrNative: String external get init { try { System.loadLibrary("errno-lib") } catch (e: UnsatisfiedLinkError) { isInited = false Log.e(TAG, "could not load errno-lib", e) } } }
apache-2.0
trubitsyn/VisibleForTesting
src/test/resources/AnnotateKtClassOrObjectMethodsIntention/guava/before.template.kt
1
239
import com.google.common.annotations.VisibleForTesting class F<caret>oo { @VisibleForTesting private fun annotatedFoo() {} fun publicFoo() {} protected fun foo() {} internal fun bar() {} private fun baz() {} }
apache-2.0
MartinStyk/AndroidApkAnalyzer
app/src/main/java/sk/styk/martin/apkanalyzer/ui/permission/detail/pager/PermissionDetailFragmentViewModel.kt
1
2437
package sk.styk.martin.apkanalyzer.ui.permission.detail.pager import android.content.pm.PackageManager import android.view.MenuItem import androidx.appcompat.widget.Toolbar import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import sk.styk.martin.apkanalyzer.R import sk.styk.martin.apkanalyzer.model.permissions.LocalPermissionData import sk.styk.martin.apkanalyzer.util.TAG_APP_ANALYSIS import sk.styk.martin.apkanalyzer.util.TextInfo import sk.styk.martin.apkanalyzer.util.components.DialogComponent import sk.styk.martin.apkanalyzer.util.live.SingleLiveEvent import timber.log.Timber class PermissionDetailFragmentViewModel @AssistedInject constructor( @Assisted val localPermissionData: LocalPermissionData, private val packageManager: PackageManager, ) : ViewModel(), Toolbar.OnMenuItemClickListener { val title = localPermissionData.permissionData.simpleName private val showDialogEvent = SingleLiveEvent<DialogComponent>() val showDialog: LiveData<DialogComponent> = showDialogEvent private val closeEvent = SingleLiveEvent<Unit>() val close: LiveData<Unit> = closeEvent fun onNavigationClick() = closeEvent.call() override fun onMenuItemClick(item: MenuItem): Boolean { when (item.itemId) { R.id.description -> showDescriptionDialog() } return true } private fun showDescriptionDialog() { val description = try { packageManager.getPermissionInfo(localPermissionData.permissionData.name, PackageManager.GET_META_DATA).loadDescription(packageManager) } catch (e: PackageManager.NameNotFoundException) { Timber.tag(TAG_APP_ANALYSIS).i("No description for permission ${localPermissionData.permissionData.name}") null }?.takeIf { it.isNotBlank() } ?.let { TextInfo.from(it) } ?: TextInfo.from(R.string.NA) showDialogEvent.value = DialogComponent( title = TextInfo.from(localPermissionData.permissionData.simpleName), message = description, negativeButtonText = TextInfo.from(R.string.dismiss) ) } @AssistedFactory interface Factory { fun create(localPermissionData: LocalPermissionData): PermissionDetailFragmentViewModel } }
gpl-3.0
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/domains/variables/TemporaryVariableRepository.kt
1
4393
package ch.rmy.android.http_shortcuts.data.domains.variables import ch.rmy.android.framework.data.BaseRepository import ch.rmy.android.framework.data.RealmFactory import ch.rmy.android.framework.data.RealmTransactionContext import ch.rmy.android.framework.extensions.swap import ch.rmy.android.http_shortcuts.data.domains.getTemporaryVariable import ch.rmy.android.http_shortcuts.data.enums.VariableType import ch.rmy.android.http_shortcuts.data.models.OptionModel import ch.rmy.android.http_shortcuts.data.models.VariableModel import io.realm.RealmList import io.realm.kotlin.deleteFromRealm import kotlinx.coroutines.flow.Flow import javax.inject.Inject class TemporaryVariableRepository @Inject constructor( realmFactory: RealmFactory, ) : BaseRepository(realmFactory) { fun getObservableTemporaryVariable(): Flow<VariableModel> = observeItem { getTemporaryVariable() } suspend fun createNewTemporaryVariable(type: VariableType) { commitTransaction { copyOrUpdate( VariableModel( id = VariableModel.TEMPORARY_ID, variableType = type, ) ) } } suspend fun setKey(key: String) { commitTransactionForVariable { variable -> variable.key = key } } suspend fun setTitle(title: String) { commitTransactionForVariable { variable -> variable.title = title } } suspend fun setMessage(message: String) { commitTransactionForVariable { variable -> variable.message = message } } suspend fun setUrlEncode(enabled: Boolean) { commitTransactionForVariable { variable -> variable.urlEncode = enabled } } suspend fun setJsonEncode(enabled: Boolean) { commitTransactionForVariable { variable -> variable.jsonEncode = enabled } } suspend fun setSharingSupport(shareText: Boolean, shareTitle: Boolean) { commitTransactionForVariable { variable -> variable.isShareText = shareText variable.isShareTitle = shareTitle } } suspend fun setRememberValue(enabled: Boolean) { commitTransactionForVariable { variable -> variable.rememberValue = enabled } } suspend fun setMultiline(enabled: Boolean) { commitTransactionForVariable { variable -> variable.isMultiline = enabled } } suspend fun setValue(value: String) { commitTransactionForVariable { variable -> variable.value = value } } suspend fun setDataForType(data: Map<String, String?>) { commitTransactionForVariable { variable -> variable.dataForType = data } } private suspend fun commitTransactionForVariable(transaction: RealmTransactionContext.(VariableModel) -> Unit) { commitTransaction { transaction( getTemporaryVariable() .findFirst() ?: return@commitTransaction ) } } suspend fun moveOption(optionId1: String, optionId2: String) { commitTransactionForVariable { variable -> variable.options?.swap(optionId1, optionId2) { id } } } suspend fun addOption(label: String, value: String) { commitTransactionForVariable { variable -> if (variable.options == null) { variable.options = RealmList() } variable.options!!.add( copy( OptionModel( label = label, value = value, ) ) ) } } suspend fun updateOption(optionId: String, label: String, value: String) { commitTransactionForVariable { variable -> val option = variable.options ?.find { it.id == optionId } ?: return@commitTransactionForVariable option.label = label option.value = value } } suspend fun removeOption(optionId: String) { commitTransactionForVariable { variable -> variable.options ?.find { it.id == optionId } ?.deleteFromRealm() } } }
mit
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/ToHexStringAction.kt
1
362
package ch.rmy.android.http_shortcuts.scripting.actions.types import ch.rmy.android.framework.extensions.toHexString import ch.rmy.android.http_shortcuts.scripting.ExecutionContext class ToHexStringAction(private val data: ByteArray) : BaseAction() { override suspend fun execute(executionContext: ExecutionContext): String = data.toHexString() }
mit
sksamuel/ktest
kotest-assertions/kotest-assertions-shared/src/commonMain/kotlin/io/kotest/assertions/timing/continually.kt
1
2261
package io.kotest.assertions.timing import io.kotest.assertions.SuspendingProducer import io.kotest.assertions.failure import io.kotest.assertions.until.Interval import io.kotest.assertions.until.fixed import kotlinx.coroutines.delay import kotlin.time.Duration import kotlin.time.TimeMark import kotlin.time.TimeSource data class ContinuallyState(val start: TimeMark, val end: TimeMark, val times: Int) fun interface ContinuallyListener<in T> { fun onEval(t: T, state: ContinuallyState) companion object { val noop = ContinuallyListener<Any?> { _, _ -> } } } data class Continually<T> ( val duration: Duration = Duration.INFINITE, val interval: Interval = Duration.milliseconds(25).fixed(), val listener: ContinuallyListener<T> = ContinuallyListener.noop, ) { suspend operator fun invoke(f: SuspendingProducer<T>): T? { val start = TimeSource.Monotonic.markNow() val end = start.plus(duration) var times = 0 var result: T? = null while (end.hasNotPassedNow()) { try { result = f() listener.onEval(result, ContinuallyState(start, end, times)) } catch (e: AssertionError) { // if this is the first time the check was executed then just rethrow the underlying error if (times == 0) throw e // if not the first attempt then include how many times/for how long the test passed throw failure( "Test failed after ${start.elapsedNow()}; expected to pass for ${duration.inWholeMilliseconds}ms; attempted $times times\nUnderlying failure was: ${e.message}", e ) } times++ delay(interval.next(times)) } return result } } @Deprecated("Use continually with an interval, using Duration based poll is deprecated", ReplaceWith("continually(duration, poll.fixed(), f = f)", "io.kotest.assertions.until.fixed") ) suspend fun <T> continually(duration: Duration, poll: Duration, f: suspend () -> T) = continually(duration, poll.fixed(), f = f) suspend fun <T> continually(duration: Duration, interval: Interval = Duration.milliseconds(10).fixed(), f: suspend () -> T) = Continually<T>(duration, interval).invoke(f)
mit
getsentry/raven-java
sentry/src/test/java/io/sentry/NoOpSpanTest.kt
1
518
package io.sentry import kotlin.test.Test import kotlin.test.assertNotNull class NoOpSpanTest { private val span = NoOpSpan.getInstance() @Test fun `startChild does not return null`() { assertNotNull(span.startChild("op")) assertNotNull(span.startChild("op", "desc")) } @Test fun `getSpanContext does not return null`() { assertNotNull(span.spanContext) } @Test fun `getOperation does not return null`() { assertNotNull(span.operation) } }
bsd-3-clause
kirimin/mitsumine
app/src/main/java/me/kirimin/mitsumine/top/TopPresenter.kt
1
4428
package me.kirimin.mitsumine.top import android.view.View import me.kirimin.mitsumine.R import me.kirimin.mitsumine._common.domain.enums.Category import me.kirimin.mitsumine._common.domain.enums.Type class TopPresenter(private val useCase: TopUseCase) { lateinit var view: TopView set var selectedType = Type.HOT private set var selectedCategory = Category.MAIN private set fun getTypeInt(type: Type) = if (type == Type.HOT) 0 else 1 fun onCreate(view: TopView, category: Category = Category.MAIN, type: Type = Type.HOT) { this.view = view selectedCategory = category selectedType = type view.initViews() view.addNavigationCategoryButton(Category.MAIN) view.addNavigationCategoryButton(Category.SOCIAL) view.addNavigationCategoryButton(Category.ECONOMICS) view.addNavigationCategoryButton(Category.LIFE) view.addNavigationCategoryButton(Category.KNOWLEDGE) view.addNavigationCategoryButton(Category.IT) view.addNavigationCategoryButton(Category.FUN) view.addNavigationCategoryButton(Category.ENTERTAINMENT) view.addNavigationCategoryButton(Category.GAME) // 古い既読を削除 useCase.deleteOldFeedData(3) view.refreshShowCategoryAndType(selectedCategory, selectedType) } fun onStart() { view.removeNavigationAdditions() useCase.additionKeywords.forEach { keyword -> view.addAdditionKeyword(keyword) } useCase.additionUsers.forEach { userId -> view.addAdditionUser(userId) } val account = useCase.account if (account != null) { view.enableUserInfo(account.displayName, account.imageUrl) } else { view.disableUserInfo() } } fun onDestroy() { } fun onNavigationClick(position: Int): Boolean { selectedType = if (position == 0) Type.HOT else Type.NEW view.closeNavigation() view.refreshShowCategoryAndType(selectedCategory, selectedType) return true } fun onToolbarClick() { if (view.isOpenNavigation()) { view.closeNavigation() } else { view.openNavigation() } } fun onBackKeyClick() { if (view.isOpenNavigation()) { view.closeNavigation() } else { view.backPress() } } fun onNavigationItemClick(id: Int) { when (id) { R.id.navigationReadTextView -> { view.startReadActivity() view.closeNavigation() } R.id.navigationSettingsTextView -> { view.startSettingActivity() view.closeNavigation() } R.id.navigationKeywordSearchTextView -> { view.startKeywordSearchActivity() view.closeNavigation() } R.id.navigationUserSearchTextView -> { view.startUserSearchActivity() view.closeNavigation() } R.id.navigationMyBookmarksButton -> { view.startMyBookmarksActivity() view.closeNavigation() } R.id.navigationLoginButton -> { view.startLoginActivity() view.closeNavigation() } } } fun onCategoryClick(category: Category) { view.closeNavigation() view.refreshShowCategoryAndType(category, selectedType) selectedCategory = category } fun onAdditionUserClick(userId: String) { view.closeNavigation() view.startUserSearchActivity(userId) } fun onAdditionUserLongClick(userId: String, target: View): Boolean { view.showDeleteUserDialog(userId, target) return false } fun onAdditionKeywordClick(keyword: String) { view.closeNavigation() view.startKeywordSearchActivity(keyword) } fun onAdditionKeywordLongClick(keyword: String, target: View): Boolean { view.showDeleteKeywordDialog(keyword, target) return false } fun onDeleteUserIdDialogClick(word: String, target: View) { useCase.deleteAdditionUser(word) target.visibility = View.GONE } fun onDeleteKeywordDialogClick(word: String, target: View) { useCase.deleteAdditionKeyword(word) target.visibility = View.GONE } }
apache-2.0
nebula-plugins/nebula-bintray-plugin
src/main/kotlin/nebula/plugin/bintray/NebulaBintrayAbstractTask.kt
1
2440
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nebula.plugin.bintray import org.gradle.api.DefaultTask import org.gradle.api.GradleException import org.gradle.api.provider.Property import org.gradle.api.provider.Provider import org.gradle.api.tasks.Input import org.gradle.api.tasks.Internal import org.gradle.api.tasks.Optional import org.gradle.kotlin.dsl.property open class NebulaBintrayAbstractTask : DefaultTask() { protected companion object { const val UNSET = "UNSET" } @Input val user: Property<String> = project.objects.property() @Input val apiKey: Property<String> = project.objects.property() @Input val apiUrl: Property<String> = project.objects.property() @Input val pkgName: Property<String> = project.objects.property() @Input val repo: Property<String> = project.objects.property() @Input @Optional val userOrg: Property<String> = project.objects.property() @Input @Optional val version: Property<String> = project.objects.property() @Internal val readTimeoutInSeconds: Property<Long> = project.objects.property() @Internal val connectionTimeoutInSeconds: Property<Long> = project.objects.property() @Internal val resolveSubject : Provider<String> = user.map { val resolvedSubject = userOrg.getOrElse(user.get()) if (resolvedSubject.isNotSet()) { throw GradleException("userOrg or bintray.user must be set") } resolvedSubject } @Internal val resolveVersion : Provider<String> = version.map { val resolvedVersion = version.getOrElse(UNSET) if (resolvedVersion == "unspecified" || resolvedVersion.isNotSet()) { throw GradleException("version or project.version must be set") } resolvedVersion } private fun String.isNotSet() = this == UNSET }
apache-2.0
justin-hayes/kotlin-boot-react
backend/src/main/kotlin/me/justinhayes/bookclub/KotlinBootReactApplication.kt
1
321
package me.justinhayes.bookclub import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication open class KotlinBootReactApplication fun main(args: Array<String>) { SpringApplication.run(KotlinBootReactApplication::class.java, *args) }
mit
Adven27/Exam
example/src/test/kotlin/specs/gettingstarted/GettingStarted.kt
1
255
package specs.gettingstarted import io.restassured.RestAssured.get import org.concordion.api.FullOGNL import specs.Specs @FullOGNL class GettingStarted : Specs() { fun isDone(id: String) = !get("/jobs/$id").body().jsonPath().getBoolean("running") }
mit
dcz-switcher/niortbus
app/src/main/java/com/niortreactnative/adapters/Stop.kt
1
147
package com.niortreactnative.adapters /** * Created by davidc on 05/10/2017. */ class Stop constructor(val name:String, val hours:Array<String>)
mit
Wackalooon/EcoMeter
app/src/main/java/com/wackalooon/ecometer/home/model/HomeEvent.kt
1
203
package com.wackalooon.ecometer.home.model import com.wackalooon.ecometer.base.Event sealed class HomeEvent : Event { object HomeItemClick : HomeEvent() object LoadMeterDetails : HomeEvent() }
apache-2.0
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/problem/rest/RestCallResult.kt
1
2074
package org.evomaster.core.problem.rest import com.google.common.annotations.VisibleForTesting import com.google.gson.Gson import com.google.gson.JsonObject import org.evomaster.core.problem.httpws.service.HttpWsCallResult import org.evomaster.core.search.Action import org.evomaster.core.search.ActionResult import javax.ws.rs.core.MediaType class RestCallResult : HttpWsCallResult { constructor(stopping: Boolean = false) : super(stopping) @VisibleForTesting internal constructor(other: ActionResult) : super(other) companion object { const val HEURISTICS_FOR_CHAINED_LOCATION = "HEURISTICS_FOR_CHAINED_LOCATION" } override fun copy(): ActionResult { return RestCallResult(this) } fun getResourceIdName() = "id" fun getResourceId(): String? { if(!MediaType.APPLICATION_JSON_TYPE.isCompatible(getBodyType())){ //TODO could also handle other media types return null } return getBody()?.let { try { /* TODO: "id" is the most common word, but could check if others are used as well. */ Gson().fromJson(it, JsonObject::class.java).get(getResourceIdName())?.asString } catch (e: Exception){ //nothing to do null } } } /** * It might happen that we need to chain call location, but * there was no "location" header in the response of call that * created a new resource. However, it "might" still be possible * to try to infer the location (based on object response and * the other available endpoints in the API) */ fun setHeuristicsForChainedLocation(on: Boolean) = addResultValue(HEURISTICS_FOR_CHAINED_LOCATION, on.toString()) fun getHeuristicsForChainedLocation(): Boolean = getResultValue(HEURISTICS_FOR_CHAINED_LOCATION)?.toBoolean() ?: false override fun matchedType(action: Action): Boolean { return action is RestCallAction } }
lgpl-3.0
grote/BlitzMail
src/de/grobox/blitzmail/send/SendLaterWorker.kt
1
1352
package de.grobox.blitzmail.send import android.content.Context import android.content.Intent import androidx.core.content.ContextCompat.startForegroundService import androidx.work.* import androidx.work.ListenableWorker.Result.success import de.grobox.blitzmail.send.SendActivity.ACTION_RESEND import java.util.concurrent.TimeUnit class SendLaterWorker(context: Context, params: WorkerParameters) : Worker(context, params) { override fun doWork(): Result { val intent = Intent(applicationContext, SenderService::class.java) startForegroundService(applicationContext, intent) return success() } } fun scheduleSending(delayInMinutes: Long = 5) { val workManager = WorkManager.getInstance() val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() val worker = OneTimeWorkRequestBuilder<SendLaterWorker>() .setInitialDelay(delayInMinutes, TimeUnit.MINUTES) .setConstraints(constraints) .build() workManager.enqueue(worker) } fun sendQueuedMails(context: Context) { val intent = Intent(context, SendActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK) intent.action = ACTION_RESEND context.startActivity(intent) }
agpl-3.0
kpspemu/kpspemu
src/jvmMain/kotlin/com/soywiz/dynarek2/target/jvm/JvmGenerator.kt
1
12669
package com.soywiz.dynarek2.target.jvm import com.soywiz.dynarek2.* import org.objectweb.asm.* import org.objectweb.asm.Type import java.lang.reflect.* import kotlin.reflect.* class JvmGenerator { val objectRef = java.lang.Object::class.asmRef val d2MemoryRef = D2Memory::class.asmRef //val classLoader = this::class.javaClass.classLoader // 0: this // 1: regs // 2: mem // 3: temp // 4: external fun generate(func: D2Func, context: D2Context, name: String?, debug: Boolean): D2Result { val cw = ClassWriter(0) val className = "Dynarek2Generated" cw.visit( Opcodes.V1_5, Opcodes.ACC_PUBLIC or Opcodes.ACC_FINAL, className, null, java.lang.Object::class.internalName, arrayOf(D2KFuncInt::class.java.internalName) ) cw.apply { // constructor visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null).apply { visitMaxs(2, 1) visitVarInsn(Opcodes.ALOAD, 0) // push `this` to the operand stack visitMethodInsn( Opcodes.INVOKESPECIAL, java.lang.Object::class.internalName, "<init>", "()V", false ) // call the constructor of super class visitInsn(Opcodes.RETURN) visitEnd() } // invoke method visitMethod( Opcodes.ACC_PUBLIC, "invoke", "($d2MemoryRef$d2MemoryRef$d2MemoryRef$objectRef)I", null, null ).apply { visitMaxs(32, 32) generate(func.body) // DUMMY to make valid labels pushInt(0) visitIReturn() visitEnd() } } cw.visitEnd() val classBytes = cw.toByteArray() try { val gclazz = createDynamicClass<D2KFuncInt>( ClassLoader.getSystemClassLoader(), className.replace('/', '.'), classBytes ) val instance = gclazz.declaredConstructors.first().newInstance() as D2KFuncInt return D2Result(name, debug, classBytes, instance::invoke, free = { }) } catch (e: VerifyError) { throw D2InvalidCodeGen("JvmGenerator", classBytes, e) } } fun MethodVisitor.generate(s: D2Stm): Unit = when (s) { is D2Stm.Stms -> for (c in s.children) generate(c) is D2Stm.Expr -> { generate(s.expr) visitPop() } is D2Stm.Return -> { generate(s.expr) visitIReturn() } is D2Stm.Set<*> -> { val ref = s.ref visitIntInsn(Opcodes.ALOAD, ref.memSlot.jArgIndex) generate(ref.offset) generate(s.value) val methodName = when (ref.size) { D2Size.BYTE -> JvmMemTools::set8.name D2Size.SHORT -> JvmMemTools::set16.name D2Size.INT -> JvmMemTools::set32.name D2Size.FLOAT -> JvmMemTools::setF32.name D2Size.LONG -> JvmMemTools::set64.name } val primType = ref.size.jPrimType val signature = "(${d2MemoryRef}I$primType)V" //println("signature:$signature") visitMethodInsn( Opcodes.INVOKESTATIC, JvmMemTools::class.internalName, methodName, signature, false ) } is D2Stm.If -> { val cond = s.cond val strue = s.strue val sfalse = s.sfalse if (sfalse == null) { // IF val endLabel = Label() generateJumpFalse(cond, endLabel) generate(strue) visitLabel(endLabel) } else { // IF+ELSE val elseLabel = Label() val endLabel = Label() generateJumpFalse(cond, elseLabel) generate(strue) generateJumpAlways(endLabel) visitLabel(elseLabel) generate(sfalse) visitLabel(endLabel) } } is D2Stm.While -> { val startLabel = Label() val endLabel = Label() visitLabel(startLabel) generateJumpFalse(s.cond, endLabel) generate(s.body) generateJumpAlways(startLabel) visitLabel(endLabel) } else -> TODO("$s") } val D2Size.jPrimType get() = when (this) { D2Size.BYTE, D2Size.SHORT, D2Size.INT -> 'I' D2Size.FLOAT -> 'F' D2Size.LONG -> 'J' } fun MethodVisitor.generateJump(e: D2Expr<*>, label: Label, isTrue: Boolean): Unit { generate(e) visitJumpInsn(if (isTrue) Opcodes.IFNE else Opcodes.IFEQ, label) } fun MethodVisitor.generateJumpFalse(e: D2Expr<*>, label: Label): Unit = generateJump(e, label, false) fun MethodVisitor.generateJumpTrue(e: D2Expr<*>, label: Label): Unit = generateJump(e, label, true) fun MethodVisitor.generateJumpAlways(label: Label): Unit = visitJumpInsn(Opcodes.GOTO, label) val D2MemSlot.jArgIndex get() = this.index + 1 // 0 is used for THIS fun MethodVisitor.generate(e: D2Expr<*>): Unit { when (e) { is D2Expr.ILit -> pushInt(e.lit) is D2Expr.FLit -> pushFloat(e.lit) is D2Expr.LLit -> pushLong(e.lit) is D2Expr.IBinOp -> { generate(e.l) generate(e.r) when (e.op) { D2IBinOp.ADD -> visitInsn(Opcodes.IADD) D2IBinOp.SUB -> visitInsn(Opcodes.ISUB) D2IBinOp.MUL -> visitInsn(Opcodes.IMUL) D2IBinOp.DIV -> visitInsn(Opcodes.IDIV) D2IBinOp.REM -> visitInsn(Opcodes.IREM) D2IBinOp.SHL -> visitInsn(Opcodes.ISHL) D2IBinOp.SHR -> visitInsn(Opcodes.ISHR) D2IBinOp.USHR -> visitInsn(Opcodes.IUSHR) D2IBinOp.OR -> visitInsn(Opcodes.IOR) D2IBinOp.AND -> visitInsn(Opcodes.IAND) D2IBinOp.XOR -> visitInsn(Opcodes.IXOR) } } is D2Expr.LBinOp -> { generate(e.l) generate(e.r) when (e.op) { D2IBinOp.ADD -> visitInsn(Opcodes.LADD) D2IBinOp.SUB -> visitInsn(Opcodes.LSUB) D2IBinOp.MUL -> visitInsn(Opcodes.LMUL) D2IBinOp.DIV -> visitInsn(Opcodes.LDIV) D2IBinOp.REM -> visitInsn(Opcodes.LREM) D2IBinOp.SHL -> visitInsn(Opcodes.LSHL) D2IBinOp.SHR -> visitInsn(Opcodes.LSHR) D2IBinOp.USHR -> visitInsn(Opcodes.LUSHR) D2IBinOp.OR -> visitInsn(Opcodes.LOR) D2IBinOp.AND -> visitInsn(Opcodes.LAND) D2IBinOp.XOR -> visitInsn(Opcodes.LXOR) } } is D2Expr.FBinOp -> { generate(e.l) generate(e.r) when (e.op) { D2FBinOp.ADD -> visitInsn(Opcodes.FADD) D2FBinOp.SUB -> visitInsn(Opcodes.FSUB) D2FBinOp.MUL -> visitInsn(Opcodes.FMUL) D2FBinOp.DIV -> visitInsn(Opcodes.FDIV) //D2FBinOp.REM -> visitInsn(Opcodes.FREM) } } is D2Expr.IComOp -> { generate(e.l) generate(e.r) val opcode = when (e.op) { D2CompOp.EQ -> Opcodes.IF_ICMPEQ D2CompOp.NE -> Opcodes.IF_ICMPNE D2CompOp.LT -> Opcodes.IF_ICMPLT D2CompOp.LE -> Opcodes.IF_ICMPLE D2CompOp.GT -> Opcodes.IF_ICMPGT D2CompOp.GE -> Opcodes.IF_ICMPGE } val label1 = Label() val label2 = Label() visitJumpInsn(opcode, label1) pushBool(false) visitJumpInsn(Opcodes.GOTO, label2) visitLabel(label1) pushBool(true) visitLabel(label2) } is D2Expr.IUnop -> { generate(e.l) when (e.op) { D2UnOp.NEG -> visitInsn(Opcodes.INEG) D2UnOp.INV -> TODO() } } is D2Expr.Ref -> { visitIntInsn(Opcodes.ALOAD, e.memSlot.jArgIndex) generate(e.offset) val methodName = when (e.size) { D2Size.BYTE -> JvmMemTools::get8.name D2Size.SHORT -> JvmMemTools::get16.name D2Size.INT -> JvmMemTools::get32.name D2Size.LONG -> JvmMemTools::get64.name D2Size.FLOAT -> JvmMemTools::getF32.name } val retType = e.size.jPrimType visitMethodInsn( Opcodes.INVOKESTATIC, JvmMemTools::class.internalName, methodName, "(${d2MemoryRef}I)$retType", false ) } is D2Expr.Invoke<*> -> { val func = e.func val name = func.name val owner = func.owner val smethod = func.method if (smethod.parameterCount != e.args.size) error("Arity mismatch generating method call") val signature = "(" + smethod.signature.substringAfter('(') for ((index, arg) in e.args.withIndex()) { generate(arg) val param = smethod.parameterTypes[index] if (!param.isPrimitive) { //println("PARAM: $param") visitTypeInsn(Opcodes.CHECKCAST, param.internalName) } } visitMethodInsn(Opcodes.INVOKESTATIC, owner.internalName, name, signature, false) } is D2Expr.External -> { visitVarInsn(Opcodes.ALOAD, 4) } else -> TODO("$e") } return } fun <T> createDynamicClass(parent: ClassLoader, clazzName: String, b: ByteArray): Class<T> = OwnClassLoader(parent).defineClass(clazzName, b) as Class<T> private class OwnClassLoader(parent: ClassLoader) : ClassLoader(parent) { fun defineClass(name: String, b: ByteArray): Class<*> = defineClass(name, b, 0, b.size) } } val KFunction<*>.owner: Class<*> get() = (javaClass.methods.first { it.name == "getOwner" }.apply { isAccessible = true }.invoke(this) as kotlin.jvm.internal.PackageReference).jClass val KFunction<*>.fullSignature: String get() = javaClass.methods.first { it.name == "getSignature" }.apply { isAccessible = true }.invoke(this) as String val KFunction<*>.method: Method get() = owner.methods.firstOrNull { it.name == name } ?: error("Can't find method $name") object JvmMemTools { @JvmStatic fun get8(m: D2Memory, index: Int): Int = m.get8(index) @JvmStatic fun get16(m: D2Memory, index: Int): Int = m.get16(index) @JvmStatic fun get32(m: D2Memory, index: Int): Int = m.get32(index) @JvmStatic fun get64(m: D2Memory, index: Int): Long = m.get64(index) @JvmStatic fun set8(m: D2Memory, index: Int, value: Int) = m.set8(index, value) @JvmStatic fun set16(m: D2Memory, index: Int, value: Int) = m.set16(index, value) @JvmStatic fun set32(m: D2Memory, index: Int, value: Int) = m.set32(index, value) @JvmStatic fun set64(m: D2Memory, index: Int, value: Long) = m.set64(index, value) @JvmStatic fun getF32(m: D2Memory, index: Int): Float = Float.fromBits(m.get32(index)) @JvmStatic fun setF32(m: D2Memory, index: Int, value: Float) = m.set32(index, value.toRawBits()) @JvmStatic fun printi(i: Int): Unit = println(i) } val <T> Class<T>.internalName get() = Type.getInternalName(this) val <T : Any> KClass<T>.internalName get() = this.java.internalName val <T> Class<T>.asmRef get() = "L" + this.internalName + ";" val <T : Any> KClass<T>.asmRef get() = this.java.asmRef
mit
square/sqldelight
sqldelight-gradle-plugin/src/test/integration-sqlite-3-24/src/test/java/com/squareup/sqldelight/integration/IntegrationTests.kt
1
1363
package com.squareup.sqldelight.integration import com.google.common.truth.Truth.assertThat import com.squareup.sqldelight.sqlite.driver.JdbcSqliteDriver import com.squareup.sqldelight.sqlite.driver.JdbcSqliteDriver.Companion.IN_MEMORY import org.junit.Before import org.junit.Test class IntegrationTests { private lateinit var queryWrapper: QueryWrapper private lateinit var personQueries: PersonQueries @Before fun before() { val database = JdbcSqliteDriver(IN_MEMORY) QueryWrapper.Schema.create(database) queryWrapper = QueryWrapper(database) personQueries = queryWrapper.personQueries } @Test fun upsertNoConflict() { // ?1 is the only arg personQueries.performUpsert(5, "Bo", "Jangles") assertThat(personQueries.selectAll().executeAsList()) .containsExactly( Person(1, "Alec", "Strong"), Person(2, "Matt", "Precious"), Person(3, "Jake", "Wharton"), Person(4, "Bob", "Bob"), Person(5, "Bo", "Jangles") ) } @Test fun upsertConflict() { // ?1 is the only arg personQueries.performUpsert(3, "James", "Mosley") assertThat(personQueries.selectAll().executeAsList()) .containsExactly( Person(1, "Alec", "Strong"), Person(2, "Matt", "Precious"), Person(3, "James", "Mosley"), Person(4, "Bob", "Bob") ) } }
apache-2.0
Litote/kmongo
kmongo-annotation-processor/src/test/kotlin/org/litote/kmongo/model/other/SimpleReferencedData.kt
1
1852
/* * Copyright (C) 2016/2022 Litote * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.litote.kmongo.model.other import org.litote.kmongo.Data import org.litote.kmongo.model.SimpleReferenced2Data import org.litote.kmongo.model.SubData import org.litote.kmongo.model.TestData import java.util.Locale /** * */ @Data class SimpleReferencedData { var version: Int = 0 private val pojo2: SimpleReferenced2Data? = null var pojo: TestData? = null private val subPojo: SubData? = null val labels: Map<Locale, List<String>> = emptyMap() override fun toString(): String { return "SimpleReferencedData(version=$version, pojo2=$pojo2, pojo=$pojo, subPojo=$subPojo)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SimpleReferencedData) return false if (version != other.version) return false if (pojo2 != other.pojo2) return false if (pojo != other.pojo) return false if (subPojo != other.subPojo) return false return true } override fun hashCode(): Int { var result = version result = 31 * result + (pojo2?.hashCode() ?: 0) result = 31 * result + (pojo?.hashCode() ?: 0) result = 31 * result + (subPojo?.hashCode() ?: 0) return result } }
apache-2.0
sonnytron/FitTrainerBasic
mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/adapters/WorkoutItemUi.kt
1
1239
package com.sonnyrodriguez.fittrainer.fittrainerbasic.adapters import android.support.v4.content.ContextCompat import android.view.Gravity import android.view.ViewGroup import com.sonnyrodriguez.fittrainer.fittrainerbasic.R import org.jetbrains.anko.* class WorkoutItemUi: AnkoComponent<ViewGroup> { override fun createView(ui: AnkoContext<ViewGroup>) = with(ui) { relativeLayout { backgroundDrawable = ContextCompat.getDrawable(ctx, R.drawable.list_background_white) lparams(width = matchParent, height = dimen(R.dimen.single_list_item_default_height)) { horizontalMargin = dip(16) topMargin = dip(6) } verticalLayout { themedTextView(R.style.BasicListItemTitle) { id = R.id.workout_item_title }.lparams(width = matchParent, height = wrapContent) { gravity = Gravity.CENTER } themedTextView(R.style.BasicListItemStyle) { id = R.id.workout_exercise_count }.lparams(width = matchParent, height = wrapContent) { gravity = Gravity.BOTTOM } } } } }
apache-2.0
proxer/ProxerLibAndroid
library/src/main/kotlin/me/proxer/library/api/apps/InternalApi.kt
1
483
package me.proxer.library.api.apps import me.proxer.library.ProxerCall import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.POST /** * @author Ruben Gees */ internal interface InternalApi { @FormUrlEncoded @POST("apps/errorlog") fun errorLog( @Field("id") id: String?, @Field("message") message: String?, @Field("anonym") anonym: Boolean?, @Field("silent") silent: Boolean? ): ProxerCall<Unit> }
gpl-3.0
RocketChat/Rocket.Chat.Android
suggestions/src/main/java/chat/rocket/android/suggestions/strategy/trie/data/Trie.kt
2
1996
package chat.rocket.android.suggestions.strategy.trie.data import chat.rocket.android.suggestions.model.SuggestionModel internal class Trie { private val root = TrieNode(' ') private var count = 0 fun insert(item: SuggestionModel) { val sanitizedWord = item.text.trim().toLowerCase() // Word exists, bail out. if (search(sanitizedWord)) return var current = root sanitizedWord.forEach { ch -> val child = current.getChild(ch) if (child == null) { val node = TrieNode(ch, current) current.children[ch] = node current = node count++ } else { current = child } } // Set last node as leaf. if (current != root) { current.isLeaf = true current.item = item } } fun search(word: String): Boolean { val sanitizedWord = word.trim().toLowerCase() var current = root sanitizedWord.forEach { ch -> val child = current.getChild(ch) ?: return false current = child } if (current.isLeaf) { return true } return false } fun autocomplete(prefix: String): List<String> { val sanitizedPrefix = prefix.trim().toLowerCase() var lastNode: TrieNode? = root sanitizedPrefix.forEach { ch -> lastNode = lastNode?.getChild(ch) if (lastNode == null) return emptyList() } return lastNode!!.getWords() } fun autocompleteItems(prefix: String): List<SuggestionModel> { val sanitizedPrefix = prefix.trim().toLowerCase() var lastNode: TrieNode? = root sanitizedPrefix.forEach { ch -> lastNode = lastNode?.getChild(ch) if (lastNode == null) return emptyList() } return lastNode!!.getItems().take(5).toList() } fun getCount() = count }
mit