repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bhubie/Expander | app/src/main/kotlin/com/wanderfar/expander/Models/Macro.kt | 1 | 1283 | /*
* Expander: Text Expansion Application
* Copyright (C) 2016 Brett Huber
*
* 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.wanderfar.expander.Models
import java.util.*
class Macro {
//If we are adding an item to the macro, be sure to update the extension function in Macro store to check for equality
var name : String = ""
var phrase : String = ""
var description : String? = null
var macroPattern : String = ""
var usageCount : Int = 0
var isCaseSensitive : Boolean = false
var expandWhenSetting : Int = MacroConstants.ON_A_SPACE_OR_PERIOD
var lastUsed : Date? = null
var expandWithinWords : Boolean = false
}
| gpl-3.0 | 4ad1e6fecb8587eaad99adb79a124db0 | 28.837209 | 122 | 0.713952 | 4.152104 | false | false | false | false |
bmaslakov/kotlin-algorithm-club | src/main/io/uuddlrlrba/ktalgs/datastructures/Stack.kt | 1 | 2764 | /*
* Copyright (c) 2017 Kotlin Algorithm Club
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.uuddlrlrba.ktalgs.datastructures
import java.util.*
@Suppress("RedundantVisibilityModifier")
public class Stack<T> : Collection<T> {
private var head: Node<T>? = null
public override var size: Int = 0
private set
private class Node<T>(var value: T) {
var next: Node<T>? = null
}
public fun push(item: T) {
val new = Node(item)
new.next = head
head = new
size++
}
public fun peek(): T {
if (size == 0) throw NoSuchElementException()
return head!!.value
}
public fun poll(): T {
if (size == 0) throw NoSuchElementException()
val old = head!!
head = old.next
size--
return old.value
}
public override fun isEmpty(): Boolean {
return size == 0
}
public override fun contains(element: T): Boolean {
for (obj in this) {
if (obj == element) return true
}
return false
}
public override fun containsAll(elements: Collection<T>): Boolean {
for (element in elements) {
if (!contains(element)) return false
}
return true
}
public override fun iterator(): Iterator<T> {
return object : Iterator<T> {
var node = head
override fun hasNext(): Boolean {
return node != null
}
override fun next(): T {
if (!hasNext()) throw NoSuchElementException()
val current = node!!
node = current.next
return current.value
}
}
}
}
| mit | d3caa1255c1401b1ee099530934876db | 29.373626 | 81 | 0.62301 | 4.668919 | false | false | false | false |
aosp-mirror/platform_frameworks_support | room/compiler/src/test/kotlin/androidx/room/verifier/DatabaseVerifierTest.kt | 1 | 10054 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.verifier
import androidx.room.parser.Collate
import androidx.room.parser.SQLTypeAffinity
import androidx.room.processor.Context
import androidx.room.testing.TestInvocation
import androidx.room.vo.CallType
import androidx.room.vo.Constructor
import androidx.room.vo.Database
import androidx.room.vo.Entity
import androidx.room.vo.Field
import androidx.room.vo.FieldGetter
import androidx.room.vo.FieldSetter
import androidx.room.vo.PrimaryKey
import collect
import columnNames
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.hasItem
import org.hamcrest.CoreMatchers.notNullValue
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.mockito.Mockito.doReturn
import org.mockito.Mockito.mock
import simpleRun
import java.sql.Connection
import javax.lang.model.element.Element
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.TypeElement
import javax.lang.model.type.DeclaredType
import javax.lang.model.type.PrimitiveType
import javax.lang.model.type.TypeKind
import javax.lang.model.type.TypeMirror
@RunWith(Parameterized::class)
class DatabaseVerifierTest(private val useLocalizedCollation: Boolean) {
@Test
fun testSimpleDatabase() {
simpleRun { invocation ->
val verifier = createVerifier(invocation)
val stmt = verifier.connection.createStatement()
val rs = stmt.executeQuery("select * from sqlite_master WHERE type='table'")
assertThat(
rs.collect { set -> set.getString("name") }, hasItem(`is`("User")))
val table = verifier.connection.prepareStatement("select * from User")
assertThat(table.columnNames(), `is`(listOf("id", "name", "lastName", "ratio")))
assertThat(getPrimaryKeys(verifier.connection, "User"), `is`(listOf("id")))
}.compilesWithoutError()
}
private fun createVerifier(invocation: TestInvocation): DatabaseVerifier {
return DatabaseVerifier.create(invocation.context, mock(Element::class.java),
userDb(invocation.context).entities)!!
}
@Test
fun testFullEntityQuery() {
validQueryTest("select * from User") {
assertThat(it, `is`(
QueryResultInfo(listOf(
ColumnInfo("id", SQLTypeAffinity.INTEGER),
ColumnInfo("name", SQLTypeAffinity.TEXT),
ColumnInfo("lastName", SQLTypeAffinity.TEXT),
ColumnInfo("ratio", SQLTypeAffinity.REAL)
))))
}
}
@Test
fun testPartialFields() {
validQueryTest("select id, lastName from User") {
assertThat(it, `is`(
QueryResultInfo(listOf(
ColumnInfo("id", SQLTypeAffinity.INTEGER),
ColumnInfo("lastName", SQLTypeAffinity.TEXT)
))))
}
}
@Test
fun testRenamedField() {
validQueryTest("select id as myId, lastName from User") {
assertThat(it, `is`(
QueryResultInfo(listOf(
ColumnInfo("myId", SQLTypeAffinity.INTEGER),
ColumnInfo("lastName", SQLTypeAffinity.TEXT)
))))
}
}
@Test
fun testGrouped() {
validQueryTest("select MAX(ratio) from User GROUP BY name") {
assertThat(it, `is`(
QueryResultInfo(listOf(
// unfortunately, we don't get this information
ColumnInfo("MAX(ratio)", SQLTypeAffinity.NULL)
))))
}
}
@Test
fun testConcat() {
validQueryTest("select name || lastName as mergedName from User") {
assertThat(it, `is`(
QueryResultInfo(listOf(
// unfortunately, we don't get this information
ColumnInfo("mergedName", SQLTypeAffinity.NULL)
))))
}
}
@Test
fun testResultWithArgs() {
validQueryTest("select id, name || lastName as mergedName from User where name LIKE ?") {
assertThat(it, `is`(
QueryResultInfo(listOf(
// unfortunately, we don't get this information
ColumnInfo("id", SQLTypeAffinity.INTEGER),
ColumnInfo("mergedName", SQLTypeAffinity.NULL)
))))
}
}
@Test
fun testDeleteQuery() {
validQueryTest("delete from User where name LIKE ?") {
assertThat(it, `is`(QueryResultInfo(emptyList())))
}
}
@Test
fun testUpdateQuery() {
validQueryTest("update User set name = ? WHERE id = ?") {
assertThat(it, `is`(QueryResultInfo(emptyList())))
}
}
@Test
fun testBadQuery() {
simpleRun { invocation ->
val verifier = createVerifier(invocation)
val (_, error) = verifier.analyze("select foo from User")
assertThat(error, notNullValue())
}.compilesWithoutError()
}
@Test
fun testCollate() {
validQueryTest("SELECT id, name FROM user ORDER BY name COLLATE LOCALIZED ASC") {
assertThat(it, `is`(
QueryResultInfo(listOf(
// unfortunately, we don't get this information
ColumnInfo("id", SQLTypeAffinity.INTEGER),
ColumnInfo("name", SQLTypeAffinity.TEXT)
))))
}
}
@Test
fun testCollateBasQuery() {
simpleRun { invocation ->
val verifier = createVerifier(invocation)
val (_, error) = verifier.analyze(
"SELECT id, name FROM user ORDER BY name COLLATE LOCALIZEDASC")
assertThat(error, notNullValue())
}.compilesWithoutError()
}
private fun validQueryTest(sql: String, cb: (QueryResultInfo) -> Unit) {
simpleRun { invocation ->
val verifier = createVerifier(invocation)
val info = verifier.analyze(sql)
cb(info)
}.compilesWithoutError()
}
private fun userDb(context: Context): Database {
return database(entity("User",
field("id", primitive(context, TypeKind.INT), SQLTypeAffinity.INTEGER),
field("name", context.COMMON_TYPES.STRING, SQLTypeAffinity.TEXT),
field("lastName", context.COMMON_TYPES.STRING, SQLTypeAffinity.TEXT),
field("ratio", primitive(context, TypeKind.FLOAT), SQLTypeAffinity.REAL)))
}
private fun database(vararg entities: Entity): Database {
return Database(
element = mock(TypeElement::class.java),
type = mock(TypeMirror::class.java),
entities = entities.toList(),
daoMethods = emptyList(),
version = -1,
exportSchema = false,
enableForeignKeys = false)
}
private fun entity(tableName: String, vararg fields: Field): Entity {
return Entity(
element = mock(TypeElement::class.java),
tableName = tableName,
type = mock(DeclaredType::class.java),
fields = fields.toList(),
embeddedFields = emptyList(),
indices = emptyList(),
primaryKey = PrimaryKey(null, fields.take(1), false),
foreignKeys = emptyList(),
constructor = Constructor(mock(ExecutableElement::class.java), emptyList())
)
}
private fun field(name: String, type: TypeMirror, affinity: SQLTypeAffinity): Field {
val element = mock(Element::class.java)
doReturn(type).`when`(element).asType()
val f = Field(
element = element,
name = name,
type = type,
columnName = name,
affinity = affinity,
collate = if (useLocalizedCollation && affinity == SQLTypeAffinity.TEXT) {
Collate.LOCALIZED
} else {
null
}
)
assignGetterSetter(f, name, type)
return f
}
private fun assignGetterSetter(f: Field, name: String, type: TypeMirror) {
f.getter = FieldGetter(name, type, CallType.FIELD)
f.setter = FieldSetter(name, type, CallType.FIELD)
}
private fun primitive(context: Context, kind: TypeKind): PrimitiveType {
return context.processingEnv.typeUtils.getPrimitiveType(kind)
}
private fun getPrimaryKeys(connection: Connection, tableName: String): List<String> {
val stmt = connection.createStatement()
val resultSet = stmt.executeQuery("PRAGMA table_info($tableName)")
return resultSet.collect {
Pair(it.getString("name"), it.getInt("pk"))
}
.filter { it.second > 0 }
.sortedBy { it.second }
.map { it.first }
}
companion object {
@Parameterized.Parameters(name = "useLocalizedCollation={0}")
@JvmStatic
fun params() = arrayListOf(true, false)
}
}
| apache-2.0 | 6218ae7b087a9cbef4436ce9e3fd0d6e | 35.827839 | 97 | 0.591108 | 4.999503 | false | true | false | false |
duftler/clouddriver | clouddriver-scattergather/src/test/kotlin/com/netflix/spinnaker/clouddriver/scattergather/ReducedResponseSpec.kt | 1 | 2287 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.clouddriver.scattergather
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import strikt.api.expectThat
import strikt.assertions.isEqualTo
import java.io.ByteArrayOutputStream
import java.io.PrintWriter
import javax.servlet.http.HttpServletResponse
internal object ReducedResponseSpec : Spek({
describe("applying a reduced response to a HttpServletResponse") {
given("a reduced response") {
val reducedResponse = ReducedResponse(
status = 200,
headers = mapOf(),
contentType = "application/json",
characterEncoding = "UTF-8",
body = "Hello world!",
isError = false
)
val byteArrayOutputStream = ByteArrayOutputStream()
val printWriter = PrintWriter(byteArrayOutputStream)
val servletResponse = mock<HttpServletResponse>() {
on { writer } doReturn printWriter
}
it("applies values to servlet response") {
reducedResponse.applyTo(servletResponse).flush()
verify(servletResponse).status = eq(200)
verify(servletResponse).contentType = eq("application/json")
verify(servletResponse).characterEncoding = eq("UTF-8")
verify(servletResponse).setContentLength(eq(reducedResponse.body!!.length))
expectThat(byteArrayOutputStream) {
get { byteArrayOutputStream.toString() }.isEqualTo("Hello world!")
}
}
}
}
})
| apache-2.0 | 93dee7b507282de17f51006a1b250570 | 33.651515 | 83 | 0.72453 | 4.519763 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/download/src/main/java/jp/hazuki/yuzubrowser/download/core/downloader/Base64TmpDownloader.kt | 1 | 2524 | /*
* Copyright (C) 2017-2021 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.download.core.downloader
import android.content.Context
import jp.hazuki.yuzubrowser.core.utility.storage.toDocumentFile
import jp.hazuki.yuzubrowser.download.DOWNLOAD_TMP_FILENAME
import jp.hazuki.yuzubrowser.download.core.data.DownloadFileInfo
import jp.hazuki.yuzubrowser.download.core.data.DownloadRequest
import jp.hazuki.yuzubrowser.download.core.utils.decodeBase64Image
import jp.hazuki.yuzubrowser.download.core.utils.saveBase64Image
import java.io.File
import java.io.IOException
import java.nio.charset.StandardCharsets
class Base64TmpDownloader(
private val context: Context,
private val info: DownloadFileInfo,
private val request: DownloadRequest,
) : Downloader {
override var downloadListener: Downloader.DownloadListener? = null
override fun download(): Boolean {
downloadListener?.onStartDownload(info)
val base64File = File(context.cacheDir, DOWNLOAD_TMP_FILENAME)
try {
val base64 = base64File.inputStream().use { it.readBytes().toString(StandardCharsets.UTF_8) }
val image = decodeBase64Image(base64)
val rootFile = info.root.toDocumentFile(context)
val file = if (request.isScopedStorageMode) {
rootFile
} else {
rootFile.createFile(image.mimeType, info.name)
}
if (file != null && context.contentResolver.saveBase64Image(image, file)) {
info.state = DownloadFileInfo.STATE_DOWNLOADED
info.size = file.length()
downloadListener?.onFileDownloaded(info, file)
return true
}
} catch (e: IOException) {
} finally {
if (base64File.exists()) base64File.delete()
}
info.state = DownloadFileInfo.STATE_UNKNOWN_ERROR
downloadListener?.onFileDownloadFailed(info)
return false
}
}
| apache-2.0 | fe2d8b1342f9867aed7a6f861bce43a5 | 39.063492 | 105 | 0.698891 | 4.435852 | false | false | false | false |
EMResearch/EvoMaster | core/src/test/kotlin/org/evomaster/core/database/extract/postgres/DatetimeTypesTest.kt | 1 | 2005 | package org.evomaster.core.database.extract.postgres
import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType
import org.evomaster.client.java.controller.db.SqlScriptRunner
import org.evomaster.client.java.controller.internal.db.SchemaExtractor
import org.evomaster.core.database.DbActionTransformer
import org.evomaster.core.database.SqlInsertBuilder
import org.evomaster.core.search.gene.datetime.DateGene
import org.evomaster.core.search.gene.datetime.DateTimeGene
import org.evomaster.core.search.gene.sql.time.SqlTimeIntervalGene
import org.evomaster.core.search.gene.datetime.TimeGene
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
/**
* Created by jgaleotti on 07-May-19.
*/
class DatetimeTypesTest : ExtractTestBasePostgres() {
override fun getSchemaLocation() = "/sql_schema/postgres_datetime_types.sql"
@Test
fun testDatetimeTypes() {
val schema = SchemaExtractor.extract(connection)
assertNotNull(schema)
assertEquals("public", schema.name.lowercase())
assertEquals(DatabaseType.POSTGRES, schema.databaseType)
val builder = SqlInsertBuilder(schema)
val actions = builder.createSqlInsertionAction(
"DatetimeTypes", setOf(
"timestampColumn",
"timestampWithTimeZoneColumn",
"dateColumn",
"timeColumn",
"timeWithTimeZoneColumn",
"intervalColumn"
)
)
val genes = actions[0].seeTopGenes()
assertEquals(6, genes.size)
assertTrue(genes[0] is DateTimeGene)
assertTrue(genes[1] is DateTimeGene)
assertTrue(genes[2] is DateGene)
assertTrue(genes[3] is TimeGene)
assertTrue(genes[4] is TimeGene)
assertTrue(genes[5] is SqlTimeIntervalGene)
val dbCommandDto = DbActionTransformer.transform(actions)
SqlScriptRunner.execInsert(connection, dbCommandDto.insertions)
}
} | lgpl-3.0 | 5db432011f22d46a46595873e055e478 | 32.433333 | 80 | 0.708728 | 4.485459 | false | true | false | false |
aucd29/crypto | library/src/main/java/net/sarangnamu/common/crypto/Hash.kt | 1 | 2996 | package net.sarangnamu.common.crypto
import org.slf4j.LoggerFactory
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.nio.charset.Charset
import java.security.MessageDigest
/**
* Created by <a href="mailto:[email protected]">Burke Choi</a> on 2017. 11. 2.. <p/>
*/
private val MD5 = "MD5"
private val SHA1 = "SHA-1"
private val SHA256 = "SHA-256"
private val SHA512 = "SHA-512"
////////////////////////////////////////////////////////////////////////////////////
//
// File
//
////////////////////////////////////////////////////////////////////////////////////
fun File.md5():String? {
return toHashString(MD5)
}
fun File.sha1(): String ? {
return toHashString(SHA1)
}
fun File.sha256(): String? {
return toHashString(SHA256)
}
fun File.sha512(): String? {
return toHashString(SHA512)
}
fun File.toHashString(type: String): String? {
return FileInputStream(this).toHashString(type)
}
////////////////////////////////////////////////////////////////////////////////////
//
// FileInputStream
//
////////////////////////////////////////////////////////////////////////////////////
fun FileInputStream.md5():String? {
return toHashString(MD5)
}
fun FileInputStream.sha1(): String ? {
return toHashString(SHA1)
}
fun FileInputStream.sha256(): String? {
return toHashString(SHA256)
}
fun FileInputStream.sha512(): String? {
return toHashString(SHA512)
}
fun FileInputStream.toHashString(type: String): String? {
use { ism ->
val md = MessageDigest.getInstance(type)
val buff = ByteArray(DEFAULT_BUFFER_SIZE)
var size = ism.read(buff)
while (size != -1) {
md.update(buff, 0, size)
size = ism.read(buff)
}
return md.digest().toHexString()
}
}
////////////////////////////////////////////////////////////////////////////////////
//
// String
//
////////////////////////////////////////////////////////////////////////////////////
fun String.md5(): String? {
return toHashString(MD5)
}
fun String.sha1(): String ? {
return toHashString(SHA1)
}
fun String.sha256(): String? {
return toHashString(SHA256)
}
fun String.sha512(): String? {
return toHashString(SHA512)
}
fun String.toHashString(type:String): String? {
return MessageDigest.getInstance(type).digest(toByteArray(Charset.defaultCharset())).toHexString()
}
////////////////////////////////////////////////////////////////////////////////////
//
// ByteArray
//
////////////////////////////////////////////////////////////////////////////////////
fun ByteArray.md5(): String? {
return toHashString(MD5)
}
fun ByteArray.sha1(): String ? {
return toHashString(SHA1)
}
fun ByteArray.sha256(): String? {
return toHashString(SHA256)
}
fun ByteArray.sha512(): String? {
return toHashString(SHA512)
}
fun ByteArray.toHashString(type: String): String? {
return MessageDigest.getInstance(type).digest(this).toHexString()
} | apache-2.0 | 3dc2bf2055f80980d21f87b12403369e | 21.704545 | 102 | 0.522029 | 4.166898 | false | false | false | false |
mikkokar/styx | components/proxy/src/test/kotlin/com/hotels/styx/services/OriginsConfigConverterTest.kt | 1 | 12710 | /*
Copyright (C) 2013-2020 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.hotels.styx.services
import com.hotels.styx.ProviderObjectRecord
import com.hotels.styx.STATE_ACTIVE
import com.hotels.styx.STATE_UNREACHABLE
import com.hotels.styx.lbGroupTag
import com.hotels.styx.RoutingObjectFactoryContext
import com.hotels.styx.routing.config.Builtins.INTERCEPTOR_PIPELINE
import com.hotels.styx.routing.db.StyxObjectStore
import com.hotels.styx.services.OriginsConfigConverter.Companion.deserialiseOrigins
import com.hotels.styx.services.OriginsConfigConverter.Companion.loadBalancingGroup
import com.hotels.styx.stateTag
import io.kotlintest.matchers.collections.shouldBeEmpty
import io.kotlintest.matchers.collections.shouldContainExactlyInAnyOrder
import io.kotlintest.matchers.types.shouldNotBeNull
import io.kotlintest.shouldBe
import io.kotlintest.specs.StringSpec
class OriginsConfigConverterTest : StringSpec({
val serviceDb = StyxObjectStore<ProviderObjectRecord>()
val ctx = RoutingObjectFactoryContext().get()
"Translates a BackendService to a LoadBalancingGroup with HostProxy objects" {
val config = """
---
- id: "app"
path: "/"
maxHeaderSize: 1000
origins:
- { id: "app1", host: "localhost:9090" }
- { id: "app2", host: "localhost:9091" }
""".trimIndent()
OriginsConfigConverter(serviceDb, ctx, "")
.routingObjects(deserialiseOrigins(config))
.let {
it.size shouldBe 3
it[0].name() shouldBe "app.app1"
it[0].tags().shouldContainExactlyInAnyOrder(lbGroupTag("app"), stateTag(STATE_ACTIVE))
it[0].type().shouldBe("HostProxy")
it[0].config().shouldNotBeNull()
it[0].config()["maxHeaderSize"].intValue() shouldBe 1000
it[1].name() shouldBe "app.app2"
it[1].tags().shouldContainExactlyInAnyOrder(lbGroupTag("app"), stateTag(STATE_ACTIVE))
it[1].type().shouldBe("HostProxy")
it[1].config().shouldNotBeNull()
it[2].name() shouldBe "app"
it[2].tags().shouldBeEmpty()
it[2].type().shouldBe("LoadBalancingGroup")
it[2].config().shouldNotBeNull()
}
}
"Translates one rewrite rules" {
val config = """
---
- id: "app"
path: "/"
rewrites:
- urlPattern: "/abc/(.*)"
replacement: "/$1"
origins:
- { id: "app1", host: "localhost:9090" }
""".trimIndent()
val app = deserialiseOrigins(config)[0]
loadBalancingGroup(app, null)
.let {
it.name() shouldBe "app"
it.type() shouldBe INTERCEPTOR_PIPELINE
}
}
"Translates many rewrite rules" {
val config = """
---
- id: "app"
path: "/"
rewrites:
- urlPattern: "/abc/(.*)"
replacement: "/$1"
- urlPattern: "/def/(.*)"
replacement: "/$1"
origins:
- { id: "app2", host: "localhost:9091" }
""".trimIndent()
val app = deserialiseOrigins(config)[0]
loadBalancingGroup(app, null)
.let {
it.name() shouldBe "app"
it.type() shouldBe INTERCEPTOR_PIPELINE
}
}
"Translates a BackendService with TlsSettings to a LoadBalancingGroup with HostProxy objects" {
val config = """
---
- id: "app"
path: "/"
tlsSettings:
trustAllCerts: true
sslProvider: JDK
origins:
- { id: "app1", host: "localhost:9090" }
- { id: "app2", host: "localhost:9091" }
""".trimIndent()
OriginsConfigConverter(serviceDb, ctx, "")
.routingObjects(deserialiseOrigins(config))
.let {
it.size shouldBe 3
it[0].name() shouldBe "app.app1"
it[0].tags().shouldContainExactlyInAnyOrder(lbGroupTag("app"), stateTag(STATE_ACTIVE))
it[0].type().shouldBe("HostProxy")
it[0].config().shouldNotBeNull()
it[1].name() shouldBe "app.app2"
it[1].tags().shouldContainExactlyInAnyOrder(lbGroupTag("app"), stateTag(STATE_ACTIVE))
it[1].type().shouldBe("HostProxy")
it[1].config().shouldNotBeNull()
it[2].name() shouldBe "app"
it[2].tags().shouldBeEmpty()
it[2].type().shouldBe("LoadBalancingGroup")
it[2].config().shouldNotBeNull()
}
}
"Translates a list of applications" {
val config = """
---
- id: "appA"
path: "/a"
origins:
- { id: "appA-1", host: "localhost:9190" }
- { id: "appA-2", host: "localhost:9191" }
- id: "appB"
path: "/b"
origins:
- { id: "appB-1", host: "localhost:9290" }
- id: "appC"
path: "/c"
origins:
- { id: "appC-1", host: "localhost:9290" }
- { id: "appC-2", host: "localhost:9291" }
""".trimIndent()
OriginsConfigConverter(serviceDb, ctx, "")
.routingObjects(deserialiseOrigins(config))
.let {
it.size shouldBe 8
it[0].name() shouldBe "appA.appA-1"
it[0].tags().shouldContainExactlyInAnyOrder(lbGroupTag("appA"), stateTag(STATE_ACTIVE))
it[0].type().shouldBe("HostProxy")
it[0].config().shouldNotBeNull()
it[1].name() shouldBe "appA.appA-2"
it[1].tags().shouldContainExactlyInAnyOrder(lbGroupTag("appA"), stateTag(STATE_ACTIVE))
it[1].type().shouldBe("HostProxy")
it[1].config().shouldNotBeNull()
it[2].name() shouldBe "appA"
it[2].tags().shouldBeEmpty()
it[2].type().shouldBe("LoadBalancingGroup")
it[2].config().shouldNotBeNull()
it[3].name() shouldBe "appB.appB-1"
it[3].tags().shouldContainExactlyInAnyOrder(lbGroupTag("appB"), stateTag(STATE_ACTIVE))
it[3].type().shouldBe("HostProxy")
it[3].config().shouldNotBeNull()
it[4].name() shouldBe "appB"
it[4].tags().shouldBeEmpty()
it[4].type().shouldBe("LoadBalancingGroup")
it[4].config().shouldNotBeNull()
it[5].name() shouldBe "appC.appC-1"
it[5].tags().shouldContainExactlyInAnyOrder(lbGroupTag("appC"), stateTag(STATE_ACTIVE))
it[5].type().shouldBe("HostProxy")
it[5].config().shouldNotBeNull()
it[6].name() shouldBe "appC.appC-2"
it[6].tags().shouldContainExactlyInAnyOrder(lbGroupTag("appC"), stateTag(STATE_ACTIVE))
it[6].type().shouldBe("HostProxy")
it[6].config().shouldNotBeNull()
it[7].name() shouldBe "appC"
it[7].tags().shouldBeEmpty()
it[7].type().shouldBe("LoadBalancingGroup")
it[7].config().shouldNotBeNull()
}
}
"Creates HealthCheckObjects from a list of applications" {
val translator = OriginsConfigConverter(serviceDb, RoutingObjectFactoryContext().get(), "")
val config = """
---
- id: "appA"
path: "/a"
healthCheck:
uri: "/apphealth.txt"
intervalMillis: 10000
unhealthyThreshold: 2
healthyThreshold: 3
origins:
- { id: "appA-1", host: "localhost:9190" }
- { id: "appA-2", host: "localhost:9191" }
- id: "appB"
path: "/b"
healthCheck:
uri: "/app-b-health.txt"
timeoutMillis: 1500
unhealthyThreshold: 5
healthyThreshold: 6
origins:
- { id: "appB-1", host: "localhost:9290" }
- id: "appC"
path: "/c"
healthCheck:
uri: "/apphealth.txt"
unhealthyThreshold: 2
healthyThreshold: 3
origins:
- { id: "appC-1", host: "localhost:9290" }
- { id: "appC-2", host: "localhost:9291" }
""".trimIndent()
val apps = deserialiseOrigins(config)
val services = translator.healthCheckServices(apps)
services.size shouldBe 3
services[0].first shouldBe "appA-monitor"
services[0].second.type shouldBe "HealthCheckMonitor"
services[0].second.styxService.shouldNotBeNull()
services[0].second.config.get(HealthCheckConfiguration::class.java).let {
it.path shouldBe "/apphealth.txt"
it.timeoutMillis shouldBe 2000
it.intervalMillis shouldBe 10000
it.unhealthyThreshold shouldBe 2
it.healthyThreshod shouldBe 3
}
services[1].first shouldBe "appB-monitor"
services[1].second.type shouldBe "HealthCheckMonitor"
services[1].second.styxService.shouldNotBeNull()
services[1].second.config.get(HealthCheckConfiguration::class.java).let {
it.path shouldBe "/app-b-health.txt"
it.timeoutMillis shouldBe 1500
it.intervalMillis shouldBe 5000
it.unhealthyThreshold shouldBe 5
it.healthyThreshod shouldBe 6
}
services[2].first shouldBe "appC-monitor"
services[2].second.type shouldBe "HealthCheckMonitor"
services[2].second.styxService.shouldNotBeNull()
services[2].second.config.get(HealthCheckConfiguration::class.java).let {
it.path shouldBe "/apphealth.txt"
it.timeoutMillis shouldBe 2000
it.intervalMillis shouldBe 5000
it.unhealthyThreshold shouldBe 2
it.healthyThreshod shouldBe 3
}
}
"Sets inactive tag on an app if there is a valid healthCheck configured" {
val config = """
---
- id: "appWithHealthCheck"
path: "/a"
healthCheck:
uri: "/apphealth.txt"
intervalMillis: 10000
unhealthyThreshold: 2
healthyThreshold: 3
origins:
- { id: "appA-1", host: "localhost:9190" }
- id: "appMissingHealthCheckUri"
path: "/b"
healthCheck:
intervalMillis: 10000
unhealthyThreshold: 2
healthyThreshold: 3
origins:
- { id: "appB-1", host: "localhost:9290" }
- id: "appWithNoHealthCheck"
path: "/c"
origins:
- { id: "appC-1", host: "localhost:9290" }
""".trimIndent()
OriginsConfigConverter(serviceDb, RoutingObjectFactoryContext().get(), "")
.routingObjects(deserialiseOrigins(config))
.let {
it[0].tags().shouldContainExactlyInAnyOrder(lbGroupTag("appWithHealthCheck"), stateTag(STATE_UNREACHABLE))
it[2].tags().shouldContainExactlyInAnyOrder(lbGroupTag("appMissingHealthCheckUri"), stateTag(STATE_ACTIVE))
it[4].tags().shouldContainExactlyInAnyOrder(lbGroupTag("appWithNoHealthCheck"), stateTag(STATE_ACTIVE))
}
}
})
| apache-2.0 | 3f224039c5eff322019c25d5fe098f67 | 37.632219 | 127 | 0.530921 | 4.659091 | false | true | false | false |
VerifAPS/verifaps-lib | lang/src/main/kotlin/edu/kit/iti/formal/automation/sfclang/Utils.kt | 1 | 1800 | package edu.kit.iti.formal.automation.sfclang
/*-
* #%L
* iec61131lang
* %%
* Copyright (C) 2016 Alexander Weigl
* %%
* This program isType 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 isType 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 clone of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import java.math.BigInteger
import java.util.regex.Pattern
internal var PATTERN = Pattern.compile("((?<prefix>\\D\\w*?)#)?((?<radix>\\d+?)#)?(?<value>.*)")
private var uniqueNameId = 0
fun getUniqueName(prefix: String = "", postfix: String = "") = "$prefix${++uniqueNameId}$postfix"
fun split(s: String): Splitted {
val t = PATTERN.matcher(s)
return if (t.matches()) {
val rd = t.group("radix")?.toInt()
Splitted(t.group("prefix"), rd, t.group("value")!!)
} else {
throw IllegalArgumentException("Argument isType not well word: expected form " + PATTERN.pattern())
}
}
fun getIntegerLiteralValue(text: String, sign: Boolean): BigInteger {
val s = split(text)
return if (sign) s.number().negate() else s.number()
}
data class Splitted(
val prefix: String?,
val ordinal: Int?,
val value: String) {
fun number(defaultRadix: Int = 10): BigInteger {
return BigInteger(value, ordinal ?: defaultRadix)
}
}
| gpl-3.0 | 42f1d4401cefadba9ed7a90b062d1cfa | 30.578947 | 107 | 0.672778 | 3.76569 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/movies/search/MoviesSearchFragment.kt | 1 | 5267 | package com.battlelancer.seriesguide.movies.search
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isGone
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.databinding.FragmentMoviesSearchBinding
import com.battlelancer.seriesguide.movies.MovieClickListenerImpl
import com.battlelancer.seriesguide.movies.MoviesDiscoverLink
import com.battlelancer.seriesguide.ui.AutoGridLayoutManager
import com.battlelancer.seriesguide.util.ViewTools
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.launch
import timber.log.Timber
/**
* Integrates with a search interface and displays movies based on query results. Can pre-populate
* the displayed movies based on a sent link.
*/
class MoviesSearchFragment : Fragment() {
internal interface OnSearchClickListener {
fun onSearchClick()
}
private var _binding: FragmentMoviesSearchBinding? = null
private val binding get() = _binding!!
private lateinit var link: MoviesDiscoverLink
private lateinit var searchClickListener: OnSearchClickListener
private lateinit var adapter: MoviesSearchAdapter
private val model: MoviesSearchViewModel by viewModels {
MoviesSearchViewModelFactory(requireActivity().application, link)
}
override fun onAttach(context: Context) {
super.onAttach(context)
searchClickListener = try {
context as OnSearchClickListener
} catch (e: ClassCastException) {
throw ClassCastException("$context must implement OnSearchClickListener")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
link = MoviesDiscoverLink.fromId(requireArguments().getInt(ARG_ID_LINK))
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMoviesSearchBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.swipeRefreshLayoutMoviesSearch.also {
it.setSwipeableChildren(R.id.scrollViewMoviesSearch, R.id.recyclerViewMoviesSearch)
it.setOnRefreshListener(onRefreshListener)
ViewTools.setSwipeRefreshLayoutColors(requireActivity().theme, it)
}
// setup empty view button
binding.emptyViewMoviesSearch.setButtonClickListener { searchClickListener.onSearchClick() }
// setup grid view
binding.recyclerViewMoviesSearch.apply {
setHasFixedSize(true)
layoutManager =
AutoGridLayoutManager(
context,
R.dimen.movie_grid_columnWidth,
1,
1
)
}
adapter = MoviesSearchAdapter(requireContext(), MovieClickListenerImpl(requireContext()))
binding.recyclerViewMoviesSearch.adapter = adapter
viewLifecycleOwner.lifecycleScope.launch {
adapter.onPagesUpdatedFlow.conflate().collectLatest {
val hasNoResults = adapter.itemCount == 0
binding.emptyViewMoviesSearch.isGone = !hasNoResults
binding.recyclerViewMoviesSearch.isGone = hasNoResults
}
}
viewLifecycleOwner.lifecycleScope.launch {
adapter.loadStateFlow
.distinctUntilChangedBy { it.refresh }
.collectLatest { loadStates ->
Timber.d("loadStates=$loadStates")
val refresh = loadStates.refresh
binding.swipeRefreshLayoutMoviesSearch.isRefreshing = refresh is LoadState.Loading
if (refresh is LoadState.Error) {
binding.emptyViewMoviesSearch.setMessage(refresh.error.message)
} else {
binding.emptyViewMoviesSearch.setMessage(R.string.no_results)
}
}
}
viewLifecycleOwner.lifecycleScope.launch {
model.items.collectLatest {
adapter.submitData(it)
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
fun search(query: String) {
model.updateQuery(query)
}
private val onRefreshListener = OnRefreshListener { adapter.refresh() }
companion object {
private const val ARG_ID_LINK = "linkId"
@JvmStatic
fun newInstance(link: MoviesDiscoverLink): MoviesSearchFragment {
val f = MoviesSearchFragment()
val args = Bundle()
args.putInt(ARG_ID_LINK, link.id)
f.arguments = args
return f
}
}
} | apache-2.0 | eec8a32bb9730faeb4d2eea50c091d5b | 34.355705 | 102 | 0.676666 | 5.463693 | false | false | false | false |
crunchersaspire/worshipsongs | app/src/main/java/org/worshipsongs/activity/DatabaseSettingActivity.kt | 3 | 13130 | package org.worshipsongs.activity
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.preference.PreferenceManager
import android.provider.OpenableColumns
import android.util.Log
import android.view.ContextThemeWrapper
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import org.apache.commons.io.FileUtils
import org.apache.commons.io.FilenameUtils
import org.worshipsongs.CommonConstants
import org.worshipsongs.R
import org.worshipsongs.WorshipSongApplication
import org.worshipsongs.fragment.AlertDialogFragment
import org.worshipsongs.locator.ImportDatabaseLocator
import org.worshipsongs.service.DatabaseService
import org.worshipsongs.service.PresentationScreenService
import org.worshipsongs.service.SongService
import org.worshipsongs.utils.PermissionUtils
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.*
/**
* @author Madasamy
* @version 3.x.
*/
class DatabaseSettingActivity : AbstractAppCompactActivity(), AlertDialogFragment.DialogListener
{
private val importDatabaseLocator = ImportDatabaseLocator()
private val songService = SongService(WorshipSongApplication.context!!)
private val databaseService = DatabaseService(WorshipSongApplication.context!!)
private val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(WorshipSongApplication.context)
private var presentationScreenService: PresentationScreenService? = null
private var defaultDatabaseButton: Button? = null
private var resultTextView: TextView? = null
val destinationFile: File
get() = File(cacheDir.absolutePath, CommonConstants.DATABASE_NAME)
val countQueryResult: String
get()
{
var count: String?
try
{
count = songService.count().toString()
} catch (e: Exception)
{
count = ""
}
return String.format(getString(R.string.songs_count), count)
}
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.database_layout)
setActionBar()
setImportDatabaseButton()
setDefaultDatabaseButton()
setResultTextView()
presentationScreenService = PresentationScreenService(this)
}
private fun setActionBar()
{
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setDisplayShowTitleEnabled(true)
supportActionBar!!.setTitle(R.string.database)
}
private fun setImportDatabaseButton()
{
val importDatabaseButton = findViewById<View>(R.id.upload_database_button) as Button
importDatabaseButton.setOnClickListener(ImportDatabaseOnClickListener())
}
private inner class ImportDatabaseOnClickListener : View.OnClickListener
{
override fun onClick(view: View)
{
if (PermissionUtils.isStoragePermissionGranted(this@DatabaseSettingActivity))
{
showDatabaseTypeDialog()
}
}
}
private fun showDatabaseTypeDialog()
{
val builder = AlertDialog.Builder(ContextThemeWrapper(this, R.style.DialogTheme))
builder.setTitle(getString(R.string.type))
builder.setItems(R.array.dataBaseTypes) { dialog, which ->
importDatabaseLocator.load(this@DatabaseSettingActivity, getStringObjectMap(which))
dialog.cancel()
}
val dialog = builder.create()
dialog.listView.setSelector(android.R.color.darker_gray)
dialog.show()
}
private fun getStringObjectMap(which: Int): Map<String, Any>
{
val objectMap = HashMap<String, Any>()
objectMap[CommonConstants.INDEX_KEY] = which
objectMap[CommonConstants.TEXTVIEW_KEY] = resultTextView!!
objectMap[CommonConstants.REVERT_DATABASE_BUTTON_KEY] = defaultDatabaseButton!!
return objectMap
}
private fun setDefaultDatabaseButton()
{
defaultDatabaseButton = findViewById<View>(R.id.default_database_button) as Button
defaultDatabaseButton!!.visibility = if (sharedPreferences.getBoolean(CommonConstants.SHOW_REVERT_DATABASE_BUTTON_KEY, false)) View.VISIBLE
else View.GONE
defaultDatabaseButton!!.setOnClickListener(DefaultDbOnClickListener())
}
private inner class DefaultDbOnClickListener : View.OnClickListener
{
override fun onClick(v: View)
{
val bundle = Bundle()
bundle.putString(CommonConstants.TITLE_KEY, getString(R.string.reset_default_title))
bundle.putString(CommonConstants.MESSAGE_KEY, getString(R.string.message_database_confirmation))
val alertDialogFragment = AlertDialogFragment.newInstance(bundle)
alertDialogFragment.setDialogListener(this@DatabaseSettingActivity)
alertDialogFragment.show(supportFragmentManager, "RevertDefaultDatabaseDialog")
}
}
private fun setResultTextView()
{
resultTextView = findViewById<View>(R.id.result_textview) as TextView
resultTextView!!.text = countQueryResult
}
override fun onOptionsItemSelected(item: MenuItem): Boolean
{
when (item.itemId)
{
android.R.id.home -> finish()
else ->
{
}
}
return true
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?)
{
when (requestCode)
{
1 -> if (resultCode == Activity.RESULT_OK)
{
val uri = intent!!.data
doCopyFile(uri, getFileName(uri!!))
}
else ->
{
}
}
super.onActivityResult(requestCode, resultCode, intent)
}
private fun doCopyFile(uri: Uri?, fileName: String)
{
try
{
val fileExtension = FilenameUtils.getExtension(fileName)
if ("sqlite".equals(fileExtension, ignoreCase = true))
{
showConfirmationDialog(uri!!, fileName)
} else
{
copyFile(uri)
}
} finally
{
destinationFile.deleteOnExit()
}
}
private fun showConfirmationDialog(uri: Uri, fileName: String)
{
val bundle = Bundle()
bundle.putString(CommonConstants.TITLE_KEY, getString(R.string.confirmation))
bundle.putString(CommonConstants.MESSAGE_KEY, String.format(getString(R.string.message_choose_local_db_confirmation), fileName))
bundle.putString(CommonConstants.NAME_KEY, uri.toString())
val alertDialogFragment = AlertDialogFragment.newInstance(bundle)
alertDialogFragment.setVisiblePositiveButton(true)
alertDialogFragment.setVisibleNegativeButton(true)
alertDialogFragment.setDialogListener(this)
alertDialogFragment.show(supportFragmentManager, "DatabaseImportConfirmation")
}
private fun copyFile(uri: Uri?)
{
try
{
val destinationFile = destinationFile
val inputStream = contentResolver.openInputStream(uri!!)
val outputstream = FileOutputStream(destinationFile)
val data = ByteArray(inputStream!!.available())
inputStream.read(data)
outputstream.write(data)
inputStream.close()
outputstream.close()
Log.i([email protected], "Size of file " + FileUtils.sizeOf(destinationFile))
validateDatabase(destinationFile.absolutePath)
} catch (ex: IOException)
{
Log.i(DatabaseSettingActivity::class.java.simpleName, "Error occurred while coping file$ex")
}
}
private fun getFileName(uri: Uri): String
{
val selectedFile = File(uri.toString())
var fileName = ""
if (uri.toString().startsWith("content://"))
{
var cursor: Cursor? = null
try
{
cursor = contentResolver.query(uri, null, null, null, null)
if (cursor != null && cursor.moveToFirst())
{
fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
}
} finally
{
cursor!!.close()
}
} else
{
fileName = selectedFile.name
}
return fileName
}
private fun validateDatabase(absolutePath: String)
{
try
{
resultTextView!!.text = ""
databaseService.close()
databaseService.copyDatabase(absolutePath, true)
databaseService.open()
if (songService.isValidDataBase)
{
updateResultTextview()
sharedPreferences.edit().putBoolean(CommonConstants.SHOW_REVERT_DATABASE_BUTTON_KEY, true).apply()
defaultDatabaseButton!!.visibility = if (sharedPreferences.getBoolean(CommonConstants.SHOW_REVERT_DATABASE_BUTTON_KEY, false)) View.VISIBLE
else View.GONE
Toast.makeText(this, R.string.import_database_successfull, Toast.LENGTH_SHORT).show()
} else
{
showWarningDialog()
}
} catch (e: IOException)
{
e.printStackTrace()
Log.i([email protected], "Error occurred while coping external db$e")
}
}
private fun updateResultTextview()
{
resultTextView!!.text = ""
resultTextView!!.text = countQueryResult
}
private fun showWarningDialog()
{
val bundle = Bundle()
bundle.putString(CommonConstants.TITLE_KEY, getString(R.string.warning))
bundle.putString(CommonConstants.MESSAGE_KEY, getString(R.string.message_database_invalid))
val alertDialogFragment = AlertDialogFragment.newInstance(bundle)
alertDialogFragment.setDialogListener(this)
alertDialogFragment.setVisibleNegativeButton(false)
alertDialogFragment.isCancelable = false
alertDialogFragment.show(supportFragmentManager, "InvalidLocalDbWaringDialog")
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray)
{
when (requestCode)
{
CommonConstants.STORAGE_PERMISSION_REQUEST_CODE ->
{
onRequestPermissionsResult(grantResults)
return
}
else ->
{
}
}
}
protected fun onRequestPermissionsResult(grantResults: IntArray)
{
if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
showDatabaseTypeDialog()
} else
{
Log.i(this.javaClass.simpleName, "Permission denied")
}
}
override fun onClickPositiveButton(bundle: Bundle?, tag: String?)
{
if ("DatabaseImportConfirmation".equals(tag, ignoreCase = true))
{
val uriString = bundle!!.getString(CommonConstants.NAME_KEY)
val uri = Uri.parse(uriString)
copyFile(uri)
} else if ("InvalidLocalDbWaringDialog".equals(tag, ignoreCase = true))
{
try
{
databaseService.close()
databaseService.copyDatabase("", true)
databaseService.open()
updateResultTextview()
} catch (e: IOException)
{
Log.e(DatabaseSettingActivity::class.java.simpleName, "Error", e)
}
} else if ("RevertDefaultDatabaseDialog".equals(tag, ignoreCase = true))
{
try
{
databaseService.close()
databaseService.copyDatabase("", true)
databaseService.open()
updateResultTextview()
sharedPreferences.edit().putBoolean(CommonConstants.SHOW_REVERT_DATABASE_BUTTON_KEY, false).apply()
defaultDatabaseButton!!.visibility = View.GONE
} catch (ex: IOException)
{
Log.e([email protected], "Error occurred while coping database $ex")
}
}
}
override fun onClickNegativeButton()
{
//Do nothing
}
override fun onResume()
{
super.onResume()
presentationScreenService!!.onResume()
}
override fun onPause()
{
super.onPause()
presentationScreenService!!.onPause()
}
override fun onStop()
{
super.onStop()
presentationScreenService!!.onStop()
}
}
| apache-2.0 | b25f7b1af8eaf51dd4b90fea7751596f | 32.494898 | 155 | 0.637091 | 5.298628 | false | false | false | false |
newbieandroid/AppBase | app/src/main/java/com/fuyoul/sanwenseller/helper/QiNiuHelper.kt | 1 | 4282 | package com.fuyoul.sanwenseller.helper
import android.content.Context
import android.text.TextUtils
import android.util.Log
import com.fuyoul.sanwenseller.bean.reshttp.ResHttpResult
import com.fuyoul.sanwenseller.bean.reshttp.ResQiNiuBean
import com.fuyoul.sanwenseller.configs.UrlInfo.GETIMGTOKEN
import com.fuyoul.sanwenseller.listener.HttpReqListener
import com.fuyoul.sanwenseller.listener.QiNiuUpLoadListener
import com.lzy.okgo.OkGo
import com.qiniu.android.common.AutoZone
import com.qiniu.android.common.Zone
import com.qiniu.android.storage.Configuration
import com.qiniu.android.storage.UpCancellationSignal
import com.qiniu.android.storage.UpProgressHandler
import com.qiniu.android.storage.UploadManager
import com.qiniu.android.storage.UploadOptions
/**
* Auther: chen
* Creat at: 2017\9\18 0018
* Desc:七牛上传
*/
object QiNiuHelper {
private var isCancle = false//控制是否终止上传图片T
private val uploadManager = UploadManager(Configuration.Builder()
.zone(AutoZone.autoZone)//自动识别上传区域
.chunkSize(512 * 1024) // 分片上传时,每片的大小。 默认256K
.putThreshhold(1024 * 1024) // 启用分片上传阀值。默认512K
.connectTimeout(10) // 链接超时。默认10秒
.useHttps(true) // 是否使用https上传域名
.responseTimeout(60) // 服务器响应超时。默认60秒
.build())
private var index = 0
private val result = ArrayList<ResQiNiuBean>()
private var token = ""
/**七牛多图上传**/
fun multQiNiuUpLoad(context: Context, localPath: List<String>, listener: QiNiuUpLoadListener) {
isCancle = false
if (TextUtils.isEmpty(token)) {
OkGo.get<ResHttpResult>(GETIMGTOKEN).execute(object : HttpReqListener(context) {
override fun reqOk(result: ResHttpResult) {
token = result.data.toString()
doUp(context, localPath, listener)
}
override fun withoutData(code: Int, msg: String) {
listener.error(msg)
}
override fun error(errorInfo: String) {
listener.error(errorInfo)
}
override fun onFinish() {
}
})
} else {
doUp(context, localPath, listener)
}
}
private fun doUp(context: Context, localPath: List<String>, listener: QiNiuUpLoadListener) {
uploadManager.put(localPath[index],
"${System.currentTimeMillis()}_${getFileName(localPath[index])}",
token,
{ s, info, jsonObject ->
Log.e("csl", "上传图片完成:$index")
if (info.isOK) {
info.error
val item = ResQiNiuBean()
item.key = s
item.info = info
item.res = jsonObject
result.add(item)
index++
if (index == localPath.size) {//全部图片上传完成
val data = ArrayList<ResQiNiuBean>()
data.addAll(result)
listener.complete(data)
stop()
} else {
multQiNiuUpLoad(context, localPath, listener)
}
} else {
stop()
listener.error(info.error)
}
},
UploadOptions(null, null, false,
UpProgressHandler { s, d ->
Log.e("csl", "上传进度:$d")
},
UpCancellationSignal { isCancle }))
}
private fun getFileName(filePath: String): String {
Log.e("csl", "上传图片地址:$filePath")
val array = filePath.split("/")
return array[array.size - 1]
}
fun stop() {
index = 0
result.clear()
isCancle = true
}
} | apache-2.0 | 69c7b68e41f823a2e00e0b180aa90bd0 | 26.493243 | 99 | 0.531711 | 4.586246 | false | false | false | false |
pronghorn-tech/server | src/main/kotlin/tech/pronghorn/server/HttpServerWorker.kt | 1 | 6098 | /*
* Copyright 2017 Pronghorn Technology LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tech.pronghorn.server
import tech.pronghorn.coroutines.core.CoroutineWorker
import tech.pronghorn.coroutines.core.Service
import tech.pronghorn.http.HttpResponseHeaderValuePair
import tech.pronghorn.http.protocol.StandardHttpResponseHeaders
import tech.pronghorn.plugins.concurrentSet.ConcurrentSetPlugin
import tech.pronghorn.server.bufferpools.OneUseByteBufferAllocator
import tech.pronghorn.server.bufferpools.ReusableBufferPoolManager
import tech.pronghorn.server.config.HttpServerConfig
import tech.pronghorn.server.requesthandlers.HttpRequestHandler
import tech.pronghorn.server.services.*
import tech.pronghorn.util.finder.*
import tech.pronghorn.util.ignoreException
import java.nio.ByteBuffer
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.Arrays
import java.util.HashMap
private class URLHandlerMapping(url: ByteArray,
internal val handler: HttpRequestHandler) : ByteBacked {
override val bytes = url
}
public open class HttpServerWorker(public val server: HttpServer,
private val config: HttpServerConfig) : CoroutineWorker() {
private val connections = ConcurrentSetPlugin.get<HttpServerConnection>()
private val connectionReadService = ConnectionReadService(this)
private val connectionCreationService = ServerConnectionCreationService(this)
private val httpRequestHandlerService = HttpRequestHandlerService(this)
private val responseWriterService = ResponseWriterService(this)
private val handlers = HashMap<String, URLHandlerMapping>()
private val gmt = ZoneId.of("GMT")
private val commonHeaderCache = calculateCommonHeaderCache()
private var latestDate = System.currentTimeMillis() / 1000
private var handlerFinder: ByteBackedFinder<URLHandlerMapping> = FinderGenerator.generateFinder(handlers.values.toTypedArray())
internal val commonHeaderSize = commonHeaderCache.size
internal val connectionBufferPool = ReusableBufferPoolManager(config.reusableBufferSize, config.useDirectByteBuffers)
internal val oneUseByteBufferAllocator = OneUseByteBufferAllocator(config.useDirectByteBuffers)
internal val connectionReadServiceQueueWriter = connectionReadService.getQueueWriter()
internal val responseWriterServiceQueueWriter = responseWriterService.getQueueWriter()
internal val httpRequestHandlerServiceQueueWriter = httpRequestHandlerService.getQueueWriter()
override val initialServices: List<Service> = listOf(
connectionReadService,
connectionCreationService,
httpRequestHandlerService,
responseWriterService
)
internal fun addConnection(connection: HttpServerConnection) {
connections.add(connection)
}
internal fun removeConnection(connection: HttpServerConnection) {
connections.remove(connection)
}
override fun onShutdown() {
if (connections.size > 0) {
logger.info { "Worker closing ${connections.size} connections" }
}
ignoreException {
connections.forEach { it.close("Server is shutting down.") }
}
}
private fun calculateCommonHeaderCache(): ByteArray {
val dateBytes = DateTimeFormatter.RFC_1123_DATE_TIME.format(ZonedDateTime.now(gmt)).toByteArray(Charsets.US_ASCII)
val dateHeader = HttpResponseHeaderValuePair(StandardHttpResponseHeaders.Date, dateBytes)
val serverHeader = HttpResponseHeaderValuePair(StandardHttpResponseHeaders.Server, config.serverName)
val bufferSize = (if (config.sendDateHeader) dateHeader.length else 0) + (if (config.sendServerHeader) serverHeader.length else 0)
val buffer = ByteBuffer.allocate(bufferSize)
if (config.sendServerHeader) {
serverHeader.writeHeader(buffer)
}
if (config.sendDateHeader) {
dateHeader.writeHeader(buffer)
}
return Arrays.copyOf(buffer.array(), buffer.capacity())
}
internal fun getCommonHeaders(): ByteArray {
if (config.sendDateHeader) {
val now = System.currentTimeMillis() / 1000
if (latestDate != now) {
latestDate = now
val dateBytes = DateTimeFormatter.RFC_1123_DATE_TIME.format(ZonedDateTime.now(gmt)).toByteArray(Charsets.US_ASCII)
val dateStart = commonHeaderCache.size - dateBytes.size - 2
var x = 0
while (x < dateBytes.size) {
commonHeaderCache[dateStart + x] = dateBytes[x]
x += 1
}
}
}
return commonHeaderCache
}
internal fun getHandler(urlBytes: ByteArray): HttpRequestHandler? = handlerFinder.find(urlBytes)?.handler
internal fun addUrlHandlers(newHandlers: Map<String, (HttpServerWorker) -> HttpRequestHandler>) {
newHandlers.forEach { (url, handlerGenerator) ->
val urlBytes = url.toByteArray(Charsets.US_ASCII)
val handler = handlerGenerator(this)
handlers.put(url, URLHandlerMapping(urlBytes, handler))
}
handlerFinder = FinderGenerator.generateFinder(handlers.values.toTypedArray())
}
internal fun removeUrlHandlers(urls: Collection<String>) {
urls.forEach { url ->
handlers.remove(url)
}
handlerFinder = FinderGenerator.generateFinder(handlers.values.toTypedArray())
}
}
| apache-2.0 | 623c802060b524ea3dd61655609bdadf | 41.943662 | 138 | 0.72368 | 4.894061 | false | true | false | false |
christophpickl/kpotpourri | spring4k/src/main/kotlin/com/github/christophpickl/kpotpourri/spring/SpringPropertiesLogger.kt | 1 | 2251 | package com.github.christophpickl.kpotpourri.spring
import mu.KotlinLogging
import org.springframework.core.env.ConfigurableEnvironment
import org.springframework.core.env.Environment
import org.springframework.core.env.MapPropertySource
class SpringPropertiesLogger(
private val springEnvironment: Environment
) {
companion object {
// sample to express "not contains term" in regexp: "^((?!term).)*\$"
val defaultExclusions = listOf(Regex(".*([Pp]assword).*"), Regex(".*([Ss]ecret).*"), Regex(".*(OAuth).*"))
}
private val log = KotlinLogging.logger {}
private val springPropertySourcePrefixForYamlFiles = "applicationConfig:"
fun logProperties(
inclusions: List<Regex> = emptyList(),
exclusions: List<Regex> = defaultExclusions
) {
val properties = fetchProperties(inclusions, exclusions)
log.info { "Spring Properties: (${inclusions.size} inclusions, ${exclusions.size} exclusions)" }
properties.forEach { (key, value) -> log.info { " $key => $value" } }
}
private fun fetchProperties(inclusions: List<Regex>, exclusions: List<Regex>): Map<String, Any> =
springEnvironment.listAllMapPropertySources()
.filter { it.name.startsWith(springPropertySourcePrefixForYamlFiles) }
.flatMap { it.propertyNames.toSet() }
.toSet()
.filter { propertyName -> exclusions.all { !it.matches(propertyName) } }
.filter { propertyName -> if (inclusions.isEmpty()) true else inclusions.any { regex -> propertyName.matches(regex) } }
.sorted()
.map { propertyName -> propertyName to (springEnvironment.getProperty(propertyName) ?: "null") }
.toList()
.toMap()
/**
* Unfortunately spring does not support accessing all keys/properties.
*
* https://stackoverflow.com/questions/23506471/spring-access-all-environment-properties-as-a-map-or-properties-object
*/
private fun Environment.listAllMapPropertySources(): List<MapPropertySource> {
val abstractEnvironment = this as? ConfigurableEnvironment ?: return emptyList()
return abstractEnvironment.propertySources.filterIsInstance<MapPropertySource>()
}
}
| apache-2.0 | a3656b354f84aae3f3275caac03961e4 | 42.288462 | 131 | 0.680586 | 4.584521 | false | true | false | false |
pixis/TraktTV | app/src/main/java/com/pixis/traktTV/screen_main/ShowsFragment.kt | 2 | 2995 | package com.pixis.traktTV.screen_main
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import com.pixis.traktTV.R
import com.pixis.traktTV.adapters.RecyclerListAdapter
import com.pixis.traktTV.base.BaseApplication
import com.pixis.traktTV.base.Repository
import com.pixis.traktTV.base.adapters.BaseViewHolder
import com.pixis.trakt_api.services_fanart.ShowImages
import com.pixis.trakt_api.services_trakt.models.Show
import com.squareup.picasso.Picasso
import io.reactivex.functions.Consumer
import javax.inject.Inject
class ShowsFragment: Fragment() {
@BindView(R.id.recyclerView)
lateinit var recyclerView: RecyclerView
lateinit var mAdapter: RecyclerListAdapter<Pair<Show, ShowImages>>
@Inject
lateinit var repo: Repository
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
return inflater.inflate(R.layout.activity_main_recyclerview, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
ButterKnife.bind(this, view)
(activity.applicationContext as BaseApplication).component.inject(this)
mAdapter = RecyclerListAdapter(ShowViewHolder(Picasso.with(activity)))
recyclerView.layoutManager = GridLayoutManager(activity, 2)
recyclerView.adapter = mAdapter
//TODO Move to presenter
repo.getTrendingShows().subscribe(getConsumer(), Consumer<Throwable>{ showError(it) })
mAdapter.clickObservable.subscribe {
Log.v("Click", "Click " + it.item.first.title + " - " + it.isLongClick)
}
}
fun getConsumer() = mAdapter.consumer //So we can mock this
fun showError(it: Throwable) {
Snackbar.make(activity.findViewById(R.id.coordinator_main_content), it.message.toString(), Snackbar.LENGTH_SHORT)
.setAction("Retry", {
}).show()
}
}
class ShowViewHolder(val picasso: Picasso): BaseViewHolder<Pair<Show, ShowImages>>() {
override val layoutId = R.layout.common_poster_summary
@BindView(R.id.imgMediaItem) lateinit var imgMediaItem: ImageView
@BindView(R.id.lblMediaTitle) lateinit var lblMediaTitle: TextView
override fun onBind(item: Pair<Show, ShowImages>) {
lblMediaTitle.text = item.first.title
if(item.second.tvposter.isNotEmpty()) {
picasso.load(item.second.tvposter.first().getPreviewUrl()).placeholder(android.R.color.darker_gray).fit().into(imgMediaItem)
}
else {
imgMediaItem.setImageResource(android.R.color.darker_gray)
}
}
} | apache-2.0 | 3eb9b5c0b0186d496eb005639d5530b4 | 36.924051 | 136 | 0.739566 | 4.171309 | false | false | false | false |
spark/photon-tinker-android | mesh/src/main/java/io/particle/mesh/bluetooth/connecting/BluetoothConnectionManager.kt | 1 | 7793 | package io.particle.mesh.bluetooth.connecting
import android.bluetooth.*
import android.bluetooth.le.ScanResult
import android.content.Context
import android.content.Intent
import androidx.annotation.MainThread
import androidx.lifecycle.LiveData
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import io.particle.mesh.bluetooth.BLELiveDataCallbacks
import io.particle.mesh.bluetooth.BTCharacteristicWriter
import io.particle.mesh.bluetooth.btAdapter
import io.particle.mesh.bluetooth.connecting.ConnectionState.DISCONNECTED
import io.particle.mesh.common.QATool
import io.particle.mesh.common.truthy
import io.particle.mesh.setup.connection.BT_SETUP_RX_CHARACTERISTIC_ID
import io.particle.mesh.setup.connection.BT_SETUP_SERVICE_ID
import io.particle.mesh.setup.connection.BT_SETUP_TX_CHARACTERISTIC_ID
import io.particle.mesh.setup.flow.DeviceTooFarException
import io.particle.mesh.setup.flow.FailedToScanBecauseOfTimeoutException
import io.particle.mesh.setup.flow.Scopes
import io.particle.mesh.setup.ui.utils.buildMatchingDeviceNameSuspender
import io.particle.mesh.setup.utils.checkIsThisTheMainThread
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.SendChannel
import mu.KotlinLogging
enum class ConnectionPriority(val sdkVal: Int) {
HIGH(1),
BALANCED(0),
LOW_POWER(2)
}
class BluetoothConnection(
private val connectionStateChangedLD: LiveData<ConnectionState?>,
private val gatt: BluetoothGatt,
private val callbacks: BLELiveDataCallbacks,
// this channel receives arbitrary-length arrays (not limited to BLE MTU)
val packetSendChannel: SendChannel<ByteArray>,
// this channel emits arbitrary-length arrays (not limited to BLE MTU)
private val closablePacketReceiveChannel: Channel<ByteArray>
) {
private val log = KotlinLogging.logger {}
init {
connectionStateChangedLD.observeForever {
if (it == DISCONNECTED) {
doDisconnect(false)
}
}
}
val deviceName: String
get() = gatt.device.name
val isConnected: Boolean
get() = connectionStateChangedLD.value == ConnectionState.CONNECTED
val packetReceiveChannel: ReceiveChannel<ByteArray>
get() = closablePacketReceiveChannel
fun setConnectionPriority(priority: ConnectionPriority) {
gatt.requestConnectionPriority(priority.sdkVal)
}
fun disconnect() {
doDisconnect(true)
}
private fun doDisconnect(needToDisconnect: Boolean = false) {
log.info { "doDisconnect(): needToDisconnect=$needToDisconnect, this.gatt=${this.gatt}" }
QATool.runSafely(
{ packetSendChannel.close() },
{ closablePacketReceiveChannel.close() },
{ callbacks.closeChannel() },
{
if (needToDisconnect) {
gatt.disconnect()
} else {
gatt.close()
}
}
)
}
}
typealias BTDeviceAddress = String
const val SCAN_TIMEOUT_MILLIS = 8000L
// FIXME: replace this with something elss hackish
const val FOUND_IN_SCAN_BROADCAST = "FOUND_IN_SCAN"
class BluetoothConnectionManager(private val ctx: Context) {
private val log = KotlinLogging.logger {}
@MainThread
suspend fun connectToDevice(
deviceName: String,
setupScopes: Scopes,
timeout: Long = SCAN_TIMEOUT_MILLIS
): Pair<BluetoothConnection, Scopes>? {
checkIsThisTheMainThread()
val newConnectionScopes = Scopes()
val scanResult = scanForDevice(deviceName, timeout, setupScopes) ?: return null
val address = if (scanResult.rssi < -80) {
throw DeviceTooFarException()
} else {
scanResult.device.address
}
LocalBroadcastManager.getInstance(ctx).sendBroadcast(Intent(FOUND_IN_SCAN_BROADCAST))
log.info { "Connecting to device $address" }
// 1. Attempt to connect
val device = ctx.btAdapter.getRemoteDevice(address)
// If this returns null, we're finished, return null ourselves
val (gatt, bleWriteChannel, callbacks) = doConnectToDevice(device, setupScopes) ?: return null
val messageWriteChannel = Channel<ByteArray>(Channel.UNLIMITED)
newConnectionScopes.backgroundScope.launch {
for (packet in messageWriteChannel) {
QATool.runSafely({ bleWriteChannel.writeToCharacteristic(packet) })
}
}
val conn = BluetoothConnection(
callbacks.connectionStateChangedLD,
gatt,
callbacks,
messageWriteChannel,
callbacks.readOrChangedReceiveChannel as Channel<ByteArray>
)
// this is the default, but ensure that the OS isn't remembering it from the
// previous connection to the device
conn.setConnectionPriority(ConnectionPriority.BALANCED)
return Pair(conn, newConnectionScopes)
}
private suspend fun scanForDevice(
deviceName: String,
timeout: Long,
scopes: Scopes
): ScanResult? {
log.info { "entering scanForDevice()" }
val scannerSuspender = buildMatchingDeviceNameSuspender(ctx, deviceName)
val scanResult = try {
scopes.withMain(timeout) { scannerSuspender.awaitResult() }
} catch (ex: Exception) {
null
} ?: throw FailedToScanBecauseOfTimeoutException()
log.info { "Address from scan result: ${scanResult.device.address}" }
return scanResult
}
private suspend fun doConnectToDevice(
device: BluetoothDevice,
scopes: Scopes
): Triple<BluetoothGatt, BTCharacteristicWriter, BLELiveDataCallbacks>? {
val gattConnectionCreator = GattConnector(ctx)
log.info { "Creating connection to device $device" }
val gattAndCallbacks = gattConnectionCreator.createGattConnection(device, scopes)
if (gattAndCallbacks == null) {
log.warn { "Got nothing back from connection creation attempt!!" }
return null
}
log.info { "Got GATT and callbacks!" }
val (gatt, callbacks) = gattAndCallbacks
val services = discoverServices(gatt, callbacks, scopes)
if (!services.truthy()) {
log.warn { "Service discovery failed!" }
return null
}
val writeCharacteristic = initCharacteristics(gatt)
if (writeCharacteristic == null) {
log.warn { "Error setting up BLE characteristics" }
return null
}
val bleWriteChannel = BTCharacteristicWriter(
gatt,
writeCharacteristic,
callbacks.onCharacteristicWriteCompleteLD
)
return Triple(gatt, bleWriteChannel, callbacks)
}
private suspend fun discoverServices(
gatt: BluetoothGatt,
btCallbacks: BLELiveDataCallbacks,
scopes: Scopes
): List<BluetoothGattService>? {
log.info { "Discovering services" }
val discoverer = ServiceDiscoverer(btCallbacks, gatt, scopes)
val services = discoverer.discoverServices()
log.debug { "Discovering services: DONE" }
return services
}
private fun initCharacteristics(gatt: BluetoothGatt): BluetoothGattCharacteristic? {
log.debug { "Initializing characteristics" }
val subscriber = CharacteristicSubscriber(
gatt,
BT_SETUP_SERVICE_ID,
BT_SETUP_RX_CHARACTERISTIC_ID,
BT_SETUP_TX_CHARACTERISTIC_ID
)
// return write characteristic
return subscriber.subscribeToReadAndReturnWrite()
}
}
| apache-2.0 | 01bae47e53b183f4675ba97a03a9e35c | 32.735931 | 102 | 0.677403 | 4.843381 | false | false | false | false |
wireapp/wire-android | storage/src/main/kotlin/com/waz/zclient/storage/db/users/migration/UserDatabase138To139Migration.kt | 1 | 2381 | @file:Suppress("MagicNumber")
package com.waz.zclient.storage.db.users.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
val USER_DATABASE_MIGRATION_138_TO_139 = object : Migration(138, 139) {
override fun migrate(database: SupportSQLiteDatabase) {
val previousTableName = "PushNotificationEvents"
val createTableEncrypted = """
CREATE TABLE IF NOT EXISTS EncryptedPushNotificationEvents(
pushId TEXT NOT NULL,
event_index INTEGER NOT NULL DEFAULT 0,
event TEXT NOT NULL DEFAULT '',
transient INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (pushId, event_index))
""".trimIndent()
val createTableDecrypted = """
CREATE TABLE IF NOT EXISTS DecryptedPushNotificationEvents(
pushId TEXT NOT NULL,
event_index INTEGER NOT NULL DEFAULT 0,
event TEXT NOT NULL DEFAULT '',
plain BLOB,
transient INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (pushId, event_index))
""".trimIndent()
val copyDecryptedFromPreviousTable = """
INSERT INTO DecryptedPushNotificationEvents(
pushId,
event_index,
event,
plain,
transient
)
SELECT
pushId,
event_index,
event,
plain,
transient
FROM $previousTableName
WHERE decrypted = 1
""".trimIndent()
val copyEncryptedFromPreviousTable = """
INSERT INTO EncryptedPushNotificationEvents(
pushId,
event_index,
event,
transient
)
SELECT
pushId,
event_index,
event,
transient
FROM $previousTableName
WHERE decrypted = 0
""".trimIndent()
with(database) {
execSQL(createTableEncrypted)
execSQL(createTableDecrypted)
if (com.waz.zclient.storage.db.MigrationUtils.tableExists(database, previousTableName)) {
execSQL(copyDecryptedFromPreviousTable)
execSQL(copyEncryptedFromPreviousTable)
execSQL("DROP TABLE $previousTableName")
}
}
}
}
| gpl-3.0 | 57be75624f2adaaf0014ab32b5ac439c | 33.014286 | 101 | 0.569089 | 5.655582 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl-integ-tests/src/integTest/kotlin/org/gradle/kotlin/dsl/integration/GradleApiExtensionsIntegrationTest.kt | 1 | 8701 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.integration
import org.gradle.api.DomainObjectCollection
import org.gradle.api.NamedDomainObjectCollection
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.Task
import org.gradle.api.tasks.Delete
import org.gradle.api.tasks.TaskCollection
import org.gradle.kotlin.dsl.fixtures.containsMultiLineString
import org.gradle.kotlin.dsl.support.normaliseLineSeparators
import org.gradle.test.fixtures.file.LeaksFileHandles
import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.CoreMatchers.not
import org.junit.Assert.assertThat
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
import java.util.jar.JarFile
class GradleApiExtensionsIntegrationTest : AbstractPluginIntegrationTest() {
@Test
fun `Kotlin chooses withType extension specialized to container type`() {
withBuildScript("""
open class A
open class B : A()
inline fun <reified T> inferredTypeOf(value: T) = typeOf<T>().toString()
task("test") {
doLast {
val ca = container(A::class)
val cb = ca.withType<B>()
println(inferredTypeOf(ca))
println(inferredTypeOf(cb))
val oca: DomainObjectCollection<A> = ca
val ocb = oca.withType<B>()
println(inferredTypeOf(oca))
println(inferredTypeOf(ocb))
val tt = tasks.withType<Task>()
val td = tt.withType<Delete>()
println(inferredTypeOf(tt))
println(inferredTypeOf(td))
}
}
""")
assertThat(
build("test", "-q").output,
containsMultiLineString("""
${NamedDomainObjectContainer::class.qualifiedName}<Build_gradle.A>
${NamedDomainObjectCollection::class.qualifiedName}<Build_gradle.B>
${DomainObjectCollection::class.qualifiedName}<Build_gradle.A>
${DomainObjectCollection::class.qualifiedName}<Build_gradle.B>
${TaskCollection::class.qualifiedName}<${Task::class.qualifiedName}>
${TaskCollection::class.qualifiedName}<${Delete::class.qualifiedName}>
""")
)
}
@Test
fun `can use Gradle API generated extensions in scripts`() {
withFile("init.gradle.kts", """
allprojects {
container(String::class)
}
""")
withDefaultSettings().appendText("""
sourceControl {
vcsMappings {
withModule("some:thing") {
from(GitVersionControlSpec::class) {
url = uri("")
}
}
}
}
""")
withBuildScript("""
container(String::class)
apply(from = "plugin.gradle.kts")
""")
withFile("plugin.gradle.kts", """
import org.apache.tools.ant.filters.ReplaceTokens
// Class<T> to KClass<T>
objects.property(Long::class)
// Groovy named arguments to vararg of Pair
fileTree("dir" to "src", "excludes" to listOf("**/ignore/**", "**/.data/**"))
// Class<T> + Action<T> to KClass<T> + T.() -> Unit
tasks.register("foo", Copy::class) {
from("src")
into("dst")
// Class<T> + Groovy named arguments to KClass<T> + vararg of Pair
filter(ReplaceTokens::class, "foo" to "bar")
}
""")
build("foo", "-I", "init.gradle.kts")
}
@Test
@LeaksFileHandles("Kotlin Compiler Daemon working directory")
fun `can use Gradle API generated extensions in buildSrc`() {
requireGradleDistributionOnEmbeddedExecuter()
withKotlinBuildSrc()
withFile("buildSrc/src/main/kotlin/foo/FooTask.kt", """
package foo
import org.gradle.api.*
import org.gradle.api.tasks.*
import org.gradle.kotlin.dsl.*
import org.apache.tools.ant.filters.ReplaceTokens
open class FooTask : DefaultTask() {
@TaskAction
fun foo() {
project.container(Long::class)
}
}
""")
withFile("buildSrc/src/main/kotlin/foo/foo.gradle.kts", """
package foo
tasks.register("foo", FooTask::class)
""")
withBuildScript("""
plugins {
id("foo.foo")
}
""")
build("foo")
}
@Test
fun `generated jar contains Gradle API extensions sources and byte code and is reproducible`() {
val guh = newDir("guh")
withBuildScript("")
executer.withGradleUserHomeDir(guh)
executer.requireIsolatedDaemons()
build("help")
val generatedJar = generatedExtensionsJarFromGradleUserHome(guh)
val (generatedSources, generatedClasses) = JarFile(generatedJar)
.use { it.entries().toList().map { entry -> entry.name } }
.filter { it.startsWith("org/gradle/kotlin/dsl/GradleApiKotlinDslExtensions") }
.groupBy { it.substring(it.lastIndexOf('.')) }
.let { it[".kt"]!! to it[".class"]!! }
assertTrue(generatedSources.isNotEmpty())
assertTrue(generatedClasses.size >= generatedSources.size)
val generatedSourceCode = JarFile(generatedJar).use { jar ->
generatedSources.joinToString("\n") { name ->
jar.getInputStream(jar.getJarEntry(name)).bufferedReader().use { it.readText() }
}
}
val extensions = listOf(
"package org.gradle.kotlin.dsl",
"""
inline fun <S : T, T : Any> org.gradle.api.DomainObjectSet<T>.`withType`(`type`: kotlin.reflect.KClass<S>): org.gradle.api.DomainObjectSet<S> =
`withType`(`type`.java)
""",
"""
inline fun org.gradle.api.tasks.AbstractCopyTask.`filter`(`filterType`: kotlin.reflect.KClass<out java.io.FilterReader>, vararg `properties`: Pair<String, Any?>): org.gradle.api.tasks.AbstractCopyTask =
`filter`(mapOf(*`properties`), `filterType`.java)
""",
"""
inline fun <T : org.gradle.api.Task> org.gradle.api.tasks.TaskContainer.`register`(`name`: String, `type`: kotlin.reflect.KClass<T>, `configurationAction`: org.gradle.api.Action<in T>): org.gradle.api.tasks.TaskProvider<T> =
`register`(`name`, `type`.java, `configurationAction`)
""",
"""
inline fun <T : Any> org.gradle.api.plugins.ExtensionContainer.`create`(`name`: String, `type`: kotlin.reflect.KClass<T>, vararg `constructionArguments`: Any): T =
`create`(`name`, `type`.java, *`constructionArguments`)
""",
"""
inline fun <T : org.gradle.api.Named> org.gradle.api.model.ObjectFactory.`named`(`type`: kotlin.reflect.KClass<T>, `name`: String): T =
`named`(`type`.java, `name`)
""")
assertThat(
generatedSourceCode,
allOf(extensions.map { containsString(it.normaliseLineSeparators().trimIndent()) })
)
assertThat(
generatedSourceCode,
not(containsString("\r"))
)
}
private
fun generatedExtensionsJarFromGradleUserHome(guh: File): File =
Regex("^\\d.*").let { startsWithDigit ->
guh.resolve("caches")
.listFiles { f -> f.isDirectory && f.name.matches(startsWithDigit) }
.single()
.resolve("generated-gradle-jars")
.listFiles { f -> f.isFile && f.name.startsWith("gradle-kotlin-dsl-extensions-") }
.single()
}
}
| apache-2.0 | 14565f823a9d9c43ada2274ea4a1dc14 | 34.084677 | 236 | 0.573612 | 4.796582 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/ide/idea/CargoConfigurationWizardStep.kt | 1 | 4168 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.idea
import com.intellij.ide.util.importProject.ProjectDescriptor
import com.intellij.ide.util.projectWizard.ModuleBuilder.ModuleConfigurationUpdater
import com.intellij.ide.util.projectWizard.ModuleWizardStep
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.module.Module
import com.intellij.openapi.options.ConfigurationException
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.layout.panel
import org.rust.cargo.CargoConstants
import org.rust.cargo.project.model.cargoProjects
import org.rust.cargo.project.settings.rustSettings
import org.rust.cargo.project.settings.ui.RustProjectSettingsPanel
import org.rust.cargo.toolchain.RustToolchain
import org.rust.ide.newProject.ui.RsNewProjectPanel
import org.rust.openapiext.pathAsPath
import javax.swing.JComponent
class CargoConfigurationWizardStep private constructor(
private val context: WizardContext,
private val projectDescriptor: ProjectDescriptor? = null
) : ModuleWizardStep() {
private val newProjectPanel = RsNewProjectPanel(showProjectTypeCheckbox = projectDescriptor == null)
override fun getComponent(): JComponent = panel {
newProjectPanel.attachTo(this)
}
override fun disposeUIResources() = Disposer.dispose(newProjectPanel)
override fun updateDataModel() {
val data = newProjectPanel.data
ConfigurationUpdater.data = data.settings
val projectBuilder = context.projectBuilder
if (projectBuilder is RsModuleBuilder) {
projectBuilder.configurationData = data
projectBuilder.addModuleConfigurationUpdater(ConfigurationUpdater)
} else {
projectDescriptor?.modules?.firstOrNull()?.addConfigurationUpdater(ConfigurationUpdater)
}
}
@Throws(ConfigurationException::class)
override fun validate(): Boolean {
newProjectPanel.validateSettings()
return true
}
private object ConfigurationUpdater : ModuleConfigurationUpdater() {
var data: RustProjectSettingsPanel.Data? = null
override fun update(module: Module, rootModel: ModifiableRootModel) {
val data = data
if (data != null) {
module.project.rustSettings.data = module.project.rustSettings.data.copy(
toolchain = data.toolchain,
explicitPathToStdlib = data.explicitPathToStdlib
)
}
// We don't use SDK, but let's inherit one to reduce the amount of
// "SDK not configured" errors
// https://github.com/intellij-rust/intellij-rust/issues/1062
rootModel.inheritSdk()
val contentEntry = rootModel.contentEntries.singleOrNull()
if (contentEntry != null) {
val manifest = contentEntry.file?.findChild(RustToolchain.CARGO_TOML)
if (manifest != null) {
module.project.cargoProjects.attachCargoProject(manifest.pathAsPath)
}
val projectRoot = contentEntry.file ?: return
val makeVfsUrl = { dirName: String -> FileUtil.join(projectRoot.url, dirName) }
CargoConstants.ProjectLayout.sources.map(makeVfsUrl).forEach {
contentEntry.addSourceFolder(it, /* test = */ false)
}
CargoConstants.ProjectLayout.tests.map(makeVfsUrl).forEach {
contentEntry.addSourceFolder(it, /* test = */ true)
}
contentEntry.addExcludeFolder(makeVfsUrl(CargoConstants.ProjectLayout.target))
}
}
}
companion object {
fun newProject(context: WizardContext) =
CargoConfigurationWizardStep(context, null)
fun importExistingProject(context: WizardContext, projectDescriptor: ProjectDescriptor) =
CargoConfigurationWizardStep(context, projectDescriptor)
}
}
| mit | 2e0e57965fdc5297b708252e6070440a | 39.862745 | 104 | 0.694098 | 5.171216 | false | true | false | false |
macrat/RuuMusic | app/src/main/java/jp/blanktar/ruumusic/view/FilerView.kt | 1 | 8267 | package jp.blanktar.ruumusic.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.os.Parcelable
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.util.AttributeSet
import android.view.ContextMenu
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import jp.blanktar.ruumusic.R
import jp.blanktar.ruumusic.util.RuuDirectory
import jp.blanktar.ruumusic.util.RuuFileBase
class FilerView(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {
val namespace = "http://ruumusic.blanktar.jp/view"
private val frame = LayoutInflater.from(context).inflate(R.layout.view_filer, this)
private val list = frame.findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.list)!!
private val adapter = Adapter()
private val layout = LinearLayoutManager(context)
init {
list.adapter = adapter
list.layoutManager = layout
list.addItemDecoration(DividerDecoration(context))
}
var parent: RuuDirectory? = null
set(x) {
val old = hasParent
field = x
when {
old && !hasParent -> adapter.notifyItemRemoved(0)
!old && hasParent -> adapter.notifyItemInserted(0)
old && hasParent -> adapter.notifyItemChanged(0)
}
}
val parentName: String?
get() {
try {
if (parent == RuuDirectory.rootDirectory(context)) {
return "/"
} else {
return parent?.name + "/"
}
} catch (e: RuuFileBase.NotFound) {
return null
}
}
val hasParent
get() = parent != null
var showPath = attrs.getAttributeBooleanValue(namespace, "show_path", false)
set(x) {
field = x
adapter.notifyItemRangeChanged(if (hasParent) 1 else 0, adapter.itemCount)
}
var files: List<RuuFileBase>? = null
private set
val hasContent
get() = (files?.size ?: 0) > 0
var loading = true
set(x) {
field = x
if (x) {
list.visibility = View.GONE
frame.findViewById<View>(R.id.progress).visibility = View.VISIBLE
} else {
frame.findViewById<View>(R.id.progress).visibility = View.GONE
list.visibility = View.VISIBLE
}
}
var onClickListener: ((RuuFileBase) -> Unit)? = { onEventListener?.onClick(it) }
var onLongClickListener: ((RuuFileBase, ContextMenu) -> Unit)? = { file, menu -> onEventListener?.onLongClick(file, menu) }
var onEventListener: OnEventListener? = null
fun changeFiles(files: List<RuuFileBase>, parent: RuuDirectory?) {
this.files = files
this.parent = parent
adapter.notifyDataSetChanged()
list.scrollToPosition(0)
loading = false
}
fun changeDirectory(dir: RuuDirectory) {
changeFiles(dir.children, if (RuuDirectory.rootDirectory(context) != dir) dir.parent else null)
}
var layoutState: Parcelable?
get() = layout.onSaveInstanceState()
set(state) = layout.onRestoreInstanceState(state!!)
inner class Adapter : androidx.recyclerview.widget.RecyclerView.Adapter<Adapter.ViewHolder>() {
val VIEWTYPE_NORMAL = 0
val VIEWTYPE_UPPER_DIR = 1
val VIEWTYPE_WITH_PATH = 2
override fun getItemViewType(position: Int) = when {
position == 0 && hasParent -> VIEWTYPE_UPPER_DIR
showPath -> VIEWTYPE_WITH_PATH
else -> VIEWTYPE_NORMAL
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): Adapter.ViewHolder {
val inflater = LayoutInflater.from(context)
val holder = when (viewType) {
VIEWTYPE_UPPER_DIR -> ViewHolder(inflater.inflate(R.layout.view_filer_upper, viewGroup, false))
VIEWTYPE_WITH_PATH -> ViewHolder(inflater.inflate(R.layout.view_filer_withpath, viewGroup, false))
else -> ViewHolder(inflater.inflate(R.layout.view_filer_item, viewGroup, false))
}
holder.itemView.setOnClickListener { _ ->
if (viewType == VIEWTYPE_UPPER_DIR) {
onClickListener?.invoke(parent!!)
} else {
files?.let {
try {
onClickListener?.invoke(it[holder.adapterPosition - if (hasParent) 1 else 0])
} catch (e: IndexOutOfBoundsException) {
}
}
}
}
holder.itemView.setOnCreateContextMenuListener { menu, _, _ ->
if (viewType == VIEWTYPE_UPPER_DIR) {
onLongClickListener?.invoke(parent!!, menu)
} else {
files?.let {
try {
onLongClickListener?.invoke(it[holder.adapterPosition - if (hasParent) 1 else 0], menu)
} catch (e: IndexOutOfBoundsException) {
}
}
}
}
return holder
}
override fun onBindViewHolder(holder: Adapter.ViewHolder, position: Int) {
if (holder.itemViewType == VIEWTYPE_UPPER_DIR) {
holder.text?.text = context.getString(R.string.upper_dir, parentName)
return
}
files?.let {
val item = it[position - if (hasParent) 1 else 0]
holder.name?.text = item.name + if (item.isDirectory) "/" else ""
try {
holder.path?.text = item.ruuPath
} catch (e: RuuFileBase.OutOfRootDirectory) {
holder.path?.text = ""
}
}
}
override fun getItemCount() = (files?.size ?: 0) + if (hasParent) 1 else 0
inner class ViewHolder(view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view) {
val name = view.findViewById<TextView?>(R.id.name)
val path = view.findViewById<TextView?>(R.id.path)
val text = view.findViewById<TextView?>(R.id.text)
}
}
class DividerDecoration(context: Context) : androidx.recyclerview.widget.RecyclerView.ItemDecoration() {
val divider = context.resources.getDrawable(R.drawable.view_filer_divider)!!
override fun onDraw(canvas: Canvas, parent: androidx.recyclerview.widget.RecyclerView, state: androidx.recyclerview.widget.RecyclerView.State) {
val left = parent.paddingLeft
val right = parent.width - parent.paddingRight
for (i in 0 until parent.childCount) {
val child = parent.getChildAt(i)
val params = child.layoutParams as androidx.recyclerview.widget.RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin
val bottom = top + divider.intrinsicHeight
divider.setBounds(left + ViewCompat.getTranslationX(child).toInt(),
top + ViewCompat.getTranslationY(child).toInt(),
right + ViewCompat.getTranslationX(child).toInt(),
bottom + ViewCompat.getTranslationY(child).toInt())
divider.alpha = (ViewCompat.getAlpha(child) * 255f).toInt()
divider.draw(canvas)
}
}
override fun getItemOffsets(rect: Rect, view: View, parent: androidx.recyclerview.widget.RecyclerView, state: androidx.recyclerview.widget.RecyclerView.State) {
rect.set(0, 0, 0, divider.intrinsicHeight)
}
}
abstract class OnEventListener {
abstract fun onClick(file: RuuFileBase)
abstract fun onLongClick(file: RuuFileBase, menu: ContextMenu)
}
}
| mit | 4c189d3cd4a2558915fcdb4a07749caa | 36.071749 | 168 | 0.583767 | 4.792464 | false | false | false | false |
google/horologist | media-sample/src/main/java/com/google/android/horologist/mediasample/ui/debug/MediaInfoTimeTextViewModel.kt | 1 | 3482 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.mediasample.ui.debug
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.android.horologist.media3.offload.AudioOffloadManager
import com.google.android.horologist.media3.offload.AudioOffloadStatus
import com.google.android.horologist.mediasample.domain.SettingsRepository
import com.google.android.horologist.networks.data.DataRequestRepository
import com.google.android.horologist.networks.data.DataUsageReport
import com.google.android.horologist.networks.data.NetworkType
import com.google.android.horologist.networks.data.Networks
import com.google.android.horologist.networks.highbandwidth.HighBandwidthNetworkMediator
import com.google.android.horologist.networks.status.NetworkRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
import kotlin.time.Duration.Companion.seconds
@HiltViewModel
class MediaInfoTimeTextViewModel @Inject constructor(
networkRepository: NetworkRepository,
dataRequestRepository: DataRequestRepository,
audioOffloadManager: AudioOffloadManager,
highBandwidthNetworkMediator: HighBandwidthNetworkMediator,
settingsRepository: SettingsRepository
) : ViewModel() {
val enabledFlow: Flow<Boolean> =
settingsRepository.settingsFlow.map { it.showTimeTextInfo }
val uiState = enabledFlow.flatMapLatest { enabled ->
if (enabled) {
combine(
networkRepository.networkStatus,
audioOffloadManager.offloadStatus,
dataRequestRepository.currentPeriodUsage(),
highBandwidthNetworkMediator.pinned
) { networkStatus, offloadStatus, currentPeriodUsage, pinnedNetworks ->
UiState(
enabled = enabled,
networks = networkStatus,
audioOffloadStatus = offloadStatus,
dataUsageReport = currentPeriodUsage,
pinnedNetworks = pinnedNetworks
)
}
} else {
flowOf(UiState())
}
}
.stateIn(
viewModelScope,
started = SharingStarted.WhileSubscribed(5.seconds.inWholeMilliseconds),
initialValue = UiState()
)
data class UiState(
val enabled: Boolean = false,
val networks: Networks = Networks(null, listOf()),
val audioOffloadStatus: AudioOffloadStatus? = null,
val dataUsageReport: DataUsageReport? = null,
val pinnedNetworks: Set<NetworkType> = setOf()
)
}
| apache-2.0 | 7b6d2918f51e7938c0cd5ccdfedf5791 | 39.964706 | 88 | 0.730615 | 4.988539 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/theme/UiColorMode.kt | 1 | 801 | package app.lawnchair.theme
@JvmInline
value class UiColorMode(val mode: Int) {
val isDarkTheme get() = (mode and FLAG_DARK) != 0
val isDarkText get() = (mode and FLAG_DARK_TEXT) != 0
val isDarkPrimaryColor get() = (mode and FLAG_DARK_PRIMARY_COLOR) != 0
companion object {
const val FLAG_DARK = 1 shl 0
const val FLAG_DARK_TEXT = 1 shl 1
const val FLAG_DARK_PRIMARY_COLOR = 1 shl 2
val Light = UiColorMode(0)
val Light_DarkText = UiColorMode(FLAG_DARK_TEXT)
val Light_DarkPrimaryColor = UiColorMode(FLAG_DARK_PRIMARY_COLOR)
val Dark = UiColorMode(FLAG_DARK)
val Dark_DarkText = UiColorMode(FLAG_DARK and FLAG_DARK_TEXT)
val Dark_DarkPrimaryColor = UiColorMode(FLAG_DARK and FLAG_DARK_PRIMARY_COLOR)
}
}
| gpl-3.0 | 8b6641da49f9c1201ac96c84b268e9ff | 33.826087 | 86 | 0.665418 | 3.575893 | false | false | false | false |
CarrotCodes/Warren | src/main/kotlin/chat/willow/warren/handler/rpl/Rpl475Handler.kt | 1 | 1213 | package chat.willow.warren.handler.rpl
import chat.willow.kale.IMetadataStore
import chat.willow.kale.KaleHandler
import chat.willow.kale.irc.message.rfc1459.rpl.Rpl475Message
import chat.willow.kale.irc.message.rfc1459.rpl.Rpl475MessageType
import chat.willow.warren.helper.loggerFor
import chat.willow.warren.state.CaseMappingState
import chat.willow.warren.state.JoiningChannelLifecycle
import chat.willow.warren.state.JoiningChannelsState
class Rpl475Handler(val channelsState: JoiningChannelsState, val caseMappingState: CaseMappingState) : KaleHandler<Rpl475MessageType>(Rpl475Message.Parser) {
private val LOGGER = loggerFor<Rpl475Handler>()
override fun handle(message: Rpl475MessageType, metadata: IMetadataStore) {
val channel = channelsState[message.channel]
if (channel == null) {
LOGGER.warn("got a bad key channel reply for a channel we don't think we're joining: $message")
LOGGER.trace("channels state: $channelsState")
return
}
LOGGER.warn("channel key wrong, failed to join: $channel")
channel.status = JoiningChannelLifecycle.FAILED
LOGGER.trace("new channels state: $channelsState")
}
}
| isc | b362ba202a45d7d8ece4f45950c39f90 | 35.757576 | 157 | 0.752679 | 4.271127 | false | false | false | false |
vase4kin/TeamCityApp | app/src/main/java/com/github/vase4kin/teamcityapp/changes/view/ChangesViewImpl.kt | 1 | 3806 | /*
* Copyright 2020 Andrey Tolpeev
*
* 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.github.vase4kin.teamcityapp.changes.view
import android.app.Activity
import android.view.View
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import com.github.vase4kin.teamcityapp.R
import com.github.vase4kin.teamcityapp.base.list.view.BaseListViewImpl
import com.github.vase4kin.teamcityapp.changes.api.Changes
import com.github.vase4kin.teamcityapp.changes.data.ChangesDataModel
import com.google.android.material.snackbar.Snackbar
import com.mugen.Mugen
import com.mugen.MugenCallbacks
import teamcityapp.features.change.view.ChangeActivity
/**
* Impl of [ChangesView]
*/
class ChangesViewImpl(
view: View,
activity: Activity,
@StringRes emptyMessage: Int,
adapter: ChangesAdapter
) : BaseListViewImpl<ChangesDataModel, ChangesAdapter>(view, activity, emptyMessage, adapter),
ChangesView {
private var loadMoreCallbacks: MugenCallbacks? = null
/**
* {@inheritDoc}
*/
override fun setLoadMoreListener(loadMoreCallbacks: MugenCallbacks) {
this.loadMoreCallbacks = loadMoreCallbacks
}
/**
* {@inheritDoc}
*/
override fun showData(dataModel: ChangesDataModel) {
Mugen.with(recyclerView, loadMoreCallbacks).start()
adapter.onChangeClickListener = this
adapter.dataModel = dataModel
recyclerView.adapter = adapter
adapter.notifyDataSetChanged()
}
/**
* {@inheritDoc}
*/
override fun addLoadMore() {
adapter.addLoadMore()
adapter.notifyDataSetChanged()
}
/**
* {@inheritDoc}
*/
override fun removeLoadMore() {
adapter.removeLoadMore()
adapter.notifyDataSetChanged()
}
/**
* {@inheritDoc}
*/
override fun addMoreBuilds(dataModel: ChangesDataModel) {
adapter.addMoreBuilds(dataModel)
adapter.notifyDataSetChanged()
}
/**
* {@inheritDoc}
*/
override fun showRetryLoadMoreSnackBar() {
val snackBar = Snackbar.make(
recyclerView,
R.string.load_more_retry_snack_bar_text,
Snackbar.LENGTH_LONG
)
.setAction(R.string.download_artifact_retry_snack_bar_retry_button) { loadMoreCallbacks!!.onLoadMore() }
snackBar.show()
}
/**
* {@inheritDoc}
*/
override fun onClick(change: Changes.Change) {
ChangeActivity.start(
activity = activity as AppCompatActivity,
commitName = change.comment,
userName = change.username,
date = change.date,
changeFileNames = change.files.file.map {
Pair<String, String>(
first = it.file,
second = it.changeType
)
},
version = change.version,
webUrl = change.webUrl,
changeId = change.getId()
)
}
/**
* {@inheritDoc}
*/
override fun replaceSkeletonViewContent() {
replaceSkeletonViewContent(R.layout.layout_skeleton_changes_list)
}
/**
* {@inheritDoc}
*/
override fun recyclerViewId(): Int {
return R.id.changes_recycler_view
}
}
| apache-2.0 | a2e2b4cafd92e93776604ff168b12121 | 27.192593 | 116 | 0.652128 | 4.525565 | false | false | false | false |
yyued/CodeX-UIKit-Android | library/src/main/java/com/yy/codex/uikit/UIKeyboardManager.kt | 1 | 2627 | package com.yy.codex.uikit
import android.app.Activity
import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver
import android.view.WindowManager
import com.yy.codex.foundation.NSLog
import com.yy.codex.foundation.NSNotificationCenter
/**
* Created by cuiminghui on 2017/2/6.
*/
class UIKeyboardManager(val activity: Activity) {
private var lastValue = 0.0
set(value) {
val oldValue = field
field = value
if (oldValue <= 0.0 && value > 0.0) {
NSNotificationCenter.defaultCenter.postNotification(UIKeyboardDidShowNotification, null, mapOf(
Pair(UIKeyboardFrameEndUserInfoKey, CGRect(0.0, UIScreen.mainScreen.bounds().height - value, UIScreen.mainScreen.bounds().width, value))
))
}
else if (oldValue > 0.0 && value <= 0.0) {
NSNotificationCenter.defaultCenter.postNotification(UIKeyboardDidHideNotification)
UIResponder.firstResponder?.resignFirstResponder()
}
else if (oldValue != value) {
NSNotificationCenter.defaultCenter.postNotification(UIKeyboardDidShowNotification, null, mapOf(
Pair(UIKeyboardFrameEndUserInfoKey, CGRect(0.0, UIScreen.mainScreen.bounds().height - value, UIScreen.mainScreen.bounds().width, value))
))
}
}
private var globalLayoutListener: Any? = null
internal fun registerListener() {
val rootView = activity.window.decorView.findViewById(android.R.id.content)
globalLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
val rect = Rect()
rootView.getWindowVisibleDisplayFrame(rect)
val heightDiff = rootView.bottom - rect.bottom
lastValue = (heightDiff.toFloat() / rootView.resources.displayMetrics.scaledDensity).toDouble()
}
rootView.viewTreeObserver.addOnGlobalLayoutListener(globalLayoutListener as ViewTreeObserver.OnGlobalLayoutListener)
}
internal fun unregisterListener() {
globalLayoutListener?.let {
val rootView = activity.window.decorView.findViewById(android.R.id.content)
rootView.viewTreeObserver.removeOnGlobalLayoutListener(it as ViewTreeObserver.OnGlobalLayoutListener)
}
}
companion object {
val UIKeyboardDidShowNotification = "UIKeyboardDidShowNotification"
val UIKeyboardDidHideNotification = "UIKeyboardDidHideNotification"
val UIKeyboardFrameEndUserInfoKey = "UIKeyboardFrameEndUserInfoKey"
}
} | gpl-3.0 | 1671edf857f9767d66ed070a28ad1a87 | 40.0625 | 160 | 0.685192 | 5.00381 | false | false | false | false |
danfma/kodando | kodando-mithril/src/main/kotlin/kodando/mithril/Builder.kt | 1 | 920 | package kodando.mithril
import kotlin.reflect.KClass
fun root(applier: Applier<Props>): VNode<*>? {
val props = createProps(applier)
return props.children.firstOrNull()
}
fun Props.addChild(vararg children: VNode<*>?) {
if (this.children === undefined) {
this.children = children
} else {
this.children += children
}
}
fun <TViewProps : Props> Props.addChild(view: View<TViewProps>, applier: Applier<TViewProps>) {
addChild(
createElement(view, createProps(applier))
)
}
fun <TViewProps : Props> Props.addChild(viewClass: JsClass<out View<TViewProps>>, applier: Applier<TViewProps>) {
addChild(
createElement(viewClass, createProps(applier))
)
}
fun <TViewProps : Props> Props.addChild(viewClass: KClass<out View<TViewProps>>, applier: Applier<TViewProps>) {
addChild(viewClass.js, applier)
}
fun Props.content(text: Any?) {
addChild("$text".unsafeCast<VNode<Nothing>>())
}
| mit | 8de9c9c4f775dc807fbf42a41a0833c6 | 23.864865 | 113 | 0.713043 | 3.432836 | false | false | false | false |
alashow/music-android | modules/base-android/src/main/java/tm/alashow/base/util/Toasts.kt | 1 | 892 | /*
* Copyright (C) 2019, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.base.util
import android.content.Context
import android.view.Gravity
import android.widget.Toast
import androidx.annotation.StringRes
/**
* Display the simple Toast message with the [Toast.LENGTH_SHORT] duration.
*
* @param message the message text.
*/
fun Context.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT, block: Toast.() -> Unit = {}): Toast = Toast
.makeText(this, message, Toast.LENGTH_SHORT)
.apply {
block(this)
show()
}
fun Context.toast(@StringRes messageRes: Int, duration: Int = Toast.LENGTH_SHORT, block: Toast.() -> Unit = {}) = toast(getString(messageRes), duration, block)
fun Context.centeredToast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
toast(message) {
setGravity(Gravity.CENTER, 0, 0)
}
}
| apache-2.0 | 503676c785952d9be3e79f04fbf144c4 | 28.733333 | 159 | 0.696188 | 3.763713 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/AnkiFont.kt | 1 | 5854 | //noinspection MissingCopyrightHeader #8659
package com.ichi2.anki
import android.content.Context
import android.graphics.Typeface
import com.ichi2.libanki.Utils
import timber.log.Timber
import java.io.File
import java.lang.RuntimeException
import java.lang.StringBuilder
import java.util.*
class AnkiFont private constructor(val name: String, private val family: String, private val attributes: List<String>, val path: String) {
private var mIsDefault = false
private var mIsOverride = false
val declaration: String
get() = "@font-face {" + getCSS(false) + " src: url(\"file://" + path + "\");}"
fun getCSS(override: Boolean): String {
val sb = StringBuilder("font-family: \"").append(family)
if (override) {
sb.append("\" !important;")
} else {
sb.append("\";")
}
for (attr in attributes) {
sb.append(" ").append(attr)
if (override) {
if (sb[sb.length - 1] == ';') {
sb.deleteCharAt(sb.length - 1)
sb.append(" !important;")
} else {
Timber.d("AnkiFont.getCSS() - unable to set a font attribute important while override is set.")
}
}
}
return sb.toString()
}
private fun setAsDefault() {
mIsDefault = true
mIsOverride = false
}
private fun setAsOverride() {
mIsOverride = true
mIsDefault = false
}
companion object {
private const val fAssetPathPrefix = "/android_asset/fonts/"
private val corruptFonts: MutableSet<String> = HashSet()
/**
* Factory for AnkiFont creation. Creates a typeface wrapper from a font file representing.
*
* @param ctx Activity context, needed to access assets
* @param filePath Path to typeface file, needed when this is a custom font.
* @param fromAssets True if the font is to be found in assets of application
* @return A new AnkiFont object or null if the file can't be interpreted as typeface.
*/
fun createAnkiFont(ctx: Context, filePath: String, fromAssets: Boolean): AnkiFont? {
val fontFile = File(filePath)
val path = if (fromAssets) {
fAssetPathPrefix + fontFile.name
} else {
filePath
}
val name = Utils.splitFilename(fontFile.name)[0]
var family = name
val attributes: MutableList<String> = ArrayList(2)
val tf = getTypeface(ctx, path) // unable to create typeface
?: return null
if (tf.isBold || name.lowercase().contains("bold")) {
attributes.add("font-weight: bolder;")
family = family.replaceFirst("(?i)-?Bold".toRegex(), "")
} else if (name.lowercase().contains("light")) {
attributes.add("font-weight: lighter;")
family = family.replaceFirst("(?i)-?Light".toRegex(), "")
} else {
attributes.add("font-weight: normal;")
}
if (tf.isItalic || name.lowercase().contains("italic")) {
attributes.add("font-style: italic;")
family = family.replaceFirst("(?i)-?Italic".toRegex(), "")
} else if (name.lowercase().contains("oblique")) {
attributes.add("font-style: oblique;")
family = family.replaceFirst("(?i)-?Oblique".toRegex(), "")
} else {
attributes.add("font-style: normal;")
}
if (name.lowercase().contains("condensed") || name.lowercase().contains("narrow")) {
attributes.add("font-stretch: condensed;")
family = family.replaceFirst("(?i)-?Condensed".toRegex(), "")
family = family.replaceFirst("(?i)-?Narrow(er)?".toRegex(), "")
} else if (name.lowercase().contains("expanded") || name.lowercase().contains("wide")) {
attributes.add("font-stretch: expanded;")
family = family.replaceFirst("(?i)-?Expanded".toRegex(), "")
family = family.replaceFirst("(?i)-?Wide(r)?".toRegex(), "")
}
val createdFont = AnkiFont(name, family, attributes, path)
// determine if override font or default font
val preferences = AnkiDroidApp.getSharedPrefs(ctx)
val defaultFont = preferences.getString("defaultFont", "")
val overrideFont = "1" == preferences.getString("overrideFontBehavior", "0")
if (defaultFont.equals(name, ignoreCase = true)) {
if (overrideFont) {
createdFont.setAsOverride()
} else {
createdFont.setAsDefault()
}
}
return createdFont
}
fun getTypeface(ctx: Context, path: String): Typeface? {
return try {
if (path.startsWith(fAssetPathPrefix)) {
Typeface.createFromAsset(ctx.assets, path.replaceFirst("/android_asset/".toRegex(), ""))
} else {
Typeface.createFromFile(path)
}
} catch (e: RuntimeException) {
Timber.w(e, "Runtime error in getTypeface for File: %s", path)
if (!corruptFonts.contains(path)) {
// Show warning toast
val name = File(path).name
val res = AnkiDroidApp.appResources
UIUtils.showThemedToast(ctx, res.getString(R.string.corrupt_font, name), false)
// Don't warn again in this session
corruptFonts.add(path)
}
null
}
}
}
}
| gpl-3.0 | eb2a48a4ed0c1da039d1009da1d15c12 | 41.42029 | 138 | 0.543731 | 4.778776 | false | false | false | false |
NooAn/bytheway | app/src/test/java/ru/a1024bits/bytheway/viewmodel/DisplayUsersViewModelTest.kt | 1 | 7616 | package ru.a1024bits.bytheway.viewmodel
import android.util.Log
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import ru.a1024bits.bytheway.model.User
import ru.a1024bits.bytheway.repository.Filter
import ru.a1024bits.bytheway.util.Constants.END_DATE
import ru.a1024bits.bytheway.util.Constants.FIRST_INDEX_CITY
import ru.a1024bits.bytheway.util.Constants.LAST_INDEX_CITY
import ru.a1024bits.bytheway.util.Constants.START_DATE
import java.util.*
private val AGE_PARAMETER = "age"
private val PHONE_PARAMETER = "phone"
private val EMAIL_PARAMETER = "email"
private val LAST_NAME_PARAMETER = "lastName"
private val NAME_PARAMETER = "name"
private val BUDGET_PARAMETER = "budget"
@RunWith(JUnit4::class)
class DisplayUsersViewModelTest {
private lateinit var displayUsersViewModel: DisplayUsersViewModel
val countAllUsers = 50
val countSimilarUsers = 5
@Before
fun initialize() {
displayUsersViewModel = DisplayUsersViewModel(null)
Log.d("testing", "start fun \"initialize\" in DisplayUsersViewModelTest(junit)")
}
@Test
fun testFilterUsersByFilters() {
var filter = Filter()
var filtrationValue = "15"
filter.startAge = filtrationValue.toInt() - 1
filter.endAge = filtrationValue.toInt() + 1
var usersForFilterFiltration = generateUsersForFiltration(countAllUsers, countSimilarUsers, AGE_PARAMETER, filtrationValue)
displayUsersViewModel.filterUsersByOptions(usersForFilterFiltration, filter)
Assert.assertEquals(usersForFilterFiltration.size, countSimilarUsers)
filter = Filter()
filtrationValue = "13232"
filter.startBudget = filtrationValue.toInt() - 1
filter.endBudget = filtrationValue.toInt() + 1
usersForFilterFiltration = generateUsersForFiltration(countAllUsers, countSimilarUsers, BUDGET_PARAMETER, filtrationValue)
displayUsersViewModel.filterUsersByOptions(usersForFilterFiltration, filter)
Assert.assertEquals(usersForFilterFiltration.size, countSimilarUsers)
filter = Filter()
filtrationValue = Calendar.getInstance().timeInMillis.toString()
filter.endDate = filtrationValue.toLong() + 10
usersForFilterFiltration = generateUsersForFiltration(countAllUsers, countSimilarUsers, END_DATE, filtrationValue)
displayUsersViewModel.filterUsersByOptions(usersForFilterFiltration, filter)
Assert.assertEquals(usersForFilterFiltration.size, countSimilarUsers)
filter = Filter()
filtrationValue = Calendar.getInstance().timeInMillis.toString()
filter.startDate = filtrationValue.toLong() - 10
usersForFilterFiltration = generateUsersForFiltration(countAllUsers, countSimilarUsers, START_DATE, filtrationValue)
displayUsersViewModel.filterUsersByOptions(usersForFilterFiltration, filter)
Assert.assertEquals(usersForFilterFiltration.size, countSimilarUsers)
filter = Filter()
filtrationValue = "CityOne"
filter.startCity = filtrationValue
usersForFilterFiltration = generateUsersForFiltration(countAllUsers, countSimilarUsers, FIRST_INDEX_CITY, filtrationValue)
displayUsersViewModel.filterUsersByOptions(usersForFilterFiltration, filter)
Assert.assertEquals(usersForFilterFiltration.size, countSimilarUsers)
filter = Filter()
filtrationValue = "CityTwo"
filter.endCity = filtrationValue
usersForFilterFiltration = generateUsersForFiltration(countAllUsers, countSimilarUsers, LAST_INDEX_CITY, filtrationValue)
displayUsersViewModel.filterUsersByOptions(usersForFilterFiltration, filter)
Assert.assertEquals(usersForFilterFiltration.size, countSimilarUsers)
}
@Test
fun testFilterUsersByStringInRandomVariable() {
var queryStringFiltration = "ExampleName"
var variableName = NAME_PARAMETER
Assert.assertEquals(displayUsersViewModel.filterUsersByString(
queryStringFiltration, generateUsersForFiltration(countAllUsers, countSimilarUsers, variableName, queryStringFiltration)
).size, countSimilarUsers)
variableName = EMAIL_PARAMETER
queryStringFiltration = "[email protected]"
Assert.assertEquals(displayUsersViewModel.filterUsersByString(
queryStringFiltration, generateUsersForFiltration(countAllUsers, countSimilarUsers, variableName, queryStringFiltration)
).size, countSimilarUsers)
variableName = AGE_PARAMETER
queryStringFiltration = "17"
Assert.assertEquals(displayUsersViewModel.filterUsersByString(
queryStringFiltration, generateUsersForFiltration(countAllUsers, countSimilarUsers, variableName, queryStringFiltration)
).size, countSimilarUsers)
variableName = LAST_NAME_PARAMETER
queryStringFiltration = "ExampleLastName"
Assert.assertEquals(displayUsersViewModel.filterUsersByString(
queryStringFiltration, generateUsersForFiltration(countAllUsers, countSimilarUsers, variableName, queryStringFiltration)
).size, countSimilarUsers)
variableName = PHONE_PARAMETER
queryStringFiltration = "380123456789"
Assert.assertEquals(displayUsersViewModel.filterUsersByString(
queryStringFiltration, generateUsersForFiltration(countAllUsers, countSimilarUsers, variableName, queryStringFiltration)
).size, countSimilarUsers)
variableName = FIRST_INDEX_CITY
queryStringFiltration = "CityFirst"
Assert.assertEquals(displayUsersViewModel.filterUsersByString(
queryStringFiltration, generateUsersForFiltration(countAllUsers, countSimilarUsers, variableName, queryStringFiltration)
).size, countSimilarUsers)
variableName = LAST_INDEX_CITY
queryStringFiltration = "CityLast"
Assert.assertEquals(displayUsersViewModel.filterUsersByString(
queryStringFiltration, generateUsersForFiltration(countAllUsers, countSimilarUsers, variableName, queryStringFiltration)
).size, countSimilarUsers)
}
private fun generateUsersForFiltration(countAllUsers: Int, countSimilarUsers: Int, currentFiltrationVariable: String, valueFiltrationVariable: String): MutableList<User> {
val originalUsers = ArrayList<User>()
for (i in 0 until countSimilarUsers) {
val currentUser = User()
when (currentFiltrationVariable) {
AGE_PARAMETER -> currentUser.age = valueFiltrationVariable.toInt()
PHONE_PARAMETER -> currentUser.phone = valueFiltrationVariable
EMAIL_PARAMETER -> currentUser.email = valueFiltrationVariable
LAST_NAME_PARAMETER -> currentUser.lastName = valueFiltrationVariable
FIRST_INDEX_CITY -> currentUser.cities[FIRST_INDEX_CITY] = valueFiltrationVariable
LAST_INDEX_CITY -> currentUser.cities[LAST_INDEX_CITY] = valueFiltrationVariable
NAME_PARAMETER -> currentUser.name = valueFiltrationVariable
BUDGET_PARAMETER -> currentUser.budget = valueFiltrationVariable.toLong()
END_DATE -> currentUser.dates[END_DATE] = valueFiltrationVariable.toLong()
START_DATE -> currentUser.dates[START_DATE] = valueFiltrationVariable.toLong()
}
originalUsers.add(currentUser)
}
for (i in 0 until countAllUsers - countSimilarUsers) originalUsers.add(User())
return originalUsers
}
} | mit | 31008c1ec50b69a789fd6a0989509af5 | 49.78 | 175 | 0.741203 | 4.464244 | false | true | false | false |
tipsy/javalin | javalin/src/main/java/io/javalin/http/util/RedirectToLowercasePathPlugin.kt | 1 | 3902 | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin.http.util
import io.javalin.Javalin
import io.javalin.core.PathParser
import io.javalin.core.plugin.Plugin
import io.javalin.core.plugin.PluginLifecycleInit
import io.javalin.core.routing.PathSegment
import io.javalin.http.HandlerType
import java.util.*
/**
* This plugin redirects requests with uppercase/mixcase paths to lowercase paths
* Ex: `/Users/John` -> `/users/John` (if endpoint is `/users/{userId}`)
* It does not affect the casing of path-params and query-params, only static
* URL fragments ('Users' becomes 'users' above, but 'John' remains 'John').
* When using this plugin, you can only add paths with lowercase URL fragments.
*/
class RedirectToLowercasePathPlugin : Plugin, PluginLifecycleInit {
override fun init(app: Javalin) {
app.events { e ->
e.handlerAdded { h ->
val parser = PathParser(h.path, app._conf.ignoreTrailingSlashes)
parser.segments.filterIsInstance<PathSegment.Normal>().map { it.content }.forEach {
if (it != it.lowercase(Locale.ROOT)) throw IllegalArgumentException("Paths must be lowercase when using RedirectToLowercasePathPlugin")
}
parser.segments
.filterIsInstance<PathSegment.MultipleSegments>()
.flatMap { it.innerSegments }
.filterIsInstance<PathSegment.Normal>()
.map { it.content }
.forEach {
if (it != it.lowercase(Locale.ROOT)) {
throw IllegalArgumentException("Paths must be lowercase when using RedirectToLowercasePathPlugin")
}
}
}
}
}
override fun apply(app: Javalin) {
app.before { ctx ->
val type = HandlerType.fromServletRequest(ctx.req)
val requestUri = ctx.req.requestURI.removePrefix(ctx.req.contextPath)
val matcher = app.javalinServlet().matcher
matcher.findEntries(type, requestUri).firstOrNull()?.let {
return@before // we found a route for this case, no need to redirect
}
matcher.findEntries(type, requestUri.lowercase(Locale.ROOT)).firstOrNull()?.let { entry ->
val clientSegments = requestUri.split("/").filter { it.isNotEmpty() }.toTypedArray()
val serverSegments = PathParser(entry.path, app._conf.ignoreTrailingSlashes).segments
serverSegments.forEachIndexed { i, serverSegment ->
if (serverSegment is PathSegment.Normal) {
clientSegments[i] = clientSegments[i].lowercase(Locale.ROOT) // this is also a "Normal" segment
}
if (serverSegment is PathSegment.MultipleSegments) {
serverSegments.forEach { innerServerSegment ->
if (innerServerSegment is PathSegment.Normal) {
// replace the non lowercased part of the segment with the lowercased version
clientSegments[i] = clientSegments[i].replace(
innerServerSegment.content,
innerServerSegment.content.lowercase(Locale.ROOT),
ignoreCase = true
)
}
}
}
}
val lowercasePath =
"/" + clientSegments.joinToString("/") + if (ctx.queryString() != null) "?" + ctx.queryString() else ""
ctx.redirect(lowercasePath, 301)
}
}
}
}
| apache-2.0 | ce6f97db75634d7db9d6709aa06430c1 | 46 | 155 | 0.573699 | 5.040052 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/view/adapter/ChatSearchTabAdapter.kt | 1 | 1972 | /*
* Copyright (c) 2017. Toshi Inc
*
* 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.toshi.view.adapter
import android.content.Context
import android.support.v4.view.PagerAdapter
import android.view.View
import android.view.ViewGroup
import com.toshi.model.local.User
import com.toshi.view.custom.ChatSearchView
class ChatSearchTabAdapter(
private val context: Context,
private val tabs: List<String>,
private val onItemUpdatedListener: (Int) -> Unit,
private val onUserClickedListener: (User) -> Unit
) : PagerAdapter() {
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val view = ChatSearchView(context)
view.onUserClickListener = onUserClickedListener
view.id = position
container.addView(view)
onItemUpdatedListener(position)
return view
}
override fun isViewFromObject(view: View, any: Any): Boolean {
return view == any
}
override fun destroyItem(container: ViewGroup, position: Int, any: Any) {
val view = any as? View ?: return
container.removeView(view)
}
override fun getCount(): Int = tabs.size
override fun getPageTitle(position: Int): CharSequence {
return if (position > tabs.size) return ""
else tabs[position]
}
} | gpl-3.0 | f01b39c92afd27ca832dabe6cb9f5262 | 33.017241 | 77 | 0.690669 | 4.343612 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/util/GeoUri.kt | 1 | 1226 | package de.westnordost.streetcomplete.util
import android.net.Uri
import androidx.core.net.toUri
import de.westnordost.streetcomplete.ktx.format
fun parseGeoUri(uri: Uri): GeoLocation? {
if (uri.scheme != "geo") return null
val geoUriRegex = Regex("(-?[0-9]*\\.?[0-9]+),(-?[0-9]*\\.?[0-9]+).*?(?:\\?z=([0-9]*\\.?[0-9]+))?")
val match = geoUriRegex.matchEntire(uri.schemeSpecificPart) ?: return null
val latitude = match.groupValues[1].toDoubleOrNull() ?: return null
if (latitude < -90 || latitude > +90) return null
val longitude = match.groupValues[2].toDoubleOrNull() ?: return null
if (longitude < -180 && longitude > +180) return null
// zoom is optional. If it is invalid, we treat it the same as if it is not there
val zoom = match.groupValues[3].toFloatOrNull()
return GeoLocation(latitude, longitude, zoom)
}
fun buildGeoUri(latitude: Double, longitude: Double, zoom: Float? = null): Uri {
val z = if (zoom != null) "?z=$zoom" else ""
val lat = latitude.format(5)
val lon = longitude.format(5)
val geoUri = "geo:$lat,$lon$z"
return geoUri.toUri()
}
data class GeoLocation(
val latitude: Double,
val longitude: Double,
val zoom: Float?
)
| gpl-3.0 | 317cf4607a6dc37fa1dc60db088efe40 | 33.055556 | 103 | 0.659054 | 3.543353 | false | false | false | false |
CajetanP/coding-exercises | Others/Kotlin/kotlin-koans/src/ii_collections/n21Partition.kt | 1 | 545 | package ii_collections
fun example8() {
val numbers = listOf(1, 3, -4, 2, -11)
// The details (how multi-assignment works) will be explained later in the 'Conventions' task
val (positive, negative) = numbers.partition { it > 0 }
positive == listOf(1, 3, 2)
negative == listOf(-4, -11)
}
fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set<Customer> {
return this.customers
.partition { it.orders.count { !it.isDelivered } > it.orders.count { it.isDelivered } }
.first.toSet()
}
| mit | feaad6eeafe2fedd2260a84f2e703f0c | 31.058824 | 99 | 0.653211 | 3.732877 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/model/WCProductImageModel.kt | 2 | 1209 | package org.wordpress.android.fluxc.model
import com.google.gson.JsonObject
import org.wordpress.android.fluxc.utils.DateUtils
class WCProductImageModel(val id: Long) {
var dateCreated: String = ""
var src: String = ""
var alt: String = ""
var name: String = ""
companion object {
fun fromMediaModel(media: MediaModel): WCProductImageModel {
with(WCProductImageModel(media.mediaId)) {
dateCreated = media.uploadDate ?: DateUtils.getCurrentDateString()
src = media.url ?: ""
alt = media.alt ?: ""
name = media.fileName ?: ""
return this
}
}
}
fun toJson(): JsonObject {
return JsonObject().also { json ->
json.addProperty("id", id)
// If id == 0 then the variation image has been deleted. Don't include the other
// fields or this delete request will fail.
if (id > 0) {
json.addProperty("date_created", dateCreated)
json.addProperty("src", src)
json.addProperty("alt", alt)
json.addProperty("name", name)
}
}
}
}
| gpl-2.0 | 9bbabed1255d8cf12640c7857bc3895b | 31.675676 | 92 | 0.550041 | 4.797619 | false | false | false | false |
ratabb/Hishoot2i | app/src/main/java/org/illegaller/ratabb/hishoot2i/ui/tools/screen/ScreenTool.kt | 1 | 2351 | package org.illegaller.ratabb.hishoot2i.ui.tools.screen
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.setFragmentResult
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import common.ext.preventMultipleClick
import dagger.hilt.android.AndroidEntryPoint
import org.illegaller.ratabb.hishoot2i.data.pref.ScreenToolPref
import org.illegaller.ratabb.hishoot2i.databinding.FragmentToolScreenBinding
import org.illegaller.ratabb.hishoot2i.ui.ARG_SCREEN1_PATH
import org.illegaller.ratabb.hishoot2i.ui.ARG_SCREEN2_PATH
import org.illegaller.ratabb.hishoot2i.ui.KEY_REQ_SCREEN_1
import org.illegaller.ratabb.hishoot2i.ui.KEY_REQ_SCREEN_2
import org.illegaller.ratabb.hishoot2i.ui.common.registerGetContent
import javax.inject.Inject
@AndroidEntryPoint
class ScreenTool : BottomSheetDialogFragment() {
@Inject
lateinit var screenToolPref: ScreenToolPref
private val screenShoot1 = registerGetContent { uri ->
setFragmentResult(
KEY_REQ_SCREEN_1,
bundleOf(ARG_SCREEN1_PATH to uri.toString())
)
}
private val screenShoot2 = registerGetContent { uri ->
setFragmentResult(
KEY_REQ_SCREEN_2,
bundleOf(ARG_SCREEN2_PATH to uri.toString())
)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = FragmentToolScreenBinding.inflate(inflater, container, false).apply {
toolScreen2.isEnabled = screenToolPref.doubleScreenEnable
toolScreenDouble.isChecked = screenToolPref.doubleScreenEnable
toolScreenDouble.setOnCheckedChangeListener { cb, isChecked ->
cb.preventMultipleClick {
if (screenToolPref.doubleScreenEnable != isChecked) {
screenToolPref.doubleScreenEnable = isChecked
toolScreen2.isEnabled = isChecked
}
}
}
toolScreen1.setOnClickListener {
it.preventMultipleClick { screenShoot1.launch("image/*") }
}
toolScreen2.setOnClickListener {
it.preventMultipleClick { screenShoot2.launch("image/*") }
}
}.run { root }
}
| apache-2.0 | 49012008aa8671a4b2125bd7153bdcfb | 36.31746 | 83 | 0.716716 | 4.547389 | false | false | false | false |
debop/debop4k | debop4k-core/src/main/kotlin/debop4k/core/io/ByteBufferInputStream.kt | 1 | 1731 | /*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package debop4k.core.io
import debop4k.core.utils.min
import java.io.InputStream
import java.nio.ByteBuffer
/**
* {@link ByteBuffer}를 저장소로 사용하는 Input Stream 구현체입니다.
*
* @author [email protected]
*/
open class ByteBufferInputStream(val buffer: ByteBuffer) : InputStream() {
@JvmOverloads
constructor(bufferSize: Int = DEFAULT_BUFFER_SIZE) : this(ByteBuffer.allocateDirect(bufferSize))
constructor(bytes: ByteArray) : this(bytes.toByteBufferDirectly())
override fun read(): Int {
return if (buffer.hasRemaining()) (buffer.get().toInt() and 0xFF) else -1
}
override fun read(b: ByteArray?, off: Int, len: Int): Int {
if (len == 0)
return 0
val count = buffer.remaining() min len
if (count == 0)
return -1
buffer.get(b, off, len)
return count
}
override fun available(): Int {
return buffer.remaining()
}
companion object {
@JvmStatic fun of(src: ByteBuffer): ByteBufferInputStream {
val buffer = src.duplicate().apply { flip() }
return ByteBufferInputStream(buffer)
}
}
} | apache-2.0 | fdb4a3fb6f497daa305fbae263943066 | 26.901639 | 98 | 0.698413 | 3.892449 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/run/latex/logtab/LatexFileStack.kt | 1 | 6310 | package nl.hannahsten.texifyidea.run.latex.logtab
import com.intellij.openapi.diagnostic.Logger
import nl.hannahsten.texifyidea.TeXception
import nl.hannahsten.texifyidea.run.latex.logtab.LatexLogMagicRegex.LINE_WIDTH
import nl.hannahsten.texifyidea.run.latex.logtab.LatexLogMagicRegex.lineNumber
import nl.hannahsten.texifyidea.util.containsAny
import nl.hannahsten.texifyidea.util.firstIndexOfAny
import nl.hannahsten.texifyidea.util.remove
import java.util.*
class LatexFileStack(
vararg val file: String,
/** Number of open parentheses that do not represent file openings and have not yet been closed. */
var notClosedNonFileOpenParentheses: Int = 0
) : ArrayDeque<String>() {
private var shouldSkipNextLine = false
// Usage: set to true to output all file openings/closings to idea.log
// Then open the LaTeX log and the relevant part of idea.log in IntelliJ, and start from the idea.log parenthesis which
// was closed incorrectly, use the LaTeX log and brace matching to find which file should have been closed, then check where it was actually closed, etc.
private val debug = false
private val logger = Logger.getInstance("LatexFileStack")
init {
addAll(file)
}
/** Collect file here if it spans multiple lines. */
private var currentCollectingFile = ""
override fun peek(): String? = if (isEmpty()) null else super.peek()
fun pushFile(file: String, line: String) {
push(file)
if (debug) logger.info("$line ---- Opening $file")
if (file.containsAny(setOf("(", ")"))) throw TeXception("$file is probably not a valid file")
}
/**
* AFTER all messages have been filtered, look for file openings and closings.
*
* Assume that all parenthesis come in pairs. Will probably fail the (few)
* cases where they don't...
* (It works for rubber: https://github.com/tsgates/die/blob/master/bin/parse-latex-log.py)
*/
fun update(line: String): LatexFileStack {
// Lines starting with a line number seem to contain user content, as well as the next line (which could be empty
// as well, but in that case it isn't interesting either)
if (lineNumber.containsMatchIn(line)) {
shouldSkipNextLine = true
return this
}
if (shouldSkipNextLine) {
shouldSkipNextLine = false
return this
}
if (currentCollectingFile.isNotEmpty()) {
// Files may end halfway the line, or right at the end of a line
// Assume there are no spaces in the path (how can we know where the file ends?)
val endIndex = if (setOf(" ", ")", "(").any { it in line }) line.firstIndexOfAny(' ', ')', '(') else line.length
currentCollectingFile += line.substring(0, endIndex).remove("\n")
// Check if this was the last part of the file
if (line.substring(0, endIndex).length < LINE_WIDTH) {
// Assume that paths can be quoted, but there are no " in folder/file names
pushFile(currentCollectingFile.trim('"'), line)
currentCollectingFile = ""
}
}
// Matches an open par with a filename, or a closing par
// If the filepath probably continues on the next line, don't try to match the extension
// (could be improved by actually checking the length of the 'file' group instead of line length)
// Otherwise, match the file extension to avoid matching just text in parentheses
val fileRegex = if (line.length >= LINE_WIDTH - 1) {
Regex("""\((?<file>"?\.*(([/\\])*[\w-\d. :])+"?)|\)""")
}
else {
Regex("""\((?<file>"?\.*(([/\\])*[\w-\d. :])+\.(\w{2,10})"?)|\)""")
}
var result = fileRegex.find(line)
var linePart = line
while (result != null) {
// If the regex matches an open par (with filename), register file
if (linePart[result.range.first] == '(') {
// Count all open pars that are before the found opening par.
if (linePart.indexOfFirst { it == '(' } in 0..result.range.first) {
notClosedNonFileOpenParentheses += linePart.substring(0, result.range.first).count { it == '(' }
}
val file = result.groups["file"]?.value?.trim() ?: break
// Check if file spans multiple lines
// +1 because the starting ( is not in the group
// -1 because the newline is not here
// Files could span exactly the full line width, but not continue on the next line
if (!file.endsWith(".tex") && (file.length + 1 >= LINE_WIDTH - 1 || (line.length >= LINE_WIDTH && line.trim().endsWith(file)))) {
currentCollectingFile += file
}
else {
pushFile(file, line)
}
}
// Regex has matched a closing par
else {
// Count all open pars that are before the found closing par.
if (linePart.indexOfFirst { it == '(' } in 0..result.range.first) {
notClosedNonFileOpenParentheses += linePart.substring(0, result.range.first).count { it == '(' }
}
if (notClosedNonFileOpenParentheses > 0) notClosedNonFileOpenParentheses--
else {
if (debug) logger.info("$line ---- Closing ${peek()}")
if (!isEmpty()) {
pop()
}
}
}
linePart = linePart.substring(result.range.last + 1)
result = fileRegex.find(linePart)
}
// When we find a closing par or no match, there can still be an open
// parenthesis somewhere on the current line (before the closing par).
// We want to detect this par, so we know that the next closing par does
// not close a file.
// This has to happen after the above while loop, to still catch leftover open brackets at the end of a line
if (result == null) {
notClosedNonFileOpenParentheses += linePart.count { it == '(' }
}
return this
}
} | mit | c0f7898fc779004c9a413f4ce4f9f828 | 44.078571 | 157 | 0.593661 | 4.516822 | false | false | false | false |
PaulWoitaschek/Voice | data/src/main/kotlin/voice/data/legacy/LegacyBookSettings.kt | 1 | 760 | package voice.data.legacy
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.io.File
import java.util.UUID
@Entity(tableName = "bookSettings")
data class LegacyBookSettings(
@ColumnInfo(name = "id")
@PrimaryKey
val id: UUID,
@ColumnInfo(name = "currentFile")
val currentFile: File,
@ColumnInfo(name = "positionInChapter")
val positionInChapter: Long,
@ColumnInfo(name = "playbackSpeed")
val playbackSpeed: Float = 1F,
@ColumnInfo(name = "loudnessGain")
val loudnessGain: Int = 0,
@ColumnInfo(name = "skipSilence")
val skipSilence: Boolean = false,
@ColumnInfo(name = "active")
val active: Boolean,
@ColumnInfo(name = "lastPlayedAtMillis")
val lastPlayedAtMillis: Long,
)
| gpl-3.0 | ccb6a5571ec39d1c0b94c22969a8041e | 26.142857 | 42 | 0.739474 | 3.8 | false | false | false | false |
KasparPeterson/Globalwave | app/src/main/java/com/kasparpeterson/globalwave/VoiceListeningActivity.kt | 1 | 2524 | package com.kasparpeterson.globalwave
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import edu.cmu.pocketsphinx.*
import java.io.File
/**
* Created by kaspar on 27/01/2017.
*/
@Deprecated("This is just a test class to see PocketSphinx capabilities")
class VoiceListeningActivity: AppCompatActivity(), RecognitionListener {
private val TAG = VoiceListeningActivity::class.java.simpleName
private val KWS_SEARCH = "wakeup"
private val KEYPHRASE = "hello"
private val PHONE_SEARCH = "phones"
var speechRecognizer: SpeechRecognizer? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_voice_listening)
val assets = Assets(this)
val assetDir = assets.syncAssets()
speechRecognizer = getRecognizer(assetDir)
}
private fun getRecognizer(assetsDir: File): SpeechRecognizer {
val speechRecognizer = getDefaultRecognizer(assetsDir)
speechRecognizer.addListener(this)
speechRecognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE)
speechRecognizer.addAllphoneSearch(PHONE_SEARCH, getPhoneticModel(assetsDir))
speechRecognizer.startListening(KWS_SEARCH)
return speechRecognizer
}
private fun getDefaultRecognizer(assetsDir: File): SpeechRecognizer {
return SpeechRecognizerSetup.defaultSetup()
.setAcousticModel(File(assetsDir, "en-us-ptm"))
.setDictionary(File(assetsDir, "cmudict-en-us.dict"))
.setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
.recognizer
}
private fun getPhoneticModel(assetsDir: File): File {
return File(assetsDir, "en-phone.dmp")
}
// Pocket Sphinx functions
override fun onPartialResult(p0: Hypothesis?) {
Log.d(TAG, "onPartialResult, hypstr: " + p0?.hypstr)
val result = p0?.hypstr
if (result.equals(KEYPHRASE)) {
speechRecognizer!!.startListening(PHONE_SEARCH, 100000)
}
}
override fun onTimeout() {
Log.d(TAG, "onTimeout")
}
override fun onEndOfSpeech() {
Log.d(TAG, "onEndOfSpeech")
}
override fun onResult(p0: Hypothesis?) {
Log.d(TAG, "onResult, hypst: " + p0?.hypstr)
}
override fun onBeginningOfSpeech() {
Log.d(TAG, "onBeginningOfSpeech")
}
override fun onError(p0: Exception?) {
Log.d(TAG, "onError")
}
} | mit | 73cfc2fed113ed36c1f8c008b51bcbdd | 30.962025 | 85 | 0.676704 | 4.117455 | false | false | false | false |
google/modernstorage | sample/src/main/java/com/google/modernstorage/sample/ui/shared/FilePreviewCards.kt | 1 | 2917 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.modernstorage.sample.ui.shared
import android.text.format.Formatter
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.google.modernstorage.storage.MetadataExtras.DisplayName
import com.google.modernstorage.storage.MetadataExtras.MimeType
import com.skydoves.landscapist.glide.GlideImage
@Composable
fun FileDetailsCard(fileDetails: FileDetails, preview: @Composable (() -> Unit)? = null) {
val context = LocalContext.current
val metadata = fileDetails.metadata
val formattedFileSize = Formatter.formatShortFileSize(context, metadata.size ?: -1)
val fileDescription = "${metadata.extra(MimeType::class)} - $formattedFileSize"
Card(
elevation = 0.dp,
border = BorderStroke(width = 1.dp, color = Color.DarkGray),
modifier = Modifier.padding(16.dp)
) {
Column {
Column(modifier = Modifier.padding(16.dp)) {
metadata.extra(DisplayName::class)?.let {
Text(text = it.value, style = MaterialTheme.typography.subtitle2)
}
Spacer(modifier = Modifier.height(4.dp))
Text(text = fileDescription, style = MaterialTheme.typography.caption)
Spacer(modifier = Modifier.height(12.dp))
Text(text = fileDetails.uri.toString(), style = MaterialTheme.typography.caption)
}
if (preview != null) {
preview()
}
}
}
}
@Composable
fun MediaPreviewCard(fileDetails: FileDetails) {
FileDetailsCard(fileDetails) {
GlideImage(
modifier = Modifier.height(200.dp),
imageModel = fileDetails.uri,
contentScale = ContentScale.FillWidth
)
}
}
| apache-2.0 | 8d21a291915756c213a24273cbcf6e3a | 36.397436 | 97 | 0.708262 | 4.406344 | false | false | false | false |
natanieljr/droidmate | project/deviceComponents/deviceControlDaemon/src/androidTest/java/org/droidmate/uiautomator2daemon/uiautomatorExtensions/UiSelector.kt | 1 | 1302 | package org.droidmate.uiautomator2daemon.uiautomatorExtensions
import android.view.accessibility.AccessibilityNodeInfo
@Suppress("MemberVisibilityCanBePrivate")
object UiSelector {
@JvmStatic
val isWebView: SelectorCondition = { it,_ -> it.packageName == "android.webkit.WebView" || it.className == "android.webkit.WebView" }
@JvmStatic
val permissionRequest: SelectorCondition = { node,_ -> node.viewIdResourceName == "com.android.packageinstaller:id/permission_allow_button"}
@JvmStatic
val ignoreSystemElem: SelectorCondition = { node,_ -> node.viewIdResourceName?.let{! it.startsWith("com.android.systemui")}?:false }
// TODO check if need special case for packages "com.android.chrome" ??
@JvmStatic
val isActable: SelectorCondition = {it,_ ->
it.isEnabled && it.isVisibleToUser
&& (it.isClickable || it.isCheckable || it.isLongClickable || it.isScrollable
|| it.isEditable || it.isFocusable )
}
@JvmStatic
val actableAppElem = { node:AccessibilityNodeInfo, xpath:String ->
UiSelector.ignoreSystemElem(node,xpath) && !isWebView(node,xpath) && // look for internal elements instead of WebView layouts
(UiSelector.isActable(node,xpath) || UiSelector.permissionRequest(node,xpath))
}
}
typealias SelectorCondition = (AccessibilityNodeInfo,xPath:String) -> Boolean
| gpl-3.0 | be27971a1c8acee775d93794b3c658c5 | 42.4 | 141 | 0.758833 | 3.852071 | false | false | false | false |
juxeii/dztools | java/dzjforex/src/main/kotlin/com/jforex/dzjforex/account/BrokerAccount.kt | 1 | 1163 | package com.jforex.dzjforex.account
import com.jforex.dzjforex.account.AccountApi.baseEequity
import com.jforex.dzjforex.account.AccountApi.tradeVal
import com.jforex.dzjforex.account.AccountApi.usedMargin
import com.jforex.dzjforex.misc.ContextDependencies
import com.jforex.dzjforex.misc.getStackTrace
import com.jforex.dzjforex.misc.logger
import com.jforex.dzjforex.zorro.ACCOUNT_AVAILABLE
import com.jforex.dzjforex.zorro.ACCOUNT_UNAVAILABLE
object BrokerAccountApi {
fun <F> ContextDependencies<F>.brokerAccount() =
createAccountData().handleError { error ->
logger.error(
"BrokerAccount failed! " +
"Error message: ${error.message} " +
"Stack trace: ${getStackTrace(error)}"
)
BrokerAccountData(ACCOUNT_UNAVAILABLE)
}
fun <F> ContextDependencies<F>.createAccountData() =
map(baseEequity(), tradeVal(), usedMargin()) {
BrokerAccountData(
returnCode = ACCOUNT_AVAILABLE,
balance = it.a,
tradeVal = it.b,
marginVal = it.c
)
}
} | mit | 28f2822747dd0baf37a5a99a0ebad9b6 | 34.272727 | 62 | 0.642304 | 4.405303 | false | false | false | false |
dykstrom/jcc | src/test/kotlin/se/dykstrom/jcc/basic/code/AbstractBasicCodeGeneratorComponentTests.kt | 1 | 2120 | package se.dykstrom.jcc.basic.code
import se.dykstrom.jcc.basic.compiler.BasicCodeGenerator
import se.dykstrom.jcc.basic.compiler.BasicTypeManager
import se.dykstrom.jcc.common.ast.FloatLiteral
import se.dykstrom.jcc.common.ast.IntegerLiteral
import se.dykstrom.jcc.common.ast.StringLiteral
import se.dykstrom.jcc.common.code.Context
import se.dykstrom.jcc.common.optimization.DefaultAstOptimizer
import se.dykstrom.jcc.common.storage.StorageFactory
import se.dykstrom.jcc.common.symbols.SymbolTable
import se.dykstrom.jcc.common.types.Arr
import se.dykstrom.jcc.common.types.I64
import se.dykstrom.jcc.common.types.Identifier
import kotlin.test.assertNotNull
open class AbstractBasicCodeGeneratorComponentTests {
protected val types = BasicTypeManager()
protected val codeGenerator = BasicCodeGenerator(types, DefaultAstOptimizer(types))
protected val symbols: SymbolTable = codeGenerator.symbols()
protected val storageFactory: StorageFactory = codeGenerator.storageFactory()
protected val context = Context(symbols, types, storageFactory, codeGenerator)
/**
* Asserts that the expected regex matches the actual string. If the regex contains
* a group, this method returns the text that was matched by the group, otherwise null.
*/
protected fun assertRegexMatches(expected: Regex, actual : String): String? {
val matchResult = expected.matchEntire(actual)
assertNotNull(matchResult, "\nExpected (regex) :${expected}\nActual (string) :${actual}")
return if (matchResult.groups.size > 1) matchResult.groups[1]?.value else null
}
companion object {
val IDENT_I64_FOO = Identifier("foo", I64.INSTANCE)
val IDENT_ARR_I64_ONE = Identifier("one", Arr.from(1, I64.INSTANCE))
val IDENT_ARR_I64_TWO = Identifier("two", Arr.from(2, I64.INSTANCE))
val IL_4 = IntegerLiteral(0, 0, 4)
val IL_53 = IntegerLiteral(0, 0, 53)
val FL_1_0 = FloatLiteral(0, 0, 1.0)
val FL_0_5 = FloatLiteral(0, 0, 0.5)
val SL_A = StringLiteral(0, 0, "a")
val SL_B = StringLiteral(0, 0, "b")
}
}
| gpl-3.0 | c91b231e076f57c8b490fc8bd0aed6bf | 43.166667 | 98 | 0.731604 | 3.897059 | false | false | false | false |
dkluffy/dkluff-code | code/LuffySubber/app/新建文件夹/MainFragment.kt | 1 | 9029 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package android.dktv.com.luffysubber
import java.util.Collections
import java.util.Timer
import java.util.TimerTask
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.Handler
import android.support.v17.leanback.app.BackgroundManager
import android.support.v17.leanback.app.BrowseFragment
import android.support.v17.leanback.widget.ArrayObjectAdapter
import android.support.v17.leanback.widget.HeaderItem
import android.support.v17.leanback.widget.ImageCardView
import android.support.v17.leanback.widget.ListRow
import android.support.v17.leanback.widget.ListRowPresenter
import android.support.v17.leanback.widget.OnItemViewClickedListener
import android.support.v17.leanback.widget.OnItemViewSelectedListener
import android.support.v17.leanback.widget.Presenter
import android.support.v17.leanback.widget.Row
import android.support.v17.leanback.widget.RowPresenter
import android.support.v4.app.ActivityOptionsCompat
import android.support.v4.content.ContextCompat
import android.util.DisplayMetrics
import android.util.Log
import android.view.Gravity
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.GlideDrawable
import com.bumptech.glide.request.animation.GlideAnimation
import com.bumptech.glide.request.target.SimpleTarget
/**
* Loads a grid of cards with movies to browse.
*/
class MainFragment : BrowseFragment() {
private val mHandler = Handler()
private lateinit var mBackgroundManager: BackgroundManager
private var mDefaultBackground: Drawable? = null
private lateinit var mMetrics: DisplayMetrics
private var mBackgroundTimer: Timer? = null
private var mBackgroundUri: String? = null
override fun onActivityCreated(savedInstanceState: Bundle?) {
Log.i(TAG, "onCreate")
super.onActivityCreated(savedInstanceState)
prepareBackgroundManager()
setupUIElements()
loadRows()
setupEventListeners()
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy: " + mBackgroundTimer?.toString())
mBackgroundTimer?.cancel()
}
private fun prepareBackgroundManager() {
mBackgroundManager = BackgroundManager.getInstance(activity)
mBackgroundManager.attach(activity.window)
mDefaultBackground = ContextCompat.getDrawable(context, R.drawable.default_background)
mMetrics = DisplayMetrics()
activity.windowManager.defaultDisplay.getMetrics(mMetrics)
}
private fun setupUIElements() {
title = getString(R.string.browse_title)
// over title
headersState = BrowseFragment.HEADERS_ENABLED
isHeadersTransitionOnBackEnabled = true
// set fastLane (or headers) background color
brandColor = ContextCompat.getColor(context, R.color.fastlane_background)
// set search icon color
searchAffordanceColor = ContextCompat.getColor(context, R.color.search_opaque)
}
private fun loadRows() {
val list = MovieList.list
val rowsAdapter = ArrayObjectAdapter(ListRowPresenter())
val cardPresenter = CardPresenter()
for (i in 0 until NUM_ROWS) {
if (i != 0) {
Collections.shuffle(list)
}
val listRowAdapter = ArrayObjectAdapter(cardPresenter)
for (j in 0 until NUM_COLS) {
listRowAdapter.add(list[j % 5])
}
val header = HeaderItem(i.toLong(), MovieList.MOVIE_CATEGORY[i])
rowsAdapter.add(ListRow(header, listRowAdapter))
}
val gridHeader = HeaderItem(NUM_ROWS.toLong(), "PREFERENCES")
val mGridPresenter = GridItemPresenter()
val gridRowAdapter = ArrayObjectAdapter(mGridPresenter)
gridRowAdapter.add(resources.getString(R.string.grid_view))
gridRowAdapter.add(getString(R.string.error_fragment))
gridRowAdapter.add(resources.getString(R.string.personal_settings))
rowsAdapter.add(ListRow(gridHeader, gridRowAdapter))
adapter = rowsAdapter
}
private fun setupEventListeners() {
setOnSearchClickedListener {
Toast.makeText(context, "Implement your own in-app search", Toast.LENGTH_LONG)
.show()
}
onItemViewClickedListener = ItemViewClickedListener()
onItemViewSelectedListener = ItemViewSelectedListener()
}
private inner class ItemViewClickedListener : OnItemViewClickedListener {
override fun onItemClicked(
itemViewHolder: Presenter.ViewHolder,
item: Any,
rowViewHolder: RowPresenter.ViewHolder,
row: Row
) {
if (item is Movie) {
Log.d(TAG, "Item: " + item.toString())
val intent = Intent(context, DetailsActivity::class.java)
intent.putExtra(DetailsActivity.MOVIE, item)
val bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
activity,
(itemViewHolder.view as ImageCardView).mainImageView,
DetailsActivity.SHARED_ELEMENT_NAME
)
.toBundle()
activity.startActivity(intent, bundle)
} else if (item is String) {
if (item.contains(getString(R.string.error_fragment))) {
val intent = Intent(context, BrowseErrorActivity::class.java)
startActivity(intent)
} else {
Toast.makeText(context, item, Toast.LENGTH_SHORT).show()
}
}
}
}
private inner class ItemViewSelectedListener : OnItemViewSelectedListener {
override fun onItemSelected(
itemViewHolder: Presenter.ViewHolder?, item: Any?,
rowViewHolder: RowPresenter.ViewHolder, row: Row
) {
if (item is Movie) {
mBackgroundUri = item.backgroundImageUrl
startBackgroundTimer()
}
}
}
private fun updateBackground(uri: String?) {
val width = mMetrics.widthPixels
val height = mMetrics.heightPixels
Glide.with(context)
.load(uri)
.centerCrop()
.error(mDefaultBackground)
.into<SimpleTarget<GlideDrawable>>(
object : SimpleTarget<GlideDrawable>(width, height) {
override fun onResourceReady(
resource: GlideDrawable,
glideAnimation: GlideAnimation<in GlideDrawable>
) {
mBackgroundManager.drawable = resource
}
})
mBackgroundTimer?.cancel()
}
private fun startBackgroundTimer() {
mBackgroundTimer?.cancel()
mBackgroundTimer = Timer()
mBackgroundTimer?.schedule(UpdateBackgroundTask(), BACKGROUND_UPDATE_DELAY.toLong())
}
private inner class UpdateBackgroundTask : TimerTask() {
override fun run() {
mHandler.post { updateBackground(mBackgroundUri) }
}
}
private inner class GridItemPresenter : Presenter() {
override fun onCreateViewHolder(parent: ViewGroup): Presenter.ViewHolder {
val view = TextView(parent.context)
view.layoutParams = ViewGroup.LayoutParams(GRID_ITEM_WIDTH, GRID_ITEM_HEIGHT)
view.isFocusable = true
view.isFocusableInTouchMode = true
view.setBackgroundColor(ContextCompat.getColor(context, R.color.default_background))
view.setTextColor(Color.WHITE)
view.gravity = Gravity.CENTER
return Presenter.ViewHolder(view)
}
override fun onBindViewHolder(viewHolder: Presenter.ViewHolder, item: Any) {
(viewHolder.view as TextView).text = item as String
}
override fun onUnbindViewHolder(viewHolder: Presenter.ViewHolder) {}
}
companion object {
private val TAG = "MainFragment"
private val BACKGROUND_UPDATE_DELAY = 300
private val GRID_ITEM_WIDTH = 200
private val GRID_ITEM_HEIGHT = 200
private val NUM_ROWS = 6
private val NUM_COLS = 15
}
}
| apache-2.0 | 65d2d4313802791a7ea0c3fdf5c46d2b | 35.554656 | 100 | 0.666076 | 4.917756 | false | false | false | false |
mix-it/mixit | src/main/kotlin/mixit/web/handler/AdminHandler.kt | 1 | 27287 | package mixit.web.handler
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.Objects
import mixit.MixitProperties
import mixit.model.Event
import mixit.model.EventOrganization
import mixit.model.EventSponsoring
import mixit.model.Language
import mixit.model.Language.ENGLISH
import mixit.model.Language.FRENCH
import mixit.model.Link
import mixit.model.Post
import mixit.model.Role
import mixit.model.Role.STAFF
import mixit.model.Role.STAFF_IN_PAUSE
import mixit.model.Role.USER
import mixit.model.Role.VOLUNTEER
import mixit.model.Room
import mixit.model.Room.AMPHI1
import mixit.model.Room.AMPHI2
import mixit.model.Room.AMPHIC
import mixit.model.Room.AMPHID
import mixit.model.Room.AMPHIK
import mixit.model.Room.MUMMY
import mixit.model.Room.OUTSIDE
import mixit.model.Room.ROOM1
import mixit.model.Room.ROOM2
import mixit.model.Room.ROOM3
import mixit.model.Room.ROOM4
import mixit.model.Room.ROOM5
import mixit.model.Room.ROOM6
import mixit.model.Room.ROOM7
import mixit.model.Room.ROOM8
import mixit.model.Room.SPEAKER
import mixit.model.Room.SURPRISE
import mixit.model.Room.UNKNOWN
import mixit.model.SponsorshipLevel
import mixit.model.Talk
import mixit.model.TalkFormat
import mixit.model.TalkFormat.CLOSING_SESSION
import mixit.model.TalkFormat.KEYNOTE
import mixit.model.TalkFormat.KEYNOTE_SURPRISE
import mixit.model.TalkFormat.LIGHTNING_TALK
import mixit.model.TalkFormat.RANDOM
import mixit.model.TalkFormat.TALK
import mixit.model.TalkFormat.WORKSHOP
import mixit.model.Ticket
import mixit.model.User
import mixit.model.Users
import mixit.repository.EventRepository
import mixit.repository.PostRepository
import mixit.repository.TalkRepository
import mixit.repository.TicketRepository
import mixit.repository.UserRepository
import mixit.util.Cryptographer
import mixit.util.camelCase
import mixit.util.language
import mixit.util.seeOther
import mixit.util.toSlug
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.BodyExtractors
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.ServerResponse
import org.springframework.web.reactive.function.server.ServerResponse.ok
import reactor.core.publisher.Mono
import kotlin.streams.toList
@Component
class AdminHandler(
private val ticketRepository: TicketRepository,
private val talkRepository: TalkRepository,
private val userRepository: UserRepository,
private val eventRepository: EventRepository,
private val postRepository: PostRepository,
private val properties: MixitProperties,
private val objectMapper: ObjectMapper,
private val cryptographer: Cryptographer
) {
fun admin(req: ServerRequest) =
ok().render("admin", mapOf(Pair("title", "admin.title")))
fun adminTicketing(req: ServerRequest) =
ok().render(
"admin-ticketing",
mapOf(
Pair(
"tickets",
ticketRepository.findAll()
.map {
Ticket(
it.email,
it.firstname.camelCase(),
it.lastname.camelCase()
)
}
.sort(
Comparator.comparing(Ticket::lastname)
.thenComparing(Comparator.comparing(Ticket::firstname))
)
),
Pair("title", "admin.ticketing.title")
)
)
fun adminDeleteTicketing(req: ServerRequest): Mono<ServerResponse> =
req.body(BodyExtractors.toFormData()).flatMap {
val formData = it.toSingleValueMap()
ticketRepository
.deleteOne(formData["email"]!!)
.then(seeOther("${properties.baseUri}/admin/ticketing"))
}
fun adminTalks(req: ServerRequest, year: String) =
ok().render(
"admin-talks",
mapOf(
Pair("year", year),
Pair(
"talks",
talkRepository
.findByEvent(year)
.collectList()
.flatMap { talks ->
userRepository
.findMany(talks.flatMap(Talk::speakerIds))
.collectMap(User::login)
.map { speakers -> talks.map { it.toDto(req.language(), it.speakerIds.mapNotNull { speakers[it] }) } }
}
),
Pair("title", "admin.talks.title")
)
)
fun adminUsers(req: ServerRequest) = ok().render("admin-users", mapOf(Pair("users", userRepository.findAll().sort(Comparator.comparing(User::lastname).thenComparing(Comparator.comparing(User::firstname)))), Pair("title", "admin.users.title")))
fun createTalk(req: ServerRequest): Mono<ServerResponse> = this.adminTalk()
fun editTalk(req: ServerRequest): Mono<ServerResponse> = talkRepository.findBySlug(req.pathVariable("slug")).flatMap(this::adminTalk)
fun adminSaveTalk(req: ServerRequest): Mono<ServerResponse> {
return req.body(BodyExtractors.toFormData()).flatMap {
val formData = it.toSingleValueMap()
val talk = Talk(
id = formData["id"],
event = formData["event"]!!,
format = TalkFormat.valueOf(formData["format"]!!),
title = formData["title"]!!,
summary = formData["summary"]!!,
description = if (formData["description"] == "") null else formData["description"],
topic = formData["topic"],
language = Language.valueOf(formData["language"]!!),
speakerIds = formData["speakers"]!!.split(","),
video = if (formData["video"] == "") null else formData["video"],
room = Room.valueOf(formData["room"]!!),
addedAt = LocalDateTime.parse(formData["addedAt"]),
start = LocalDateTime.parse(formData["start"]),
end = LocalDateTime.parse(formData["end"]),
photoUrls = if (formData["photoUrls"].isNullOrEmpty()) emptyList() else formData["photoUrls"]!!.toLinks()
)
talkRepository.save(talk).then(seeOther("${properties.baseUri}/admin/talks"))
}
}
fun adminDeleteTalk(req: ServerRequest): Mono<ServerResponse> =
req.body(BodyExtractors.toFormData()).flatMap {
val formData = it.toSingleValueMap()
talkRepository
.deleteOne(formData["id"]!!)
.then(seeOther("${properties.baseUri}/admin/talks"))
}
private fun adminTalk(talk: Talk = Talk(TALK, "2021", "", "")) = ok().render(
"admin-talk",
mapOf(
Pair("talk", talk),
Pair("title", "admin.talk.title"),
Pair(
"rooms",
listOf(
Triple(AMPHI1, "rooms.${AMPHI1.name.lowercase()}", AMPHI1 == talk.room),
Triple(AMPHI2, "rooms.${AMPHI2.name.lowercase()}", AMPHI2 == talk.room),
Triple(ROOM1, "rooms.${ROOM1.name.lowercase()}", ROOM1 == talk.room),
Triple(ROOM2, "rooms.${ROOM2.name.lowercase()}", ROOM2 == talk.room),
Triple(ROOM3, "rooms.${ROOM3.name.lowercase()}", ROOM3 == talk.room),
Triple(ROOM4, "rooms.${ROOM4.name.lowercase()}", ROOM4 == talk.room),
Triple(ROOM5, "rooms.${ROOM5.name.lowercase()}", ROOM5 == talk.room),
Triple(ROOM6, "rooms.${ROOM6.name.lowercase()}", ROOM6 == talk.room),
Triple(ROOM7, "rooms.${ROOM7.name.lowercase()}", ROOM7 == talk.room),
Triple(ROOM7, "rooms.${ROOM8.name.lowercase()}", ROOM8 == talk.room),
Triple(OUTSIDE, "rooms.${OUTSIDE.name.lowercase()}", OUTSIDE == talk.room),
Triple(AMPHIC, "rooms.${AMPHIC.name.lowercase()}", AMPHIC == talk.room),
Triple(AMPHID, "rooms.${AMPHID.name.lowercase()}", AMPHID == talk.room),
Triple(AMPHIK, "rooms.${AMPHIK.name.lowercase()}", AMPHIK == talk.room),
Triple(SURPRISE, "rooms.${SURPRISE.name.lowercase()}", SURPRISE == talk.room),
Triple(SPEAKER, "rooms.${SPEAKER.name.lowercase()}", SPEAKER == talk.room),
Triple(MUMMY, "rooms.${MUMMY.name.lowercase()}", MUMMY == talk.room),
Triple(UNKNOWN, "rooms.${UNKNOWN.name.lowercase()}", UNKNOWN == talk.room)
)
),
Pair(
"formats",
listOf(
Pair(TALK, TALK == talk.format),
Pair(LIGHTNING_TALK, LIGHTNING_TALK == talk.format),
Pair(WORKSHOP, WORKSHOP == talk.format),
Pair(RANDOM, RANDOM == talk.format),
Pair(KEYNOTE, KEYNOTE == talk.format),
Pair(KEYNOTE_SURPRISE, KEYNOTE_SURPRISE == talk.format),
Pair(CLOSING_SESSION, CLOSING_SESSION == talk.format)
)
),
Pair(
"languages",
listOf(
Pair(ENGLISH, ENGLISH == talk.language),
Pair(FRENCH, FRENCH == talk.language)
)
),
Pair(
"topics",
listOf(
Pair("makers", "makers" == talk.topic),
Pair("aliens", "aliens" == talk.topic),
Pair("tech", "tech" == talk.topic),
Pair("team", "team" == talk.topic),
Pair("other", "other" == talk.topic),
Pair("design", "design" == talk.topic),
Pair("hacktivism", "hacktivism" == talk.topic),
Pair("ethics", "ethics" == talk.topic),
Pair("lifestyle", "lifestyle" == talk.topic),
Pair("learn", "learn" == talk.topic)
)
),
Pair("speakers", talk.speakerIds.joinToString(separator = ",")),
Pair("photos", talk.photoUrls.toJson())
)
)
fun adminEvents(req: ServerRequest) = ok().render("admin-events", mapOf(Pair("events", eventRepository.findAll()), Pair("title", "admin.events.title")))
fun createEvent(req: ServerRequest): Mono<ServerResponse> = this.adminEvent()
fun editEvent(req: ServerRequest): Mono<ServerResponse> = eventRepository.findOne(req.pathVariable("eventId")).flatMap { this.adminEvent(it) }
private fun adminEvent(event: Event = Event("", LocalDate.now(), LocalDate.now())) = ok().render(
"admin-event",
mapOf(
Pair("creationMode", event.id == ""),
Pair("event", event),
Pair("links", event.photoUrls.toJson()),
Pair("videolink", if (event.videoUrl == null) "" else event.videoUrl.toJson())
)
)
fun adminSaveEvent(req: ServerRequest): Mono<ServerResponse> {
return req.body(BodyExtractors.toFormData()).flatMap {
val formData = it.toSingleValueMap()
// We need to find the event in database
eventRepository
.findOne(formData["eventId"]!!)
.flatMap {
val event = Event(
it.id,
LocalDate.parse(formData["start"]!!),
LocalDate.parse(formData["end"]!!),
if (formData["current"] == null) false else formData["current"]!!.toBoolean(),
it.sponsors,
it.organizations,
if (formData["photoUrls"].isNullOrEmpty()) emptyList() else formData["photoUrls"]!!.toLinks(),
if (formData["videoUrl"].isNullOrEmpty()) null else formData["videoUrl"]!!.toLink()
)
eventRepository.save(event).then(seeOther("${properties.baseUri}/admin/events"))
}
.switchIfEmpty(
eventRepository.save(
Event(
formData["eventId"]!!,
LocalDate.parse(formData["start"]!!),
LocalDate.parse(formData["end"]!!),
if (formData["current"] == null) false else formData["current"]!!.toBoolean()
)
).then(seeOther("${properties.baseUri}/admin/events"))
)
}
}
fun createEventSponsoring(req: ServerRequest): Mono<ServerResponse> = adminEventSponsoring(req.pathVariable("eventId"))
private fun adminEventSponsoring(eventId: String, eventSponsoring: EventSponsoring = EventSponsoring(SponsorshipLevel.NONE, "", LocalDate.now())) = ok().render(
"admin-event-sponsor",
mapOf(
Pair("creationMode", eventSponsoring.sponsorId == ""),
Pair("eventId", eventId),
Pair("eventSponsoring", eventSponsoring),
Pair(
"levels",
listOf(
Pair(SponsorshipLevel.ACCESSIBILITY, SponsorshipLevel.ACCESSIBILITY == eventSponsoring.level),
Pair(SponsorshipLevel.BREAKFAST, SponsorshipLevel.ACCESSIBILITY == eventSponsoring.level),
Pair(SponsorshipLevel.BRONZE, SponsorshipLevel.BRONZE == eventSponsoring.level),
Pair(SponsorshipLevel.COMMUNITY, SponsorshipLevel.COMMUNITY == eventSponsoring.level),
Pair(SponsorshipLevel.ECOCUP, SponsorshipLevel.ECOCUP == eventSponsoring.level),
Pair(SponsorshipLevel.GOLD, SponsorshipLevel.GOLD == eventSponsoring.level),
Pair(SponsorshipLevel.HOSTING, SponsorshipLevel.ACCESSIBILITY == eventSponsoring.level),
Pair(SponsorshipLevel.ECOLOGY, SponsorshipLevel.ECOLOGY == eventSponsoring.level),
Pair(SponsorshipLevel.LANYARD, SponsorshipLevel.ACCESSIBILITY == eventSponsoring.level),
Pair(SponsorshipLevel.LUNCH, SponsorshipLevel.ACCESSIBILITY == eventSponsoring.level),
Pair(SponsorshipLevel.MIXTEEN, SponsorshipLevel.MIXTEEN == eventSponsoring.level),
Pair(SponsorshipLevel.NONE, SponsorshipLevel.NONE == eventSponsoring.level),
Pair(SponsorshipLevel.PARTY, SponsorshipLevel.PARTY == eventSponsoring.level),
Pair(SponsorshipLevel.SILVER, SponsorshipLevel.SILVER == eventSponsoring.level),
Pair(SponsorshipLevel.VIDEO, SponsorshipLevel.VIDEO == eventSponsoring.level)
)
)
)
)
private fun eventSponsoringMatch(sponsorId: String, level: String, eventSponsoring: EventSponsoring): Boolean =
sponsorId.equals(eventSponsoring.sponsorId) && level.equals(eventSponsoring.level.name)
fun adminUpdateEventSponsoring(req: ServerRequest): Mono<ServerResponse> = req.body(BodyExtractors.toFormData()).flatMap {
val formData = it.toSingleValueMap()
// We need to find the event in database
eventRepository
.findOne(formData["eventId"]!!)
.flatMap {
// We create a mutable list
val sponsors = it.sponsors
.stream()
.map {
if (eventSponsoringMatch(formData["eventId"]!!, formData["sponsorId"]!!, it)) {
EventSponsoring(it.level, it.sponsorId, if (formData["subscriptionDate"] == null) LocalDate.now() else LocalDate.parse(formData["subscriptionDate"]!!))
} else {
it
}
}
.toList()
eventRepository.save(Event(it.id, it.start, it.end, it.current, sponsors)).then(seeOther("${properties.baseUri}/admin/events/edit/${formData["eventId"]!!}"))
}
}
fun adminCreateEventSponsoring(req: ServerRequest): Mono<ServerResponse> = req.body(BodyExtractors.toFormData()).flatMap {
val formData = it.toSingleValueMap()
// We need to find the event in database
eventRepository
.findOne(formData["eventId"]!!)
.flatMap {
// We create a mutable list
val sponsors = it.sponsors.toMutableList()
sponsors.add(
EventSponsoring(
SponsorshipLevel.valueOf(formData["level"]!!),
formData["sponsorId"]!!,
if (formData["subscriptionDate"] == null) LocalDate.now() else LocalDate.parse(formData["subscriptionDate"]!!)
)
)
eventRepository.save(Event(it.id, it.start, it.end, it.current, sponsors)).then(seeOther("${properties.baseUri}/admin/events/edit/${formData["eventId"]!!}"))
}
}
fun adminDeleteEventSponsoring(req: ServerRequest): Mono<ServerResponse> = req.body(BodyExtractors.toFormData()).flatMap {
val formData = it.toSingleValueMap()
// We need to find the event in database
eventRepository
.findOne(formData["eventId"]!!)
.flatMap {
// We create a mutable list
val sponsors = it.sponsors
.stream()
.map {
if (eventSponsoringMatch(formData["sponsorId"]!!, formData["level"]!!, it)) null else it
}
.filter(Objects::nonNull)
.toList()
.requireNoNulls()
eventRepository.save(Event(it.id, it.start, it.end, it.current, sponsors))
.then(seeOther("${properties.baseUri}/admin/events/edit/${formData["eventId"]!!}"))
}
}
fun editEventSponsoring(req: ServerRequest): Mono<ServerResponse> = eventRepository
.findOne(req.pathVariable("eventId"))
.flatMap {
adminEventSponsoring(
req.pathVariable("eventId"),
it.sponsors.stream()
.filter { eventSponsoringMatch(req.pathVariable("sponsorId"), req.pathVariable("level"), it) }
.findAny().get()
)
}
fun editEventOrganization(req: ServerRequest): Mono<ServerResponse> =
req.pathVariable("eventId").let { eventId ->
eventRepository
.findOne(eventId)
.flatMap { event ->
adminEventOrganization(
eventId,
event.organizations.first { it.organizationLogin == req.pathVariable("organizationLogin") }
)
}
}
fun createEventOrganization(req: ServerRequest): Mono<ServerResponse> =
adminEventOrganization(req.pathVariable("eventId"))
private fun adminEventOrganization(eventId: String, eventOrganization: EventOrganization? = null) = ok()
.render(
"admin-event-organization",
mapOf(
Pair("creationMode", eventOrganization == null),
Pair("eventId", eventId),
Pair("eventOrganization", eventOrganization)
)
)
fun adminUpdateEventOrganization(req: ServerRequest): Mono<ServerResponse> = req.body(BodyExtractors.toFormData()).flatMap {
val formData = it.toSingleValueMap()
// We need to find the event in database
eventRepository
.findOne(formData["eventId"]!!)
.flatMap {
// For the moment we have noting to save
seeOther("${properties.baseUri}/admin/events/edit/${formData["eventId"]!!}")
}
}
fun adminCreateEventOrganization(req: ServerRequest): Mono<ServerResponse> =
req.body(BodyExtractors.toFormData()).flatMap {
val formData = it.toSingleValueMap()
// We need to find the event in database
eventRepository
.findOne(formData["eventId"]!!)
.flatMap { event ->
val organizations = event.organizations.toMutableList()
organizations.add(EventOrganization(formData["organizationLogin"]!!))
eventRepository.save(Event(event.id, event.start, event.end, event.current, event.sponsors, organizations))
.then(seeOther("${properties.baseUri}/admin/events/edit/${formData["eventId"]!!}"))
}
}
fun adminDeleteEventOrganization(req: ServerRequest): Mono<ServerResponse> =
req.body(BodyExtractors.toFormData()).flatMap {
val formData = it.toSingleValueMap()
// We need to find the event in database
eventRepository
.findOne(formData["eventId"]!!)
.flatMap { event ->
val organizations = event.organizations.filter { it.organizationLogin != formData["organizationLogin"]!! }
eventRepository.save(Event(event.id, event.start, event.end, event.current, event.sponsors, organizations))
.then(seeOther("${properties.baseUri}/admin/events/edit/${formData["eventId"]!!}"))
}
}
fun createUser(req: ServerRequest): Mono<ServerResponse> = this.adminUser()
fun editUser(req: ServerRequest): Mono<ServerResponse> =
userRepository.findOne(req.pathVariable("login")).flatMap(this::adminUser)
fun adminDeleteUser(req: ServerRequest): Mono<ServerResponse> =
req.body(BodyExtractors.toFormData()).flatMap {
val formData = it.toSingleValueMap()
userRepository
.deleteOne(formData["login"]!!)
.then(seeOther("${properties.baseUri}/admin/users"))
}
private fun adminUser(user: User = User("", "", "", "")) = ok().render(
"admin-user",
mapOf(
Pair("user", user),
Pair("usermail", cryptographer.decrypt(user.email)),
Pair("description-fr", user.description[FRENCH]),
Pair("description-en", user.description[ENGLISH]),
Pair(
"roles",
listOf(
Pair(USER, USER == user.role),
Pair(STAFF, STAFF == user.role),
Pair(STAFF_IN_PAUSE, STAFF_IN_PAUSE == user.role),
Pair(VOLUNTEER, VOLUNTEER == user.role)
)
),
Pair("links", user.links.toJson())
)
)
fun adminSaveUser(req: ServerRequest): Mono<ServerResponse> {
return req.body(BodyExtractors.toFormData()).flatMap {
val formData = it.toSingleValueMap()
val user = User(
login = formData["login"]!!,
firstname = formData["firstname"]!!,
lastname = formData["lastname"]!!,
email = if (formData["email"] == "") null else cryptographer.encrypt(formData["email"]),
emailHash = if (formData["emailHash"] == "") null else formData["emailHash"],
photoUrl = if (formData["photoUrl"] == "") {
if (formData["emailHash"] == "") Users.DEFAULT_IMG_URL else null
} else {
if (formData["emailHash"] == "") formData["photoUrl"] else null
},
company = if (formData["company"] == "") null else formData["company"],
description = mapOf(Pair(FRENCH, formData["description-fr"]!!), Pair(ENGLISH, formData["description-en"]!!)),
role = Role.valueOf(formData["role"]!!),
links = formData["links"]!!.toLinks(),
legacyId = if (formData["legacyId"] == "") null else formData["legacyId"]!!.toLong()
)
userRepository.save(user).then(seeOther("${properties.baseUri}/admin/users"))
}
}
fun adminBlog(req: ServerRequest): Mono<ServerResponse> = ok().render(
"admin-blog",
mapOf(
Pair(
"posts",
postRepository.findAll().collectList()
.flatMap { posts ->
userRepository
.findMany(posts.map { it.authorId })
.collectMap(User::login)
.map { authors -> posts.map { it.toDto(if (authors[it.authorId] == null) User("mixit", "", "MiXiT", "") else authors[it.authorId]!!, req.language()) } }
}
),
Pair("title", "admin.blog.title")
)
)
fun createPost(req: ServerRequest): Mono<ServerResponse> = this.adminPost()
fun editPost(req: ServerRequest): Mono<ServerResponse> = postRepository.findOne(req.pathVariable("id")).flatMap(this::adminPost)
fun adminDeletePost(req: ServerRequest): Mono<ServerResponse> =
req.body(BodyExtractors.toFormData()).flatMap {
val formData = it.toSingleValueMap()
postRepository
.deleteOne(formData["id"]!!)
.then(seeOther("${properties.baseUri}/admin/blog"))
}
private fun adminPost(post: Post = Post("")) = ok().render(
"admin-post",
mapOf(
Pair("post", post),
Pair("title-fr", post.title[FRENCH]),
Pair("title-en", post.title[ENGLISH]),
Pair("headline-fr", post.headline[FRENCH]),
Pair("headline-en", post.headline[ENGLISH]),
Pair("content-fr", post.content?.get(FRENCH)),
Pair("content-en", post.content?.get(ENGLISH))
)
)
fun adminSavePost(req: ServerRequest): Mono<ServerResponse> {
return req.body(BodyExtractors.toFormData()).flatMap {
val formData = it.toSingleValueMap()
val post = Post(
id = formData["id"],
addedAt = LocalDateTime.parse(formData["addedAt"]),
authorId = formData["authorId"]!!,
title = mapOf(Pair(FRENCH, formData["title-fr"]!!), Pair(ENGLISH, formData["title-en"]!!)),
slug = mapOf(Pair(FRENCH, formData["title-fr"]!!.toSlug()), Pair(ENGLISH, formData["title-en"]!!.toSlug())),
headline = mapOf(Pair(FRENCH, formData["headline-fr"]!!), Pair(ENGLISH, formData["headline-en"]!!)),
content = mapOf(Pair(FRENCH, formData["content-fr"]!!), Pair(ENGLISH, formData["content-en"]!!))
)
postRepository.save(post).then(seeOther("${properties.baseUri}/admin/blog"))
}
}
private fun Any.toJson() = objectMapper.writeValueAsString(this).replace("\"", """)
private fun String.toLinks() = objectMapper.readValue<List<Link>>(this)
private fun String.toLink() = objectMapper.readValue<Link>(this)
}
| apache-2.0 | 885d476cb470ef103f2212bf97eec440 | 45.564846 | 247 | 0.569282 | 4.787193 | false | false | false | false |
0legg/bodylookin | src/main/kotlin/net/olegg/lottie/idea/Icons.kt | 1 | 386 | package net.olegg.lottie.idea
import com.intellij.openapi.util.IconLoader
/**
* Helper class to store icons.
*/
object Icons {
fun load(path: String) = IconLoader.getIcon(path)
val LOAD = load("/icons/wiggle.png")
val OPEN = load("/icons/in.png")
val PLAY = load("/icons/play.png")
val PAUSE = load("/icons/pause.png")
val LOOP = load("/icons/repeat.png")
} | mit | 8ec147116810f6c30f7e636a0990e464 | 23.1875 | 53 | 0.658031 | 3.327586 | false | false | false | false |
pyamsoft/padlock | padlock/src/main/java/com/pyamsoft/padlock/list/info/LockInfoViewImpl.kt | 1 | 10217 | /*
* Copyright 2019 Peter Kenji Yamanaka
*
* 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.pyamsoft.padlock.list.info
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle.Event.ON_DESTROY
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.mikepenz.fastadapter.FastAdapter
import com.mikepenz.fastadapter.adapters.ModelAdapter
import com.pyamsoft.padlock.R
import com.pyamsoft.padlock.databinding.DialogLockInfoBinding
import com.pyamsoft.padlock.helper.ListStateUtil
import com.pyamsoft.padlock.list.FilterListDelegate
import com.pyamsoft.padlock.loader.AppIconLoader
import com.pyamsoft.padlock.model.list.ActivityEntry
import com.pyamsoft.pydroid.loader.ImageLoader
import com.pyamsoft.pydroid.loader.ImageTarget
import com.pyamsoft.pydroid.loader.Loaded
import com.pyamsoft.pydroid.ui.theme.Theming
import com.pyamsoft.pydroid.ui.util.DebouncedOnClickListener
import com.pyamsoft.pydroid.ui.util.Snackbreak
import com.pyamsoft.pydroid.ui.util.refreshing
import com.pyamsoft.pydroid.ui.util.setOnDebouncedClickListener
import com.pyamsoft.pydroid.ui.util.setUpEnabled
import com.pyamsoft.pydroid.util.tintWith
import com.pyamsoft.pydroid.util.toDp
import java.util.Collections
import javax.inject.Inject
import javax.inject.Named
internal class LockInfoViewImpl @Inject internal constructor(
@Named("app_name") private val applicationName: String,
@Named("package_name") private val packageName: String,
@Named("list_state_tag") private val listStateTag: String,
@Named("app_icon") private val icon: Int,
@Named("app_system") private val isSystem: Boolean,
private val activity: FragmentActivity,
private val theming: Theming,
private val owner: LifecycleOwner,
private val inflater: LayoutInflater,
private val container: ViewGroup?,
private val savedInstanceState: Bundle?,
private val appIconLoader: AppIconLoader,
private val imageLoader: ImageLoader
) : LockInfoView, LifecycleObserver {
private lateinit var binding: DialogLockInfoBinding
private lateinit var modelAdapter: ModelAdapter<ActivityEntry, LockInfoBaseItem<*, *, *>>
private lateinit var filterListDelegate: FilterListDelegate
private var appIconLoaded: Loaded? = null
private var toolbarIconLoaded: Loaded? = null
private var lastPosition: Int = 0
init {
owner.lifecycle.addObserver(this)
}
@Suppress("unused")
@OnLifecycleEvent(ON_DESTROY)
internal fun destroy() {
owner.lifecycle.removeObserver(this)
filterListDelegate.onDestroyView()
binding.apply {
lockInfoRecycler.setOnDebouncedClickListener(null)
lockInfoRecycler.layoutManager = null
lockInfoRecycler.adapter = null
unbind()
}
appIconLoaded?.dispose()
toolbarIconLoaded?.dispose()
modelAdapter.clear()
}
override fun root(): View {
return binding.root
}
override fun create() {
binding = DialogLockInfoBinding.inflate(inflater, container, false)
setupSwipeRefresh()
setupRecyclerView()
setupPackageInfo()
setupToolbar()
loadToolbarIcon()
prepareFilterDelegate()
restoreListPosition()
loadAppIcon()
}
private fun loadToolbarIcon() {
toolbarIconLoaded?.dispose()
toolbarIconLoaded = imageLoader.load(R.drawable.ic_close_24dp)
.into(object : ImageTarget<Drawable> {
override fun clear() {
binding.lockInfoToolbar.navigationIcon = null
}
override fun setError(error: Drawable?) {
binding.lockInfoToolbar.navigationIcon = error
}
override fun setImage(image: Drawable) {
val color = ContextCompat.getColor(binding.lockInfoToolbar.context, R.color.white)
binding.lockInfoToolbar.navigationIcon = image.tintWith(color)
}
override fun setPlaceholder(placeholder: Drawable?) {
binding.lockInfoToolbar.navigationIcon = placeholder
}
override fun view(): View {
return binding.lockInfoToolbar
}
})
}
private fun loadAppIcon() {
appIconLoaded?.dispose()
appIconLoaded = appIconLoader.loadAppIcon(packageName, icon)
.into(binding.lockInfoIcon)
}
override fun commitListState(outState: Bundle?) {
if (outState == null) {
// If we are not commiting to bundle, commit to local var
lastPosition = ListStateUtil.getCurrentPosition(binding.lockInfoRecycler)
}
ListStateUtil.saveState(listStateTag, outState, binding.lockInfoRecycler)
}
override fun getListData(): List<ActivityEntry> {
return Collections.unmodifiableList(modelAdapter.models)
}
private fun setupSwipeRefresh() {
binding.lockInfoSwipeRefresh.apply {
setColorSchemeResources(R.color.blue500, R.color.blue700)
}
}
override fun onSwipeRefresh(onSwipe: () -> Unit) {
binding.lockInfoSwipeRefresh.setOnRefreshListener {
startRefreshing()
onSwipe()
}
}
private fun restoreListPosition() {
lastPosition = ListStateUtil.restoreState(listStateTag, savedInstanceState)
}
private fun setupRecyclerView() {
// Setup adapter
modelAdapter = ModelAdapter {
return@ModelAdapter when (it) {
is ActivityEntry.Item -> LockInfoItem(it, isSystem)
is ActivityEntry.Group -> LockInfoGroup(packageName, it)
}
}
binding.lockInfoRecycler.apply {
layoutManager = LinearLayoutManager(activity).apply {
isItemPrefetchEnabled = true
initialPrefetchItemCount = 3
}
setHasFixedSize(true)
addItemDecoration(DividerItemDecoration(activity, DividerItemDecoration.VERTICAL))
adapter = FastAdapter.with<
LockInfoBaseItem<*, *, *>,
ModelAdapter<ActivityEntry, LockInfoBaseItem<*, *, *>>
>(modelAdapter)
}
// Set initial view state
showRecycler()
}
private fun startRefreshing() {
filterListDelegate.setEnabled(false)
binding.lockInfoSwipeRefresh.refreshing(true)
}
private fun doneRefreshing() {
filterListDelegate.setEnabled(true)
binding.lockInfoSwipeRefresh.refreshing(false)
if (modelAdapter.adapterItemCount > 0) {
showRecycler()
// Restore last position
lastPosition = ListStateUtil.restorePosition(lastPosition, binding.lockInfoRecycler)
} else {
hideRecycler()
}
}
private fun setupToolbar() {
val theme: Int
if (theming.isDarkTheme()) {
theme = R.style.ThemeOverlay_MaterialComponents
} else {
theme = R.style.ThemeOverlay_MaterialComponents_Light
}
binding.lockInfoToolbar.apply {
popupTheme = theme
title = applicationName
inflateMenu(R.menu.search_menu)
inflateMenu(R.menu.lockinfo_menu)
// Tint search icon white to match Toolbar
val searchItem = menu.findItem(R.id.menu_search)
val searchIcon = searchItem.icon
searchIcon.mutate()
.also { icon ->
val tintedIcon = icon.tintWith(context, R.color.white)
searchItem.icon = tintedIcon
}
ViewCompat.setElevation(this, 4f.toDp(context).toFloat())
setUpEnabled(true)
}
}
private fun prepareFilterDelegate() {
filterListDelegate = FilterListDelegate()
filterListDelegate.onViewCreated(modelAdapter)
filterListDelegate.onPrepareOptionsMenu(binding.lockInfoToolbar.menu, modelAdapter)
}
override fun onToolbarNavigationClicked(onClick: () -> Unit) {
binding.lockInfoToolbar.setNavigationOnClickListener(
DebouncedOnClickListener.create { onClick() }
)
}
override fun onToolbarMenuItemClicked(onClick: (id: Int) -> Unit) {
binding.lockInfoToolbar.setOnMenuItemClickListener {
onClick(it.itemId)
return@setOnMenuItemClickListener true
}
}
private fun setupPackageInfo() {
binding.apply {
lockInfoPackageName.text = packageName
lockInfoSystem.text = if (isSystem) "YES" else "NO"
}
}
private fun showRecycler() {
binding.apply {
lockInfoEmpty.visibility = View.GONE
lockInfoRecycler.visibility = View.VISIBLE
}
}
private fun hideRecycler() {
binding.apply {
lockInfoRecycler.visibility = View.GONE
lockInfoEmpty.visibility = View.VISIBLE
}
}
override fun onListPopulateBegin() {
startRefreshing()
}
override fun onListPopulated() {
doneRefreshing()
}
override fun onListLoaded(list: List<ActivityEntry>) {
modelAdapter.set(list)
}
override fun onListPopulateError(onAction: () -> Unit) {
Snackbreak.bindTo(owner)
.long(root(), "Failed to load list for $applicationName")
.setAction("Retry") { onAction() }
.show()
}
override fun onModifyEntryError(onAction: () -> Unit) {
Snackbreak.bindTo(owner)
.long(root(), "Failed to modify list for $applicationName")
.setAction("Retry") { onAction() }
.show()
}
override fun onDatabaseChangeError(onAction: () -> Unit) {
Snackbreak.bindTo(owner)
.long(root(), "Failed realtime monitoring for $applicationName")
.setAction("Retry") { onAction() }
.show()
}
override fun onDatabaseChangeReceived(
index: Int,
entry: ActivityEntry
) {
modelAdapter.set(index, entry)
}
}
| apache-2.0 | ebaa7acb12f8a77f7d0d1de2ede06ef2 | 28.961877 | 94 | 0.717627 | 4.559125 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/lints/RsWhileTrueLoopInspection.kt | 3 | 2116 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.lints
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.rust.ide.inspections.RsProblemsHolder
import org.rust.ide.utils.skipParenExprDown
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.endOffsetInParent
/**
* Change `while true` to `loop`.
*/
class RsWhileTrueLoopInspection : RsLintInspection() {
override fun getDisplayName(): String = "While true loop"
override fun getLint(element: PsiElement): RsLint = RsLint.WhileTrue
override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): RsVisitor = object : RsVisitor() {
override fun visitWhileExpr(o: RsWhileExpr) {
val condition = o.condition ?: return
val expr = condition.skipParenExprDown() as? RsLitExpr ?: return
if (o.block == null) return
if (expr.textMatches("true")) {
holder.registerLintProblem(
o,
"Denote infinite loops with `loop { ... }`",
TextRange.create(o.`while`.startOffsetInParent, condition.endOffsetInParent),
RsLintHighlightingType.WEAK_WARNING,
listOf(UseLoopFix())
)
}
}
}
override val isSyntaxOnly: Boolean = true
private class UseLoopFix : LocalQuickFix {
override fun getFamilyName(): String = "Use `loop`"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? RsWhileExpr ?: return
val block = element.block ?: return
val label = element.labelDecl?.text ?: ""
val loopExpr = RsPsiFactory(project).createExpression("${label}loop ${block.text}") as RsLoopExpr
element.replace(loopExpr)
}
}
}
| mit | e0843c1b00f1729fe99cb5c50354304e | 37.472727 | 112 | 0.659263 | 4.620087 | false | false | false | false |
deva666/anko | anko/library/generated/sdk19/src/Views.kt | 2 | 107727 | @file:JvmName("Sdk19ViewsKt")
package org.jetbrains.anko
import org.jetbrains.anko.custom.*
import org.jetbrains.anko.AnkoViewDslMarker
import android.view.ViewManager
import android.view.ViewGroup.LayoutParams
import android.app.Activity
import android.app.Fragment
import android.content.Context
import android.os.Build
import android.widget.*
@PublishedApi
internal object `$$Anko$Factories$Sdk19View` {
val MEDIA_ROUTE_BUTTON = { ctx: Context -> android.app.MediaRouteButton(ctx) }
val GESTURE_OVERLAY_VIEW = { ctx: Context -> android.gesture.GestureOverlayView(ctx) }
val EXTRACT_EDIT_TEXT = { ctx: Context -> android.inputmethodservice.ExtractEditText(ctx) }
val G_L_SURFACE_VIEW = { ctx: Context -> android.opengl.GLSurfaceView(ctx) }
val SURFACE_VIEW = { ctx: Context -> android.view.SurfaceView(ctx) }
val TEXTURE_VIEW = { ctx: Context -> android.view.TextureView(ctx) }
val VIEW = { ctx: Context -> android.view.View(ctx) }
val VIEW_STUB = { ctx: Context -> android.view.ViewStub(ctx) }
val ADAPTER_VIEW_FLIPPER = { ctx: Context -> android.widget.AdapterViewFlipper(ctx) }
val ANALOG_CLOCK = { ctx: Context -> android.widget.AnalogClock(ctx) }
val AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> android.widget.AutoCompleteTextView(ctx) }
val BUTTON = { ctx: Context -> android.widget.Button(ctx) }
val CALENDAR_VIEW = { ctx: Context -> android.widget.CalendarView(ctx) }
val CHECK_BOX = { ctx: Context -> android.widget.CheckBox(ctx) }
val CHECKED_TEXT_VIEW = { ctx: Context -> android.widget.CheckedTextView(ctx) }
val CHRONOMETER = { ctx: Context -> android.widget.Chronometer(ctx) }
val DATE_PICKER = { ctx: Context -> android.widget.DatePicker(ctx) }
val DIALER_FILTER = { ctx: Context -> android.widget.DialerFilter(ctx) }
val DIGITAL_CLOCK = { ctx: Context -> android.widget.DigitalClock(ctx) }
val EDIT_TEXT = { ctx: Context -> android.widget.EditText(ctx) }
val EXPANDABLE_LIST_VIEW = { ctx: Context -> android.widget.ExpandableListView(ctx) }
val IMAGE_BUTTON = { ctx: Context -> android.widget.ImageButton(ctx) }
val IMAGE_VIEW = { ctx: Context -> android.widget.ImageView(ctx) }
val LIST_VIEW = { ctx: Context -> android.widget.ListView(ctx) }
val MULTI_AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> android.widget.MultiAutoCompleteTextView(ctx) }
val NUMBER_PICKER = { ctx: Context -> android.widget.NumberPicker(ctx) }
val PROGRESS_BAR = { ctx: Context -> android.widget.ProgressBar(ctx) }
val QUICK_CONTACT_BADGE = { ctx: Context -> android.widget.QuickContactBadge(ctx) }
val RADIO_BUTTON = { ctx: Context -> android.widget.RadioButton(ctx) }
val RATING_BAR = { ctx: Context -> android.widget.RatingBar(ctx) }
val SEARCH_VIEW = { ctx: Context -> android.widget.SearchView(ctx) }
val SEEK_BAR = { ctx: Context -> android.widget.SeekBar(ctx) }
val SLIDING_DRAWER = { ctx: Context -> android.widget.SlidingDrawer(ctx, null) }
val SPACE = { ctx: Context -> android.widget.Space(ctx) }
val SPINNER = { ctx: Context -> android.widget.Spinner(ctx) }
val STACK_VIEW = { ctx: Context -> android.widget.StackView(ctx) }
val SWITCH = { ctx: Context -> android.widget.Switch(ctx) }
val TAB_HOST = { ctx: Context -> android.widget.TabHost(ctx) }
val TAB_WIDGET = { ctx: Context -> android.widget.TabWidget(ctx) }
val TEXT_CLOCK = { ctx: Context -> android.widget.TextClock(ctx) }
val TEXT_VIEW = { ctx: Context -> android.widget.TextView(ctx) }
val TIME_PICKER = { ctx: Context -> android.widget.TimePicker(ctx) }
val TOGGLE_BUTTON = { ctx: Context -> android.widget.ToggleButton(ctx) }
val TWO_LINE_LIST_ITEM = { ctx: Context -> android.widget.TwoLineListItem(ctx) }
val VIDEO_VIEW = { ctx: Context -> android.widget.VideoView(ctx) }
val VIEW_FLIPPER = { ctx: Context -> android.widget.ViewFlipper(ctx) }
val ZOOM_BUTTON = { ctx: Context -> android.widget.ZoomButton(ctx) }
val ZOOM_CONTROLS = { ctx: Context -> android.widget.ZoomControls(ctx) }
}
inline fun ViewManager.mediaRouteButton(): android.app.MediaRouteButton = mediaRouteButton() {}
inline fun ViewManager.mediaRouteButton(init: (@AnkoViewDslMarker android.app.MediaRouteButton).() -> Unit): android.app.MediaRouteButton {
return ankoView(`$$Anko$Factories$Sdk19View`.MEDIA_ROUTE_BUTTON, theme = 0) { init() }
}
inline fun ViewManager.themedMediaRouteButton(theme: Int = 0): android.app.MediaRouteButton = themedMediaRouteButton(theme) {}
inline fun ViewManager.themedMediaRouteButton(theme: Int = 0, init: (@AnkoViewDslMarker android.app.MediaRouteButton).() -> Unit): android.app.MediaRouteButton {
return ankoView(`$$Anko$Factories$Sdk19View`.MEDIA_ROUTE_BUTTON, theme) { init() }
}
inline fun ViewManager.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView() {}
inline fun ViewManager.gestureOverlayView(init: (@AnkoViewDslMarker android.gesture.GestureOverlayView).() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk19View`.GESTURE_OVERLAY_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedGestureOverlayView(theme: Int = 0): android.gesture.GestureOverlayView = themedGestureOverlayView(theme) {}
inline fun ViewManager.themedGestureOverlayView(theme: Int = 0, init: (@AnkoViewDslMarker android.gesture.GestureOverlayView).() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk19View`.GESTURE_OVERLAY_VIEW, theme) { init() }
}
inline fun Context.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView() {}
inline fun Context.gestureOverlayView(init: (@AnkoViewDslMarker android.gesture.GestureOverlayView).() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk19View`.GESTURE_OVERLAY_VIEW, theme = 0) { init() }
}
inline fun Context.themedGestureOverlayView(theme: Int = 0): android.gesture.GestureOverlayView = themedGestureOverlayView(theme) {}
inline fun Context.themedGestureOverlayView(theme: Int = 0, init: (@AnkoViewDslMarker android.gesture.GestureOverlayView).() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk19View`.GESTURE_OVERLAY_VIEW, theme) { init() }
}
inline fun Activity.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView() {}
inline fun Activity.gestureOverlayView(init: (@AnkoViewDslMarker android.gesture.GestureOverlayView).() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk19View`.GESTURE_OVERLAY_VIEW, theme = 0) { init() }
}
inline fun Activity.themedGestureOverlayView(theme: Int = 0): android.gesture.GestureOverlayView = themedGestureOverlayView(theme) {}
inline fun Activity.themedGestureOverlayView(theme: Int = 0, init: (@AnkoViewDslMarker android.gesture.GestureOverlayView).() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk19View`.GESTURE_OVERLAY_VIEW, theme) { init() }
}
inline fun ViewManager.extractEditText(): android.inputmethodservice.ExtractEditText = extractEditText() {}
inline fun ViewManager.extractEditText(init: (@AnkoViewDslMarker android.inputmethodservice.ExtractEditText).() -> Unit): android.inputmethodservice.ExtractEditText {
return ankoView(`$$Anko$Factories$Sdk19View`.EXTRACT_EDIT_TEXT, theme = 0) { init() }
}
inline fun ViewManager.themedExtractEditText(theme: Int = 0): android.inputmethodservice.ExtractEditText = themedExtractEditText(theme) {}
inline fun ViewManager.themedExtractEditText(theme: Int = 0, init: (@AnkoViewDslMarker android.inputmethodservice.ExtractEditText).() -> Unit): android.inputmethodservice.ExtractEditText {
return ankoView(`$$Anko$Factories$Sdk19View`.EXTRACT_EDIT_TEXT, theme) { init() }
}
inline fun ViewManager.gLSurfaceView(): android.opengl.GLSurfaceView = gLSurfaceView() {}
inline fun ViewManager.gLSurfaceView(init: (@AnkoViewDslMarker android.opengl.GLSurfaceView).() -> Unit): android.opengl.GLSurfaceView {
return ankoView(`$$Anko$Factories$Sdk19View`.G_L_SURFACE_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedGLSurfaceView(theme: Int = 0): android.opengl.GLSurfaceView = themedGLSurfaceView(theme) {}
inline fun ViewManager.themedGLSurfaceView(theme: Int = 0, init: (@AnkoViewDslMarker android.opengl.GLSurfaceView).() -> Unit): android.opengl.GLSurfaceView {
return ankoView(`$$Anko$Factories$Sdk19View`.G_L_SURFACE_VIEW, theme) { init() }
}
inline fun ViewManager.surfaceView(): android.view.SurfaceView = surfaceView() {}
inline fun ViewManager.surfaceView(init: (@AnkoViewDslMarker android.view.SurfaceView).() -> Unit): android.view.SurfaceView {
return ankoView(`$$Anko$Factories$Sdk19View`.SURFACE_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedSurfaceView(theme: Int = 0): android.view.SurfaceView = themedSurfaceView(theme) {}
inline fun ViewManager.themedSurfaceView(theme: Int = 0, init: (@AnkoViewDslMarker android.view.SurfaceView).() -> Unit): android.view.SurfaceView {
return ankoView(`$$Anko$Factories$Sdk19View`.SURFACE_VIEW, theme) { init() }
}
inline fun ViewManager.textureView(): android.view.TextureView = textureView() {}
inline fun ViewManager.textureView(init: (@AnkoViewDslMarker android.view.TextureView).() -> Unit): android.view.TextureView {
return ankoView(`$$Anko$Factories$Sdk19View`.TEXTURE_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedTextureView(theme: Int = 0): android.view.TextureView = themedTextureView(theme) {}
inline fun ViewManager.themedTextureView(theme: Int = 0, init: (@AnkoViewDslMarker android.view.TextureView).() -> Unit): android.view.TextureView {
return ankoView(`$$Anko$Factories$Sdk19View`.TEXTURE_VIEW, theme) { init() }
}
inline fun ViewManager.view(): android.view.View = view() {}
inline fun ViewManager.view(init: (@AnkoViewDslMarker android.view.View).() -> Unit): android.view.View {
return ankoView(`$$Anko$Factories$Sdk19View`.VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedView(theme: Int = 0): android.view.View = themedView(theme) {}
inline fun ViewManager.themedView(theme: Int = 0, init: (@AnkoViewDslMarker android.view.View).() -> Unit): android.view.View {
return ankoView(`$$Anko$Factories$Sdk19View`.VIEW, theme) { init() }
}
inline fun ViewManager.viewStub(): android.view.ViewStub = viewStub() {}
inline fun ViewManager.viewStub(init: (@AnkoViewDslMarker android.view.ViewStub).() -> Unit): android.view.ViewStub {
return ankoView(`$$Anko$Factories$Sdk19View`.VIEW_STUB, theme = 0) { init() }
}
inline fun ViewManager.themedViewStub(theme: Int = 0): android.view.ViewStub = themedViewStub(theme) {}
inline fun ViewManager.themedViewStub(theme: Int = 0, init: (@AnkoViewDslMarker android.view.ViewStub).() -> Unit): android.view.ViewStub {
return ankoView(`$$Anko$Factories$Sdk19View`.VIEW_STUB, theme) { init() }
}
inline fun ViewManager.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper() {}
inline fun ViewManager.adapterViewFlipper(init: (@AnkoViewDslMarker android.widget.AdapterViewFlipper).() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk19View`.ADAPTER_VIEW_FLIPPER, theme = 0) { init() }
}
inline fun ViewManager.themedAdapterViewFlipper(theme: Int = 0): android.widget.AdapterViewFlipper = themedAdapterViewFlipper(theme) {}
inline fun ViewManager.themedAdapterViewFlipper(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.AdapterViewFlipper).() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk19View`.ADAPTER_VIEW_FLIPPER, theme) { init() }
}
inline fun Context.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper() {}
inline fun Context.adapterViewFlipper(init: (@AnkoViewDslMarker android.widget.AdapterViewFlipper).() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk19View`.ADAPTER_VIEW_FLIPPER, theme = 0) { init() }
}
inline fun Context.themedAdapterViewFlipper(theme: Int = 0): android.widget.AdapterViewFlipper = themedAdapterViewFlipper(theme) {}
inline fun Context.themedAdapterViewFlipper(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.AdapterViewFlipper).() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk19View`.ADAPTER_VIEW_FLIPPER, theme) { init() }
}
inline fun Activity.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper() {}
inline fun Activity.adapterViewFlipper(init: (@AnkoViewDslMarker android.widget.AdapterViewFlipper).() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk19View`.ADAPTER_VIEW_FLIPPER, theme = 0) { init() }
}
inline fun Activity.themedAdapterViewFlipper(theme: Int = 0): android.widget.AdapterViewFlipper = themedAdapterViewFlipper(theme) {}
inline fun Activity.themedAdapterViewFlipper(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.AdapterViewFlipper).() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk19View`.ADAPTER_VIEW_FLIPPER, theme) { init() }
}
inline fun ViewManager.analogClock(): android.widget.AnalogClock = analogClock() {}
inline fun ViewManager.analogClock(init: (@AnkoViewDslMarker android.widget.AnalogClock).() -> Unit): android.widget.AnalogClock {
return ankoView(`$$Anko$Factories$Sdk19View`.ANALOG_CLOCK, theme = 0) { init() }
}
inline fun ViewManager.themedAnalogClock(theme: Int = 0): android.widget.AnalogClock = themedAnalogClock(theme) {}
inline fun ViewManager.themedAnalogClock(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.AnalogClock).() -> Unit): android.widget.AnalogClock {
return ankoView(`$$Anko$Factories$Sdk19View`.ANALOG_CLOCK, theme) { init() }
}
inline fun ViewManager.autoCompleteTextView(): android.widget.AutoCompleteTextView = autoCompleteTextView() {}
inline fun ViewManager.autoCompleteTextView(init: (@AnkoViewDslMarker android.widget.AutoCompleteTextView).() -> Unit): android.widget.AutoCompleteTextView {
return ankoView(`$$Anko$Factories$Sdk19View`.AUTO_COMPLETE_TEXT_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedAutoCompleteTextView(theme: Int = 0): android.widget.AutoCompleteTextView = themedAutoCompleteTextView(theme) {}
inline fun ViewManager.themedAutoCompleteTextView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.AutoCompleteTextView).() -> Unit): android.widget.AutoCompleteTextView {
return ankoView(`$$Anko$Factories$Sdk19View`.AUTO_COMPLETE_TEXT_VIEW, theme) { init() }
}
inline fun ViewManager.button(): android.widget.Button = button() {}
inline fun ViewManager.button(init: (@AnkoViewDslMarker android.widget.Button).() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk19View`.BUTTON, theme = 0) { init() }
}
inline fun ViewManager.themedButton(theme: Int = 0): android.widget.Button = themedButton(theme) {}
inline fun ViewManager.themedButton(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.Button).() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk19View`.BUTTON, theme) { init() }
}
inline fun ViewManager.button(text: CharSequence?): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk19View`.BUTTON, theme = 0) {
setText(text)
}
}
inline fun ViewManager.button(text: CharSequence?, init: (@AnkoViewDslMarker android.widget.Button).() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk19View`.BUTTON, theme = 0) {
init()
setText(text)
}
}
inline fun ViewManager.themedButton(text: CharSequence?, theme: Int): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk19View`.BUTTON, theme) {
setText(text)
}
}
inline fun ViewManager.themedButton(text: CharSequence?, theme: Int, init: (@AnkoViewDslMarker android.widget.Button).() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk19View`.BUTTON, theme) {
init()
setText(text)
}
}
inline fun ViewManager.button(text: Int): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk19View`.BUTTON, theme = 0) {
setText(text)
}
}
inline fun ViewManager.button(text: Int, init: (@AnkoViewDslMarker android.widget.Button).() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk19View`.BUTTON, theme = 0) {
init()
setText(text)
}
}
inline fun ViewManager.themedButton(text: Int, theme: Int): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk19View`.BUTTON, theme) {
setText(text)
}
}
inline fun ViewManager.themedButton(text: Int, theme: Int, init: (@AnkoViewDslMarker android.widget.Button).() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk19View`.BUTTON, theme) {
init()
setText(text)
}
}
inline fun ViewManager.calendarView(): android.widget.CalendarView = calendarView() {}
inline fun ViewManager.calendarView(init: (@AnkoViewDslMarker android.widget.CalendarView).() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk19View`.CALENDAR_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedCalendarView(theme: Int = 0): android.widget.CalendarView = themedCalendarView(theme) {}
inline fun ViewManager.themedCalendarView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.CalendarView).() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk19View`.CALENDAR_VIEW, theme) { init() }
}
inline fun Context.calendarView(): android.widget.CalendarView = calendarView() {}
inline fun Context.calendarView(init: (@AnkoViewDslMarker android.widget.CalendarView).() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk19View`.CALENDAR_VIEW, theme = 0) { init() }
}
inline fun Context.themedCalendarView(theme: Int = 0): android.widget.CalendarView = themedCalendarView(theme) {}
inline fun Context.themedCalendarView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.CalendarView).() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk19View`.CALENDAR_VIEW, theme) { init() }
}
inline fun Activity.calendarView(): android.widget.CalendarView = calendarView() {}
inline fun Activity.calendarView(init: (@AnkoViewDslMarker android.widget.CalendarView).() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk19View`.CALENDAR_VIEW, theme = 0) { init() }
}
inline fun Activity.themedCalendarView(theme: Int = 0): android.widget.CalendarView = themedCalendarView(theme) {}
inline fun Activity.themedCalendarView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.CalendarView).() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk19View`.CALENDAR_VIEW, theme) { init() }
}
inline fun ViewManager.checkBox(): android.widget.CheckBox = checkBox() {}
inline fun ViewManager.checkBox(init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme = 0) { init() }
}
inline fun ViewManager.themedCheckBox(theme: Int = 0): android.widget.CheckBox = themedCheckBox(theme) {}
inline fun ViewManager.themedCheckBox(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme) { init() }
}
inline fun ViewManager.checkBox(text: CharSequence?): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme = 0) {
setText(text)
}
}
inline fun ViewManager.checkBox(text: CharSequence?, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme = 0) {
init()
setText(text)
}
}
inline fun ViewManager.themedCheckBox(text: CharSequence?, theme: Int): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme) {
setText(text)
}
}
inline fun ViewManager.themedCheckBox(text: CharSequence?, theme: Int, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme) {
init()
setText(text)
}
}
inline fun ViewManager.checkBox(text: Int): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme = 0) {
setText(text)
}
}
inline fun ViewManager.checkBox(text: Int, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme = 0) {
init()
setText(text)
}
}
inline fun ViewManager.themedCheckBox(text: Int, theme: Int): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme) {
setText(text)
}
}
inline fun ViewManager.themedCheckBox(text: Int, theme: Int, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme) {
init()
setText(text)
}
}
inline fun ViewManager.checkBox(text: CharSequence?, checked: Boolean): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme = 0) {
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.checkBox(text: CharSequence?, checked: Boolean, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme = 0) {
init()
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.themedCheckBox(text: CharSequence?, checked: Boolean, theme: Int): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme) {
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.themedCheckBox(text: CharSequence?, checked: Boolean, theme: Int, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme) {
init()
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.checkBox(text: Int, checked: Boolean): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme = 0) {
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.checkBox(text: Int, checked: Boolean, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme = 0) {
init()
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.themedCheckBox(text: Int, checked: Boolean, theme: Int): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme) {
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.themedCheckBox(text: Int, checked: Boolean, theme: Int, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX, theme) {
init()
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.checkedTextView(): android.widget.CheckedTextView = checkedTextView() {}
inline fun ViewManager.checkedTextView(init: (@AnkoViewDslMarker android.widget.CheckedTextView).() -> Unit): android.widget.CheckedTextView {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECKED_TEXT_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedCheckedTextView(theme: Int = 0): android.widget.CheckedTextView = themedCheckedTextView(theme) {}
inline fun ViewManager.themedCheckedTextView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.CheckedTextView).() -> Unit): android.widget.CheckedTextView {
return ankoView(`$$Anko$Factories$Sdk19View`.CHECKED_TEXT_VIEW, theme) { init() }
}
inline fun ViewManager.chronometer(): android.widget.Chronometer = chronometer() {}
inline fun ViewManager.chronometer(init: (@AnkoViewDslMarker android.widget.Chronometer).() -> Unit): android.widget.Chronometer {
return ankoView(`$$Anko$Factories$Sdk19View`.CHRONOMETER, theme = 0) { init() }
}
inline fun ViewManager.themedChronometer(theme: Int = 0): android.widget.Chronometer = themedChronometer(theme) {}
inline fun ViewManager.themedChronometer(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.Chronometer).() -> Unit): android.widget.Chronometer {
return ankoView(`$$Anko$Factories$Sdk19View`.CHRONOMETER, theme) { init() }
}
inline fun ViewManager.datePicker(): android.widget.DatePicker = datePicker() {}
inline fun ViewManager.datePicker(init: (@AnkoViewDslMarker android.widget.DatePicker).() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk19View`.DATE_PICKER, theme = 0) { init() }
}
inline fun ViewManager.themedDatePicker(theme: Int = 0): android.widget.DatePicker = themedDatePicker(theme) {}
inline fun ViewManager.themedDatePicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.DatePicker).() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk19View`.DATE_PICKER, theme) { init() }
}
inline fun Context.datePicker(): android.widget.DatePicker = datePicker() {}
inline fun Context.datePicker(init: (@AnkoViewDslMarker android.widget.DatePicker).() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk19View`.DATE_PICKER, theme = 0) { init() }
}
inline fun Context.themedDatePicker(theme: Int = 0): android.widget.DatePicker = themedDatePicker(theme) {}
inline fun Context.themedDatePicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.DatePicker).() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk19View`.DATE_PICKER, theme) { init() }
}
inline fun Activity.datePicker(): android.widget.DatePicker = datePicker() {}
inline fun Activity.datePicker(init: (@AnkoViewDslMarker android.widget.DatePicker).() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk19View`.DATE_PICKER, theme = 0) { init() }
}
inline fun Activity.themedDatePicker(theme: Int = 0): android.widget.DatePicker = themedDatePicker(theme) {}
inline fun Activity.themedDatePicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.DatePicker).() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk19View`.DATE_PICKER, theme) { init() }
}
inline fun ViewManager.dialerFilter(): android.widget.DialerFilter = dialerFilter() {}
inline fun ViewManager.dialerFilter(init: (@AnkoViewDslMarker android.widget.DialerFilter).() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk19View`.DIALER_FILTER, theme = 0) { init() }
}
inline fun ViewManager.themedDialerFilter(theme: Int = 0): android.widget.DialerFilter = themedDialerFilter(theme) {}
inline fun ViewManager.themedDialerFilter(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.DialerFilter).() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk19View`.DIALER_FILTER, theme) { init() }
}
inline fun Context.dialerFilter(): android.widget.DialerFilter = dialerFilter() {}
inline fun Context.dialerFilter(init: (@AnkoViewDslMarker android.widget.DialerFilter).() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk19View`.DIALER_FILTER, theme = 0) { init() }
}
inline fun Context.themedDialerFilter(theme: Int = 0): android.widget.DialerFilter = themedDialerFilter(theme) {}
inline fun Context.themedDialerFilter(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.DialerFilter).() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk19View`.DIALER_FILTER, theme) { init() }
}
inline fun Activity.dialerFilter(): android.widget.DialerFilter = dialerFilter() {}
inline fun Activity.dialerFilter(init: (@AnkoViewDslMarker android.widget.DialerFilter).() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk19View`.DIALER_FILTER, theme = 0) { init() }
}
inline fun Activity.themedDialerFilter(theme: Int = 0): android.widget.DialerFilter = themedDialerFilter(theme) {}
inline fun Activity.themedDialerFilter(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.DialerFilter).() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk19View`.DIALER_FILTER, theme) { init() }
}
inline fun ViewManager.digitalClock(): android.widget.DigitalClock = digitalClock() {}
inline fun ViewManager.digitalClock(init: (@AnkoViewDslMarker android.widget.DigitalClock).() -> Unit): android.widget.DigitalClock {
return ankoView(`$$Anko$Factories$Sdk19View`.DIGITAL_CLOCK, theme = 0) { init() }
}
inline fun ViewManager.themedDigitalClock(theme: Int = 0): android.widget.DigitalClock = themedDigitalClock(theme) {}
inline fun ViewManager.themedDigitalClock(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.DigitalClock).() -> Unit): android.widget.DigitalClock {
return ankoView(`$$Anko$Factories$Sdk19View`.DIGITAL_CLOCK, theme) { init() }
}
inline fun ViewManager.editText(): android.widget.EditText = editText() {}
inline fun ViewManager.editText(init: (@AnkoViewDslMarker android.widget.EditText).() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk19View`.EDIT_TEXT, theme = 0) { init() }
}
inline fun ViewManager.themedEditText(theme: Int = 0): android.widget.EditText = themedEditText(theme) {}
inline fun ViewManager.themedEditText(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.EditText).() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk19View`.EDIT_TEXT, theme) { init() }
}
inline fun ViewManager.editText(text: CharSequence?): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk19View`.EDIT_TEXT, theme = 0) {
setText(text)
}
}
inline fun ViewManager.editText(text: CharSequence?, init: (@AnkoViewDslMarker android.widget.EditText).() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk19View`.EDIT_TEXT, theme = 0) {
init()
setText(text)
}
}
inline fun ViewManager.themedEditText(text: CharSequence?, theme: Int): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk19View`.EDIT_TEXT, theme) {
setText(text)
}
}
inline fun ViewManager.themedEditText(text: CharSequence?, theme: Int, init: (@AnkoViewDslMarker android.widget.EditText).() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk19View`.EDIT_TEXT, theme) {
init()
setText(text)
}
}
inline fun ViewManager.editText(text: Int): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk19View`.EDIT_TEXT, theme = 0) {
setText(text)
}
}
inline fun ViewManager.editText(text: Int, init: (@AnkoViewDslMarker android.widget.EditText).() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk19View`.EDIT_TEXT, theme = 0) {
init()
setText(text)
}
}
inline fun ViewManager.themedEditText(text: Int, theme: Int): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk19View`.EDIT_TEXT, theme) {
setText(text)
}
}
inline fun ViewManager.themedEditText(text: Int, theme: Int, init: (@AnkoViewDslMarker android.widget.EditText).() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk19View`.EDIT_TEXT, theme) {
init()
setText(text)
}
}
inline fun ViewManager.expandableListView(): android.widget.ExpandableListView = expandableListView() {}
inline fun ViewManager.expandableListView(init: (@AnkoViewDslMarker android.widget.ExpandableListView).() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk19View`.EXPANDABLE_LIST_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedExpandableListView(theme: Int = 0): android.widget.ExpandableListView = themedExpandableListView(theme) {}
inline fun ViewManager.themedExpandableListView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ExpandableListView).() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk19View`.EXPANDABLE_LIST_VIEW, theme) { init() }
}
inline fun Context.expandableListView(): android.widget.ExpandableListView = expandableListView() {}
inline fun Context.expandableListView(init: (@AnkoViewDslMarker android.widget.ExpandableListView).() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk19View`.EXPANDABLE_LIST_VIEW, theme = 0) { init() }
}
inline fun Context.themedExpandableListView(theme: Int = 0): android.widget.ExpandableListView = themedExpandableListView(theme) {}
inline fun Context.themedExpandableListView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ExpandableListView).() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk19View`.EXPANDABLE_LIST_VIEW, theme) { init() }
}
inline fun Activity.expandableListView(): android.widget.ExpandableListView = expandableListView() {}
inline fun Activity.expandableListView(init: (@AnkoViewDslMarker android.widget.ExpandableListView).() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk19View`.EXPANDABLE_LIST_VIEW, theme = 0) { init() }
}
inline fun Activity.themedExpandableListView(theme: Int = 0): android.widget.ExpandableListView = themedExpandableListView(theme) {}
inline fun Activity.themedExpandableListView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ExpandableListView).() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk19View`.EXPANDABLE_LIST_VIEW, theme) { init() }
}
inline fun ViewManager.imageButton(): android.widget.ImageButton = imageButton() {}
inline fun ViewManager.imageButton(init: (@AnkoViewDslMarker android.widget.ImageButton).() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_BUTTON, theme = 0) { init() }
}
inline fun ViewManager.themedImageButton(theme: Int = 0): android.widget.ImageButton = themedImageButton(theme) {}
inline fun ViewManager.themedImageButton(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ImageButton).() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_BUTTON, theme) { init() }
}
inline fun ViewManager.imageButton(imageDrawable: android.graphics.drawable.Drawable?): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_BUTTON, theme = 0) {
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.imageButton(imageDrawable: android.graphics.drawable.Drawable?, init: (@AnkoViewDslMarker android.widget.ImageButton).() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_BUTTON, theme = 0) {
init()
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.themedImageButton(imageDrawable: android.graphics.drawable.Drawable?, theme: Int): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_BUTTON, theme) {
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.themedImageButton(imageDrawable: android.graphics.drawable.Drawable?, theme: Int, init: (@AnkoViewDslMarker android.widget.ImageButton).() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_BUTTON, theme) {
init()
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.imageButton(imageResource: Int): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_BUTTON, theme = 0) {
setImageResource(imageResource)
}
}
inline fun ViewManager.imageButton(imageResource: Int, init: (@AnkoViewDslMarker android.widget.ImageButton).() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_BUTTON, theme = 0) {
init()
setImageResource(imageResource)
}
}
inline fun ViewManager.themedImageButton(imageResource: Int, theme: Int): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_BUTTON, theme) {
setImageResource(imageResource)
}
}
inline fun ViewManager.themedImageButton(imageResource: Int, theme: Int, init: (@AnkoViewDslMarker android.widget.ImageButton).() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_BUTTON, theme) {
init()
setImageResource(imageResource)
}
}
inline fun ViewManager.imageView(): android.widget.ImageView = imageView() {}
inline fun ViewManager.imageView(init: (@AnkoViewDslMarker android.widget.ImageView).() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedImageView(theme: Int = 0): android.widget.ImageView = themedImageView(theme) {}
inline fun ViewManager.themedImageView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ImageView).() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_VIEW, theme) { init() }
}
inline fun ViewManager.imageView(imageDrawable: android.graphics.drawable.Drawable?): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_VIEW, theme = 0) {
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.imageView(imageDrawable: android.graphics.drawable.Drawable?, init: (@AnkoViewDslMarker android.widget.ImageView).() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_VIEW, theme = 0) {
init()
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.themedImageView(imageDrawable: android.graphics.drawable.Drawable?, theme: Int): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_VIEW, theme) {
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.themedImageView(imageDrawable: android.graphics.drawable.Drawable?, theme: Int, init: (@AnkoViewDslMarker android.widget.ImageView).() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_VIEW, theme) {
init()
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.imageView(imageResource: Int): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_VIEW, theme = 0) {
setImageResource(imageResource)
}
}
inline fun ViewManager.imageView(imageResource: Int, init: (@AnkoViewDslMarker android.widget.ImageView).() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_VIEW, theme = 0) {
init()
setImageResource(imageResource)
}
}
inline fun ViewManager.themedImageView(imageResource: Int, theme: Int): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_VIEW, theme) {
setImageResource(imageResource)
}
}
inline fun ViewManager.themedImageView(imageResource: Int, theme: Int, init: (@AnkoViewDslMarker android.widget.ImageView).() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_VIEW, theme) {
init()
setImageResource(imageResource)
}
}
inline fun ViewManager.listView(): android.widget.ListView = listView() {}
inline fun ViewManager.listView(init: (@AnkoViewDslMarker android.widget.ListView).() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk19View`.LIST_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedListView(theme: Int = 0): android.widget.ListView = themedListView(theme) {}
inline fun ViewManager.themedListView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ListView).() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk19View`.LIST_VIEW, theme) { init() }
}
inline fun Context.listView(): android.widget.ListView = listView() {}
inline fun Context.listView(init: (@AnkoViewDslMarker android.widget.ListView).() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk19View`.LIST_VIEW, theme = 0) { init() }
}
inline fun Context.themedListView(theme: Int = 0): android.widget.ListView = themedListView(theme) {}
inline fun Context.themedListView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ListView).() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk19View`.LIST_VIEW, theme) { init() }
}
inline fun Activity.listView(): android.widget.ListView = listView() {}
inline fun Activity.listView(init: (@AnkoViewDslMarker android.widget.ListView).() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk19View`.LIST_VIEW, theme = 0) { init() }
}
inline fun Activity.themedListView(theme: Int = 0): android.widget.ListView = themedListView(theme) {}
inline fun Activity.themedListView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ListView).() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk19View`.LIST_VIEW, theme) { init() }
}
inline fun ViewManager.multiAutoCompleteTextView(): android.widget.MultiAutoCompleteTextView = multiAutoCompleteTextView() {}
inline fun ViewManager.multiAutoCompleteTextView(init: (@AnkoViewDslMarker android.widget.MultiAutoCompleteTextView).() -> Unit): android.widget.MultiAutoCompleteTextView {
return ankoView(`$$Anko$Factories$Sdk19View`.MULTI_AUTO_COMPLETE_TEXT_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedMultiAutoCompleteTextView(theme: Int = 0): android.widget.MultiAutoCompleteTextView = themedMultiAutoCompleteTextView(theme) {}
inline fun ViewManager.themedMultiAutoCompleteTextView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.MultiAutoCompleteTextView).() -> Unit): android.widget.MultiAutoCompleteTextView {
return ankoView(`$$Anko$Factories$Sdk19View`.MULTI_AUTO_COMPLETE_TEXT_VIEW, theme) { init() }
}
inline fun ViewManager.numberPicker(): android.widget.NumberPicker = numberPicker() {}
inline fun ViewManager.numberPicker(init: (@AnkoViewDslMarker android.widget.NumberPicker).() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk19View`.NUMBER_PICKER, theme = 0) { init() }
}
inline fun ViewManager.themedNumberPicker(theme: Int = 0): android.widget.NumberPicker = themedNumberPicker(theme) {}
inline fun ViewManager.themedNumberPicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.NumberPicker).() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk19View`.NUMBER_PICKER, theme) { init() }
}
inline fun Context.numberPicker(): android.widget.NumberPicker = numberPicker() {}
inline fun Context.numberPicker(init: (@AnkoViewDslMarker android.widget.NumberPicker).() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk19View`.NUMBER_PICKER, theme = 0) { init() }
}
inline fun Context.themedNumberPicker(theme: Int = 0): android.widget.NumberPicker = themedNumberPicker(theme) {}
inline fun Context.themedNumberPicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.NumberPicker).() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk19View`.NUMBER_PICKER, theme) { init() }
}
inline fun Activity.numberPicker(): android.widget.NumberPicker = numberPicker() {}
inline fun Activity.numberPicker(init: (@AnkoViewDslMarker android.widget.NumberPicker).() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk19View`.NUMBER_PICKER, theme = 0) { init() }
}
inline fun Activity.themedNumberPicker(theme: Int = 0): android.widget.NumberPicker = themedNumberPicker(theme) {}
inline fun Activity.themedNumberPicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.NumberPicker).() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk19View`.NUMBER_PICKER, theme) { init() }
}
inline fun ViewManager.progressBar(): android.widget.ProgressBar = progressBar() {}
inline fun ViewManager.progressBar(init: (@AnkoViewDslMarker android.widget.ProgressBar).() -> Unit): android.widget.ProgressBar {
return ankoView(`$$Anko$Factories$Sdk19View`.PROGRESS_BAR, theme = 0) { init() }
}
inline fun ViewManager.themedProgressBar(theme: Int = 0): android.widget.ProgressBar = themedProgressBar(theme) {}
inline fun ViewManager.themedProgressBar(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ProgressBar).() -> Unit): android.widget.ProgressBar {
return ankoView(`$$Anko$Factories$Sdk19View`.PROGRESS_BAR, theme) { init() }
}
inline fun ViewManager.quickContactBadge(): android.widget.QuickContactBadge = quickContactBadge() {}
inline fun ViewManager.quickContactBadge(init: (@AnkoViewDslMarker android.widget.QuickContactBadge).() -> Unit): android.widget.QuickContactBadge {
return ankoView(`$$Anko$Factories$Sdk19View`.QUICK_CONTACT_BADGE, theme = 0) { init() }
}
inline fun ViewManager.themedQuickContactBadge(theme: Int = 0): android.widget.QuickContactBadge = themedQuickContactBadge(theme) {}
inline fun ViewManager.themedQuickContactBadge(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.QuickContactBadge).() -> Unit): android.widget.QuickContactBadge {
return ankoView(`$$Anko$Factories$Sdk19View`.QUICK_CONTACT_BADGE, theme) { init() }
}
inline fun ViewManager.radioButton(): android.widget.RadioButton = radioButton() {}
inline fun ViewManager.radioButton(init: (@AnkoViewDslMarker android.widget.RadioButton).() -> Unit): android.widget.RadioButton {
return ankoView(`$$Anko$Factories$Sdk19View`.RADIO_BUTTON, theme = 0) { init() }
}
inline fun ViewManager.themedRadioButton(theme: Int = 0): android.widget.RadioButton = themedRadioButton(theme) {}
inline fun ViewManager.themedRadioButton(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.RadioButton).() -> Unit): android.widget.RadioButton {
return ankoView(`$$Anko$Factories$Sdk19View`.RADIO_BUTTON, theme) { init() }
}
inline fun ViewManager.ratingBar(): android.widget.RatingBar = ratingBar() {}
inline fun ViewManager.ratingBar(init: (@AnkoViewDslMarker android.widget.RatingBar).() -> Unit): android.widget.RatingBar {
return ankoView(`$$Anko$Factories$Sdk19View`.RATING_BAR, theme = 0) { init() }
}
inline fun ViewManager.themedRatingBar(theme: Int = 0): android.widget.RatingBar = themedRatingBar(theme) {}
inline fun ViewManager.themedRatingBar(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.RatingBar).() -> Unit): android.widget.RatingBar {
return ankoView(`$$Anko$Factories$Sdk19View`.RATING_BAR, theme) { init() }
}
inline fun ViewManager.searchView(): android.widget.SearchView = searchView() {}
inline fun ViewManager.searchView(init: (@AnkoViewDslMarker android.widget.SearchView).() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk19View`.SEARCH_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedSearchView(theme: Int = 0): android.widget.SearchView = themedSearchView(theme) {}
inline fun ViewManager.themedSearchView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.SearchView).() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk19View`.SEARCH_VIEW, theme) { init() }
}
inline fun Context.searchView(): android.widget.SearchView = searchView() {}
inline fun Context.searchView(init: (@AnkoViewDslMarker android.widget.SearchView).() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk19View`.SEARCH_VIEW, theme = 0) { init() }
}
inline fun Context.themedSearchView(theme: Int = 0): android.widget.SearchView = themedSearchView(theme) {}
inline fun Context.themedSearchView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.SearchView).() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk19View`.SEARCH_VIEW, theme) { init() }
}
inline fun Activity.searchView(): android.widget.SearchView = searchView() {}
inline fun Activity.searchView(init: (@AnkoViewDslMarker android.widget.SearchView).() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk19View`.SEARCH_VIEW, theme = 0) { init() }
}
inline fun Activity.themedSearchView(theme: Int = 0): android.widget.SearchView = themedSearchView(theme) {}
inline fun Activity.themedSearchView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.SearchView).() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk19View`.SEARCH_VIEW, theme) { init() }
}
inline fun ViewManager.seekBar(): android.widget.SeekBar = seekBar() {}
inline fun ViewManager.seekBar(init: (@AnkoViewDslMarker android.widget.SeekBar).() -> Unit): android.widget.SeekBar {
return ankoView(`$$Anko$Factories$Sdk19View`.SEEK_BAR, theme = 0) { init() }
}
inline fun ViewManager.themedSeekBar(theme: Int = 0): android.widget.SeekBar = themedSeekBar(theme) {}
inline fun ViewManager.themedSeekBar(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.SeekBar).() -> Unit): android.widget.SeekBar {
return ankoView(`$$Anko$Factories$Sdk19View`.SEEK_BAR, theme) { init() }
}
inline fun ViewManager.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer() {}
inline fun ViewManager.slidingDrawer(init: (@AnkoViewDslMarker android.widget.SlidingDrawer).() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk19View`.SLIDING_DRAWER, theme = 0) { init() }
}
inline fun ViewManager.themedSlidingDrawer(theme: Int = 0): android.widget.SlidingDrawer = themedSlidingDrawer(theme) {}
inline fun ViewManager.themedSlidingDrawer(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.SlidingDrawer).() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk19View`.SLIDING_DRAWER, theme) { init() }
}
inline fun Context.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer() {}
inline fun Context.slidingDrawer(init: (@AnkoViewDslMarker android.widget.SlidingDrawer).() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk19View`.SLIDING_DRAWER, theme = 0) { init() }
}
inline fun Context.themedSlidingDrawer(theme: Int = 0): android.widget.SlidingDrawer = themedSlidingDrawer(theme) {}
inline fun Context.themedSlidingDrawer(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.SlidingDrawer).() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk19View`.SLIDING_DRAWER, theme) { init() }
}
inline fun Activity.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer() {}
inline fun Activity.slidingDrawer(init: (@AnkoViewDslMarker android.widget.SlidingDrawer).() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk19View`.SLIDING_DRAWER, theme = 0) { init() }
}
inline fun Activity.themedSlidingDrawer(theme: Int = 0): android.widget.SlidingDrawer = themedSlidingDrawer(theme) {}
inline fun Activity.themedSlidingDrawer(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.SlidingDrawer).() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk19View`.SLIDING_DRAWER, theme) { init() }
}
inline fun ViewManager.space(): android.widget.Space = space() {}
inline fun ViewManager.space(init: (@AnkoViewDslMarker android.widget.Space).() -> Unit): android.widget.Space {
return ankoView(`$$Anko$Factories$Sdk19View`.SPACE, theme = 0) { init() }
}
inline fun ViewManager.themedSpace(theme: Int = 0): android.widget.Space = themedSpace(theme) {}
inline fun ViewManager.themedSpace(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.Space).() -> Unit): android.widget.Space {
return ankoView(`$$Anko$Factories$Sdk19View`.SPACE, theme) { init() }
}
inline fun ViewManager.spinner(): android.widget.Spinner = spinner() {}
inline fun ViewManager.spinner(init: (@AnkoViewDslMarker android.widget.Spinner).() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk19View`.SPINNER, theme = 0) { init() }
}
inline fun ViewManager.themedSpinner(theme: Int = 0): android.widget.Spinner = themedSpinner(theme) {}
inline fun ViewManager.themedSpinner(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.Spinner).() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk19View`.SPINNER, theme) { init() }
}
inline fun Context.spinner(): android.widget.Spinner = spinner() {}
inline fun Context.spinner(init: (@AnkoViewDslMarker android.widget.Spinner).() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk19View`.SPINNER, theme = 0) { init() }
}
inline fun Context.themedSpinner(theme: Int = 0): android.widget.Spinner = themedSpinner(theme) {}
inline fun Context.themedSpinner(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.Spinner).() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk19View`.SPINNER, theme) { init() }
}
inline fun Activity.spinner(): android.widget.Spinner = spinner() {}
inline fun Activity.spinner(init: (@AnkoViewDslMarker android.widget.Spinner).() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk19View`.SPINNER, theme = 0) { init() }
}
inline fun Activity.themedSpinner(theme: Int = 0): android.widget.Spinner = themedSpinner(theme) {}
inline fun Activity.themedSpinner(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.Spinner).() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk19View`.SPINNER, theme) { init() }
}
inline fun ViewManager.stackView(): android.widget.StackView = stackView() {}
inline fun ViewManager.stackView(init: (@AnkoViewDslMarker android.widget.StackView).() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk19View`.STACK_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedStackView(theme: Int = 0): android.widget.StackView = themedStackView(theme) {}
inline fun ViewManager.themedStackView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.StackView).() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk19View`.STACK_VIEW, theme) { init() }
}
inline fun Context.stackView(): android.widget.StackView = stackView() {}
inline fun Context.stackView(init: (@AnkoViewDslMarker android.widget.StackView).() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk19View`.STACK_VIEW, theme = 0) { init() }
}
inline fun Context.themedStackView(theme: Int = 0): android.widget.StackView = themedStackView(theme) {}
inline fun Context.themedStackView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.StackView).() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk19View`.STACK_VIEW, theme) { init() }
}
inline fun Activity.stackView(): android.widget.StackView = stackView() {}
inline fun Activity.stackView(init: (@AnkoViewDslMarker android.widget.StackView).() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk19View`.STACK_VIEW, theme = 0) { init() }
}
inline fun Activity.themedStackView(theme: Int = 0): android.widget.StackView = themedStackView(theme) {}
inline fun Activity.themedStackView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.StackView).() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk19View`.STACK_VIEW, theme) { init() }
}
inline fun ViewManager.switch(): android.widget.Switch = switch() {}
inline fun ViewManager.switch(init: (@AnkoViewDslMarker android.widget.Switch).() -> Unit): android.widget.Switch {
return ankoView(`$$Anko$Factories$Sdk19View`.SWITCH, theme = 0) { init() }
}
inline fun ViewManager.themedSwitch(theme: Int = 0): android.widget.Switch = themedSwitch(theme) {}
inline fun ViewManager.themedSwitch(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.Switch).() -> Unit): android.widget.Switch {
return ankoView(`$$Anko$Factories$Sdk19View`.SWITCH, theme) { init() }
}
inline fun ViewManager.tabHost(): android.widget.TabHost = tabHost() {}
inline fun ViewManager.tabHost(init: (@AnkoViewDslMarker android.widget.TabHost).() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk19View`.TAB_HOST, theme = 0) { init() }
}
inline fun ViewManager.themedTabHost(theme: Int = 0): android.widget.TabHost = themedTabHost(theme) {}
inline fun ViewManager.themedTabHost(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TabHost).() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk19View`.TAB_HOST, theme) { init() }
}
inline fun Context.tabHost(): android.widget.TabHost = tabHost() {}
inline fun Context.tabHost(init: (@AnkoViewDslMarker android.widget.TabHost).() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk19View`.TAB_HOST, theme = 0) { init() }
}
inline fun Context.themedTabHost(theme: Int = 0): android.widget.TabHost = themedTabHost(theme) {}
inline fun Context.themedTabHost(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TabHost).() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk19View`.TAB_HOST, theme) { init() }
}
inline fun Activity.tabHost(): android.widget.TabHost = tabHost() {}
inline fun Activity.tabHost(init: (@AnkoViewDslMarker android.widget.TabHost).() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk19View`.TAB_HOST, theme = 0) { init() }
}
inline fun Activity.themedTabHost(theme: Int = 0): android.widget.TabHost = themedTabHost(theme) {}
inline fun Activity.themedTabHost(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TabHost).() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk19View`.TAB_HOST, theme) { init() }
}
inline fun ViewManager.tabWidget(): android.widget.TabWidget = tabWidget() {}
inline fun ViewManager.tabWidget(init: (@AnkoViewDslMarker android.widget.TabWidget).() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk19View`.TAB_WIDGET, theme = 0) { init() }
}
inline fun ViewManager.themedTabWidget(theme: Int = 0): android.widget.TabWidget = themedTabWidget(theme) {}
inline fun ViewManager.themedTabWidget(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TabWidget).() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk19View`.TAB_WIDGET, theme) { init() }
}
inline fun Context.tabWidget(): android.widget.TabWidget = tabWidget() {}
inline fun Context.tabWidget(init: (@AnkoViewDslMarker android.widget.TabWidget).() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk19View`.TAB_WIDGET, theme = 0) { init() }
}
inline fun Context.themedTabWidget(theme: Int = 0): android.widget.TabWidget = themedTabWidget(theme) {}
inline fun Context.themedTabWidget(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TabWidget).() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk19View`.TAB_WIDGET, theme) { init() }
}
inline fun Activity.tabWidget(): android.widget.TabWidget = tabWidget() {}
inline fun Activity.tabWidget(init: (@AnkoViewDslMarker android.widget.TabWidget).() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk19View`.TAB_WIDGET, theme = 0) { init() }
}
inline fun Activity.themedTabWidget(theme: Int = 0): android.widget.TabWidget = themedTabWidget(theme) {}
inline fun Activity.themedTabWidget(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TabWidget).() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk19View`.TAB_WIDGET, theme) { init() }
}
inline fun ViewManager.textClock(): android.widget.TextClock = textClock() {}
inline fun ViewManager.textClock(init: (@AnkoViewDslMarker android.widget.TextClock).() -> Unit): android.widget.TextClock {
return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_CLOCK, theme = 0) { init() }
}
inline fun ViewManager.themedTextClock(theme: Int = 0): android.widget.TextClock = themedTextClock(theme) {}
inline fun ViewManager.themedTextClock(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TextClock).() -> Unit): android.widget.TextClock {
return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_CLOCK, theme) { init() }
}
inline fun ViewManager.textView(): android.widget.TextView = textView() {}
inline fun ViewManager.textView(init: (@AnkoViewDslMarker android.widget.TextView).() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedTextView(theme: Int = 0): android.widget.TextView = themedTextView(theme) {}
inline fun ViewManager.themedTextView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TextView).() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_VIEW, theme) { init() }
}
inline fun ViewManager.textView(text: CharSequence?): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_VIEW, theme = 0) {
setText(text)
}
}
inline fun ViewManager.textView(text: CharSequence?, init: (@AnkoViewDslMarker android.widget.TextView).() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_VIEW, theme = 0) {
init()
setText(text)
}
}
inline fun ViewManager.themedTextView(text: CharSequence?, theme: Int): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_VIEW, theme) {
setText(text)
}
}
inline fun ViewManager.themedTextView(text: CharSequence?, theme: Int, init: (@AnkoViewDslMarker android.widget.TextView).() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_VIEW, theme) {
init()
setText(text)
}
}
inline fun ViewManager.textView(text: Int): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_VIEW, theme = 0) {
setText(text)
}
}
inline fun ViewManager.textView(text: Int, init: (@AnkoViewDslMarker android.widget.TextView).() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_VIEW, theme = 0) {
init()
setText(text)
}
}
inline fun ViewManager.themedTextView(text: Int, theme: Int): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_VIEW, theme) {
setText(text)
}
}
inline fun ViewManager.themedTextView(text: Int, theme: Int, init: (@AnkoViewDslMarker android.widget.TextView).() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_VIEW, theme) {
init()
setText(text)
}
}
inline fun ViewManager.timePicker(): android.widget.TimePicker = timePicker() {}
inline fun ViewManager.timePicker(init: (@AnkoViewDslMarker android.widget.TimePicker).() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk19View`.TIME_PICKER, theme = 0) { init() }
}
inline fun ViewManager.themedTimePicker(theme: Int = 0): android.widget.TimePicker = themedTimePicker(theme) {}
inline fun ViewManager.themedTimePicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TimePicker).() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk19View`.TIME_PICKER, theme) { init() }
}
inline fun Context.timePicker(): android.widget.TimePicker = timePicker() {}
inline fun Context.timePicker(init: (@AnkoViewDslMarker android.widget.TimePicker).() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk19View`.TIME_PICKER, theme = 0) { init() }
}
inline fun Context.themedTimePicker(theme: Int = 0): android.widget.TimePicker = themedTimePicker(theme) {}
inline fun Context.themedTimePicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TimePicker).() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk19View`.TIME_PICKER, theme) { init() }
}
inline fun Activity.timePicker(): android.widget.TimePicker = timePicker() {}
inline fun Activity.timePicker(init: (@AnkoViewDslMarker android.widget.TimePicker).() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk19View`.TIME_PICKER, theme = 0) { init() }
}
inline fun Activity.themedTimePicker(theme: Int = 0): android.widget.TimePicker = themedTimePicker(theme) {}
inline fun Activity.themedTimePicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TimePicker).() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk19View`.TIME_PICKER, theme) { init() }
}
inline fun ViewManager.toggleButton(): android.widget.ToggleButton = toggleButton() {}
inline fun ViewManager.toggleButton(init: (@AnkoViewDslMarker android.widget.ToggleButton).() -> Unit): android.widget.ToggleButton {
return ankoView(`$$Anko$Factories$Sdk19View`.TOGGLE_BUTTON, theme = 0) { init() }
}
inline fun ViewManager.themedToggleButton(theme: Int = 0): android.widget.ToggleButton = themedToggleButton(theme) {}
inline fun ViewManager.themedToggleButton(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ToggleButton).() -> Unit): android.widget.ToggleButton {
return ankoView(`$$Anko$Factories$Sdk19View`.TOGGLE_BUTTON, theme) { init() }
}
inline fun ViewManager.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem() {}
inline fun ViewManager.twoLineListItem(init: (@AnkoViewDslMarker android.widget.TwoLineListItem).() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk19View`.TWO_LINE_LIST_ITEM, theme = 0) { init() }
}
inline fun ViewManager.themedTwoLineListItem(theme: Int = 0): android.widget.TwoLineListItem = themedTwoLineListItem(theme) {}
inline fun ViewManager.themedTwoLineListItem(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TwoLineListItem).() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk19View`.TWO_LINE_LIST_ITEM, theme) { init() }
}
inline fun Context.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem() {}
inline fun Context.twoLineListItem(init: (@AnkoViewDslMarker android.widget.TwoLineListItem).() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk19View`.TWO_LINE_LIST_ITEM, theme = 0) { init() }
}
inline fun Context.themedTwoLineListItem(theme: Int = 0): android.widget.TwoLineListItem = themedTwoLineListItem(theme) {}
inline fun Context.themedTwoLineListItem(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TwoLineListItem).() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk19View`.TWO_LINE_LIST_ITEM, theme) { init() }
}
inline fun Activity.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem() {}
inline fun Activity.twoLineListItem(init: (@AnkoViewDslMarker android.widget.TwoLineListItem).() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk19View`.TWO_LINE_LIST_ITEM, theme = 0) { init() }
}
inline fun Activity.themedTwoLineListItem(theme: Int = 0): android.widget.TwoLineListItem = themedTwoLineListItem(theme) {}
inline fun Activity.themedTwoLineListItem(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TwoLineListItem).() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk19View`.TWO_LINE_LIST_ITEM, theme) { init() }
}
inline fun ViewManager.videoView(): android.widget.VideoView = videoView() {}
inline fun ViewManager.videoView(init: (@AnkoViewDslMarker android.widget.VideoView).() -> Unit): android.widget.VideoView {
return ankoView(`$$Anko$Factories$Sdk19View`.VIDEO_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedVideoView(theme: Int = 0): android.widget.VideoView = themedVideoView(theme) {}
inline fun ViewManager.themedVideoView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.VideoView).() -> Unit): android.widget.VideoView {
return ankoView(`$$Anko$Factories$Sdk19View`.VIDEO_VIEW, theme) { init() }
}
inline fun ViewManager.viewFlipper(): android.widget.ViewFlipper = viewFlipper() {}
inline fun ViewManager.viewFlipper(init: (@AnkoViewDslMarker android.widget.ViewFlipper).() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk19View`.VIEW_FLIPPER, theme = 0) { init() }
}
inline fun ViewManager.themedViewFlipper(theme: Int = 0): android.widget.ViewFlipper = themedViewFlipper(theme) {}
inline fun ViewManager.themedViewFlipper(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ViewFlipper).() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk19View`.VIEW_FLIPPER, theme) { init() }
}
inline fun Context.viewFlipper(): android.widget.ViewFlipper = viewFlipper() {}
inline fun Context.viewFlipper(init: (@AnkoViewDslMarker android.widget.ViewFlipper).() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk19View`.VIEW_FLIPPER, theme = 0) { init() }
}
inline fun Context.themedViewFlipper(theme: Int = 0): android.widget.ViewFlipper = themedViewFlipper(theme) {}
inline fun Context.themedViewFlipper(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ViewFlipper).() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk19View`.VIEW_FLIPPER, theme) { init() }
}
inline fun Activity.viewFlipper(): android.widget.ViewFlipper = viewFlipper() {}
inline fun Activity.viewFlipper(init: (@AnkoViewDslMarker android.widget.ViewFlipper).() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk19View`.VIEW_FLIPPER, theme = 0) { init() }
}
inline fun Activity.themedViewFlipper(theme: Int = 0): android.widget.ViewFlipper = themedViewFlipper(theme) {}
inline fun Activity.themedViewFlipper(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ViewFlipper).() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk19View`.VIEW_FLIPPER, theme) { init() }
}
inline fun ViewManager.zoomButton(): android.widget.ZoomButton = zoomButton() {}
inline fun ViewManager.zoomButton(init: (@AnkoViewDslMarker android.widget.ZoomButton).() -> Unit): android.widget.ZoomButton {
return ankoView(`$$Anko$Factories$Sdk19View`.ZOOM_BUTTON, theme = 0) { init() }
}
inline fun ViewManager.themedZoomButton(theme: Int = 0): android.widget.ZoomButton = themedZoomButton(theme) {}
inline fun ViewManager.themedZoomButton(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ZoomButton).() -> Unit): android.widget.ZoomButton {
return ankoView(`$$Anko$Factories$Sdk19View`.ZOOM_BUTTON, theme) { init() }
}
inline fun ViewManager.zoomControls(): android.widget.ZoomControls = zoomControls() {}
inline fun ViewManager.zoomControls(init: (@AnkoViewDslMarker android.widget.ZoomControls).() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk19View`.ZOOM_CONTROLS, theme = 0) { init() }
}
inline fun ViewManager.themedZoomControls(theme: Int = 0): android.widget.ZoomControls = themedZoomControls(theme) {}
inline fun ViewManager.themedZoomControls(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ZoomControls).() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk19View`.ZOOM_CONTROLS, theme) { init() }
}
inline fun Context.zoomControls(): android.widget.ZoomControls = zoomControls() {}
inline fun Context.zoomControls(init: (@AnkoViewDslMarker android.widget.ZoomControls).() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk19View`.ZOOM_CONTROLS, theme = 0) { init() }
}
inline fun Context.themedZoomControls(theme: Int = 0): android.widget.ZoomControls = themedZoomControls(theme) {}
inline fun Context.themedZoomControls(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ZoomControls).() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk19View`.ZOOM_CONTROLS, theme) { init() }
}
inline fun Activity.zoomControls(): android.widget.ZoomControls = zoomControls() {}
inline fun Activity.zoomControls(init: (@AnkoViewDslMarker android.widget.ZoomControls).() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk19View`.ZOOM_CONTROLS, theme = 0) { init() }
}
inline fun Activity.themedZoomControls(theme: Int = 0): android.widget.ZoomControls = themedZoomControls(theme) {}
inline fun Activity.themedZoomControls(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ZoomControls).() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk19View`.ZOOM_CONTROLS, theme) { init() }
}
@PublishedApi
internal object `$$Anko$Factories$Sdk19ViewGroup` {
val APP_WIDGET_HOST_VIEW = { ctx: Context -> _AppWidgetHostView(ctx) }
val WEB_VIEW = { ctx: Context -> _WebView(ctx) }
val ABSOLUTE_LAYOUT = { ctx: Context -> _AbsoluteLayout(ctx) }
val FRAME_LAYOUT = { ctx: Context -> _FrameLayout(ctx) }
val GALLERY = { ctx: Context -> _Gallery(ctx) }
val GRID_LAYOUT = { ctx: Context -> _GridLayout(ctx) }
val GRID_VIEW = { ctx: Context -> _GridView(ctx) }
val HORIZONTAL_SCROLL_VIEW = { ctx: Context -> _HorizontalScrollView(ctx) }
val IMAGE_SWITCHER = { ctx: Context -> _ImageSwitcher(ctx) }
val LINEAR_LAYOUT = { ctx: Context -> _LinearLayout(ctx) }
val RADIO_GROUP = { ctx: Context -> _RadioGroup(ctx) }
val RELATIVE_LAYOUT = { ctx: Context -> _RelativeLayout(ctx) }
val SCROLL_VIEW = { ctx: Context -> _ScrollView(ctx) }
val TABLE_LAYOUT = { ctx: Context -> _TableLayout(ctx) }
val TABLE_ROW = { ctx: Context -> _TableRow(ctx) }
val TEXT_SWITCHER = { ctx: Context -> _TextSwitcher(ctx) }
val VIEW_ANIMATOR = { ctx: Context -> _ViewAnimator(ctx) }
val VIEW_SWITCHER = { ctx: Context -> _ViewSwitcher(ctx) }
}
inline fun ViewManager.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView() {}
inline fun ViewManager.appWidgetHostView(init: (@AnkoViewDslMarker _AppWidgetHostView).() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.APP_WIDGET_HOST_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedAppWidgetHostView(theme: Int = 0): android.appwidget.AppWidgetHostView = themedAppWidgetHostView(theme) {}
inline fun ViewManager.themedAppWidgetHostView(theme: Int = 0, init: (@AnkoViewDslMarker _AppWidgetHostView).() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.APP_WIDGET_HOST_VIEW, theme) { init() }
}
inline fun Context.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView() {}
inline fun Context.appWidgetHostView(init: (@AnkoViewDslMarker _AppWidgetHostView).() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.APP_WIDGET_HOST_VIEW, theme = 0) { init() }
}
inline fun Context.themedAppWidgetHostView(theme: Int = 0): android.appwidget.AppWidgetHostView = themedAppWidgetHostView(theme) {}
inline fun Context.themedAppWidgetHostView(theme: Int = 0, init: (@AnkoViewDslMarker _AppWidgetHostView).() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.APP_WIDGET_HOST_VIEW, theme) { init() }
}
inline fun Activity.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView() {}
inline fun Activity.appWidgetHostView(init: (@AnkoViewDslMarker _AppWidgetHostView).() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.APP_WIDGET_HOST_VIEW, theme = 0) { init() }
}
inline fun Activity.themedAppWidgetHostView(theme: Int = 0): android.appwidget.AppWidgetHostView = themedAppWidgetHostView(theme) {}
inline fun Activity.themedAppWidgetHostView(theme: Int = 0, init: (@AnkoViewDslMarker _AppWidgetHostView).() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.APP_WIDGET_HOST_VIEW, theme) { init() }
}
inline fun ViewManager.webView(): android.webkit.WebView = webView() {}
inline fun ViewManager.webView(init: (@AnkoViewDslMarker _WebView).() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.WEB_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedWebView(theme: Int = 0): android.webkit.WebView = themedWebView(theme) {}
inline fun ViewManager.themedWebView(theme: Int = 0, init: (@AnkoViewDslMarker _WebView).() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.WEB_VIEW, theme) { init() }
}
inline fun Context.webView(): android.webkit.WebView = webView() {}
inline fun Context.webView(init: (@AnkoViewDslMarker _WebView).() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.WEB_VIEW, theme = 0) { init() }
}
inline fun Context.themedWebView(theme: Int = 0): android.webkit.WebView = themedWebView(theme) {}
inline fun Context.themedWebView(theme: Int = 0, init: (@AnkoViewDslMarker _WebView).() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.WEB_VIEW, theme) { init() }
}
inline fun Activity.webView(): android.webkit.WebView = webView() {}
inline fun Activity.webView(init: (@AnkoViewDslMarker _WebView).() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.WEB_VIEW, theme = 0) { init() }
}
inline fun Activity.themedWebView(theme: Int = 0): android.webkit.WebView = themedWebView(theme) {}
inline fun Activity.themedWebView(theme: Int = 0, init: (@AnkoViewDslMarker _WebView).() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.WEB_VIEW, theme) { init() }
}
inline fun ViewManager.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout() {}
inline fun ViewManager.absoluteLayout(init: (@AnkoViewDslMarker _AbsoluteLayout).() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.ABSOLUTE_LAYOUT, theme = 0) { init() }
}
inline fun ViewManager.themedAbsoluteLayout(theme: Int = 0): android.widget.AbsoluteLayout = themedAbsoluteLayout(theme) {}
inline fun ViewManager.themedAbsoluteLayout(theme: Int = 0, init: (@AnkoViewDslMarker _AbsoluteLayout).() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.ABSOLUTE_LAYOUT, theme) { init() }
}
inline fun Context.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout() {}
inline fun Context.absoluteLayout(init: (@AnkoViewDslMarker _AbsoluteLayout).() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.ABSOLUTE_LAYOUT, theme = 0) { init() }
}
inline fun Context.themedAbsoluteLayout(theme: Int = 0): android.widget.AbsoluteLayout = themedAbsoluteLayout(theme) {}
inline fun Context.themedAbsoluteLayout(theme: Int = 0, init: (@AnkoViewDslMarker _AbsoluteLayout).() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.ABSOLUTE_LAYOUT, theme) { init() }
}
inline fun Activity.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout() {}
inline fun Activity.absoluteLayout(init: (@AnkoViewDslMarker _AbsoluteLayout).() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.ABSOLUTE_LAYOUT, theme = 0) { init() }
}
inline fun Activity.themedAbsoluteLayout(theme: Int = 0): android.widget.AbsoluteLayout = themedAbsoluteLayout(theme) {}
inline fun Activity.themedAbsoluteLayout(theme: Int = 0, init: (@AnkoViewDslMarker _AbsoluteLayout).() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.ABSOLUTE_LAYOUT, theme) { init() }
}
inline fun ViewManager.frameLayout(): android.widget.FrameLayout = frameLayout() {}
inline fun ViewManager.frameLayout(init: (@AnkoViewDslMarker _FrameLayout).() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.FRAME_LAYOUT, theme = 0) { init() }
}
inline fun ViewManager.themedFrameLayout(theme: Int = 0): android.widget.FrameLayout = themedFrameLayout(theme) {}
inline fun ViewManager.themedFrameLayout(theme: Int = 0, init: (@AnkoViewDslMarker _FrameLayout).() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.FRAME_LAYOUT, theme) { init() }
}
inline fun Context.frameLayout(): android.widget.FrameLayout = frameLayout() {}
inline fun Context.frameLayout(init: (@AnkoViewDslMarker _FrameLayout).() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.FRAME_LAYOUT, theme = 0) { init() }
}
inline fun Context.themedFrameLayout(theme: Int = 0): android.widget.FrameLayout = themedFrameLayout(theme) {}
inline fun Context.themedFrameLayout(theme: Int = 0, init: (@AnkoViewDslMarker _FrameLayout).() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.FRAME_LAYOUT, theme) { init() }
}
inline fun Activity.frameLayout(): android.widget.FrameLayout = frameLayout() {}
inline fun Activity.frameLayout(init: (@AnkoViewDslMarker _FrameLayout).() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.FRAME_LAYOUT, theme = 0) { init() }
}
inline fun Activity.themedFrameLayout(theme: Int = 0): android.widget.FrameLayout = themedFrameLayout(theme) {}
inline fun Activity.themedFrameLayout(theme: Int = 0, init: (@AnkoViewDslMarker _FrameLayout).() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.FRAME_LAYOUT, theme) { init() }
}
inline fun ViewManager.gallery(): android.widget.Gallery = gallery() {}
inline fun ViewManager.gallery(init: (@AnkoViewDslMarker _Gallery).() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GALLERY, theme = 0) { init() }
}
inline fun ViewManager.themedGallery(theme: Int = 0): android.widget.Gallery = themedGallery(theme) {}
inline fun ViewManager.themedGallery(theme: Int = 0, init: (@AnkoViewDslMarker _Gallery).() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GALLERY, theme) { init() }
}
inline fun Context.gallery(): android.widget.Gallery = gallery() {}
inline fun Context.gallery(init: (@AnkoViewDslMarker _Gallery).() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GALLERY, theme = 0) { init() }
}
inline fun Context.themedGallery(theme: Int = 0): android.widget.Gallery = themedGallery(theme) {}
inline fun Context.themedGallery(theme: Int = 0, init: (@AnkoViewDslMarker _Gallery).() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GALLERY, theme) { init() }
}
inline fun Activity.gallery(): android.widget.Gallery = gallery() {}
inline fun Activity.gallery(init: (@AnkoViewDslMarker _Gallery).() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GALLERY, theme = 0) { init() }
}
inline fun Activity.themedGallery(theme: Int = 0): android.widget.Gallery = themedGallery(theme) {}
inline fun Activity.themedGallery(theme: Int = 0, init: (@AnkoViewDslMarker _Gallery).() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GALLERY, theme) { init() }
}
inline fun ViewManager.gridLayout(): android.widget.GridLayout = gridLayout() {}
inline fun ViewManager.gridLayout(init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_LAYOUT, theme = 0) { init() }
}
inline fun ViewManager.themedGridLayout(theme: Int = 0): android.widget.GridLayout = themedGridLayout(theme) {}
inline fun ViewManager.themedGridLayout(theme: Int = 0, init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_LAYOUT, theme) { init() }
}
inline fun Context.gridLayout(): android.widget.GridLayout = gridLayout() {}
inline fun Context.gridLayout(init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_LAYOUT, theme = 0) { init() }
}
inline fun Context.themedGridLayout(theme: Int = 0): android.widget.GridLayout = themedGridLayout(theme) {}
inline fun Context.themedGridLayout(theme: Int = 0, init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_LAYOUT, theme) { init() }
}
inline fun Activity.gridLayout(): android.widget.GridLayout = gridLayout() {}
inline fun Activity.gridLayout(init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_LAYOUT, theme = 0) { init() }
}
inline fun Activity.themedGridLayout(theme: Int = 0): android.widget.GridLayout = themedGridLayout(theme) {}
inline fun Activity.themedGridLayout(theme: Int = 0, init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_LAYOUT, theme) { init() }
}
inline fun ViewManager.gridView(): android.widget.GridView = gridView() {}
inline fun ViewManager.gridView(init: (@AnkoViewDslMarker _GridView).() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedGridView(theme: Int = 0): android.widget.GridView = themedGridView(theme) {}
inline fun ViewManager.themedGridView(theme: Int = 0, init: (@AnkoViewDslMarker _GridView).() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_VIEW, theme) { init() }
}
inline fun Context.gridView(): android.widget.GridView = gridView() {}
inline fun Context.gridView(init: (@AnkoViewDslMarker _GridView).() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_VIEW, theme = 0) { init() }
}
inline fun Context.themedGridView(theme: Int = 0): android.widget.GridView = themedGridView(theme) {}
inline fun Context.themedGridView(theme: Int = 0, init: (@AnkoViewDslMarker _GridView).() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_VIEW, theme) { init() }
}
inline fun Activity.gridView(): android.widget.GridView = gridView() {}
inline fun Activity.gridView(init: (@AnkoViewDslMarker _GridView).() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_VIEW, theme = 0) { init() }
}
inline fun Activity.themedGridView(theme: Int = 0): android.widget.GridView = themedGridView(theme) {}
inline fun Activity.themedGridView(theme: Int = 0, init: (@AnkoViewDslMarker _GridView).() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_VIEW, theme) { init() }
}
inline fun ViewManager.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView() {}
inline fun ViewManager.horizontalScrollView(init: (@AnkoViewDslMarker _HorizontalScrollView).() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.HORIZONTAL_SCROLL_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedHorizontalScrollView(theme: Int = 0): android.widget.HorizontalScrollView = themedHorizontalScrollView(theme) {}
inline fun ViewManager.themedHorizontalScrollView(theme: Int = 0, init: (@AnkoViewDslMarker _HorizontalScrollView).() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.HORIZONTAL_SCROLL_VIEW, theme) { init() }
}
inline fun Context.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView() {}
inline fun Context.horizontalScrollView(init: (@AnkoViewDslMarker _HorizontalScrollView).() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.HORIZONTAL_SCROLL_VIEW, theme = 0) { init() }
}
inline fun Context.themedHorizontalScrollView(theme: Int = 0): android.widget.HorizontalScrollView = themedHorizontalScrollView(theme) {}
inline fun Context.themedHorizontalScrollView(theme: Int = 0, init: (@AnkoViewDslMarker _HorizontalScrollView).() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.HORIZONTAL_SCROLL_VIEW, theme) { init() }
}
inline fun Activity.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView() {}
inline fun Activity.horizontalScrollView(init: (@AnkoViewDslMarker _HorizontalScrollView).() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.HORIZONTAL_SCROLL_VIEW, theme = 0) { init() }
}
inline fun Activity.themedHorizontalScrollView(theme: Int = 0): android.widget.HorizontalScrollView = themedHorizontalScrollView(theme) {}
inline fun Activity.themedHorizontalScrollView(theme: Int = 0, init: (@AnkoViewDslMarker _HorizontalScrollView).() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.HORIZONTAL_SCROLL_VIEW, theme) { init() }
}
inline fun ViewManager.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher() {}
inline fun ViewManager.imageSwitcher(init: (@AnkoViewDslMarker _ImageSwitcher).() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.IMAGE_SWITCHER, theme = 0) { init() }
}
inline fun ViewManager.themedImageSwitcher(theme: Int = 0): android.widget.ImageSwitcher = themedImageSwitcher(theme) {}
inline fun ViewManager.themedImageSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _ImageSwitcher).() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.IMAGE_SWITCHER, theme) { init() }
}
inline fun Context.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher() {}
inline fun Context.imageSwitcher(init: (@AnkoViewDslMarker _ImageSwitcher).() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.IMAGE_SWITCHER, theme = 0) { init() }
}
inline fun Context.themedImageSwitcher(theme: Int = 0): android.widget.ImageSwitcher = themedImageSwitcher(theme) {}
inline fun Context.themedImageSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _ImageSwitcher).() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.IMAGE_SWITCHER, theme) { init() }
}
inline fun Activity.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher() {}
inline fun Activity.imageSwitcher(init: (@AnkoViewDslMarker _ImageSwitcher).() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.IMAGE_SWITCHER, theme = 0) { init() }
}
inline fun Activity.themedImageSwitcher(theme: Int = 0): android.widget.ImageSwitcher = themedImageSwitcher(theme) {}
inline fun Activity.themedImageSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _ImageSwitcher).() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.IMAGE_SWITCHER, theme) { init() }
}
inline fun ViewManager.linearLayout(): android.widget.LinearLayout = linearLayout() {}
inline fun ViewManager.linearLayout(init: (@AnkoViewDslMarker _LinearLayout).() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.LINEAR_LAYOUT, theme = 0) { init() }
}
inline fun ViewManager.themedLinearLayout(theme: Int = 0): android.widget.LinearLayout = themedLinearLayout(theme) {}
inline fun ViewManager.themedLinearLayout(theme: Int = 0, init: (@AnkoViewDslMarker _LinearLayout).() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.LINEAR_LAYOUT, theme) { init() }
}
inline fun Context.linearLayout(): android.widget.LinearLayout = linearLayout() {}
inline fun Context.linearLayout(init: (@AnkoViewDslMarker _LinearLayout).() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.LINEAR_LAYOUT, theme = 0) { init() }
}
inline fun Context.themedLinearLayout(theme: Int = 0): android.widget.LinearLayout = themedLinearLayout(theme) {}
inline fun Context.themedLinearLayout(theme: Int = 0, init: (@AnkoViewDslMarker _LinearLayout).() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.LINEAR_LAYOUT, theme) { init() }
}
inline fun Activity.linearLayout(): android.widget.LinearLayout = linearLayout() {}
inline fun Activity.linearLayout(init: (@AnkoViewDslMarker _LinearLayout).() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.LINEAR_LAYOUT, theme = 0) { init() }
}
inline fun Activity.themedLinearLayout(theme: Int = 0): android.widget.LinearLayout = themedLinearLayout(theme) {}
inline fun Activity.themedLinearLayout(theme: Int = 0, init: (@AnkoViewDslMarker _LinearLayout).() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.LINEAR_LAYOUT, theme) { init() }
}
inline fun ViewManager.radioGroup(): android.widget.RadioGroup = radioGroup() {}
inline fun ViewManager.radioGroup(init: (@AnkoViewDslMarker _RadioGroup).() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RADIO_GROUP, theme = 0) { init() }
}
inline fun ViewManager.themedRadioGroup(theme: Int = 0): android.widget.RadioGroup = themedRadioGroup(theme) {}
inline fun ViewManager.themedRadioGroup(theme: Int = 0, init: (@AnkoViewDslMarker _RadioGroup).() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RADIO_GROUP, theme) { init() }
}
inline fun Context.radioGroup(): android.widget.RadioGroup = radioGroup() {}
inline fun Context.radioGroup(init: (@AnkoViewDslMarker _RadioGroup).() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RADIO_GROUP, theme = 0) { init() }
}
inline fun Context.themedRadioGroup(theme: Int = 0): android.widget.RadioGroup = themedRadioGroup(theme) {}
inline fun Context.themedRadioGroup(theme: Int = 0, init: (@AnkoViewDslMarker _RadioGroup).() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RADIO_GROUP, theme) { init() }
}
inline fun Activity.radioGroup(): android.widget.RadioGroup = radioGroup() {}
inline fun Activity.radioGroup(init: (@AnkoViewDslMarker _RadioGroup).() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RADIO_GROUP, theme = 0) { init() }
}
inline fun Activity.themedRadioGroup(theme: Int = 0): android.widget.RadioGroup = themedRadioGroup(theme) {}
inline fun Activity.themedRadioGroup(theme: Int = 0, init: (@AnkoViewDslMarker _RadioGroup).() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RADIO_GROUP, theme) { init() }
}
inline fun ViewManager.relativeLayout(): android.widget.RelativeLayout = relativeLayout() {}
inline fun ViewManager.relativeLayout(init: (@AnkoViewDslMarker _RelativeLayout).() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RELATIVE_LAYOUT, theme = 0) { init() }
}
inline fun ViewManager.themedRelativeLayout(theme: Int = 0): android.widget.RelativeLayout = themedRelativeLayout(theme) {}
inline fun ViewManager.themedRelativeLayout(theme: Int = 0, init: (@AnkoViewDslMarker _RelativeLayout).() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RELATIVE_LAYOUT, theme) { init() }
}
inline fun Context.relativeLayout(): android.widget.RelativeLayout = relativeLayout() {}
inline fun Context.relativeLayout(init: (@AnkoViewDslMarker _RelativeLayout).() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RELATIVE_LAYOUT, theme = 0) { init() }
}
inline fun Context.themedRelativeLayout(theme: Int = 0): android.widget.RelativeLayout = themedRelativeLayout(theme) {}
inline fun Context.themedRelativeLayout(theme: Int = 0, init: (@AnkoViewDslMarker _RelativeLayout).() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RELATIVE_LAYOUT, theme) { init() }
}
inline fun Activity.relativeLayout(): android.widget.RelativeLayout = relativeLayout() {}
inline fun Activity.relativeLayout(init: (@AnkoViewDslMarker _RelativeLayout).() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RELATIVE_LAYOUT, theme = 0) { init() }
}
inline fun Activity.themedRelativeLayout(theme: Int = 0): android.widget.RelativeLayout = themedRelativeLayout(theme) {}
inline fun Activity.themedRelativeLayout(theme: Int = 0, init: (@AnkoViewDslMarker _RelativeLayout).() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RELATIVE_LAYOUT, theme) { init() }
}
inline fun ViewManager.scrollView(): android.widget.ScrollView = scrollView() {}
inline fun ViewManager.scrollView(init: (@AnkoViewDslMarker _ScrollView).() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.SCROLL_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedScrollView(theme: Int = 0): android.widget.ScrollView = themedScrollView(theme) {}
inline fun ViewManager.themedScrollView(theme: Int = 0, init: (@AnkoViewDslMarker _ScrollView).() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.SCROLL_VIEW, theme) { init() }
}
inline fun Context.scrollView(): android.widget.ScrollView = scrollView() {}
inline fun Context.scrollView(init: (@AnkoViewDslMarker _ScrollView).() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.SCROLL_VIEW, theme = 0) { init() }
}
inline fun Context.themedScrollView(theme: Int = 0): android.widget.ScrollView = themedScrollView(theme) {}
inline fun Context.themedScrollView(theme: Int = 0, init: (@AnkoViewDslMarker _ScrollView).() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.SCROLL_VIEW, theme) { init() }
}
inline fun Activity.scrollView(): android.widget.ScrollView = scrollView() {}
inline fun Activity.scrollView(init: (@AnkoViewDslMarker _ScrollView).() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.SCROLL_VIEW, theme = 0) { init() }
}
inline fun Activity.themedScrollView(theme: Int = 0): android.widget.ScrollView = themedScrollView(theme) {}
inline fun Activity.themedScrollView(theme: Int = 0, init: (@AnkoViewDslMarker _ScrollView).() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.SCROLL_VIEW, theme) { init() }
}
inline fun ViewManager.tableLayout(): android.widget.TableLayout = tableLayout() {}
inline fun ViewManager.tableLayout(init: (@AnkoViewDslMarker _TableLayout).() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_LAYOUT, theme = 0) { init() }
}
inline fun ViewManager.themedTableLayout(theme: Int = 0): android.widget.TableLayout = themedTableLayout(theme) {}
inline fun ViewManager.themedTableLayout(theme: Int = 0, init: (@AnkoViewDslMarker _TableLayout).() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_LAYOUT, theme) { init() }
}
inline fun Context.tableLayout(): android.widget.TableLayout = tableLayout() {}
inline fun Context.tableLayout(init: (@AnkoViewDslMarker _TableLayout).() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_LAYOUT, theme = 0) { init() }
}
inline fun Context.themedTableLayout(theme: Int = 0): android.widget.TableLayout = themedTableLayout(theme) {}
inline fun Context.themedTableLayout(theme: Int = 0, init: (@AnkoViewDslMarker _TableLayout).() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_LAYOUT, theme) { init() }
}
inline fun Activity.tableLayout(): android.widget.TableLayout = tableLayout() {}
inline fun Activity.tableLayout(init: (@AnkoViewDslMarker _TableLayout).() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_LAYOUT, theme = 0) { init() }
}
inline fun Activity.themedTableLayout(theme: Int = 0): android.widget.TableLayout = themedTableLayout(theme) {}
inline fun Activity.themedTableLayout(theme: Int = 0, init: (@AnkoViewDslMarker _TableLayout).() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_LAYOUT, theme) { init() }
}
inline fun ViewManager.tableRow(): android.widget.TableRow = tableRow() {}
inline fun ViewManager.tableRow(init: (@AnkoViewDslMarker _TableRow).() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_ROW, theme = 0) { init() }
}
inline fun ViewManager.themedTableRow(theme: Int = 0): android.widget.TableRow = themedTableRow(theme) {}
inline fun ViewManager.themedTableRow(theme: Int = 0, init: (@AnkoViewDslMarker _TableRow).() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_ROW, theme) { init() }
}
inline fun Context.tableRow(): android.widget.TableRow = tableRow() {}
inline fun Context.tableRow(init: (@AnkoViewDslMarker _TableRow).() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_ROW, theme = 0) { init() }
}
inline fun Context.themedTableRow(theme: Int = 0): android.widget.TableRow = themedTableRow(theme) {}
inline fun Context.themedTableRow(theme: Int = 0, init: (@AnkoViewDslMarker _TableRow).() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_ROW, theme) { init() }
}
inline fun Activity.tableRow(): android.widget.TableRow = tableRow() {}
inline fun Activity.tableRow(init: (@AnkoViewDslMarker _TableRow).() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_ROW, theme = 0) { init() }
}
inline fun Activity.themedTableRow(theme: Int = 0): android.widget.TableRow = themedTableRow(theme) {}
inline fun Activity.themedTableRow(theme: Int = 0, init: (@AnkoViewDslMarker _TableRow).() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_ROW, theme) { init() }
}
inline fun ViewManager.textSwitcher(): android.widget.TextSwitcher = textSwitcher() {}
inline fun ViewManager.textSwitcher(init: (@AnkoViewDslMarker _TextSwitcher).() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TEXT_SWITCHER, theme = 0) { init() }
}
inline fun ViewManager.themedTextSwitcher(theme: Int = 0): android.widget.TextSwitcher = themedTextSwitcher(theme) {}
inline fun ViewManager.themedTextSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _TextSwitcher).() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TEXT_SWITCHER, theme) { init() }
}
inline fun Context.textSwitcher(): android.widget.TextSwitcher = textSwitcher() {}
inline fun Context.textSwitcher(init: (@AnkoViewDslMarker _TextSwitcher).() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TEXT_SWITCHER, theme = 0) { init() }
}
inline fun Context.themedTextSwitcher(theme: Int = 0): android.widget.TextSwitcher = themedTextSwitcher(theme) {}
inline fun Context.themedTextSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _TextSwitcher).() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TEXT_SWITCHER, theme) { init() }
}
inline fun Activity.textSwitcher(): android.widget.TextSwitcher = textSwitcher() {}
inline fun Activity.textSwitcher(init: (@AnkoViewDslMarker _TextSwitcher).() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TEXT_SWITCHER, theme = 0) { init() }
}
inline fun Activity.themedTextSwitcher(theme: Int = 0): android.widget.TextSwitcher = themedTextSwitcher(theme) {}
inline fun Activity.themedTextSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _TextSwitcher).() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TEXT_SWITCHER, theme) { init() }
}
inline fun ViewManager.viewAnimator(): android.widget.ViewAnimator = viewAnimator() {}
inline fun ViewManager.viewAnimator(init: (@AnkoViewDslMarker _ViewAnimator).() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_ANIMATOR, theme = 0) { init() }
}
inline fun ViewManager.themedViewAnimator(theme: Int = 0): android.widget.ViewAnimator = themedViewAnimator(theme) {}
inline fun ViewManager.themedViewAnimator(theme: Int = 0, init: (@AnkoViewDslMarker _ViewAnimator).() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_ANIMATOR, theme) { init() }
}
inline fun Context.viewAnimator(): android.widget.ViewAnimator = viewAnimator() {}
inline fun Context.viewAnimator(init: (@AnkoViewDslMarker _ViewAnimator).() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_ANIMATOR, theme = 0) { init() }
}
inline fun Context.themedViewAnimator(theme: Int = 0): android.widget.ViewAnimator = themedViewAnimator(theme) {}
inline fun Context.themedViewAnimator(theme: Int = 0, init: (@AnkoViewDslMarker _ViewAnimator).() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_ANIMATOR, theme) { init() }
}
inline fun Activity.viewAnimator(): android.widget.ViewAnimator = viewAnimator() {}
inline fun Activity.viewAnimator(init: (@AnkoViewDslMarker _ViewAnimator).() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_ANIMATOR, theme = 0) { init() }
}
inline fun Activity.themedViewAnimator(theme: Int = 0): android.widget.ViewAnimator = themedViewAnimator(theme) {}
inline fun Activity.themedViewAnimator(theme: Int = 0, init: (@AnkoViewDslMarker _ViewAnimator).() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_ANIMATOR, theme) { init() }
}
inline fun ViewManager.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher() {}
inline fun ViewManager.viewSwitcher(init: (@AnkoViewDslMarker _ViewSwitcher).() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_SWITCHER, theme = 0) { init() }
}
inline fun ViewManager.themedViewSwitcher(theme: Int = 0): android.widget.ViewSwitcher = themedViewSwitcher(theme) {}
inline fun ViewManager.themedViewSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _ViewSwitcher).() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_SWITCHER, theme) { init() }
}
inline fun Context.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher() {}
inline fun Context.viewSwitcher(init: (@AnkoViewDslMarker _ViewSwitcher).() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_SWITCHER, theme = 0) { init() }
}
inline fun Context.themedViewSwitcher(theme: Int = 0): android.widget.ViewSwitcher = themedViewSwitcher(theme) {}
inline fun Context.themedViewSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _ViewSwitcher).() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_SWITCHER, theme) { init() }
}
inline fun Activity.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher() {}
inline fun Activity.viewSwitcher(init: (@AnkoViewDslMarker _ViewSwitcher).() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_SWITCHER, theme = 0) { init() }
}
inline fun Activity.themedViewSwitcher(theme: Int = 0): android.widget.ViewSwitcher = themedViewSwitcher(theme) {}
inline fun Activity.themedViewSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _ViewSwitcher).() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_SWITCHER, theme) { init() }
}
| apache-2.0 | 00c3265c497b5e4ed063f877c7850c4c | 58.948247 | 200 | 0.745663 | 4.268106 | false | false | false | false |
yschimke/okhttp | okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt | 7 | 5253 | /*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.logging
import java.io.IOException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Proxy
import java.util.concurrent.TimeUnit
import okhttp3.Call
import okhttp3.Connection
import okhttp3.EventListener
import okhttp3.Handshake
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.Response
/**
* An OkHttp EventListener, which logs call events. Can be applied as an
* [event listener factory][OkHttpClient.eventListenerFactory].
*
* The format of the logs created by this class should not be considered stable and may change
* slightly between releases. If you need a stable logging format, use your own event listener.
*/
class LoggingEventListener private constructor(
private val logger: HttpLoggingInterceptor.Logger
) : EventListener() {
private var startNs: Long = 0
override fun callStart(call: Call) {
startNs = System.nanoTime()
logWithTime("callStart: ${call.request()}")
}
override fun proxySelectStart(call: Call, url: HttpUrl) {
logWithTime("proxySelectStart: $url")
}
override fun proxySelectEnd(call: Call, url: HttpUrl, proxies: List<Proxy>) {
logWithTime("proxySelectEnd: $proxies")
}
override fun dnsStart(call: Call, domainName: String) {
logWithTime("dnsStart: $domainName")
}
override fun dnsEnd(call: Call, domainName: String, inetAddressList: List<InetAddress>) {
logWithTime("dnsEnd: $inetAddressList")
}
override fun connectStart(call: Call, inetSocketAddress: InetSocketAddress, proxy: Proxy) {
logWithTime("connectStart: $inetSocketAddress $proxy")
}
override fun secureConnectStart(call: Call) {
logWithTime("secureConnectStart")
}
override fun secureConnectEnd(call: Call, handshake: Handshake?) {
logWithTime("secureConnectEnd: $handshake")
}
override fun connectEnd(
call: Call,
inetSocketAddress: InetSocketAddress,
proxy: Proxy,
protocol: Protocol?
) {
logWithTime("connectEnd: $protocol")
}
override fun connectFailed(
call: Call,
inetSocketAddress: InetSocketAddress,
proxy: Proxy,
protocol: Protocol?,
ioe: IOException
) {
logWithTime("connectFailed: $protocol $ioe")
}
override fun connectionAcquired(call: Call, connection: Connection) {
logWithTime("connectionAcquired: $connection")
}
override fun connectionReleased(call: Call, connection: Connection) {
logWithTime("connectionReleased")
}
override fun requestHeadersStart(call: Call) {
logWithTime("requestHeadersStart")
}
override fun requestHeadersEnd(call: Call, request: Request) {
logWithTime("requestHeadersEnd")
}
override fun requestBodyStart(call: Call) {
logWithTime("requestBodyStart")
}
override fun requestBodyEnd(call: Call, byteCount: Long) {
logWithTime("requestBodyEnd: byteCount=$byteCount")
}
override fun requestFailed(call: Call, ioe: IOException) {
logWithTime("requestFailed: $ioe")
}
override fun responseHeadersStart(call: Call) {
logWithTime("responseHeadersStart")
}
override fun responseHeadersEnd(call: Call, response: Response) {
logWithTime("responseHeadersEnd: $response")
}
override fun responseBodyStart(call: Call) {
logWithTime("responseBodyStart")
}
override fun responseBodyEnd(call: Call, byteCount: Long) {
logWithTime("responseBodyEnd: byteCount=$byteCount")
}
override fun responseFailed(call: Call, ioe: IOException) {
logWithTime("responseFailed: $ioe")
}
override fun callEnd(call: Call) {
logWithTime("callEnd")
}
override fun callFailed(call: Call, ioe: IOException) {
logWithTime("callFailed: $ioe")
}
override fun canceled(call: Call) {
logWithTime("canceled")
}
override fun satisfactionFailure(call: Call, response: Response) {
logWithTime("satisfactionFailure: $response")
}
override fun cacheHit(call: Call, response: Response) {
logWithTime("cacheHit: $response")
}
override fun cacheMiss(call: Call) {
logWithTime("cacheMiss")
}
override fun cacheConditionalHit(call: Call, cachedResponse: Response) {
logWithTime("cacheConditionalHit: $cachedResponse")
}
private fun logWithTime(message: String) {
val timeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs)
logger.log("[$timeMs ms] $message")
}
open class Factory @JvmOverloads constructor(
private val logger: HttpLoggingInterceptor.Logger = HttpLoggingInterceptor.Logger.DEFAULT
) : EventListener.Factory {
override fun create(call: Call): EventListener = LoggingEventListener(logger)
}
}
| apache-2.0 | 4a24ce97774d5729ee9c20036167676a | 27.548913 | 95 | 0.732343 | 4.188995 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/res/PainterResources.desktop.kt | 3 | 2772 | /*
* 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.compose.ui.res
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.platform.LocalDensity
import org.xml.sax.InputSource
/**
* Load a [Painter] from an resource stored in resources for the application and decode
* it based on the file extension.
*
* Supported formats:
* - SVG
* - XML vector drawable
* (see https://developer.android.com/guide/topics/graphics/vector-drawable-resources)
* - raster formats (BMP, GIF, HEIF, ICO, JPEG, PNG, WBMP, WebP)
*
* To load an image from other places (file storage, database, network), use these
* functions inside [LaunchedEffect] or [remember]:
* [loadImageBitmap]
* [loadSvgPainter]
* [loadXmlImageVector]
*
* @param resourcePath path to the file in the resources folder
* @return [Painter] used for drawing the loaded resource
*/
@Composable
fun painterResource(
resourcePath: String
): Painter = when (resourcePath.substringAfterLast(".")) {
"svg" -> rememberSvgResource(resourcePath)
"xml" -> rememberVectorXmlResource(resourcePath)
else -> rememberBitmapResource(resourcePath)
}
@Composable
private fun rememberSvgResource(resourcePath: String): Painter {
val density = LocalDensity.current
return remember(resourcePath, density) {
useResource(resourcePath) {
loadSvgPainter(it, density)
}
}
}
@Composable
private fun rememberVectorXmlResource(resourcePath: String): Painter {
val density = LocalDensity.current
val image = remember(resourcePath, density) {
useResource(resourcePath) {
loadXmlImageVector(InputSource(it), density)
}
}
return rememberVectorPainter(image)
}
@Composable
private fun rememberBitmapResource(resourcePath: String): Painter {
val image = remember(resourcePath) {
useResource(resourcePath, ::loadImageBitmap)
}
return BitmapPainter(image)
} | apache-2.0 | 631b766b4a8591b46aff1613dd3f9f32 | 32.409639 | 88 | 0.742785 | 4.291022 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/stories/viewer/info/StoryInfoState.kt | 1 | 753 | package org.thoughtcrime.securesms.stories.viewer.info
import org.thoughtcrime.securesms.database.model.MediaMmsMessageRecord
import org.thoughtcrime.securesms.messagedetails.MessageDetails
/**
* Contains the needed information to render the story info sheet.
*/
data class StoryInfoState(
val messageDetails: MessageDetails? = null
) {
private val mediaMessage = messageDetails?.conversationMessage?.messageRecord as? MediaMmsMessageRecord
val sentMillis: Long = mediaMessage?.dateSent ?: -1L
val receivedMillis: Long = mediaMessage?.dateReceived ?: -1L
val size: Long = mediaMessage?.slideDeck?.thumbnailSlide?.fileSize ?: 0
val isOutgoing: Boolean = mediaMessage?.isOutgoing ?: false
val isLoaded: Boolean = mediaMessage != null
}
| gpl-3.0 | fc7a2ab3ef418df25a9c255fdc073e89 | 38.631579 | 105 | 0.788845 | 4.377907 | false | false | false | false |
oleksiyp/mockk | mockk/common/src/main/kotlin/io/mockk/impl/recording/ChainedCallDetector.kt | 1 | 5372 | package io.mockk.impl.recording
import io.mockk.*
import io.mockk.InternalPlatformDsl.toArray
import io.mockk.InternalPlatformDsl.toStr
import io.mockk.impl.InternalPlatform
import io.mockk.impl.log.Logger
import io.mockk.impl.log.SafeToString
class ChainedCallDetector(safeToString: SafeToString) {
val log = safeToString(Logger<SignatureMatcherDetector>())
val argMatchers = mutableListOf<Matcher<*>>()
lateinit var call: RecordedCall
@Suppress("CAST_NEVER_SUCCEEDS")
fun detect(
callRounds: List<CallRound>,
callN: Int,
matcherMap: HashMap<List<Any>, Matcher<*>>
) {
val callInAllRounds = callRounds.map { it.calls[callN] }
val zeroCall = callInAllRounds[0]
var allAny = false
log.trace { "Processing call #$callN: ${zeroCall.method.toStr()}" }
fun buildMatcher(isStart: Boolean, zeroCallValue: Any?, matcherBySignature: Matcher<*>?): Matcher<*> {
return if (matcherBySignature == null) {
if (allAny)
ConstantMatcher(true)
else {
eqOrNullMatcher(zeroCallValue)
}
} else {
if (isStart && matcherBySignature is AllAnyMatcher) {
allAny = true
ConstantMatcher<Any>(true)
} else {
matcherBySignature
}
}
}
fun regularArgument(nArgument: Int): Matcher<*> {
val signature = callInAllRounds.map {
InternalPlatform.packRef(it.args[nArgument])
}.toList()
log.trace { "Signature for $nArgument argument of ${zeroCall.method.toStr()}: $signature" }
val matcherBySignature = matcherMap.remove(signature)
return buildMatcher(
nArgument == 0,
zeroCall.args[nArgument],
matcherBySignature
)
}
@Suppress("UNCHECKED_CAST")
fun composeVarArgMatcher(matchers: List<Matcher<*>>): Matcher<*> {
val idx = matchers.indexOfFirst { it is VarargMatcher<*> }
val prefix = matchers.subList(0, idx) as List<Matcher<Any>>
val postfix = matchers.subList(idx + 1, matchers.size) as List<Matcher<Any>>
val matcher = matchers[idx] as VarargMatcher<*>
return matcher.copy(prefix = prefix, postfix = postfix)
}
@Suppress("UNCHECKED_CAST")
fun varArgArgument(nArgument: Int): Matcher<*> {
val varArgMatchers = mutableListOf<Matcher<*>>()
val zeroCallArg = zeroCall.args[nArgument]!!.toArray()
repeat(zeroCallArg.size) { nVarArg ->
val signature = callInAllRounds.map {
val arg = it.args[nArgument]!!.toArray()
InternalPlatform.packRef(arg[nVarArg])
}.toList()
log.trace { "Signature for $nArgument/$nVarArg argument of ${zeroCall.method.toStr()}: $signature" }
val matcherBySignature = matcherMap.remove(signature)
varArgMatchers.add(
buildMatcher(
nArgument == 0 && nVarArg == 0,
zeroCallArg[nVarArg],
matcherBySignature
)
)
}
val nVarArgMatchers = varArgMatchers.count { it is VarargMatcher<*> }
return when (nVarArgMatchers) {
0 -> ArrayMatcher<Any>(varArgMatchers.map { it } as List<Matcher<Any>>)
1 -> composeVarArgMatcher(varArgMatchers)
else -> throw MockKException("using more then one vararg VarargMatcher in one expression is not possible: $varArgMatchers")
}
}
fun detectArgMatchers() {
allAny = false
val varArgsArg = zeroCall.method.varArgsArg
repeat(zeroCall.args.size) { nArgument ->
val matcher = if (varArgsArg == nArgument) {
varArgArgument(nArgument)
} else {
regularArgument(nArgument)
}
argMatchers.add(matcher)
}
}
@Suppress("UNCHECKED_CAST")
fun buildRecordedCall(): RecordedCall {
if (zeroCall.method.isSuspend) {
log.trace { "Suspend function found. Replacing continuation with any() matcher" }
argMatchers[argMatchers.size - 1] = ConstantMatcher<Any>(true)
}
val im = InvocationMatcher(
zeroCall.self,
zeroCall.method,
argMatchers.toList() as List<Matcher<Any>>,
allAny
)
log.trace { "Built matcher: $im" }
return RecordedCall(
zeroCall.retValue,
zeroCall.isRetValueMock,
zeroCall.retType,
im,
null,
null
)
}
detectArgMatchers()
call = buildRecordedCall()
}
companion object {
fun eqOrNullMatcher(arg: Any?): Matcher<Any> {
return if (arg == null) {
NullCheckMatcher(false)
} else {
EqMatcher(arg)
}
}
}
} | apache-2.0 | df4d640eda640ddea0089f0540587124 | 33.006329 | 139 | 0.537975 | 4.91042 | false | false | false | false |
ice1000/PlasticApp | app/src/main/kotlin/utils/BaseActivity.kt | 1 | 3431 | package utils
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import data.constants.SAVE_LL_MODE_ON
import org.jetbrains.anko.async
import org.jetbrains.anko.uiThread
/**
* @author ice1000
* Created by ice1000 on 2016/6/4.
*/
open class BaseActivity : AppCompatActivity() {
protected val URL = "URL"
/**
* if this value is null,
* it means I have 2 load data from Sp.
*/
val connection: NetworkInfo?
get() = (getSystemService(Context.CONNECTIVITY_SERVICE)
as ConnectivityManager).activeNetworkInfo
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
protected fun openWeb(url: String) {
// startActivity(intentFor<WebViewerActivity>()
// .putExtra(URL, url))
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
}
protected fun checkNetwork(): Boolean {
Log.v("not important", "connection? = ${connection ?: "no network found!"}")
return connection != null && connection!!.isConnected
}
protected val DEFAULT_VALUE = "DEFAULT_VALUE"
/**
* this will cache the data into SharedPreference
* next time when the network is invalid, it will return the data
* stored in the SharedPreference.
*
* this method extended String.
*/
fun String.webResource(submit: (String) -> Unit, default: String = DEFAULT_VALUE) {
async() {
var ret = readString(default)
uiThread { submit(ret) }
// Log.i("important", "ret = $ret")
Log.i([email protected](), this@webResource)
if (SAVE_LL_MODE_ON.readBoolean(false) || !ret.equals(DEFAULT_VALUE) &&
!checkNetwork()) {
Log.i("important", "linking to SharedPreference")
uiThread { submit(ret) }
} else {
Log.i("important", "linking to web")
ret = java.net.URL(this@webResource).readText(Charsets.UTF_8)
uiThread { submit(ret) }
save(ret)
}
}
}
/**
* insert a value in2 SharedPreference
* any types of value is accepted.
*
* Will be smart casted.
*/
fun String.save(value: Any) {
val editor = openPreference().edit()
if (value is Int) editor.putInt(this, value)
else if (value is Float) editor.putFloat(this, value)
else if (value is Long) editor.putLong(this, value)
else if (value is Boolean) editor.putBoolean(this, value)
else if (value is String) editor.putString(this, value)
else throw Exception("not supported type")
editor.apply()
}
fun String.readString(default: String = "") = openPreference().getString(this, default) ?: ""
fun String.readInt(default: Int = 0) = openPreference().getInt(this, default)
fun String.readBoolean(default: Boolean = false) = openPreference().getBoolean(this, default)
/**
* @return a SharedPreference
*/
private fun openPreference(): SharedPreferences =
getSharedPreferences("MainPreference", MODE_ENABLE_WRITE_AHEAD_LOGGING)
}
| apache-2.0 | 56d2e4c8f10639a37a6da51d23c99ad5 | 32.31068 | 97 | 0.633926 | 4.332071 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/translations/intentions/TranslationFileAnnotator.kt | 1 | 2875 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.intentions
import com.demonwav.mcdev.translations.Translation
import com.demonwav.mcdev.translations.TranslationFiles
import com.demonwav.mcdev.translations.index.TranslationIndex
import com.demonwav.mcdev.translations.lang.gen.psi.LangTypes
import com.demonwav.mcdev.util.mcDomain
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.psi.PsiElement
class TranslationFileAnnotator : Annotator {
override fun annotate(element: PsiElement, annotations: AnnotationHolder) {
val translation = TranslationFiles.toTranslation(element)
if (translation != null) {
checkEntryKey(element, translation, annotations)
checkEntryDuplicates(element, translation, annotations)
checkEntryMatchesDefault(element, translation, annotations)
}
if (element.node.elementType == LangTypes.DUMMY) {
annotations.newAnnotation(HighlightSeverity.ERROR, "Translations must not contain incomplete entries.")
.range(element)
.create()
}
}
private fun checkEntryKey(element: PsiElement, translation: Translation, annotations: AnnotationHolder) {
if (translation.key != translation.trimmedKey) {
annotations.newAnnotation(HighlightSeverity.WARNING, "Translation key contains whitespace at start or end.")
.range(element)
.newFix(TrimKeyIntention()).registerFix()
.create()
}
}
private fun checkEntryDuplicates(element: PsiElement, translation: Translation, annotations: AnnotationHolder) {
val count = TranslationIndex.getTranslations(element.containingFile).count { it.key == translation.key }
if (count > 1) {
annotations.newAnnotation(HighlightSeverity.WARNING, "Duplicate translation keys \"${translation.key}\".")
.newFix(RemoveDuplicatesIntention(translation)).registerFix()
.create()
}
}
private fun checkEntryMatchesDefault(element: PsiElement, translation: Translation, annotations: AnnotationHolder) {
val domain = element.containingFile?.virtualFile?.mcDomain
val defaultEntries = TranslationIndex.getAllDefaultEntries(element.project, domain)
if (defaultEntries.any { it.contains(translation.key) }) {
return
}
val warningText = "Translation key not included in default localization file."
annotations.newAnnotation(HighlightSeverity.WARNING, warningText)
.newFix(RemoveUnmatchedEntryIntention()).registerFix()
.create()
}
}
| mit | 072e9b7fa17c0e749daf3c49e6d8d030 | 41.910448 | 120 | 0.706435 | 5.017452 | false | false | false | false |
handstandsam/ShoppingApp | multiplatform/src/jsMain/kotlin/com/handstandsam/shoppingapp/multiplatform/ui/CategoryDetailViewModel.kt | 1 | 3247 | package com.handstandsam.shoppingapp.multiplatform.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import com.handstandsam.shoppingapp.models.Category
import com.handstandsam.shoppingapp.models.Item
import com.handstandsam.shoppingapp.multiplatform.JsMultiplatformApi
import com.handstandsam.shoppingapp.network.Response
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.jetbrains.compose.web.dom.Div
import org.jetbrains.compose.web.dom.H1
import org.jetbrains.compose.web.dom.Text
class CategoryDetailViewModel(
scope: CoroutineScope = CoroutineScope(Dispatchers.Unconfined),
initialState: State = State()
) : JsMviViewModel<CategoryDetailViewModel.State, CategoryDetailViewModel.Intent>(
scope,
initialState
) {
sealed interface Intent {
object NoState : Intent
data class InitialState(val category: Category) : Intent
data class ItemsForCategoryReceived(val items: List<Item>) : Intent
data class ItemClicked(val item: Item) : Intent
}
data class State(
val category: Category? = null,
val isLoading: Boolean = true,
val items: List<Item> = listOf(),
)
override fun reduce(state: State, intent: Intent): State {
return when (intent) {
Intent.NoState -> {
State()
}
is Intent.ItemClicked -> {
navController.tryEmit(NavRoute.ItemDetailScreen(intent.item))
state.copy()
}
is Intent.ItemsForCategoryReceived -> {
state.copy(
isLoading = false,
items = intent.items
)
}
is Intent.InitialState -> {
CoroutineScope(Dispatchers.Default).launch {
val result =
JsMultiplatformApi().networkGraph.itemRepo.getItemsForCategory(intent.category.label)
when (result) {
is Response.Success -> {
sendIntention(Intent.ItemsForCategoryReceived(result.body))
}
is Response.Failure -> TODO()
}
}
state.copy(
isLoading = true
)
}
}
}
@Composable
fun ItemsComposable(categories: List<Item>) {
ShoppingAppList {
categories.forEach { item ->
ImageAndTextRow(label = item.label, imageUrl = item.image) {
sendIntention(Intent.ItemClicked(item))
}
}
}
}
@Composable
fun CategoryDetailScreen(category: Category) {
sendIntention(Intent.InitialState(category))
val state: State by states.collectAsState()
Div {
WrappedPreformattedText(state.toString())
if (state.isLoading) {
H1 { Text("LOADING Items for Category ${state.category}...") }
} else {
ItemsComposable(state.items)
}
}
}
} | apache-2.0 | 9912adecc70fe5889e249d29da36f771 | 32.833333 | 109 | 0.592547 | 5.170382 | false | false | false | false |
world-federation-of-advertisers/panel-exchange-client | src/main/kotlin/org/wfanet/panelmatch/common/certificates/GenerateCsr.kt | 1 | 1758 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.panelmatch.common.certificates
import java.io.ByteArrayOutputStream
import java.security.PrivateKey
import org.wfanet.measurement.common.crypto.PemWriter
/**
* Generates a PEM format CSR through OpenSSL for a given private key, organization and common name.
*/
fun generateCsrFromPrivateKey(key: PrivateKey, organization: String, commonName: String): String {
val outputStream = ByteArrayOutputStream()
PemWriter(outputStream).write(key)
return runProcessWithInputAndReturnOutput(
outputStream.toByteArray(),
"openssl",
"req",
"-new",
"-subj",
"/O=$organization/CN=$commonName",
"-key",
"/dev/stdin"
)
}
private fun runProcessWithInputAndReturnOutput(input: ByteArray, vararg args: String): String {
val process = ProcessBuilder(*args).redirectErrorStream(true).start()
process.outputStream.write(input)
process.outputStream.close()
val exitCode = process.waitFor()
val output = process.inputStream.use { it.bufferedReader().readText() }
check(exitCode == 0) {
"Command ${args.joinToString(" ")} failed with code $exitCode. Output:\n$output"
}
return output
}
| apache-2.0 | 56ab1dbf231dd9a3d09dfd0ec7d53783 | 34.877551 | 100 | 0.74289 | 4.236145 | false | false | false | false |
ajordens/lalas | jvm/sleepybaby-api-core/src/main/kotlin/org/jordens/sleepybaby/ext/Date.kt | 2 | 1272 | /*
* Copyright 2017 Adam Jordens
*
* 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.jordens.sleepybaby.ext
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
fun parseDate(format: String, input: String) : Date = SimpleDateFormat(format).parse(input)
fun formatDate(format: String, input: Date) : String = SimpleDateFormat(format).format(input)
fun Date.format(format: String) : String = formatDate(format, this)
fun Date.minusDays(days: Long): Date = Date(this.time - TimeUnit.DAYS.toMillis(days))
fun Date.diffDays(input: Date) : Long {
val difference = Math.abs(this.time - input.time)
return TimeUnit.DAYS.convert(difference, TimeUnit.MILLISECONDS)
}
fun Date.yesterday(): Date = this.minusDays(1)
| apache-2.0 | aac345c02bebfd636b95631986086007 | 37.545455 | 93 | 0.753931 | 3.8429 | false | false | false | false |
y2k/JoyReactor | android/src/main/kotlin/y2k/joyreactor/common/AndroidPlatform.kt | 1 | 3287 | package y2k.joyreactor.common
import android.Manifest
import android.app.Activity
import android.app.Application
import android.content.pm.PackageManager
import android.database.sqlite.SQLiteDatabase
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.media.ThumbnailUtils
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.widget.Toast
import com.j256.ormlite.android.AndroidConnectionSource
import com.j256.ormlite.support.ConnectionSource
import rx.Completable
import rx.Single
import y2k.joyreactor.App
import y2k.joyreactor.R
import y2k.joyreactor.common.platform.NavigationService
import y2k.joyreactor.common.platform.Platform
import y2k.joyreactor.platform.AndroidNavigation
import y2k.joyreactor.platform.AndroidReportService
import y2k.joyreactor.platform.ImageViewMetaStorage
import y2k.joyreactor.services.ImageService
import y2k.joyreactor.services.ReportService
import java.io.File
/**
* Created by y2k on 5/11/16.
*/
class AndroidPlatform(private val app: Application) : Platform {
init {
ServiceLocator.register<ImageService.MetaStorage> { ImageViewMetaStorage() }
}
override fun createTmpThumbnail(videoFile: File): Single<File> {
return ioSingle {
val thumb = ThumbnailUtils.createVideoThumbnail(
videoFile.absolutePath, MediaStore.Video.Thumbnails.MINI_KIND)
createTempFile().apply {
outputStream().use { thumb.compress(Bitmap.CompressFormat.JPEG, 90, it) }
}
}
}
override fun makeReportService(): ReportService = AndroidReportService()
@Suppress("UNCHECKED_CAST")
override fun <T> decodeImage(path: File): T {
return BitmapFactory.decodeFile(path.absolutePath) as T
}
override fun buildConnection(file: File): ConnectionSource {
val database = SQLiteDatabase.openDatabase(file.absolutePath, null,
SQLiteDatabase.OPEN_READWRITE or SQLiteDatabase.CREATE_IF_NECESSARY)
return AndroidConnectionSource(database)
}
override val currentDirectory: File = app.filesDir
override val navigator: NavigationService = AndroidNavigation(App.instance)
override fun loadFromBundle(name: String, ext: String): ByteArray {
return app.assets.open(name + "." + ext).use { it.readBytes() }
}
override fun saveToGallery(imageFile: File): Completable {
return ioCompletable {
val permissionCheck = ContextCompat.checkSelfPermission(app, Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
val perms = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)
getActivity()?.let {
ActivityCompat.requestPermissions(it, perms, 1)
it.runOnUiThread { Toast.makeText(app, R.string.allow_permission_and_try_again, Toast.LENGTH_LONG).show() }
}
} else {
MediaStore.Images.Media.insertImage(app.contentResolver, imageFile.absolutePath, null, null)
}
}
}
private fun getActivity(): Activity? = (navigator as AndroidNavigation).currentActivity
} | gpl-2.0 | f0e743e68604ecd6c6b9a9fbb71b90ca | 37.232558 | 127 | 0.727107 | 4.533793 | false | false | false | false |
sybila/ode-generator | src/main/java/com/github/sybila/ode/generator/CutStateMap.kt | 1 | 1165 | package com.github.sybila.ode.generator
import com.github.sybila.checker.StateMap
class CutStateMap<out Params : Any>(
private val encoder: NodeEncoder,
private val dimension: Int,
private val threshold: Int,
private val gt: Boolean,
private val stateCount: Int,
override val sizeHint: Int,
private val value: Params,
private val default: Params
) : StateMap<Params> {
override fun contains(state: Int): Boolean {
val dimensionIndex = encoder.coordinate(state, dimension)
val lowThreshold = dimensionIndex
val highThreshold = dimensionIndex + 1
return if (gt) {
lowThreshold >= threshold
} else {
highThreshold <= threshold
}
}
override fun get(state: Int): Params {
return if (state in this) value else default
}
override fun entries(): Iterator<Pair<Int, Params>> = (0 until stateCount).asSequence()
.filter { it in this }.map { it to get(it) }.iterator()
override fun states(): Iterator<Int> = (0 until stateCount).asSequence()
.filter { it in this }.iterator()
} | gpl-3.0 | 8b78f50171738ef49e0a63428ceea935 | 30.513514 | 91 | 0.625751 | 4.604743 | false | false | false | false |
ifabijanovic/kotlin-state-machine | app/src/test/java/com/ifabijanovic/kotlinstatemachine/DictionaryStateMachineDeviceTests.kt | 1 | 3090 | package com.ifabijanovic.kotlinstatemachine
import io.reactivex.Observable
import io.reactivex.observers.TestObserver
import io.reactivex.schedulers.TestScheduler
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import java.util.concurrent.TimeUnit
/**
* Created by Ivan Fabijanovic on 07/05/2017.
*/
class DictionaryStateMachineDeviceTests {
var scheduler = TestScheduler()
var observer = TestObserver<Map<Device, TestDeviceState>>()
var stateMachine = DictionaryStateMachine<Device,TestDeviceState>(this.scheduler, { _ -> { _ -> Observable.empty() } })
var connectionCount = 0
val pairData = "pair data"
val syncData = "sync data"
val syncSavePath = "file://test.file"
val errorSyncData = "error"
@Before
fun setUp() {
this.scheduler = TestScheduler()
this.observer = TestObserver()
this.connectionCount = 0
}
@After
fun tearDown() {
this.observer.dispose()
this.stateMachine.dispose()
}
fun makeStateMachine(connect: (Device) -> Observable<ConnectionResult>, syncData: String = this.syncData) {
this.stateMachine = DictionaryStateMachine(this.scheduler, TestDeviceStateFeedbackLoops(this.scheduler, this.pairData, syncData, this.syncSavePath, connect)::feedbackLoops)
this.stateMachine.state.subscribe(this.observer)
}
fun perfectConnection(device: Device): Observable<ConnectionResult> {
return Observable
.just(ConnectionResult.Success(ConnectedDevice(device)))
.delay(10, TimeUnit.SECONDS, this.scheduler)
.doOnNext { this.connectionCount++ }
.map { it }
}
fun pair(device: Device) {
this.stateMachine.transition(Pair(device, TestDeviceState.Start(TestDeviceState.Pair(TestDeviceState.PairState.Read))))
}
fun sync(device: Device) {
this.stateMachine.transition(Pair(device, TestDeviceState.Start(TestDeviceState.Sync(TestDeviceState.SyncState.Read))))
}
@Test
fun singleDeviceSingleOperation() {
this.makeStateMachine(this::perfectConnection)
val device = Device(1)
assertEquals(this.connectionCount, 0)
this.scheduler.createWorker().schedule({ this.sync(device) }, 300, TimeUnit.SECONDS)
this.scheduler.advanceTimeBy(1000, TimeUnit.SECONDS)
assertEquals(this.observer.values(), listOf(
mapOf(),
mapOf(Pair(device, TestDeviceState.Start(TestDeviceState.Sync(TestDeviceState.SyncState.Read)))),
mapOf(Pair(device, TestDeviceState.Sync(TestDeviceState.SyncState.Read))),
mapOf(Pair(device, TestDeviceState.Sync(TestDeviceState.SyncState.Process(this.syncData)))),
mapOf(Pair(device, TestDeviceState.Sync(TestDeviceState.SyncState.Save(this.syncData, this.syncSavePath)))),
mapOf(Pair(device, TestDeviceState.Sync(TestDeviceState.SyncState.Clear))),
mapOf()
))
assertEquals(this.connectionCount, 1)
}
}
| mit | 08b84fa4da0c7af22a0fa633eb238f8a | 36.228916 | 180 | 0.687055 | 4.45245 | false | true | false | false |
ligee/kotlin-jupyter | src/main/kotlin/org/jetbrains/kotlinx/jupyter/repl/CompletionResult.kt | 1 | 2492 | package org.jetbrains.kotlinx.jupyter.repl
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlinx.jupyter.compiler.util.CodeInterval
import org.jetbrains.kotlinx.jupyter.messaging.CompleteReply
import org.jetbrains.kotlinx.jupyter.messaging.ErrorReply
import org.jetbrains.kotlinx.jupyter.messaging.MessageContent
import org.jetbrains.kotlinx.jupyter.messaging.Paragraph
import kotlin.script.experimental.api.SourceCodeCompletionVariant
abstract class CompletionResult {
abstract val message: MessageContent
open class Success(
private val matches: List<String>,
private val bounds: CodeInterval,
private val metadata: List<SourceCodeCompletionVariant>,
private val text: String,
private val cursor: Int
) : CompletionResult() {
init {
assert(matches.size == metadata.size)
}
override val message: MessageContent
get() = CompleteReply(
matches,
bounds.from,
bounds.to,
Paragraph(cursor, text),
CompleteReply.Metadata(
metadata.map {
CompleteReply.ExperimentalType(
it.text,
it.tail,
bounds.from,
bounds.to
)
},
metadata.map {
CompleteReply.ExtendedMetadataEntry(
it.text,
it.displayText,
it.icon,
it.tail,
it.deprecationLevel?.name,
)
}
)
)
@TestOnly
fun sortedMatches(): List<String> = matches.sorted()
@TestOnly
fun matches(): List<String> = matches
@TestOnly
fun sortedRaw(): List<SourceCodeCompletionVariant> = metadata.sortedBy { it.text }
}
class Empty(
text: String,
cursor: Int
) : Success(emptyList(), CodeInterval(cursor, cursor), emptyList(), text, cursor)
class Error(
private val errorName: String,
private val errorValue: String,
private val traceBack: List<String>
) : CompletionResult() {
override val message: MessageContent
get() = ErrorReply(errorName, errorValue, traceBack)
}
}
| apache-2.0 | 8851a22f5396c34b7c43ca8d8d219d3b | 32.226667 | 90 | 0.550562 | 5.452954 | false | true | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/LeaveNoteInsteadFragment.kt | 1 | 2276 | package de.westnordost.streetcomplete.quests
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.quest.QuestGroup
import kotlinx.android.synthetic.main.form_leave_note.*
import kotlinx.android.synthetic.main.fragment_quest_answer.*
/** Bottom sheet fragment with which the user can leave a note instead of solving the quest */
class LeaveNoteInsteadFragment : AbstractCreateNoteFragment(), IsShowingQuestDetails {
interface Listener {
fun onCreatedNoteInstead(questId: Long, group: QuestGroup, questTitle: String, note: String, imagePaths: List<String>?)
}
private val listener: Listener? get() = parentFragment as? Listener ?: activity as? Listener
override val layoutResId = R.layout.fragment_quest_answer
private lateinit var questTitle: String
override var questId: Long = 0L
override var questGroup: QuestGroup = QuestGroup.OSM
override fun onCreate(inState: Bundle?) {
super.onCreate(inState)
val args = requireArguments()
questTitle = args.getString(ARG_QUEST_TITLE)!!
questId = args.getLong(ARG_QUEST_ID)
questGroup = QuestGroup.valueOf(args.getString(ARG_QUEST_GROUP)!!)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
titleLabel.text = getString(R.string.map_btn_create_note)
descriptionLabel.text = null
}
override fun onComposedNote(text: String, imagePaths: List<String>?) {
listener?.onCreatedNoteInstead(questId, questGroup, questTitle, text, imagePaths)
}
companion object {
private const val ARG_QUEST_TITLE = "questTitle"
private const val ARG_QUEST_ID = "questId"
private const val ARG_QUEST_GROUP = "questGroup"
@JvmStatic
fun create(questId: Long, group: QuestGroup, questTitle: String): LeaveNoteInsteadFragment {
val f = LeaveNoteInsteadFragment()
f.arguments = bundleOf(
ARG_QUEST_GROUP to group.name,
ARG_QUEST_ID to questId,
ARG_QUEST_TITLE to questTitle
)
return f
}
}
}
| gpl-3.0 | e8df1d716d28ca5c22422552807934e7 | 36.311475 | 127 | 0.696397 | 4.436647 | false | false | false | false |
Fewlaps/quitnow-cache | src/main/java/com/fewlaps/quitnowcache/QNCache.kt | 1 | 7087 | package com.fewlaps.quitnowcache
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
class QNCache<T>(
val caseSensitiveKeys: Boolean = true,
val autoReleaseInSeconds: Int = WITHOUT_AUTORELEASE,
val defaultKeepaliveInMillis: Long = KEEPALIVE_FOREVER) {
private val cache: ConcurrentHashMap<String, QNCacheBean<T>> = ConcurrentHashMap()
private var executorService: ScheduledExecutorService? = null
var dateProvider = DateProvider.SYSTEM!!
init {
startAutoReleaseServiceIfNeeded()
}
/**
* The common isEmpty() method, but only looking for alive elements
*/
fun isEmpty() = sizeAliveElements() == 0
fun shutdown() {
clear()
executorService?.shutdown()
}
private fun startAutoReleaseServiceIfNeeded() {
if (autoReleaseInSeconds > 0) {
executorService = Executors.newSingleThreadScheduledExecutor()
executorService?.scheduleAtFixedRate({ purge() }, autoReleaseInSeconds.toLong(), autoReleaseInSeconds.toLong(), TimeUnit.SECONDS)
}
}
operator fun set(key: String, value: T) {
set(key, value, defaultKeepaliveInMillis)
}
operator fun set(key: String, value: T, keepAliveUnits: Long, timeUnit: TimeUnit) {
set(key, value, timeUnit.toMillis(keepAliveUnits))
}
operator fun set(key: String, value: T, keepAliveInMillis: Long) {
if (keepAliveInMillis >= 0) {
cache[getEffectiveKey(key)] = QNCacheBean(value, now(), keepAliveInMillis)
}
}
/**
* Gets an element from the cache. If it's null, the default value will be returned instead.
*/
fun getOrDefault(key: String, defaultValue: T): T = get(key) ?: defaultValue
/**
* Gets an element from the cache.
*/
operator fun get(key: String) = get(key, purgeIfDead = false)
/**
* Gets an element from the cache. If the element exists but is dead,
* it will be removed from the cache to free memory. It could call
* an internal synchronized method, so avoid calling this method if
* you are not storing huge objects in terms of memory.
*/
fun getAndPurgeIfDead(key: String) = get(key, purgeIfDead = true)
private fun get(key: String, purgeIfDead: Boolean): T? {
val effectiveKey = getEffectiveKey(key)
val retrievedValue = cache[effectiveKey]
return when {
retrievedValue == null -> null
retrievedValue.isAlive(now()) -> retrievedValue.value
else -> {
if (purgeIfDead) {
cache.remove(effectiveKey)
}
null
}
}
}
fun remove(key: String) {
val effectiveKey = getEffectiveKey(key)
cache.remove(effectiveKey)
}
/**
* Removes all the elements of the cache, ignoring if they're dead or alive
*/
fun clear() = cache.clear()
fun keySet() = keySetAlive()
fun keySetDeadAndAlive(): List<String> = cache.keys().toList()
fun keySetAlive(): List<String> {
return keySetDeadAndAlive().filter {
isKeyAlive(it)
}
}
fun keySetDead(): List<String> {
return keySetDeadAndAlive().filter {
isKeyDead(it)
}
}
fun keySetStartingWith(start: String?): List<String> {
if (start == null) return Collections.emptyList()
val effectiveKeyStartingWith = getEffectiveKey(start)
return keySetDeadAndAlive().filter {
it.startsWith(effectiveKeyStartingWith)
}
}
fun keySetAliveStartingWith(start: String?): List<String> {
if (start == null) return Collections.emptyList()
return keySetStartingWith(start).filter {
isKeyAlive(it)
}
}
fun isKeyAlive(key: String): Boolean {
val value = cache[key] ?: return false
return value.isAlive(now())
}
fun isKeyDead(key: String) = !isKeyAlive(key)
/**
* Counts how much alive elements are living in the cache
*/
fun size() = sizeAliveElements()
/**
* Counts how much alive elements are living in the cache
*/
fun sizeAliveElements(): Int {
return cache.values.filter { it.isAlive(now()) }.count()
}
/**
* Counts how much dead elements exist in the cache
*/
fun sizeDeadElements() = cache.size - sizeAliveElements()
/**
* Counts how much elements are living in the cache, ignoring if they are dead or alive
*/
fun sizeDeadAndAliveElements() = cache.size
/**
* The common contains() method that looks for alive elements
*/
operator fun contains(key: String) = get(getEffectiveKey(key)) != null
/**
* Removes the dead elements of the cache to free memory
*/
fun purge() = cache.entries.removeIf { isKeyDead(it.key) }
/**
* If caseSensitiveKeys is false, it returns a key in lowercase. It will be
* the key of all stored values, so the cache will be totally caseinsensitive
*/
private fun getEffectiveKey(key: String): String {
return when {
caseSensitiveKeys -> key
else -> key.toLowerCase()
}
}
private fun now(): Long {
return dateProvider.now()
}
class Builder {
private var caseSensitiveKeys = true
private var autoReleaseInSeconds: Int = QNCache.WITHOUT_AUTORELEASE
private var defaultKeepaliveInMillis = QNCache.KEEPALIVE_FOREVER
fun caseSensitiveKeys(caseSensitiveKeys: Boolean): Builder {
this.caseSensitiveKeys = caseSensitiveKeys
return this
}
fun autoRelease(units: Int, timeUnit: TimeUnit): Builder {
this.autoReleaseInSeconds = java.lang.Long.valueOf(timeUnit.toSeconds(units.toLong())).toInt()
return this
}
fun autoReleaseInSeconds(autoReleaseInSeconds: Int): Builder {
this.autoReleaseInSeconds = autoReleaseInSeconds
return this
}
fun defaultKeepalive(units: Int, timeUnit: TimeUnit): Builder {
this.defaultKeepaliveInMillis = timeUnit.toMillis(units.toLong())
return this
}
fun defaultKeepaliveInMillis(defaultKeepaliveInMillis: Long): Builder {
this.defaultKeepaliveInMillis = defaultKeepaliveInMillis
return this
}
fun <T> build(): QNCache<T> {
if (autoReleaseInSeconds < 0) {
this.autoReleaseInSeconds = WITHOUT_AUTORELEASE
}
if (defaultKeepaliveInMillis < 0) {
this.defaultKeepaliveInMillis = KEEPALIVE_FOREVER
}
return QNCache(caseSensitiveKeys, autoReleaseInSeconds, defaultKeepaliveInMillis)
}
}
companion object {
const val WITHOUT_AUTORELEASE: Int = 0
const val KEEPALIVE_FOREVER: Long = 0
}
} | mit | 3cb466efa7799be936155605d59b4232 | 29.551724 | 141 | 0.627346 | 4.590026 | false | false | false | false |
Heiner1/AndroidAPS | core/src/main/java/info/nightscout/androidaps/utils/ui/BasalProfileGraph.kt | 1 | 3973 | package info.nightscout.androidaps.utils.ui
import android.content.Context
import android.util.AttributeSet
import com.jjoe64.graphview.DefaultLabelFormatter
import com.jjoe64.graphview.GraphView
import com.jjoe64.graphview.series.DataPoint
import com.jjoe64.graphview.series.LineGraphSeries
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.utils.Round
import java.text.NumberFormat
import kotlin.math.max
import kotlin.math.min
class BasalProfileGraph : GraphView {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
fun show(profile: Profile) {
removeAllSeries()
val basalArray: MutableList<DataPoint> = ArrayList()
for (hour in 0..23) {
val basal = profile.getBasalTimeFromMidnight(hour * 60 * 60)
basalArray.add(DataPoint(hour.toDouble(), basal))
basalArray.add(DataPoint((hour + 1).toDouble(), basal))
}
val basalDataPoints: Array<DataPoint> = Array(basalArray.size) { i -> basalArray[i] }
val basalSeries: LineGraphSeries<DataPoint> = LineGraphSeries(basalDataPoints)
addSeries(basalSeries)
basalSeries.thickness = 8
basalSeries.isDrawBackground = true
viewport.isXAxisBoundsManual = true
viewport.setMinX(0.0)
viewport.setMaxX(24.0)
viewport.isYAxisBoundsManual = true
viewport.setMinY(0.0)
viewport.setMaxY(Round.ceilTo(profile.getMaxDailyBasal() * 1.1, 0.5))
gridLabelRenderer.numHorizontalLabels = 13
gridLabelRenderer.verticalLabelsColor = basalSeries.color
val nf: NumberFormat = NumberFormat.getInstance()
nf.maximumFractionDigits = 1
gridLabelRenderer.labelFormatter = DefaultLabelFormatter(nf, nf)
}
fun show(profile1: Profile, profile2: Profile) {
removeAllSeries()
// profile 1
val basalArray1: MutableList<DataPoint> = ArrayList()
var minBasal = 1000.0
var maxBasal = 0.0
for (hour in 0..23) {
val basal = profile1.getBasalTimeFromMidnight(hour * 60 * 60)
minBasal = min(minBasal, basal)
maxBasal = max(maxBasal, basal)
basalArray1.add(DataPoint(hour.toDouble(), basal))
basalArray1.add(DataPoint((hour + 1).toDouble(), basal))
}
val basalSeries1: LineGraphSeries<DataPoint> = LineGraphSeries(Array(basalArray1.size) { i -> basalArray1[i] })
addSeries(basalSeries1)
basalSeries1.thickness = 8
basalSeries1.isDrawBackground = true
// profile 2
val basalArray2: MutableList<DataPoint> = ArrayList()
for (hour in 0..23) {
val basal = profile2.getBasalTimeFromMidnight(hour * 60 * 60)
minBasal = min(minBasal, basal)
maxBasal = max(maxBasal, basal)
basalArray2.add(DataPoint(hour.toDouble(), basal))
basalArray2.add(DataPoint((hour + 1).toDouble(), basal))
}
val basalSeries2: LineGraphSeries<DataPoint> = LineGraphSeries(Array(basalArray2.size) { i -> basalArray2[i] })
addSeries(basalSeries2)
basalSeries2.thickness = 8
basalSeries2.isDrawBackground = false
basalSeries2.color = context.getColor(R.color.examinedProfile)
basalSeries2.backgroundColor = context.getColor(R.color.examinedProfile)
viewport.isXAxisBoundsManual = true
viewport.setMinX(0.0)
viewport.setMaxX(24.0)
viewport.isYAxisBoundsManual = true
viewport.setMinY(Round.floorTo(minBasal / 1.1, 0.5))
viewport.setMaxY(Round.ceilTo(maxBasal * 1.1, 0.5))
gridLabelRenderer.numHorizontalLabels = 13
val nf: NumberFormat = NumberFormat.getInstance()
nf.maximumFractionDigits = 1
gridLabelRenderer.labelFormatter = DefaultLabelFormatter(nf, nf)
}
} | agpl-3.0 | 06a189e990a3203f7a9e87495dbe7965 | 40.831579 | 119 | 0.679336 | 4.112836 | false | false | false | false |
exponentjs/exponent | android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/components/webview/events/TopLoadingProgressEvent.kt | 2 | 765 | package versioned.host.exp.exponent.modules.api.components.webview.events
import com.facebook.react.bridge.WritableMap
import com.facebook.react.uimanager.events.Event
import com.facebook.react.uimanager.events.RCTEventEmitter
/**
* Event emitted when there is a loading progress event.
*/
class TopLoadingProgressEvent(viewId: Int, private val mEventData: WritableMap) :
Event<TopLoadingProgressEvent>(viewId) {
companion object {
const val EVENT_NAME = "topLoadingProgress"
}
override fun getEventName(): String = EVENT_NAME
override fun canCoalesce(): Boolean = false
override fun getCoalescingKey(): Short = 0
override fun dispatch(rctEventEmitter: RCTEventEmitter) =
rctEventEmitter.receiveEvent(viewTag, eventName, mEventData)
}
| bsd-3-clause | 8d4f9f39b6e0a85f6a1fbc4f7961423e | 30.875 | 81 | 0.784314 | 4.553571 | false | false | false | false |
aarmea/noise | app/src/main/java/com/alternativeinfrastructures/noise/sync/bluetooth/BluetoothSyncService.kt | 1 | 20226 | package com.alternativeinfrastructures.noise.sync.bluetooth
import android.annotation.SuppressLint
import android.app.Service
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothServerSocket
import android.bluetooth.BluetoothSocket
import android.bluetooth.le.AdvertiseCallback
import android.bluetooth.le.AdvertiseData
import android.bluetooth.le.AdvertiseSettings
import android.bluetooth.le.BluetoothLeAdvertiser
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.IBinder
import android.os.ParcelUuid
import android.preference.PreferenceManager
import android.util.Log
import android.widget.Toast
import net.vidageek.mirror.dsl.Mirror
import com.alternativeinfrastructures.noise.R
import com.alternativeinfrastructures.noise.sync.StreamSync
import com.alternativeinfrastructures.noise.views.SettingsActivity
import java.io.IOException
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
import java.util.regex.Pattern
class BluetoothSyncService : Service() {
private var started = false
private var serviceUuidAndAddress: UUID? = null
private var bluetoothAdapter: BluetoothAdapter? = null
private var bluetoothLeAdvertiser: BluetoothLeAdvertiser? = null
private var bluetoothLeScanner: BluetoothLeScanner? = null
private var bluetoothClassicServer: Thread? = null
private var openConnections: ConcurrentHashMap<String, Boolean>? = null
override fun onBind(intent: Intent): IBinder? {
// TODO: Return the communication channel to the service.
throw UnsupportedOperationException("Not yet implemented")
}
enum class CanStartResult {
CAN_START,
BLUETOOTH_OR_BLE_UNSUPPORTED,
BLUETOOTH_OFF,
BLUETOOTH_ADDRESS_UNAVAILABLE
}
private fun buildAdvertiseData(): AdvertiseData {
val builder = AdvertiseData.Builder()
// We are including this device's physical MAC address in the advertisement to enable higher bandwidth pair-free communication over Bluetooth Classic sockets.
// While our communications will always be anonymous by design, this still has privacy implications:
// If an attacker manages to associate an address with a person, they will be able to determine if that person is nearby as long as the app is installed on that phone.
builder.addServiceUuid(ParcelUuid(serviceUuidAndAddress))
// TODO: Include some portion of the sync bit string/Bloom filter from the database
builder.setIncludeDeviceName(false)
return builder.build()
}
private fun buildAdvertiseSettings(): AdvertiseSettings {
val builder = AdvertiseSettings.Builder()
builder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_POWER)
builder.setTimeout(0) // Advertise as long as Bluetooth is on, blatantly ignoring Google's advice.
builder.setConnectable(false)
return builder.build()
}
private fun buildScanSettings(): ScanSettings {
val builder = ScanSettings.Builder()
builder.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
if (Build.VERSION.SDK_INT >= 23 /* Marshmallow */) {
builder.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE)
builder.setNumOfMatches(ScanSettings.MATCH_NUM_MAX_ADVERTISEMENT)
builder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
}
return builder.build()
}
private fun startBluetoothLeDiscovery(startId: Int) {
bluetoothLeAdvertiser!!.startAdvertising(buildAdvertiseSettings(), buildAdvertiseData(),
object : AdvertiseCallback() {
override fun onStartSuccess(settingsInEffect: AdvertiseSettings) {
super.onStartSuccess(settingsInEffect)
Log.d(TAG, "BLE advertise started")
}
override fun onStartFailure(errorCode: Int) {
super.onStartFailure(errorCode)
Log.e(TAG, "BLE advertise failed to start: error $errorCode")
stopSelf(startId)
// TODO: Is it safe to restart the advertisement?
}
})
// Scan filters on service UUIDs were completely broken on the devices I tested (fully updated Google Pixel and Moto G4 Play as of March 2017)
// https://stackoverflow.com/questions/29664316/bluetooth-le-scan-filter-not-working
// TODO: Check if that's supported using bluetoothAdapter.isOffloadedFilteringSupported/isOffloadedScanBatchingSupported
// https://stackoverflow.com/questions/26482611/chipsets-devices-supporting-android-5-ble-peripheral-mode
bluetoothLeScanner!!.startScan(null, buildScanSettings(),
object : ScanCallback() {
override fun onScanFailed(errorCode: Int) {
super.onScanFailed(errorCode)
Log.e(TAG, "BLE scan failed to start: error $errorCode")
stopSelf(startId)
// TODO: Is it safe to restart the scan?
}
override fun onScanResult(callbackType: Int, result: ScanResult) {
super.onScanResult(callbackType, result)
if (result.scanRecord == null || result.scanRecord!!.serviceUuids == null)
return
for (uuid in result.scanRecord!!.serviceUuids) {
if (!matchesServiceUuid(uuid.uuid))
continue
Log.d(TAG, "BLE scanner found supported device")
// Android uses randomly-generated MAC addresses in its broadcasts, and result.getDevice() uses that broadcast address.
// Unfortunately, the device that sent the broadcast can't listen using that MAC address.
// As a result, we can't use result.getDevice() to establish a Bluetooth Classic connection.
// Instead, we use the MAC address that was included in the service UUID.
val remoteDeviceMacAddress = macAddressFromLong(uuid.uuid.leastSignificantBits)
val remoteDevice = bluetoothAdapter!!.getRemoteDevice(remoteDeviceMacAddress)
// TODO: Interrupt this thread when the service is stopping
BluetoothClassicClient(remoteDevice, uuid.uuid).start()
}
}
})/*filters*/
}
private fun stopBluetoothLeDiscovery() {
if (!bluetoothAdapter!!.isEnabled)
return
if (bluetoothLeAdvertiser != null) {
bluetoothLeAdvertiser!!.stopAdvertising(object : AdvertiseCallback() {
override fun onStartFailure(errorCode: Int) {
super.onStartFailure(errorCode)
Log.e(TAG, "BLE advertise failed to stop: error $errorCode")
}
})
}
if (bluetoothLeScanner != null) {
bluetoothLeScanner!!.stopScan(object : ScanCallback() {
override fun onScanFailed(errorCode: Int) {
super.onScanFailed(errorCode)
Log.e(TAG, "BLE scan failed to stop: error $errorCode")
}
})
}
}
private inner class BluetoothClassicServer(uuid: UUID) : Thread() {
private var serverSocket: BluetoothServerSocket? = null
init {
try {
serverSocket = bluetoothAdapter!!.listenUsingInsecureRfcommWithServiceRecord(TAG, uuid)
} catch (e: IOException) {
Log.e(TAG, "Failed to set up Bluetooth Classic connection as a server", e)
}
}
override fun run() {
var socket: BluetoothSocket? = null
while (bluetoothAdapter!!.isEnabled && started) {
var macAddress: String? = null
try {
// This will block until there is a connection
Log.d(TAG, "Bluetooth Classic server is listening for a client")
socket = serverSocket!!.accept()
macAddress = socket!!.remoteDevice.address
if (!openConnections!!.containsKey(macAddress)) {
openConnections!![macAddress!!] = true
StreamSync.bidirectionalSync(socket.inputStream, socket.outputStream)
}
socket.close()
} catch (connectException: IOException) {
Log.e(TAG, "Failed to start a Bluetooth Classic connection as a server", connectException)
try {
socket?.close()
} catch (closeException: IOException) {
Log.e(TAG, "Failed to close a Bluetooth Classic connection as a server", closeException)
}
}
if (macAddress != null)
openConnections!!.remove(macAddress)
}
}
}
private inner class BluetoothClassicClient(device: BluetoothDevice, uuid: UUID) : Thread() {
internal var socket: BluetoothSocket? = null
internal var macAddress: String? = null
init {
macAddress = device.address
try {
socket = device.createInsecureRfcommSocketToServiceRecord(uuid)
} catch (connectException: IOException) {
Log.e(TAG, "Failed to set up a Bluetooth Classic connection as a client", connectException)
}
}
override fun run() {
// TODO: This should be done with a counter instead (with AtomicInteger)
if (openConnections!!.containsKey(macAddress))
return
openConnections!![macAddress!!] = true
try {
// This will block until there is a connection
Log.d(TAG, "Bluetooth Classic client is attempting to connect to a server")
socket!!.connect()
StreamSync.bidirectionalSync(socket!!.inputStream, socket!!.outputStream)
socket!!.close()
} catch (connectException: IOException) {
Log.e(TAG, "Failed to start a Bluetooth Classic connection as a client", connectException)
try {
socket!!.close()
} catch (closeException: IOException) {
Log.e(TAG, "Failed to close a Bluetooth Classic connection as a client", closeException)
}
}
openConnections!!.remove(macAddress!!)
}
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
if (canStart(this) != CanStartResult.CAN_START) {
Log.e(TAG, "Trying to start the service even though Bluetooth is off or BLE is unsupported")
stopSelf(startId)
return Service.START_NOT_STICKY
}
if (started) {
Log.d(TAG, "Started again")
return Service.START_STICKY
}
bluetoothAdapter = getBluetoothAdapter(this)
// First half identifies that the advertisement is for Noise.
// Second half is the MAC address of this device's Bluetooth adapter so that clients know how to connect to it.
// These are not listed separately in the advertisement because a UUID is 16 bytes and ads are limited to 31 bytes.
val macAddress = getBluetoothAdapterAddress(bluetoothAdapter!!, this)
if (macAddress == null) {
Log.e(TAG, "Unable to get this device's Bluetooth MAC address")
stopSelf(startId)
return Service.START_NOT_STICKY
}
val uuid = UUID(SERVICE_UUID_HALF.mostSignificantBits, longFromMacAddress(macAddress))
serviceUuidAndAddress = uuid
bluetoothLeAdvertiser = bluetoothAdapter!!.bluetoothLeAdvertiser
bluetoothLeScanner = bluetoothAdapter!!.bluetoothLeScanner
startBluetoothLeDiscovery(startId)
started = true
bluetoothClassicServer = BluetoothClassicServer(uuid)
bluetoothClassicServer!!.start()
openConnections = ConcurrentHashMap()
Log.d(TAG, "Started")
Toast.makeText(this, R.string.bluetooth_sync_started, Toast.LENGTH_LONG).show()
return Service.START_STICKY
}
override fun onDestroy() {
started = false
stopBluetoothLeDiscovery()
// TODO: Verify that this actually stops the thread
bluetoothClassicServer!!.interrupt()
// TODO: Stop all BluetoothClassicClient threads
Toast.makeText(this, R.string.bluetooth_sync_stopped, Toast.LENGTH_LONG).show()
Log.d(TAG, "Stopped")
super.onDestroy()
}
companion object {
val TAG = "BluetoothSyncService"
val SERVICE_UUID_HALF = UUID.fromString("5ac825f4-6084-42a6-0000-000000000000")
private val FAKE_MAC_ADDRESS = "02:00:00:00:00:00"
private val MAC_PATTERN = Pattern.compile("\\w\\w:\\w\\w:\\w\\w:\\w\\w:\\w\\w:\\w\\w")
fun canStart(context: Context): CanStartResult {
val packageManager = context.packageManager
val bluetoothAdapter = getBluetoothAdapter(context)
if (!packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH) || !packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
return CanStartResult.BLUETOOTH_OR_BLE_UNSUPPORTED
} else if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled) {
return CanStartResult.BLUETOOTH_OFF
} else if (!bluetoothAdapter.isMultipleAdvertisementSupported) {
return CanStartResult.BLUETOOTH_OR_BLE_UNSUPPORTED
} else if (getBluetoothAdapterAddress(bluetoothAdapter, context) == null) {
return CanStartResult.BLUETOOTH_ADDRESS_UNAVAILABLE
}
return CanStartResult.CAN_START
}
fun startOrPromptBluetooth(context: Context) {
when (canStart(context)) {
BluetoothSyncService.CanStartResult.CAN_START -> {
Log.d(TAG, "Starting BLE sync service")
context.startService(Intent(context, BluetoothSyncService::class.java))
}
BluetoothSyncService.CanStartResult.BLUETOOTH_OR_BLE_UNSUPPORTED -> {
Log.d(TAG, "BLE not supported, not starting BLE sync service")
Toast.makeText(context, R.string.bluetooth_not_supported, Toast.LENGTH_LONG).show()
}
BluetoothSyncService.CanStartResult.BLUETOOTH_OFF -> {
Log.d(TAG, "BLE supported but Bluetooth is off; will prompt for Bluetooth and start once it's on")
Toast.makeText(context, R.string.bluetooth_ask_enable, Toast.LENGTH_LONG).show()
context.startActivity(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE))
}
BluetoothSyncService.CanStartResult.BLUETOOTH_ADDRESS_UNAVAILABLE -> {
Log.d(TAG, "BLE supported but MAC address is unavailable; will prompt for address and start once it's available")
Toast.makeText(context, R.string.bluetooth_ask_address, Toast.LENGTH_LONG).show()
}
}// BluetoothSyncServiceManager will start this service once Bluetooth is on.
// TODO: Open the app's settings? Maybe getting the address should be part of onboarding UI
// BluetoothSyncServiceManager will start this (re)start this service when the address changes.
}
private fun getBluetoothAdapter(context: Context): BluetoothAdapter? {
val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
?: return null
return bluetoothManager.adapter
}
private fun getBluetoothAdapterAddress(bluetoothAdapter: BluetoothAdapter, context: Context): String? {
@SuppressLint("HardwareIds") // Pair-free peer-to-peer communication should qualify as an "advanced telephony use case".
var address = bluetoothAdapter.address
if (address == FAKE_MAC_ADDRESS && Build.VERSION.SDK_INT < 26 /* Oreo */) {
Log.w(TAG, "bluetoothAdapter.getAddress() did not return the physical address")
// HACK HACK HACK: getAddress is intentionally broken (but not deprecated?!) on Marshmallow and up:
// * https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-notifications
// * https://code.google.com/p/android/issues/detail?id=197718
// However, we need it to establish pair-free Bluetooth Classic connections:
// * All BLE advertisements include a MAC address, but Android broadcasts a temporary, randomly-generated address.
// * Currently, it is only possible to listen for connections using the device's physical address.
// So we use reflection to get it anyway: http://stackoverflow.com/a/35984808
// This hack won't be necessary if getAddress is ever fixed (unlikely) or (preferably) we can listen using an arbitrary address.
val bluetoothManagerService = Mirror().on(bluetoothAdapter).get().field("mService")
if (bluetoothManagerService == null) {
Log.w(TAG, "Couldn't retrieve bluetoothAdapter.mService using reflection")
return null
}
val internalAddress = Mirror().on(bluetoothManagerService).invoke().method("getAddress").withoutArgs()
if (internalAddress == null || internalAddress !is String) {
Log.w(TAG, "Couldn't call bluetoothAdapter.mService.getAddress() using reflection")
return null
}
address = internalAddress
}
// On Oreo and above, Android will throw a SecurityException if we try to get the MAC address with reflection
// https://android-developers.googleblog.com/2017/04/changes-to-device-identifiers-in.html
// https://stackoverflow.com/a/35984808/702467
if (address == FAKE_MAC_ADDRESS) {
Log.w(TAG, "Android is actively blocking requests to get the MAC address")
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
address = preferences.getString(SettingsActivity.KEY_BLUETOOTH_MAC, "")!!.toUpperCase()
if (!MAC_PATTERN.matcher(address).matches())
return null
}
return address
}
private fun matchesServiceUuid(uuid: UUID): Boolean {
return SERVICE_UUID_HALF.mostSignificantBits == uuid.mostSignificantBits
}
private fun longFromMacAddress(macAddress: String): Long {
return java.lang.Long.parseLong(macAddress.replace(":".toRegex(), ""), 16)
}
private fun macAddressFromLong(macAddressLong: Long): String {
return String.format("%02x:%02x:%02x:%02x:%02x:%02x",
(macAddressLong shr 40).toByte(),
(macAddressLong shr 32).toByte(),
(macAddressLong shr 24).toByte(),
(macAddressLong shr 16).toByte(),
(macAddressLong shr 8).toByte(),
macAddressLong.toByte()).toUpperCase()
}
}
}
| mit | 91fc1a04e76470d7b33868e9ad3fbfda | 45.603687 | 175 | 0.625878 | 5.242613 | false | false | false | false |
k9mail/k-9 | app/core/src/main/java/com/fsck/k9/mailstore/K9BackendStorageFactory.kt | 2 | 1246 | package com.fsck.k9.mailstore
import com.fsck.k9.Account
import com.fsck.k9.Preferences
class K9BackendStorageFactory(
private val preferences: Preferences,
private val folderRepository: FolderRepository,
private val messageStoreManager: MessageStoreManager,
private val specialFolderSelectionStrategy: SpecialFolderSelectionStrategy,
private val saveMessageDataCreator: SaveMessageDataCreator
) {
fun createBackendStorage(account: Account): K9BackendStorage {
val messageStore = messageStoreManager.getMessageStore(account)
val folderSettingsProvider = FolderSettingsProvider(preferences, account)
val specialFolderUpdater = SpecialFolderUpdater(
preferences,
folderRepository,
specialFolderSelectionStrategy,
account
)
val specialFolderListener = SpecialFolderBackendFoldersRefreshListener(specialFolderUpdater)
val autoExpandFolderListener = AutoExpandFolderBackendFoldersRefreshListener(preferences, account, folderRepository)
val listeners = listOf(specialFolderListener, autoExpandFolderListener)
return K9BackendStorage(messageStore, folderSettingsProvider, saveMessageDataCreator, listeners)
}
}
| apache-2.0 | 383361fa93b73107e80568405e26c86c | 45.148148 | 124 | 0.778491 | 5.5625 | false | false | false | false |
ligi/PassAndroid | android/src/main/java/org/ligi/passandroid/functions/InputStreamProvider.kt | 1 | 2575 | package org.ligi.passandroid.functions
import android.content.Context
import android.net.Uri
import okhttp3.OkHttpClient
import okhttp3.Request
import org.ligi.passandroid.Tracker
import org.ligi.passandroid.model.InputStreamWithSource
import java.io.BufferedInputStream
import java.net.URL
const val IPHONE_USER_AGENT = "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53"
fun fromURI(context: Context, uri: Uri, tracker: Tracker): InputStreamWithSource? {
tracker.trackEvent("protocol", "to_inputstream", uri.scheme, null)
return when (uri.scheme) {
"content" -> fromContent(context, uri)
"http", "https" ->
// TODO check if SPDY should be here
return fromOKHttp(uri, tracker)
"file" -> getDefaultInputStreamForUri(uri)
else -> {
tracker.trackException("unknown scheme in ImportAsyncTask" + uri.scheme, false)
getDefaultInputStreamForUri(uri)
}
}
}
private fun fromOKHttp(uri: Uri, tracker: Tracker): InputStreamWithSource? {
val client = OkHttpClient()
val url = URL("$uri")
val requestBuilder = Request.Builder().url(url)
// fake to be an iPhone in some cases when the server decides to send no passbook
// to android phones - but only do it then - we are proud to be Android ;-)
val iPhoneFakeMap = mapOf(
"air_canada" to "//m.aircanada.ca/ebp/",
"air_canada2" to "//services.aircanada.com/ebp/",
"air_canada3" to "//mci.aircanada.com/mci/bp/",
"icelandair" to "//checkin.si.amadeus.net",
"mbk" to "//mbk.thy.com/",
"heathrow" to "//passbook.heathrow.com/",
"eventbrite" to "//www.eventbrite.com/passes/order"
)
for ((key, value) in iPhoneFakeMap) {
if ("$uri".contains(value)) {
tracker.trackEvent("quirk_fix", "ua_fake", key, null)
requestBuilder.header("User-Agent", IPHONE_USER_AGENT)
}
}
val request = requestBuilder.build()
val response = client.newCall(request).execute()
val body = response.body()
if (body != null) {
return InputStreamWithSource("$uri", body.byteStream())
}
return null
}
private fun fromContent(ctx: Context, uri: Uri) = ctx.contentResolver.openInputStream(uri)?.let {
InputStreamWithSource("$uri", it)
}
private fun getDefaultInputStreamForUri(uri: Uri) = InputStreamWithSource("$uri", BufferedInputStream(URL("$uri").openStream(), 4096))
| gpl-3.0 | f86a92c92d0ce485533a3bdcfebd6e44 | 34.763889 | 174 | 0.658641 | 3.742733 | false | false | false | false |
yole/faguirra | src/ru/yole/faguirra/FaguirraFileSystem.kt | 1 | 3768 | package ru.yole.faguirra.fs
import com.intellij.openapi.vfs.DeprecatedVirtualFileSystem
import com.intellij.openapi.vfs.VirtualFile
import java.io.OutputStream
import java.io.InputStream
import com.intellij.openapi.vfs.VirtualFileManager
import java.util.ArrayList
import com.intellij.openapi.fileTypes.FileType
import javax.swing.Icon
public class FaguirraFileType(): FileType {
override fun getName() = "Faguirra"
override fun getDescription() = "Internal file type for Faguirra panels"
override fun getDefaultExtension() = "faguirra"
override fun getIcon() = null
override fun isBinary() = false
override fun isReadOnly() = true
override fun getCharset(file: VirtualFile, content: ByteArray?): String? = null
class object {
val INSTANCE = FaguirraFileType()
}
}
public class FaguirraVirtualFile(val fileName: String): VirtualFile() {
override fun getName() = fileName
override fun getFileSystem() = FaguirraFileSystem.INSTANCE
override fun getPath() = "Faguirra"
override fun isWritable() = false
override fun isDirectory() = false
override fun isValid() = true
override fun getParent() = null
override fun getChildren(): Array<VirtualFile>? = array()
override fun getOutputStream(requestor: Any?, newModificationStamp: Long, newTimeStamp: Long): OutputStream {
throw UnsupportedOperationException()
}
override fun getInputStream(): InputStream? {
throw UnsupportedOperationException()
}
override fun contentsToByteArray() = byteArray()
override fun getTimeStamp() = 0.toLong()
override fun getModificationStamp() = 0.toLong()
override fun getLength() = 0.toLong()
override fun refresh(asynchronous: Boolean, recursive: Boolean, postRunnable: Runnable?) {
}
override fun getFileType() = FaguirraFileType.INSTANCE
}
public class FaguirraFileSystem(): DeprecatedVirtualFileSystem() {
private val files = ArrayList<FaguirraVirtualFile>()
public fun allocateFile(): VirtualFile {
val name = if (files.size() == 0) "Faguirra" else "Faguirra (${files.size})"
val result = FaguirraVirtualFile(name)
files.add(result)
return result
}
override fun getProtocol(): String = PROTOCOL
override fun findFileByPath(path: String): VirtualFile? {
val result = files.find { it.getName() == path }
if (result != null) return result
if (path.equals("Faguirra") && files.size() == 0) {
return allocateFile()
}
return null
}
override fun refresh(asynchronous: Boolean) {
}
override fun refreshAndFindFileByPath(path: String): VirtualFile? = findFileByPath(path)
override fun deleteFile(requestor: Any?, vFile: VirtualFile) {
throw UnsupportedOperationException()
}
override fun moveFile(requestor: Any?, vFile: VirtualFile, newParent: VirtualFile) {
throw UnsupportedOperationException()
}
override fun renameFile(requestor: Any?, vFile: VirtualFile, newName: String) {
throw UnsupportedOperationException()
}
override fun createChildFile(requestor: Any?, vDir: VirtualFile, fileName: String): VirtualFile? {
throw UnsupportedOperationException()
}
override fun createChildDirectory(requestor: Any?, vDir: VirtualFile, dirName: String): VirtualFile {
throw UnsupportedOperationException()
}
override fun copyFile(requestor: Any?, virtualFile: VirtualFile, newParent: VirtualFile, copyName: String): VirtualFile? {
throw UnsupportedOperationException()
}
class object {
val PROTOCOL = "faguirra"
val INSTANCE = VirtualFileManager.getInstance().getFileSystem(PROTOCOL) as FaguirraFileSystem
}
} | apache-2.0 | 84280eda2a1f606d840c74abd0b68eb3 | 34.556604 | 126 | 0.706476 | 4.657602 | false | false | false | false |
NCBSinfo/NCBSinfo | app/src/main/java/com/rohitsuratekar/NCBSinfo/MainActivity.kt | 2 | 7914 | package com.rohitsuratekar.NCBSinfo
import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.annotation.NonNull
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavController
import androidx.navigation.NavDirections
import androidx.navigation.Navigation
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.rohitsuratekar.NCBSinfo.adapters.ContactDetailsAdapter
import com.rohitsuratekar.NCBSinfo.common.Constants
import com.rohitsuratekar.NCBSinfo.common.MainCallbacks
import com.rohitsuratekar.NCBSinfo.common.hideMe
import com.rohitsuratekar.NCBSinfo.common.showMe
import com.rohitsuratekar.NCBSinfo.di.*
import com.rohitsuratekar.NCBSinfo.fragments.ContactDetailsFragment
import com.rohitsuratekar.NCBSinfo.fragments.SettingsFragmentDirections
import com.rohitsuratekar.NCBSinfo.fragments.TransportRoutesFragment
import com.rohitsuratekar.NCBSinfo.models.Contact
import com.rohitsuratekar.NCBSinfo.viewmodels.SharedViewModel
import kotlinx.android.synthetic.main.activity_main.*
import javax.inject.Inject
class MainActivity : AppCompatActivity(), MainCallbacks, ContactDetailsAdapter.OnCalled {
val CALL_PERMISSION = 1989 // Should NOT be private
@Inject
lateinit var repository: Repository
private lateinit var navController: NavController
private lateinit var sharedViewModel: SharedViewModel
private val permissions = arrayOf(Manifest.permission.CALL_PHONE)
private var tempNumber = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navController = Navigation.findNavController(this, R.id.nav_host)
sharedViewModel = ViewModelProvider(this).get(SharedViewModel::class.java)
DaggerAppComponent.builder()
.appModule(AppModule(application))
.prefModule(PrefModule(baseContext))
.roomModule(RoomModule(application))
.build()
.inject(this)
bottom_navigation.setupWithNavController(navController)
}
fun checkSharedModel(): SharedViewModel {
if (!this::sharedViewModel.isInitialized) {
sharedViewModel = ViewModelProvider(this).get(SharedViewModel::class.java)
}
return sharedViewModel
}
fun checkRepository(): Repository {
if (!this::repository.isInitialized) {
DaggerAppComponent.builder()
.appModule(AppModule(application))
.prefModule(PrefModule(baseContext))
.roomModule(RoomModule(application))
.build()
.inject(this)
}
return repository
}
private fun gotoHome() {
// Following code is needed to change start destination
// https://stackoverflow.com/questions/51929290/
// is-it-possible-to-set-startdestination-conditionally-using-android-navigation-ar
val navHostFragment = nav_host as NavHostFragment
val inflater = navHostFragment.navController.navInflater
val graph = inflater.inflate(R.navigation.navigation)
graph.startDestination = R.id.homeFragment
navHostFragment.navController.graph = graph
bottom_navigation.setupWithNavController(navController)
navController.popBackStack()
navController.navigate(R.id.homeFragment)
// for (item in bottom_navigation.menu.children) {
// item.isEnabled = true
// }
}
override fun showProgress() {
progress_frame.showMe()
}
override fun hideProgress() {
progress_frame.hideMe()
}
override fun showError(message: String) {
hideProgress()
AlertDialog.Builder(this@MainActivity)
.setTitle(R.string.oops)
.setMessage(message)
.setPositiveButton(android.R.string.ok) { _, _ -> }
.show()
}
override fun navigate(option: Int) {
when (option) {
Constants.NAVIGATE_HOME -> gotoHome()
Constants.NAVIGATE_TIMETABLE -> navController.navigate(R.id.timetableFragment)
Constants.NAVIGATE_LOCATIONS -> navController.navigate(R.id.action_informationFragment_to_locationFragment)
Constants.NAVIGATE_MANAGE_TRANSPORT -> navController.navigate(R.id.action_informationFragment_to_manageTransportFragment)
Constants.NAVIGATE_EDIT_TRANSPORT -> navController.navigate(R.id.action_manageTransportFragment_to_editTransport)
}
}
override fun showRouteList(currentRoute: Int) {
val sheet = TransportRoutesFragment()
val args = Bundle()
args.putInt(Constants.BOTTOM_SHEET_ROUTE_ID, currentRoute)
sheet.arguments = args
sheet.show(supportFragmentManager, sheet.tag)
}
override fun showContact(contact: Contact) {
val sheet = ContactDetailsFragment()
val args = Bundle()
args.putString(Constants.BOTTOM_SHEET_CONTACT_NAME, contact.name)
args.putString(Constants.BOTTOM_SHEET_CONTACT_EXTENSION, contact.primaryExtension)
args.putString(Constants.BOTTOM_SHEET_CONTACT_EXTRA, contact.otherExtensions)
args.putString(Constants.BOTTOM_SHEET_CONTACT_DETAILS, contact.details)
sheet.arguments = args
sheet.show(supportFragmentManager, sheet.tag)
}
override fun calledNumber(number: String) {
//Check permissions
if (ContextCompat.checkSelfPermission(
baseContext,
Manifest.permission.CALL_PHONE
) == PackageManager.PERMISSION_GRANTED
) {
call(number)
} else {
tempNumber = number
showDenied()
}
}
private fun showDenied() {
AlertDialog.Builder(this@MainActivity)
.setTitle(getString(R.string.ct_permission_needed))
.setMessage(getString(R.string.ct_warning_permission))
.setPositiveButton(
android.R.string.ok
) { _, _ ->
ActivityCompat.requestPermissions(
this@MainActivity,
permissions,
CALL_PERMISSION
)
}.setNegativeButton(
android.R.string.cancel
) { _, _ -> }.show()
}
override fun onRequestPermissionsResult(
requestCode: Int,
@NonNull permissions: Array<String>,
@NonNull grantResults: IntArray
) {
when (requestCode) {
CALL_PERMISSION -> if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
call(tempNumber)
} else {
Log.e("Contacts", "Permission Denied")
showDenied()
}
}
}
@SuppressLint("MissingPermission")
private fun call(number: String) {
val intent = Intent(Intent.ACTION_CALL)
intent.data = Uri.parse("tel:$number")
startActivity(intent)
}
override fun editRoute(navDirections: NavDirections) {
navController.navigate(navDirections)
}
override fun showSettingsInfo(action: Int) {
val arg = SettingsFragmentDirections.actionSettingsFragmentToSettingsInfoFragment(action)
navController.navigate(arg)
}
}
| mit | 681774f1d3be3481bf58f95ca8c6c5ed | 33.648649 | 133 | 0.661107 | 5.060102 | false | false | false | false |
c4gnv/things-android | app/src/main/java/c4gnv/com/thingsregistry/net/ServiceError.kt | 1 | 2076 | package c4gnv.com.thingsregistry.net
import java.io.IOException
import java.io.Serializable
import java.net.ConnectException
import java.net.UnknownHostException
import okhttp3.Request
import retrofit2.Call
class ServiceError(val statusCode: Int, val error: String, val message: String) : Serializable {
enum class ErrorType {
UNKNOWN,
IOEXCEPTION,
CONNECTION
}
companion object {
private const val serialVersionUID: Long = 1
fun from(call: Call<*>?, t: Throwable): ServiceError {
val request = call?.request() as Request
if (t is UnknownHostException || t is ConnectException) {
return createError(request, ErrorType.CONNECTION)
}
if (t is IOException) {
return createError(request, ErrorType.IOEXCEPTION)
}
return createError(request, ErrorType.UNKNOWN)
}
fun createError(request: Request, type: ErrorType): ServiceError {
val statusCode: Int
val error: String
val message: String
when (type) {
ServiceError.ErrorType.IOEXCEPTION -> {
statusCode = -2
error = "IOException"
message = "Sorry, there was an IO exception."
}
ServiceError.ErrorType.CONNECTION -> {
statusCode = -3
error = "ConnectionError"
message = "Sorry, there was a connection error."
}
ServiceError.ErrorType.UNKNOWN -> {
statusCode = -1
error = "UnknownError"
message = "Sorry, something doesn't seem right."
}
else -> {
statusCode = -1
error = "UnknownError"
message = "Sorry, something doesn't seem right."
}
}
return ServiceError(statusCode, error, message)
}
}
}
| mit | 8285a5b890a84a9ca22db92d3f0a306a | 28.657143 | 96 | 0.53131 | 5.477573 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/recurrent/lstm/LSTMForwardHelper.kt | 1 | 3940 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.layers.models.recurrent.lstm
import com.kotlinnlp.simplednn.core.layers.helpers.ForwardHelper
import com.kotlinnlp.simplednn.core.layers.Layer
import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
/**
* The helper which executes the forward on a [layer].
*
* @property layer the [LSTMLayer] in which the forward is executed
*/
internal class LSTMForwardHelper<InputNDArrayType : NDArray<InputNDArrayType>>(
override val layer: LSTMLayer<InputNDArrayType>
) : ForwardHelper<InputNDArrayType>(layer) {
/**
* Forward the input to the output combining it with the parameters.
*
* y = outG * f(cell)
*/
override fun forward() {
this.setGates(this.layer.layersWindow.getPrevState()) // must be called before accessing to the activated values of the gates
val y: DenseNDArray = this.layer.outputArray.values
val outG: DenseNDArray = this.layer.outputGate.values
val cellA: DenseNDArray = this.layer.cell.values
y.assignProd(outG, cellA)
}
/**
* Set gates values
*
* inG = sigmoid(wIn (dot) x + bIn + wInRec (dot) yPrev)
* outG = sigmoid(wOut (dot) x + bOut + wOutRec (dot) yPrev)
* forG = sigmoid(wFor (dot) x + bFor + wForRec (dot) yPrev)
* cand = f(wCand (dot) x + bC + wCandRec (dot) yPrev)
* cell = inG * cand + forG * cellPrev
*/
private fun setGates(prevStateLayer: Layer<*>?) {
this.forwardGates()
if (prevStateLayer != null) {
this.addGatesRecurrentContribution(prevStateLayer)
}
this.activateGates()
val cell: DenseNDArray = this.layer.cell.values
val inG: DenseNDArray = this.layer.inputGate.values
val cand: DenseNDArray = this.layer.candidate.values
cell.assignProd(inG, cand)
if (prevStateLayer != null) { // add recurrent contribution to the cell
val forG: DenseNDArray = this.layer.forgetGate.values
val cellPrev: DenseNDArray = (prevStateLayer as LSTMLayer).cell.valuesNotActivated
cell.assignSum(forG.prod(cellPrev))
}
this.layer.cell.activate()
}
/**
*
*/
private fun forwardGates() {
val x: InputNDArrayType = this.layer.inputArray.values
this.layer.inputGate.forward(
w = this.layer.params.inputGate.weights.values,
b = this.layer.params.inputGate.biases.values,
x = x
)
this.layer.outputGate.forward(
w = this.layer.params.outputGate.weights.values,
b = this.layer.params.outputGate.biases.values,
x = x
)
this.layer.forgetGate.forward(
w = this.layer.params.forgetGate.weights.values,
b = this.layer.params.forgetGate.biases.values,
x = x
)
this.layer.candidate.forward(
w = this.layer.params.candidate.weights.values,
b = this.layer.params.candidate.biases.values,
x = x
)
}
/**
*
*/
private fun addGatesRecurrentContribution(prevStateLayer: Layer<*>) {
val yPrev: DenseNDArray = prevStateLayer.outputArray.values
this.layer.inputGate.addRecurrentContribution(this.layer.params.inputGate, yPrev)
this.layer.outputGate.addRecurrentContribution(this.layer.params.outputGate, yPrev)
this.layer.forgetGate.addRecurrentContribution(this.layer.params.forgetGate, yPrev)
this.layer.candidate.addRecurrentContribution(this.layer.params.candidate, yPrev)
}
/**
*
*/
private fun activateGates() {
this.layer.inputGate.activate()
this.layer.outputGate.activate()
this.layer.forgetGate.activate()
this.layer.candidate.activate()
}
}
| mpl-2.0 | 73287d501847624cd2b510d5021825ac | 30.023622 | 129 | 0.689848 | 3.745247 | false | false | false | false |
mdaniel/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/lang/parser/frontmatter/FrontMatterHeaderMarkerProvider.kt | 4 | 1866 | package org.intellij.plugins.markdown.lang.parser.frontmatter
import com.intellij.openapi.util.registry.Registry
import org.intellij.markdown.MarkdownElementType
import org.intellij.markdown.parser.LookaheadText
import org.intellij.markdown.parser.MarkerProcessor
import org.intellij.markdown.parser.ProductionHolder
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.markerblocks.MarkerBlock
import org.intellij.markdown.parser.markerblocks.MarkerBlockProvider
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
class FrontMatterHeaderMarkerProvider: MarkerBlockProvider<MarkerProcessor.StateInfo> {
override fun createMarkerBlocks(
position: LookaheadText.Position,
productionHolder: ProductionHolder,
stateInfo: MarkerProcessor.StateInfo
): List<MarkerBlock> {
if (position.offset != 0) {
return emptyList()
}
return when (isDelimiterLine(position.currentLine)) {
true -> listOf(FrontMatterHeaderBlock(position, stateInfo.currentConstraints, productionHolder))
else -> emptyList()
}
}
override fun interruptsParagraph(pos: LookaheadText.Position, constraints: MarkdownConstraints): Boolean {
return false
}
companion object {
@JvmField
val FRONT_MATTER_HEADER = MarkdownElementType("FRONT_MATTER_HEADER")
@JvmField
val FRONT_MATTER_HEADER_DELIMITER = MarkdownElementType("FRONT_MATTER_HEADER_DELIMITER", isToken = true)
@JvmField
val FRONT_MATTER_HEADER_CONTENT = MarkdownElementType("FRONT_MATTER_HEADER_CONTENT", isToken = true)
fun isDelimiterLine(line: String): Boolean {
return line.length >= 3 && line.all { it == '-' }
}
@JvmStatic
fun isFrontMatterSupportEnabled(): Boolean {
return Registry.`is`("markdown.experimental.frontmatter.support.enable", false)
}
}
}
| apache-2.0 | 2dd8e4448a4aa4bd7bba616108c1238d | 34.884615 | 108 | 0.769025 | 4.665 | false | false | false | false |
mdaniel/intellij-community | jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/TestCaseWithConstructorInspection.kt | 1 | 2955 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInspection.test
import com.intellij.analysis.JvmAnalysisBundle
import com.intellij.codeInspection.AbstractBaseUastLocalInspectionTool
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.codeInspection.registerUProblem
import com.intellij.lang.jvm.JvmModifier
import com.intellij.psi.PsiElementVisitor
import com.intellij.uast.UastHintedVisitorAdapter
import com.intellij.util.castSafelyTo
import com.siyeh.ig.psiutils.MethodUtils
import com.siyeh.ig.psiutils.TestUtils
import org.jetbrains.uast.*
import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor
class TestCaseWithConstructorInspection : AbstractBaseUastLocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor =
UastHintedVisitorAdapter.create(
holder.file.language,
TestCaseWithConstructorVisitor(holder),
arrayOf(UMethod::class.java), // TODO enable UClassInitializer when it has proper uastAnchor implementation
directOnly = true
)
}
private class TestCaseWithConstructorVisitor(private val holder: ProblemsHolder) : AbstractUastNonRecursiveVisitor() {
override fun visitInitializer(node: UClassInitializer): Boolean {
if (node.isStatic) return true
val containingClass = node.castSafelyTo<UClassInitializerEx>()?.javaPsi?.containingClass ?: return true
if (!TestUtils.isTestClass(containingClass)) return true
if (MethodUtils.isTrivial(node)) return true
val message = JvmAnalysisBundle.message("jvm.inspections.test.case.with.constructor.problem.descriptor.initializer")
holder.registerUProblem(node, message)
return true
}
override fun visitMethod(node: UMethod): Boolean {
val method = node.javaPsi
if (!node.isConstructor) return true
val containingClass = method.containingClass ?: return true
if (!TestUtils.isTestClass(containingClass)) return true
if (TestUtils.isParameterizedTest(containingClass)) return true
if (MethodUtils.isTrivial(node, ::isAssignmentToFinalField)) return true
val message = JvmAnalysisBundle.message("jvm.inspections.test.case.with.constructor.problem.descriptor")
holder.registerUProblem(node, message)
return true
}
private fun isAssignmentToFinalField(expression: UExpression): Boolean {
val assignmentExpression = expression.castSafelyTo<UBinaryExpression>() ?: return false
if (assignmentExpression.operator != UastBinaryOperator.EQUALS) return false
val lhs = assignmentExpression.leftOperand.skipParenthesizedExprDown().castSafelyTo<UReferenceExpression>() ?: return false
val target = lhs.resolveToUElement()
return target is UFieldEx && target.javaPsi.hasModifier(JvmModifier.FINAL)
}
} | apache-2.0 | 377f0a3c7168a1607692450a5f9a32d0 | 49.965517 | 130 | 0.803723 | 5.121317 | false | true | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/MapGetWithNotNullAssertionOperatorInspection.kt | 1 | 5362 | // 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
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor
class MapGetWithNotNullAssertionOperatorInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
postfixExpressionVisitor(fun(expression: KtPostfixExpression) {
if (expression.operationToken != KtTokens.EXCLEXCL) return
if (expression.getReplacementData() == null) return
if (expression.baseExpression?.resolveToCall()?.resultingDescriptor?.fqNameSafe != FqName("kotlin.collections.Map.get")) return
holder.registerProblem(
expression.operationReference,
KotlinBundle.message("map.get.with.not.null.assertion.operator"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceWithGetValueCallFix(),
ReplaceWithGetOrElseFix(),
ReplaceWithElvisErrorFix()
)
})
private class ReplaceWithGetValueCallFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.get.value.call.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expression = descriptor.psiElement.parent as? KtPostfixExpression ?: return
val (reference, index) = expression.getReplacementData() ?: return
val replaced = expression.replaced(KtPsiFactory(expression).createExpressionByPattern("$0.getValue($1)", reference, index))
replaced.findExistingEditor()?.caretModel?.moveToOffset(replaced.endOffset)
}
}
private class ReplaceWithGetOrElseFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.get.or.else.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expression = descriptor.psiElement.parent as? KtPostfixExpression ?: return
val (reference, index) = expression.getReplacementData() ?: return
val replaced = expression.replaced(KtPsiFactory(expression).createExpressionByPattern("$0.getOrElse($1){}", reference, index))
val editor = replaced.findExistingEditor() ?: return
val offset = (replaced as KtQualifiedExpression).callExpression?.lambdaArguments?.firstOrNull()?.startOffset ?: return
val document = editor.document
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document)
document.insertString(offset + 1, " ")
editor.caretModel.moveToOffset(offset + 2)
}
}
private class ReplaceWithElvisErrorFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.elvis.error.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expression = descriptor.psiElement.parent as? KtPostfixExpression ?: return
val (reference, index) = expression.getReplacementData() ?: return
val replaced = expression.replace(KtPsiFactory(expression).createExpressionByPattern("$0[$1] ?: error(\"\")", reference, index))
val editor = replaced.findExistingEditor() ?: return
val offset = (replaced as? KtBinaryExpression)?.right?.endOffset ?: return
editor.caretModel.moveToOffset(offset - 2)
}
}
}
private fun KtPostfixExpression.getReplacementData(): Pair<KtExpression, KtExpression>? {
when (val base = baseExpression) {
is KtQualifiedExpression -> {
if (base.callExpression?.calleeExpression?.text != "get") return null
val reference = base.receiverExpression
val index = base.callExpression?.valueArguments?.firstOrNull()?.getArgumentExpression() ?: return null
return reference to index
}
is KtArrayAccessExpression -> {
val reference = base.arrayExpression ?: return null
val index = base.indexExpressions.firstOrNull() ?: return null
return reference to index
}
else -> return null
}
} | apache-2.0 | 08e45cb629120b71f129f825f9269186 | 53.171717 | 158 | 0.715964 | 5.356643 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildSourceEntityImpl.kt | 2 | 9681 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import java.util.*
import java.util.UUID
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildSourceEntityImpl(val dataSource: ChildSourceEntityData) : ChildSourceEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(SourceEntity::class.java, ChildSourceEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val data: String
get() = dataSource.data
override val parentEntity: SourceEntity
get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)!!
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: ChildSourceEntityData?) : ModifiableWorkspaceEntityBase<ChildSourceEntity, ChildSourceEntityData>(
result), ChildSourceEntity.Builder {
constructor() : this(ChildSourceEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildSourceEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDataInitialized()) {
error("Field ChildSourceEntity#data should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field ChildSourceEntity#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field ChildSourceEntity#parentEntity should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ChildSourceEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.data != dataSource.data) this.data = dataSource.data
if (parents != null) {
val parentEntityNew = parents.filterIsInstance<SourceEntity>().single()
if ((this.parentEntity as WorkspaceEntityBase).id != (parentEntityNew as WorkspaceEntityBase).id) {
this.parentEntity = parentEntityNew
}
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData(true).data = value
changedProperty.add("data")
}
override var parentEntity: SourceEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)]!! as SourceEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as SourceEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*, *>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*, *>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityClass(): Class<ChildSourceEntity> = ChildSourceEntity::class.java
}
}
class ChildSourceEntityData : WorkspaceEntityData<ChildSourceEntity>() {
lateinit var data: String
fun isDataInitialized(): Boolean = ::data.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ChildSourceEntity> {
val modifiable = ChildSourceEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ChildSourceEntity {
return getCached(snapshot) {
val entity = ChildSourceEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildSourceEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ChildSourceEntity(data, entitySource) {
this.parentEntity = parents.filterIsInstance<SourceEntity>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(SourceEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ChildSourceEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ChildSourceEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 3b32bcbdffebff6962bdef413999a444 | 36.234615 | 150 | 0.698585 | 5.270005 | false | false | false | false |
GunoH/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packagedetails/PackageDetailsHeaderPanel.kt | 3 | 16480 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packagedetails
import com.intellij.icons.AllIcons
import com.intellij.ide.plugins.newui.ColorButton
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.JBPopupMenu
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.UIUtil
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration
import com.jetbrains.packagesearch.intellij.plugin.normalizeWhitespace
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.OperationExecutor
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageOperations
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.RepositoryModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageOperationType
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation
import com.jetbrains.packagesearch.intellij.plugin.ui.util.AbstractLayoutManager2
import com.jetbrains.packagesearch.intellij.plugin.ui.util.HtmlEditorPane
import com.jetbrains.packagesearch.intellij.plugin.ui.util.MenuAction
import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScaledPixels
import com.jetbrains.packagesearch.intellij.plugin.ui.util.bottom
import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder
import com.jetbrains.packagesearch.intellij.plugin.ui.util.horizontal
import com.jetbrains.packagesearch.intellij.plugin.ui.util.left
import com.jetbrains.packagesearch.intellij.plugin.ui.util.onRightClick
import com.jetbrains.packagesearch.intellij.plugin.ui.util.right
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaledFontSize
import com.jetbrains.packagesearch.intellij.plugin.ui.util.showUnderneath
import com.jetbrains.packagesearch.intellij.plugin.ui.util.top
import com.jetbrains.packagesearch.intellij.plugin.ui.util.vertical
import com.jetbrains.packagesearch.intellij.plugin.ui.util.verticalCenter
import com.jetbrains.packagesearch.intellij.plugin.util.nullIfBlank
import kotlinx.coroutines.Deferred
import java.awt.BorderLayout
import java.awt.Component
import java.awt.Container
import java.awt.Dimension
import java.awt.Rectangle
import java.awt.datatransfer.StringSelection
import java.awt.event.KeyEvent
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.text.JTextComponent
import javax.swing.text.html.HTMLEditorKit
import javax.swing.text.html.parser.ParserDelegator
private val minPopupMenuWidth = 175.scaled()
internal class PackageDetailsHeaderPanel(
private val project: Project,
private val operationExecutor: OperationExecutor
) : JPanel() {
private val repoWarningBanner = InfoBannerPanel().apply {
isVisible = false
}
private val nameLabel = HtmlEditorPane().apply {
border = emptyBorder()
font = JBFont.label().asBold().deriveFont(16.scaledFontSize())
}
private val identifierLabel = HtmlEditorPane().apply {
border = emptyBorder()
foreground = PackageSearchUI.getTextColorSecondary()
}
private val primaryActionButton = ColorButton().apply {
addActionListener { onPrimaryActionClicked() }
}
private var primaryOperations: Deferred<List<PackageSearchOperation<*>>>? = null
private val removeMenuAction = MenuAction().apply {
add(object : DumbAwareAction(PackageSearchBundle.message("packagesearch.ui.toolwindow.actions.remove.text")) {
init {
minimumSize = Dimension(minPopupMenuWidth, 0)
}
override fun actionPerformed(e: AnActionEvent) {
onRemoveClicked()
}
})
}
private val overflowButton = run {
val presentation = Presentation()
presentation.icon = AllIcons.Actions.More
presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, true)
ActionButton(removeMenuAction, presentation, "PackageSearchPackageDetailsHeader", ActionToolbar.NAVBAR_MINIMUM_BUTTON_SIZE)
}
private var removeOperations: Deferred<List<PackageSearchOperation<*>>>? = null
private val copyMenuItem = PackageSearchUI.menuItem(
title = PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.menu.copy"),
icon = null,
handler = ::onCopyClicked
).apply {
mnemonic = KeyEvent.VK_C
minimumSize = Dimension(minPopupMenuWidth, 0)
}
private val copyMenu = JBPopupMenu().apply {
minimumSize = Dimension(minPopupMenuWidth, 0)
add(copyMenuItem)
}
private val infoPanel = PackageSearchUI.borderPanel(PackageSearchUI.Colors.panelBackground) {
border = emptyBorder(12.scaled())
layout = HeaderLayout()
add(nameLabel, HeaderLayout.Role.NAME)
add(primaryActionButton, HeaderLayout.Role.PRIMARY_ACTION)
add(overflowButton, HeaderLayout.Role.OVERFLOW_BUTTON)
add(identifierLabel, HeaderLayout.Role.IDENTIFIER)
}
init {
layout = BorderLayout()
border = JBEmptyBorder(0)
add(repoWarningBanner, BorderLayout.NORTH)
add(infoPanel, BorderLayout.CENTER)
UIUtil.enableEagerSoftWrapping(nameLabel)
UIUtil.enableEagerSoftWrapping(identifierLabel)
nameLabel.onRightClick { if (nameLabel.isVisible) copyMenu.showUnderneath(nameLabel) }
identifierLabel.onRightClick { if (identifierLabel.isVisible) copyMenu.showUnderneath(identifierLabel) }
}
internal data class ViewModel(
val uiPackageModel: UiPackageModel<*>,
val knownRepositoriesInTargetModules: KnownRepositories.InTargetModules,
val targetModules: TargetModules,
val onlyStable: Boolean
)
fun display(viewModel: ViewModel) {
val packageModel = viewModel.uiPackageModel.packageModel
val name = packageModel.remoteInfo?.name
val rawIdentifier = viewModel.uiPackageModel.identifier.rawValue
if (name != null && name != rawIdentifier) {
@Suppress("HardCodedStringLiteral") // The name comes from the API
nameLabel.setBody(
listOf(
HtmlChunk.span("font-size: ${16.scaledFontSize()};")
.addRaw("<b>" + packageModel.remoteInfo.name.normalizeWhitespace() + "</b>")
)
)
identifierLabel.setBodyText(rawIdentifier)
identifierLabel.isVisible = true
} else {
nameLabel.setBody(
listOf(
HtmlChunk.span("font-size: ${16.scaledFontSize()};")
.addRaw("<b>$rawIdentifier</b>")
)
)
identifierLabel.text = null
identifierLabel.isVisible = false
}
val packageOperations = viewModel.uiPackageModel.packageOperations
val repoToInstall = packageOperations.repoToAddWhenInstalling
updateRepoWarningBanner(repoToInstall)
updateActions(packageOperations)
overflowButton.componentPopupMenu?.isVisible = false
}
private fun updateRepoWarningBanner(repoToInstall: RepositoryModel?) {
when {
repoToInstall == null -> {
repoWarningBanner.isVisible = false
}
willAutomaticallyAddRepo() -> {
repoWarningBanner.text = PackageSearchBundle.message(
"packagesearch.repository.willBeAddedOnInstall",
repoToInstall.displayName
)
repoWarningBanner.isVisible = true
}
}
}
private fun willAutomaticallyAddRepo() =
PackageSearchGeneralConfiguration.getInstance(project)
.autoAddMissingRepositories
private fun updateActions(packageOperations: PackageOperations) {
overflowButton.isVisible = true
if (packageOperations.primaryOperationType != null) {
primaryOperations = packageOperations.primaryOperations
primaryActionButton.isVisible = true
when (packageOperations.primaryOperationType) {
PackageOperationType.INSTALL -> {
primaryActionButton.text = PackageSearchBundle.message("packagesearch.ui.toolwindow.actions.add.text")
}
PackageOperationType.UPGRADE -> {
primaryActionButton.text = PackageSearchBundle.message("packagesearch.ui.toolwindow.actions.upgrade.text")
}
PackageOperationType.SET -> {
primaryActionButton.text = PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.actions.set")
}
}
} else {
primaryOperations = null
primaryActionButton.isVisible = false
}
removeOperations = packageOperations.removeOperations
}
private fun onPrimaryActionClicked() {
primaryOperations?.let { operationExecutor.executeOperations(it) }
}
private fun onRemoveClicked() {
removeOperations?.let { operationExecutor.executeOperations(it) }
}
private fun onCopyClicked() {
val text = (copyMenu.invoker as? JTextComponent)?.text?.nullIfBlank()
?: return
CopyPasteManager.getInstance()
.setContents(StringSelection(text.stripHtml()))
}
private fun String.stripHtml(): String {
val stringBuilder = StringBuilder()
val parserDelegator = ParserDelegator()
val parserCallback: HTMLEditorKit.ParserCallback = object : HTMLEditorKit.ParserCallback() {
override fun handleText(data: CharArray, pos: Int) {
stringBuilder.append(data)
}
}
parserDelegator.parse(this.reader(), parserCallback, true)
return stringBuilder.toString()
}
}
private class HeaderLayout : AbstractLayoutManager2() {
@ScaledPixels
private val overflowButtonSize = 20.scaled()
@ScaledPixels
private val gapBetweenPrimaryActionAndOverflow = 2.scaled()
@ScaledPixels
private val primaryActionButtonHeight = 26.scaled()
@ScaledPixels
private val gapBetweenNameAndButtons = 4.scaled()
@ScaledPixels
private val vGapBetweenNameAndIdentifier = 4.scaled()
private val componentByRole = mutableMapOf<Role, JComponent>()
private var dirty = true
override fun addLayoutComponent(comp: Component, constraints: Any?) {
if (constraints !is Role) throw UnsupportedOperationException("A Role must be provided for the component")
componentByRole[constraints] = comp as JComponent
}
override fun minimumLayoutSize(parent: Container) = preferredLayoutSize(parent)
override fun preferredLayoutSize(parent: Container): Dimension {
layoutContainer(parent) // Re-layout if needed
val identifierLabel = componentByRole[Role.IDENTIFIER]?.bottom ?: error("Identifier label missing")
return Dimension(
parent.width - parent.insets.horizontal,
identifierLabel + parent.insets.vertical
)
}
override fun maximumLayoutSize(target: Container) =
target.maximumSize ?: Dimension(Int.MAX_VALUE, Int.MAX_VALUE)
@Suppress("ComplexMethod", "LongMethod") // Such is the life of a Swing layout manager...
override fun layoutContainer(parent: Container) {
synchronized(parent.treeLock) {
if (!dirty) return
if (parent.width <= 0) return
val insets = parent.insets
val bounds = Rectangle(insets.left, insets.top, parent.width - insets.horizontal, parent.height - insets.vertical)
val overflowButton = componentByRole[Role.OVERFLOW_BUTTON] ?: error("Overflow button missing")
val overflowButtonWidth = if (overflowButton.isVisible) overflowButtonSize else 0
overflowButton.setBounds(
bounds.right - overflowButtonSize,
bounds.top + primaryActionButtonHeight / 2 - overflowButtonSize / 2,
overflowButtonWidth,
overflowButtonSize
)
val primaryActionButton = componentByRole[Role.PRIMARY_ACTION] ?: error("Primary action button missing")
val primaryActionWidth = if (primaryActionButton.isVisible) primaryActionButton.preferredSize.width else 0
val buttonsGap = if (primaryActionButton.isVisible && overflowButton.isVisible) gapBetweenPrimaryActionAndOverflow else 0
primaryActionButton.setBounds(
overflowButton.left - buttonsGap - primaryActionWidth,
bounds.top,
primaryActionWidth,
primaryActionButtonHeight
)
val nameLabel = componentByRole[Role.NAME] ?: error("Name label missing")
val nameLabelHeight = nameLabel.preferredSize.height.coerceAtLeast(nameLabel.font.size)
val nameLabelButtonGap = if (primaryActionButton.isVisible || overflowButton.isVisible) gapBetweenNameAndButtons else 0
val nameLabelWidth = primaryActionButton.left - bounds.left - nameLabelButtonGap
if (nameLabelHeight >= primaryActionButtonHeight) {
nameLabel.setBounds(bounds.left, bounds.top, nameLabelWidth, nameLabelHeight)
} else {
nameLabel.setBounds(
bounds.left,
primaryActionButton.verticalCenter - nameLabelHeight / 2, // Center vertically on primary action
nameLabelWidth,
nameLabelHeight
)
}
val identifierLabel = componentByRole[Role.IDENTIFIER] ?: error("Identifier label missing")
val identifierLabelHeight = identifierLabel.preferredSize.height.coerceAtLeast(identifierLabel.font.size)
val labelsY = maxOf(nameLabel.bottom + vGapBetweenNameAndIdentifier, primaryActionButton.bottom + vGapBetweenNameAndIdentifier)
if (identifierLabel.isVisible) {
identifierLabel.setBounds(
bounds.left,
labelsY,
bounds.width,
if (identifierLabel.isVisible) identifierLabelHeight else 0
)
} else {
identifierLabel.setBounds(0, nameLabel.bottom, bounds.width, 0)
}
dirty = false
}
}
override fun getLayoutAlignmentX(target: Container) = 0.0F
override fun getLayoutAlignmentY(target: Container) = 0.0F
override fun invalidateLayout(target: Container) {
dirty = true
}
enum class Role {
NAME,
PRIMARY_ACTION,
OVERFLOW_BUTTON,
IDENTIFIER
}
}
| apache-2.0 | 3faf3896d82c1f156b45034bf75a4803 | 40.616162 | 139 | 0.693204 | 5.21519 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-tests/jvmAndNix/test/io/ktor/tests/server/plugins/ContentNegotiationTest.kt | 1 | 25794 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.tests.server.plugins
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.serialization.*
import io.ktor.server.application.*
import io.ktor.server.plugins.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.doublereceive.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.testing.*
import io.ktor.util.reflect.*
import io.ktor.utils.io.*
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
import kotlin.test.*
@Suppress("DEPRECATION")
class ContentNegotiationTest {
private val customContentType = ContentType.parse("application/ktor")
private val customContentConverter = object : ContentConverter {
override suspend fun serializeNullable(
contentType: ContentType,
charset: Charset,
typeInfo: TypeInfo,
value: Any?
): OutgoingContent? {
if (value !is Wrapper) return null
return TextContent("[${value.value}]", contentType.withCharset(charset))
}
override suspend fun deserialize(charset: Charset, typeInfo: TypeInfo, content: ByteReadChannel): Any? {
if (typeInfo.type != Wrapper::class) return null
return Wrapper(content.readRemaining().readText().removeSurrounding("[", "]"))
}
}
private val textContentConverter = object : ContentConverter {
override suspend fun serializeNullable(
contentType: ContentType,
charset: Charset,
typeInfo: TypeInfo,
value: Any?
): OutgoingContent? {
if (value !is Wrapper) return null
return TextContent(value.value, contentType.withCharset(charset))
}
override suspend fun deserialize(charset: Charset, typeInfo: TypeInfo, content: ByteReadChannel): Any? {
if (typeInfo.type != Wrapper::class) return null
return Wrapper(content.readRemaining().readText())
}
}
private fun alwaysFailingConverter(ignoreString: Boolean) = object : ContentConverter {
override suspend fun serializeNullable(
contentType: ContentType,
charset: Charset,
typeInfo: TypeInfo,
value: Any?
): OutgoingContent? {
fail("This converter should be never started for send")
}
override suspend fun deserialize(charset: Charset, typeInfo: TypeInfo, content: ByteReadChannel): Any? {
if (ignoreString && typeInfo.type == String::class) return null
fail("This converter should be never started for receive")
}
}
@Test
fun testEmpty(): Unit = withTestApplication {
application.install(ContentNegotiation) {
}
application.routing {
get("/") {
call.respond("OK")
}
post("/") {
val text = call.receive<String>()
call.respond("OK: $text")
}
}
handleRequest(HttpMethod.Get, "/") { }.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(ContentType.Text.Plain, call.response.contentType().withoutParameters())
assertEquals("OK", call.response.content)
}
handleRequest(HttpMethod.Post, "/") {
setBody("The Text")
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(ContentType.Text.Plain, call.response.contentType().withoutParameters())
assertEquals("OK: The Text", call.response.content)
}
}
data class Wrapper(val value: String)
@Test
fun testTransformWithNotAcceptable(): Unit = withTestApplication {
application.install(ContentNegotiation) {
register(ContentType.Application.Zip, customContentConverter)
}
application.routing {
post("/") {
call.respond(Wrapper("hello"))
}
}
handleRequest(HttpMethod.Post, "/") {
setBody(""" {"value" : "value" }""")
addHeader(HttpHeaders.Accept, "application/xml")
addHeader(HttpHeaders.ContentType, "application/json")
}.let { call ->
assertEquals(HttpStatusCode.NotAcceptable, call.response.status())
}
}
@Test
fun testTransformWithUnsupportedMediaType(): Unit = withTestApplication {
application.install(ContentNegotiation) {
register(ContentType.Application.Xml, customContentConverter)
}
application.routing {
post("/") {
val wrapper = call.receive<Wrapper>()
call.respond(wrapper.value)
}
}
handleRequest(HttpMethod.Post, "/") {
setBody(""" {"value" : "value" }""")
addHeader(HttpHeaders.Accept, "application/xml")
addHeader(HttpHeaders.ContentType, "application/json")
}.let { call ->
assertEquals(HttpStatusCode.UnsupportedMediaType, call.response.status())
}
}
@Test
fun testCustom() {
withTestApplication {
application.install(ContentNegotiation) {
register(customContentType, customContentConverter)
}
application.routing {
get("/") {
call.respond(Wrapper("OK"))
}
post("/") {
val text = call.receive<Wrapper>().value
call.respond(Wrapper("OK: $text"))
}
post("/raw") {
val text = call.receiveText()
call.respond("RAW: $text")
}
}
// Acceptable
handleRequest(HttpMethod.Get, "/") {
addHeader(HttpHeaders.Accept, customContentType.toString())
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(customContentType, call.response.contentType().withoutParameters())
assertEquals("[OK]", call.response.content)
}
// Acceptable with charset
handleRequest(HttpMethod.Get, "/") {
addHeader(HttpHeaders.Accept, customContentType.toString())
addHeader(HttpHeaders.AcceptCharset, Charsets.ISO_8859_1.toString())
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(customContentType, call.response.contentType().withoutParameters())
assertEquals(Charsets.ISO_8859_1, call.response.contentType().charset())
assertEquals("[OK]", call.response.content)
}
// Acceptable with any charset
handleRequest(HttpMethod.Get, "/") {
addHeader(HttpHeaders.Accept, customContentType.toString())
addHeader(HttpHeaders.AcceptCharset, "*, ISO-8859-1;q=0.5")
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(customContentType, call.response.contentType().withoutParameters())
assertEquals(Charsets.UTF_8, call.response.contentType().charset())
assertEquals("[OK]", call.response.content)
}
// Acceptable with multiple charsets and one preferred
handleRequest(HttpMethod.Get, "/") {
addHeader(HttpHeaders.Accept, customContentType.toString())
addHeader(HttpHeaders.AcceptCharset, "ISO-8859-1;q=0.5, UTF-8;q=0.8")
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(customContentType, call.response.contentType().withoutParameters())
assertEquals(Charsets.UTF_8, call.response.contentType().charset())
assertEquals("[OK]", call.response.content)
}
// Missing acceptable charset
handleRequest(HttpMethod.Get, "/") {
addHeader(HttpHeaders.Accept, customContentType.toString())
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(customContentType, call.response.contentType().withoutParameters())
assertEquals(Charsets.UTF_8, call.response.contentType().charset()) // should be default
assertEquals("[OK]", call.response.content)
}
// Unacceptable
handleRequest(HttpMethod.Get, "/") {
addHeader(HttpHeaders.Accept, ContentType.Text.Plain.toString())
}.let { call ->
assertEquals(HttpStatusCode.NotAcceptable, call.response.status())
assertNull(call.response.headers[HttpHeaders.ContentType])
assertNull(call.response.content)
}
// Content-Type pattern
handleRequest(HttpMethod.Get, "/") {
addHeader(HttpHeaders.Accept, ContentType(customContentType.contentType, "*").toString())
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(customContentType, call.response.contentType().withoutParameters())
assertEquals(Charsets.UTF_8, call.response.contentType().charset())
assertEquals("[OK]", call.response.content)
}
// Content-Type twice
handleRequest(HttpMethod.Get, "/") {
addHeader(HttpHeaders.Accept, "$customContentType,$customContentType")
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(customContentType, call.response.contentType().withoutParameters())
assertEquals(Charsets.UTF_8, call.response.contentType().charset())
assertEquals("[OK]", call.response.content)
}
// Post
handleRequest(HttpMethod.Post, "/") {
addHeader(HttpHeaders.ContentType, customContentType.toString())
addHeader(HttpHeaders.Accept, customContentType.toString())
setBody("[The Text]")
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(customContentType, call.response.contentType().withoutParameters())
assertEquals("[OK: The Text]", call.response.content)
}
// Post to raw endpoint with custom content type
handleRequest(HttpMethod.Post, "/raw") {
addHeader(HttpHeaders.ContentType, customContentType.toString())
addHeader(HttpHeaders.Accept, customContentType.toString())
setBody("[The Text]")
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(ContentType.Text.Plain, call.response.contentType().withoutParameters())
assertEquals("RAW: [The Text]", call.response.content)
}
// Post with charset
handleRequest(HttpMethod.Post, "/") {
addHeader(HttpHeaders.ContentType, customContentType.withCharset(Charsets.UTF_8).toString())
addHeader(HttpHeaders.Accept, customContentType.toString())
setBody("[The Text]")
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(customContentType, call.response.contentType().withoutParameters())
assertEquals("[OK: The Text]", call.response.content)
}
}
}
@Test
fun testSubrouteInstall() {
withTestApplication {
application.routing {
application.routing {
route("1") {
install(ContentNegotiation) {
register(customContentType, customContentConverter)
}
get { call.respond(Wrapper("OK")) }
}
get("2") { call.respond(Wrapper("OK")) }
}
}
handleRequest(HttpMethod.Get, "/1") {
addHeader(HttpHeaders.Accept, customContentType.toString())
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(customContentType, call.response.contentType().withoutParameters())
assertEquals("[OK]", call.response.content)
}
handleRequest(HttpMethod.Get, "/2") {
addHeader(HttpHeaders.Accept, customContentType.toString())
}.let { call ->
assertEquals(HttpStatusCode.NotAcceptable, call.response.status())
}
}
}
@Test
fun testMultiple() {
val textContentConverter: ContentConverter = textContentConverter
withTestApplication {
application.install(ContentNegotiation) {
// Order here matters. The first registered content type matching the Accept header will be chosen.
register(customContentType, customContentConverter)
register(ContentType.Text.Plain, textContentConverter)
}
application.routing {
get("/") {
call.respond(Wrapper("OK"))
}
}
// Accept: application/ktor
handleRequest(HttpMethod.Get, "/") {
addHeader(HttpHeaders.Accept, customContentType.toString())
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(customContentType, call.response.contentType().withoutParameters())
assertEquals("[OK]", call.response.content)
}
// Accept: text/plain
handleRequest(HttpMethod.Get, "/") {
addHeader(HttpHeaders.Accept, ContentType.Text.Plain.toString())
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(ContentType.Text.Plain, call.response.contentType().withoutParameters())
assertEquals("OK", call.response.content)
}
// Accept: text/*
handleRequest(HttpMethod.Get, "/") {
addHeader(HttpHeaders.Accept, ContentType.Text.Any.toString())
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(ContentType.Text.Plain, call.response.contentType().withoutParameters())
assertEquals("OK", call.response.content)
}
// Accept: */*
handleRequest(HttpMethod.Get, "/") {
addHeader(HttpHeaders.Accept, ContentType.Any.toString())
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(customContentType, call.response.contentType().withoutParameters())
assertEquals("[OK]", call.response.content)
}
// No Accept header
handleRequest(HttpMethod.Get, "/") {
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals(customContentType, call.response.contentType().withoutParameters())
assertEquals("[OK]", call.response.content)
}
}
}
@Suppress("ReplaceSingleLineLet", "MoveLambdaOutsideParentheses")
@Test
fun testReceiveTransformedByDefault(): Unit = withTestApplication {
application.install(ContentNegotiation) {
// Order here matters. The first registered content type matching the Accept header will be chosen.
register(ContentType.Any, alwaysFailingConverter(true))
ignoreType<String>()
}
application.routing {
post("/byte-channel") {
val count = call.receive<ByteReadChannel>().discard()
call.respondText("bytes: $count")
}
post("/byte-array") {
val array = call.receive<ByteArray>()
call.respondText("array: ${array.size}")
}
post("/string") {
val text = call.receive<String>()
call.respondText("text: $text")
}
post("/parameters") {
val receivedParameters = call.receiveParameters()
call.respondText(receivedParameters.toString())
}
}
handleRequest(HttpMethod.Post, "/byte-channel", { setBody("123") }).let { call ->
assertEquals("bytes: 3", call.response.content)
}
handleRequest(HttpMethod.Post, "/byte-array", { setBody("123") }).let { call ->
assertEquals("array: 3", call.response.content)
}
handleRequest(HttpMethod.Post, "/string", { setBody("123") }).let { call ->
assertEquals("text: 123", call.response.content)
}
handleRequest(HttpMethod.Post, "/parameters") {
setBody("k=v")
addHeader(
HttpHeaders.ContentType,
ContentType.Application.FormUrlEncoded.toString()
)
}.let { call ->
assertEquals("Parameters [k=[v]]", call.response.content)
}
}
@Test
fun testReceiveTextIgnoresContentNegotiation(): Unit = testApplication {
install(ContentNegotiation) {
register(ContentType.Any, alwaysFailingConverter(false))
}
routing {
post("/text") {
val text = call.receiveText()
call.respondText("text: $text")
}
}
client.post("/text") {
setBody("\"k=v\"")
contentType(ContentType.Application.Json)
}.let { response ->
assertEquals("text: \"k=v\"", response.bodyAsText())
}
}
@Test
fun testRespondByteReadChannelIgnoresContentNegotiation(): Unit = testApplication {
install(ContentNegotiation) {
register(ContentType.Any, alwaysFailingConverter(false))
}
routing {
get("/text") {
call.response.header(HttpHeaders.ContentType, ContentType.Application.Json.toString())
call.respond(ByteReadChannel("""{"x": 123}""".toByteArray()))
}
}
client.get("/text").let { response ->
assertEquals("""{"x": 123}""", response.bodyAsText())
}
}
@Test
fun testCustomAcceptedContentTypesContributor(): Unit = withTestApplication {
with(application) {
install(ContentNegotiation) {
register(ContentType.Text.Plain, textContentConverter)
register(ContentType.Text.Html, textContentConverter)
accept { call, acceptedContentTypes ->
call.request.queryParameters["format"]?.let { format ->
when (format) {
"text" -> listOf(ContentTypeWithQuality(ContentType.Text.Plain))
"html" -> listOf(ContentTypeWithQuality(ContentType.Text.Html))
else -> null
}
} ?: acceptedContentTypes
}
}
routing {
get("/") {
call.respond(Wrapper("test content"))
}
}
}
handleRequest(HttpMethod.Get, "/") {
addHeader(HttpHeaders.Accept, "text/plain")
}.let { call ->
assertEquals("test content", call.response.content)
assertEquals(ContentType.Text.Plain, call.response.contentType().withoutParameters())
}
handleRequest(HttpMethod.Get, "/") {
addHeader(HttpHeaders.Accept, "text/html")
}.let { call ->
assertEquals("test content", call.response.content)
assertEquals(ContentType.Text.Html, call.response.contentType().withoutParameters())
}
handleRequest(HttpMethod.Get, "/") {
addHeader(HttpHeaders.Accept, "text/plain, text/html")
}.let { call ->
assertEquals("test content", call.response.content)
assertEquals(ContentType.Text.Plain, call.response.contentType().withoutParameters())
}
handleRequest(HttpMethod.Get, "/") {
addHeader(HttpHeaders.Accept, "text/plain; q=0.9, text/html")
}.let { call ->
assertEquals("test content", call.response.content)
assertEquals(ContentType.Text.Html, call.response.contentType().withoutParameters())
}
handleRequest(HttpMethod.Get, "/?format=html") {
addHeader(HttpHeaders.Accept, "text/plain")
}.let { call ->
assertEquals("test content", call.response.content)
assertEquals(ContentType.Text.Html, call.response.contentType().withoutParameters())
}
handleRequest(HttpMethod.Get, "/?format=text") {
addHeader(HttpHeaders.Accept, "text/html")
}.let { call ->
assertEquals("test content", call.response.content)
assertEquals(ContentType.Text.Plain, call.response.contentType().withoutParameters())
}
}
@Test
fun testDoubleReceive(): Unit = withTestApplication {
with(application) {
install(DoubleReceive)
install(ContentNegotiation) {
register(ContentType.Text.Plain, textContentConverter)
}
}
application.routing {
get("/") {
call.respondText(call.receive<Wrapper>().value + "-" + call.receive<Wrapper>().value)
}
}
handleRequest(HttpMethod.Get, "/?format=text") {
addHeader(HttpHeaders.Accept, "text/plain")
addHeader(HttpHeaders.ContentType, "text/plain")
setBody("[content]")
}.let { call ->
assertEquals("[content]-[content]", call.response.content)
assertEquals(ContentType.Text.Plain, call.response.contentType().withoutParameters())
}
}
@Test
fun testIllegalAcceptAndContentTypes(): Unit = withTestApplication {
with(application) {
install(ContentNegotiation) {
register(ContentType.Text.Plain, textContentConverter)
}
routing {
get("/receive") {
assertFailsWith<BadRequestException> {
call.receive<String>()
}.let { throw it }
}
get("/send") {
assertFailsWith<BadRequestException> {
call.respond(Any())
}.let { throw it }
}
}
}
handleRequest(HttpMethod.Get, "/receive") {
addHeader("Content-Type", "...la..lla..la")
setBody("any")
}.let { call ->
assertEquals(HttpStatusCode.BadRequest, call.response.status())
}
handleRequest(HttpMethod.Get, "/send") {
addHeader("Accept", "....aa..laa...laa")
}.let { call ->
assertEquals(HttpStatusCode.BadRequest, call.response.status())
}
}
@Test
fun testIllegalAcceptAndCheckAcceptHeader(): Unit = withTestApplication {
with(application) {
install(ContentNegotiation) {
checkAcceptHeaderCompliance = true
register(ContentType.Text.Plain, textContentConverter)
}
routing {
get("/send") {
assertFailsWith<BadRequestException> {
call.respond(Any())
}.let { throw it }
}
}
}
handleRequest(HttpMethod.Get, "/send") {
addHeader("Accept", "....aa..laa...laa")
}.let { call ->
assertEquals(HttpStatusCode.BadRequest, call.response.status())
}
}
@Test
fun testMatchingAcceptAndContentTypes(): Unit = withTestApplication {
with(application) {
install(ContentNegotiation) {
checkAcceptHeaderCompliance = true
}
routing {
get("/send") {
call.respond("some text")
}
}
}
handleRequest(HttpMethod.Get, "/send") {
addHeader("Accept", "text/plain")
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
}
handleRequest(HttpMethod.Get, "/send") {
addHeader("Accept", "application/json, text/plain;q=0.1")
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
}
handleRequest(HttpMethod.Get, "/send") {
addHeader("Accept", "*/*")
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
}
handleRequest(HttpMethod.Get, "/send") {
addHeader("Accept", "text/*")
}.let { call ->
assertEquals(HttpStatusCode.OK, call.response.status())
}
}
}
| apache-2.0 | cff2323a361ec2bb99ead354d7b2a454 | 37.963746 | 119 | 0.563697 | 5.349233 | false | true | false | false |
marukami/RxKotlin-Android-Samples | app/src/main/kotlin/au/com/tilbrook/android/rxkotlin/fragments/PseudoCacheMergeFragment.kt | 1 | 4971 | package au.com.tilbrook.android.rxkotlin.fragments
import android.os.Bundle
import android.view.*
import android.widget.ArrayAdapter
import android.widget.ListView
import au.com.tilbrook.android.rxkotlin.R
import au.com.tilbrook.android.rxkotlin.retrofit.Contributor
import au.com.tilbrook.android.rxkotlin.retrofit.GithubService
import au.com.tilbrook.android.rxkotlin.utils.unSubscribeIfNotNull
import org.jetbrains.anko.*
import org.jetbrains.anko.support.v4.ctx
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import timber.log.Timber
import java.util.*
class PseudoCacheMergeFragment : BaseFragment() {
// @Bind(R.id.log_list) internal var _resultList: ListView
private lateinit var _resultList: ListView
private lateinit var _contributionMap: HashMap<String, Long>
private lateinit var _adapter: ArrayAdapter<String>
private var _subscription: Subscription? = null
private val _resultAgeMap = HashMap<Contributor, Long>()
override fun onCreateView(inflater: LayoutInflater?,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
_initializeCache()
val layout = with(ctx) {
verticalLayout {
isBaselineAligned = false
button("Start disk > network call") {
lparams(width = wrapContent, height = wrapContent) {
gravity = Gravity.CENTER
margin = dip(30)
}
onClick(onDemoPseudoCacheClicked)
}
_resultList = listView {
lparams(width = matchParent, height = wrapContent)
}
}
}
return layout
}
override fun onPause() {
super.onPause()
_subscription.unSubscribeIfNotNull()
}
val onDemoPseudoCacheClicked = { v: View? ->
_adapter = ArrayAdapter(
activity,
R.layout.item_log,
R.id.item_log,
ArrayList<String>()
)
_resultList.adapter = _adapter
_initializeCache()
_subscription = Observable
.merge(_getCachedData(), _getFreshData())
.subscribeOn(Schedulers.io())
.unsubscribeOn(AndroidSchedulers.mainThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ contributorAgePair ->
val contributor = contributorAgePair.first
if (_resultAgeMap.containsKey(contributor)
and
((_resultAgeMap[contributor] ?: 0) > contributorAgePair.second)
) {
return@subscribe
}
_contributionMap.put(contributor.login, contributor.contributions)
_resultAgeMap.put(contributor, contributorAgePair.second)
_adapter.clear()
_adapter.addAll(listStringFromMap)
},
{
Timber.e(it, "arr something went wrong")
},
{
Timber.d("done loading all data")
}
)
}
private val listStringFromMap: List<String>
get() {
val list = ArrayList<String>()
for (username in _contributionMap.keys) {
val rowLog = "$username [${_contributionMap[username]}]"
list.add(rowLog)
}
return list
}
private fun _getCachedData(): Observable<Pair<Contributor, Long>> {
val list = ArrayList<Pair<Contributor, Long>>()
var dataWithAgePair: Pair<Contributor, Long>
for (username in _contributionMap.keys) {
val c = Contributor(
login = username,
contributions = _contributionMap[username] ?: 0
)
dataWithAgePair = Pair(c, System.currentTimeMillis())
list.add(dataWithAgePair)
}
return Observable.from(list)
}
private fun _getFreshData(): Observable<Pair<Contributor, Long>> {
val githubToken = resources.getString(R.string.github_oauth_token);
val githubService = GithubService.createGithubService(githubToken)
return githubService.contributors("square", "retrofit")
.flatMap { contributors -> Observable.from(contributors) }
.map { contributor -> Pair(contributor, System.currentTimeMillis()) }
}
private fun _initializeCache() {
_contributionMap = HashMap<String, Long>()
_contributionMap.put("JakeWharton", 0L)
_contributionMap.put("pforhan", 0L)
_contributionMap.put("edenman", 0L)
_contributionMap.put("swankjesse", 0L)
_contributionMap.put("bruceLee", 0L)
}
}
| apache-2.0 | a03b0ea53a911bc69992f064f5ca19cc | 32.362416 | 87 | 0.580768 | 5.006042 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-plugins/ktor-server-velocity/jvm/src/io/ktor/server/velocity/Velocity.kt | 1 | 2151 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.velocity
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.server.application.*
import org.apache.velocity.*
import org.apache.velocity.app.*
import org.apache.velocity.context.*
import java.io.*
/**
* A response content handled by the [io.ktor.server.velocity.Velocity] plugin.
*
* @param template name to be resolved by Velocity
* @param model to be passed during template rendering
* @param etag value for the `E-Tag` header (optional)
* @param contentType of response (optional, `text/html` with the UTF-8 character encoding by default)
*/
public class VelocityContent(
public val template: String,
public val model: Map<String, Any>,
public val etag: String? = null,
public val contentType: ContentType = ContentType.Text.Html.withCharset(Charsets.UTF_8)
)
internal fun velocityOutgoingContent(
template: Template,
model: Context,
etag: String?,
contentType: ContentType
): OutgoingContent {
val writer = StringWriter()
template.merge(model, writer)
val result = TextContent(text = writer.toString(), contentType)
if (etag != null) {
result.versions += EntityTagVersion(etag)
}
return result
}
/**
* A plugin that allows you to use Velocity templates as views within your application.
* Provides the ability to respond with [VelocityContent].
* You can learn more from [Velocity](https://ktor.io/docs/velocity.html).
*/
public val Velocity: ApplicationPlugin<VelocityEngine> = createApplicationPlugin("Velocity", ::VelocityEngine) {
pluginConfig.init()
fun process(content: VelocityContent): OutgoingContent {
return velocityOutgoingContent(
pluginConfig.getTemplate(content.template),
VelocityContext(content.model),
content.etag,
content.contentType
)
}
onCallRespond { _, value ->
if (value is VelocityContent) {
transformBody {
process(value)
}
}
}
}
| apache-2.0 | 92b40598efb28618f00b1204174257b7 | 29.295775 | 119 | 0.690841 | 4.259406 | false | false | false | false |
mdanielwork/intellij-community | plugins/git4idea/src/git4idea/repo/GitConfigHelper.kt | 12 | 1708 | /*
* 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 git4idea.repo
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import org.ini4j.Ini
import java.io.File
import java.io.IOException
private val LOG: Logger get() = logger(::LOG)
@Throws(IOException::class)
internal fun loadIniFile(file: File): Ini {
val ini = Ini()
ini.config.isMultiOption = true // duplicate keys (e.g. url in [remote])
ini.config.isTree = false // don't need tree structure: it corrupts url in section name (e.g. [url "http://github.com/"]
ini.config.isLowerCaseOption = true
try {
ini.load(file)
return ini
}
catch (e: IOException) {
LOG.warn("Couldn't load config file at ${file.path}", e)
throw e
}
}
internal fun findClassLoader(): ClassLoader? {
val javaClass = ::findClassLoader.javaClass
val plugin = PluginManager.getPlugin(PluginManagerCore.getPluginByClassName(javaClass.name))
return plugin?.pluginClassLoader ?: javaClass.classLoader // null e.g. if IDEA is started from IDEA
}
| apache-2.0 | df9c326fa4a607b4eb3b2ed45793526b | 34.583333 | 129 | 0.739461 | 3.829596 | false | true | false | false |
JetBrains/spek | spek-runtime/src/nativeMain/kotlin/org/spekframework/spek2/runtime/util/Base64.kt | 1 | 3632 | package org.spekframework.spek2.runtime.util
private val BASE64_ALPHABET: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
private val BASE64_MASK: Byte = 0x3f
private val BASE64_INVERSE_MASK: Int = 0b1111_1111
private val BASE64_PAD: Char = '='
private val BASE64_PAD_BYTE: Byte = BASE64_PAD.toByte()
private val BASE64_INVERSE_ALPHABET = IntArray(256) {
BASE64_ALPHABET.indexOf(it.toChar())
}
private fun Int.toBase64(): Char = BASE64_ALPHABET[this]
actual object Base64 {
actual fun encodeToString(text: String): String {
val encoded = encode(text.toByteArray())
return buildString(encoded.size) {
encoded.forEach { append(it.toChar()) }
}
}
actual fun decodeToString(encodedText: String): String {
val decoded = decode(encodedText.toByteArray())
return buildString(decoded.size) {
decoded.forEach { append(it.toChar()) }
}
}
private fun encode(src: ByteArray): ByteArray {
fun ByteArray.getOrZero(index: Int): Int = if (index >= size) 0 else get(index).toInt()
// 4n / 3 is expected Base64 payload
val result = ArrayList<Byte>(4 * src.size / 3)
var index = 0
while (index < src.size) {
val symbolsLeft = src.size - index
val padSize = if (symbolsLeft >= 3) 0 else (3 - symbolsLeft) * 8 / 6
val chunk = (src.getOrZero(index) shl 16) or (src.getOrZero(index + 1) shl 8) or src.getOrZero(index + 2)
index += 3
for (i in 3 downTo padSize) {
val char = (chunk shr (6 * i)) and BASE64_MASK.toInt()
result.add(char.toBase64().toByte())
}
// Fill the pad with '='
repeat(padSize) { result.add(BASE64_PAD_BYTE) }
}
return result.toByteArray()
}
fun decode(src: ByteArray): ByteArray {
if (src.size % 4 != 0) {
throw IllegalArgumentException("Invalid Base64 encoded data.")
}
if (src.size == 0) {
return ByteArray(0)
}
val last = src.last()
val secondLast = src.dropLast(1).last()
val paddingSize = if (secondLast == BASE64_PAD_BYTE && last == BASE64_PAD_BYTE) {
2
} else if (last == BASE64_PAD_BYTE) {
1
} else {
0
}
val size = (3 * src.size / 4) - paddingSize
val result = ArrayList<Byte>(size)
var index = 0
while (index < src.size) {
val isLastChunk = index == src.size - 4
val first = decodeByte(src.get(index))
val second = decodeByte(src.get(index + 1))
val third = if (isLastChunk && paddingSize == 2) 0 else decodeByte(src.get(index + 2))
val fourth = if (isLastChunk && paddingSize >= 1) 0 else decodeByte(src.get(index + 3))
val chunk = (first shl 18) or (second shl 12) or (third shl 6) or fourth
val paddingChars = if (isLastChunk) paddingSize else 0
for (i in 2 downTo paddingChars) {
val char = (chunk shr (8 * i)) and BASE64_INVERSE_MASK
result.add(char.toByte())
}
index += 4
}
return result.toByteArray()
}
private fun decodeByte(byte: Byte): Int {
val inverse = BASE64_INVERSE_ALPHABET[byte.toInt()]
if (inverse == -1) {
throw IllegalArgumentException("Invalid Base64 encoded data.")
}
return inverse
}
}
private fun String.toByteArray() = ByteArray(length) {
get(it).toByte()
} | bsd-3-clause | dfb71fa9a01abcc3b15c18453e0cceb0 | 30.868421 | 117 | 0.574339 | 4.040044 | false | false | false | false |
JonathanxD/CodeAPI | src/main/kotlin/com/github/jonathanxd/kores/base/comment/Code.kt | 1 | 2813 | /*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.jonathanxd.kores.base.comment
import com.github.jonathanxd.kores.KoresPart
/**
* Code comment
*
* @property code Code Node
*/
data class Code(val code: CodeNode) : Comment {
override fun builder(): Builder = Builder(this)
/**
* Node of the code.
*/
interface CodeNode {
/**
* Plain code
*
* @param plain Code string,
*/
data class Plain(val plain: String) : CodeNode
/**
* Kores code representation (let generator generate the code).
*
* @param representation Code representation.
*/
data class CodeRepresentation(val representation: KoresPart) : CodeNode
}
class Builder() : com.github.jonathanxd.kores.builder.Builder<Code, Builder> {
lateinit var code: CodeNode
constructor(defaults: Code) : this() {
this.code = defaults.code
}
/**
* See [Code.code]
*/
fun code(value: CodeNode): Builder {
this.code = value
return this
}
override fun build(): Code = Code(this.code)
companion object {
@JvmStatic
fun builder(): Builder = Builder()
@JvmStatic
fun builder(defaults: Code): Builder = Builder(defaults)
}
}
}
| mit | 9b41a5a12a2040b9a9fb7a3065ded674 | 30.606742 | 118 | 0.632065 | 4.573984 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/devkit/intellij.devkit.workspaceModel/src/WorkspaceImplAbsentInspection.kt | 7 | 2081 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.devkit.workspaceModel
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.LocalQuickFixOnPsiElement
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.workspaceModel.codegen.SKIPPED_TYPES
import org.jetbrains.kotlin.idea.stubindex.KotlinClassShortNameIndex
import org.jetbrains.kotlin.psi.*
class WorkspaceImplAbsentInspection: LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitClass(klass: KtClass) {
if (!klass.isWorkspaceEntity()) return
if (klass.name in SKIPPED_TYPES) return
if (klass.isAbstractEntity()) return
if (klass.name == "Builder") return
val foundImplClasses = KotlinClassShortNameIndex.get("${klass.name}Impl", klass.project, GlobalSearchScope.allScope(klass.project))
if (!foundImplClasses.isEmpty()) return
holder.registerProblem(klass.nameIdentifier!!, DevKitWorkspaceModelBundle.message("inspection.workspace.absent.model.display.name"),
GenerateWorkspaceModelFix(klass.nameIdentifier!!))
}
}
}
private class GenerateWorkspaceModelFix(psiElement: PsiElement) : LocalQuickFixOnPsiElement(psiElement) {
override fun getText() = DevKitWorkspaceModelBundle.message("inspection.workspace.msg.generate.implementation")
override fun getFamilyName() = name
override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) {
val projectFileIndex = ProjectRootManager.getInstance(project).fileIndex
val module = projectFileIndex.getModuleForFile(file.virtualFile)
WorkspaceModelGenerator.generate(project, module!!)
}
} | apache-2.0 | 362440745d23651c901cb08a6abcbf85 | 48.571429 | 138 | 0.790966 | 4.93128 | false | false | false | false |
DreierF/MyTargets | shared/src/test/java/de/dreier/mytargets/shared/models/ScoreTest.kt | 1 | 3406 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.shared.models
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.*
class ScoreTest {
@Test
@Throws(Exception::class)
fun zeroShots() {
val s = Score(10)
assertEquals(0, s.reachedPoints)
assertEquals(10, s.totalPoints)
assertEquals(0, s.shotCount)
}
@Test
@Throws(Exception::class)
fun singleShot() {
val s = Score(9, 10)
assertEquals(9, s.reachedPoints)
assertEquals(10, s.totalPoints)
assertEquals(1, s.shotCount)
}
@Test
@Throws(Exception::class)
fun add() {
val s = Score(9, 10)
s.add(Score(8, 10))
assertEquals(17, s.reachedPoints)
assertEquals(20, s.totalPoints)
assertEquals(2, s.shotCount)
}
@Test
@Throws(Exception::class)
fun string() {
val s = Score(7, 10)
assertEquals("7/10", s.toString())
}
@Test
@Throws(Exception::class)
fun format() {
val s = Score(9, 10)
val config = Score.Configuration()
config.showAverage = true
config.showPercentage = true
config.showReachedScore = true
config.showTotalScore = true
assertEquals("9/10 (90%, 9.00∅)", s.format(Locale.US, config))
config.showPercentage = false
assertEquals("9/10 (9,00∅)", s.format(Locale.GERMAN, config))
config.showTotalScore = false
assertEquals("9 (9,00∅)", s.format(Locale.GERMAN, config))
config.showReachedScore = false
config.showTotalScore = true
assertEquals("", s.format(Locale.GERMAN, config))
config.showReachedScore = true
config.showAverage = false
assertEquals("9/10", s.format(Locale.GERMAN, config))
config.showReachedScore = false
config.showTotalScore = false
assertEquals("", s.format(Locale.GERMAN, config))
}
@Test
@Throws(Exception::class)
fun getShotAverage() {
val score = Score(9, 10)
assertEquals(9.0f, score.shotAverage)
score.add(Score(6, 10))
assertEquals(7.5f, score.shotAverage)
assertEquals(-1.0f, Score(10).shotAverage)
}
@Test
@Throws(Exception::class)
fun getShotAverageFormatted() {
val score = Score(9, 11)
assertEquals("9,00", score.getShotAverageFormatted(Locale.GERMAN))
score.add(Score(6, 11))
assertEquals("7.50", score.getShotAverageFormatted(Locale.US))
assertEquals("-", Score(11).getShotAverageFormatted(Locale.US))
}
@Test
@Throws(Exception::class)
fun getPercent() {
val score = Score(9, 10)
assertEquals(0.9f, score.percent)
score.add(Score(6, 10))
assertEquals(0.75f, score.percent)
assertEquals(0f, Score(0).percent)
assertEquals(0f, Score(0, 10).percent)
}
}
| gpl-2.0 | 6a05cef3b7f4a7b2c691ce792145ceea | 28.565217 | 74 | 0.629118 | 3.828829 | false | true | false | false |
securityfirst/Umbrella_android | app/src/main/java/org/secfirst/umbrella/feature/segment/view/adapter/HostSegmentAdapter.kt | 1 | 2399 | package org.secfirst.umbrella.feature.segment.view.adapter
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.Router
import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.support.RouterPagerAdapter
import org.secfirst.umbrella.feature.checklist.view.controller.ChecklistController
import org.secfirst.umbrella.feature.segment.view.controller.SegmentController
import org.secfirst.umbrella.feature.segment.view.controller.SegmentDetailController
import org.secfirst.umbrella.misc.AppExecutors.Companion.uiContext
import org.secfirst.umbrella.misc.launchSilent
class HostSegmentAdapter(host: Controller,
private val controllers: List<Controller>,
private val segmentPageLimit: Int) : RouterPagerAdapter(host) {
override fun configureRouter(router: Router, position: Int) {
if (!router.hasRootController()) {
when (position) {
0 -> {
val segmentController = controllers[position] as SegmentController
launchSilent(uiContext) { router.setRoot(RouterTransaction.with(segmentController)) }
}
in 1..segmentPageLimit -> {
val detailController = controllers[position] as SegmentDetailController
launchSilent(uiContext) { router.setRoot(RouterTransaction.with(detailController)) }
}
else -> {
val checklistController = controllers[position] as ChecklistController
launchSilent(uiContext) { router.setRoot(RouterTransaction.with(checklistController)) }
}
}
}
}
override fun getPageTitle(position: Int): String {
return when (position) {
0 -> {
val currentController = controllers[position] as SegmentController
currentController.getTitle()
}
in 1..segmentPageLimit -> {
val currentController = controllers[position] as SegmentDetailController
currentController.getTitle()
}
else -> {
val currentController = controllers[position] as ChecklistController
currentController.getTitle()
}
}
}
override fun getCount() = controllers.size
} | gpl-3.0 | b42ff1471fbaa08e409dc5cf9ee27818 | 41.105263 | 107 | 0.648187 | 5.57907 | false | false | false | false |
phylame/jem | jem-formats/src/main/kotlin/jem/format/pmab/Supports.kt | 1 | 1424 | /*
* Copyright 2015-2017 Peng Wan <[email protected]>
*
* This file is part of Jem.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jem.format.pmab
import jem.epm.*
internal object PMAB {
/////** MIME type for PMAB **\\\\\
const val MIME_PATH = "mimetype"
const val MIME_PMAB = "application/pmab+zip"
/////** PBM(PMAB Book Metadata) **\\\\\
const val PBM_PATH = "book.xml"
const val PBM_XMLNS = "http://phylame.pw/format/pmab/pbm"
/////** PBC(PMAB Book Contents) **\\\\\
const val PBC_PATH = "content.xml"
const val PBC_XMLNS = "http://phylame.pw/format/pmab/pbc"
}
class PmabFactory : EpmFactory, FileParser {
override val keys = setOf(PMAB_NAME, "pem")
override val name = "PMAB for Jem"
override val hasMaker = true
override val maker: Maker = PmabMaker
override val hasParser = true
override val parser: Parser = PmabParser
}
| apache-2.0 | 8052af911ee3543056e2d7654d0330fa | 28.061224 | 75 | 0.678371 | 3.516049 | false | false | false | false |
TheMrMilchmann/lwjgl3 | modules/lwjgl/tinyexr/src/templates/kotlin/tinyexr/templates/tinyexr.kt | 1 | 13913 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package tinyexr.templates
import org.lwjgl.generator.*
import tinyexr.*
val tinyexr = "TinyEXR".nativeClass(Module.TINYEXR, prefix = "TINYEXR", prefixMethod = "") {
nativeDirective("""DISABLE_WARNINGS()
#include "tinyexr.h"
ENABLE_WARNINGS()""")
documentation =
"""
Native bindings to the ${url("https://github.com/syoyo/tinyexr", "Tiny OpenEXR")} image library.
tinyexr is a small, single header-only library to load and save OpenEXR(.exr) images.
"""
IntConstant(
"Error codes.",
"SUCCESS".."0",
"ERROR_INVALID_MAGIC_NUMBER".."-1",
"ERROR_INVALID_EXR_VERSION".."-2",
"ERROR_INVALID_ARGUMENT".."-3",
"ERROR_INVALID_DATA".."-4",
"ERROR_INVALID_FILE".."-5",
"ERROR_INVALID_PARAMETER".."-6",
"ERROR_CANT_OPEN_FILE".."-7",
"ERROR_UNSUPPORTED_FORMAT".."-8",
"ERROR_INVALID_HEADER".."-9",
"ERROR_UNSUPPORTED_FEATURE".."-10",
"ERROR_CANT_WRITE_FILE".."-11",
"ERROR_SERIALZATION_FAILED".."-12",
"ERROR_LAYER_NOT_FOUND".."-13"
)
IntConstant(
"Pixel types.",
"PIXELTYPE_UINT".."0",
"PIXELTYPE_HALF".."1",
"PIXELTYPE_FLOAT".."2"
)
IntConstant(
"",
"MAX_HEADER_ATTRIBUTES".."1024",
"MAX_CUSTOM_ATTRIBUTES".."128"
)
IntConstant(
"Compression types.",
"COMPRESSIONTYPE_NONE".."0",
"COMPRESSIONTYPE_RLE".."1",
"COMPRESSIONTYPE_ZIPS".."2",
"COMPRESSIONTYPE_ZIP".."3",
"COMPRESSIONTYPE_PIZ".."4",
"COMPRESSIONTYPE_ZFP".."128"
)
IntConstant(
"ZFP compression types.",
"ZFP_COMPRESSIONTYPE_RATE".."0",
"ZFP_COMPRESSIONTYPE_PRECISION".."1",
"ZFP_COMPRESSIONTYPE_ACCURACY".."2"
)
IntConstant(
"Tile level types.",
"TILE_ONE_LEVEL".."0",
"TILE_MIPMAP_LEVELS".."1",
"TILE_RIPMAP_LEVELS".."2"
)
IntConstant(
"Tile rounding types.",
"TILE_ROUND_DOWN".."0",
"TILE_ROUND_UP".."1"
)
int(
"LoadEXRWithLayer",
"""
Loads single-frame OpenEXR image by specifying layer name.
Assume EXR image contains A(single channel alpha) or RGB(A) channels. Application must free image data as returned by {@code out_rgba}. Result image
format is: float x RGBA x width x height.
""",
Check(1)..float.p.p("out_rgba", ""),
Check(1)..int.p("width", ""),
Check(1)..int.p("height", ""),
charUTF8.const.p("filename", ""),
charUTF8.const.p("layer_name", ""),
Check(1)..charASCII.const.p.p("err", ""),
returnDoc =
"""
negative value and may set error string in {@code err} when there's an error. When the specified layer name is not found in the EXR file, the function
will return #ERROR_LAYER_NOT_FOUND.
"""
)
int(
"EXRLayers",
"Get layer infos from EXR file.",
charUTF8.const.p("filename", ""),
Check(1)..charUTF8.const.p.p.p("layer_names", "list of layer names. Application must free memory after using this."),
Check(1)..int.p("num_layers", "the number of layers"),
Check(1)..charASCII.const.p.p("err", "Error string(will be filled when the function returns error code). Free it using FreeEXRErrorMessage after using this value."),
returnDoc = "#SUCCESS upon success."
)
int(
"EXRNumLevels",
"Returns the number of resolution levels of the image (including the base).",
EXRImage.const.p("exr_image", "")
)
void(
"InitEXRHeader",
"Initialize ##EXRHeader struct.",
EXRHeader.p("exr_header", "")
)
void(
"EXRSetNameAttr",
"Sets name attribute of ##EXRHeader struct (it makes a copy).",
EXRHeader.p("exr_header", ""),
charUTF8.const.p("name", "")
)
void(
"InitEXRImage",
"Initialize ##EXRImage struct.",
EXRImage.p("exr_image", "")
)
int(
"FreeEXRHeader",
"Frees internal data of ##EXRHeader struct",
EXRHeader.p("exr_header", "")
)
int(
"FreeEXRImage",
"Frees internal data of ##EXRImage struct",
EXRImage.p("exr_image", "")
)
void(
"FreeEXRErrorMessage",
"Frees error message",
Unsafe..char.const.p("msg", "")
)
int(
"ParseEXRVersionFromFile",
"Parse EXR version header of a file.",
EXRVersion.p("version", ""),
charUTF8.const.p("filename", "")
)
int(
"ParseEXRVersionFromMemory",
"Parse EXR version header from memory-mapped EXR data.",
EXRVersion.p("version", ""),
unsigned_char.const.p("memory", ""),
AutoSize("memory")..size_t("size", "")
)
int(
"ParseEXRHeaderFromFile",
"""
Parse single-part OpenEXR header from a file and initialize ##EXRHeader.
When there was an error message, Application must free {@code err} with #FreeEXRErrorMessage().
""",
EXRHeader.p("header", ""),
EXRVersion.const.p("version", ""),
charUTF8.const.p("filename", ""),
Check(1)..charASCII.const.p.p("err", "")
)
int(
"ParseEXRHeaderFromMemory",
"""
Parse single-part OpenEXR header from a memory and initialize ##EXRHeader.
When there was an error message, Application must free {@code err} with #FreeEXRErrorMessage().
""",
EXRHeader.p("header", ""),
EXRVersion.const.p("version", ""),
unsigned_char.const.p("memory", ""),
AutoSize("memory")..size_t("size", ""),
Check(1)..charASCII.const.p.p("err", "")
)
int(
"ParseEXRMultipartHeaderFromFile",
"""
Parse multi-part OpenEXR headers from a file and initialize ##EXRHeader* array.
When there was an error message, Application must free {@code err} with #FreeEXRErrorMessage().
""",
Check(1)..EXRHeader.p.p.p("headers", ""),
Check(1)..int.p("num_headers", ""),
EXRVersion.const.p("version", ""),
charUTF8.const.p("filename", ""),
Check(1)..charASCII.const.p.p("err", "")
)
int(
"ParseEXRMultipartHeaderFromMemory",
"""
Parse multi-part OpenEXR headers from a memory and initialize ##EXRHeader* array.
When there was an error message, Application must free {@code err} with #FreeEXRErrorMessage().
""",
Check(1)..EXRHeader.p.p.p("headers", ""),
Check(1)..int.p("num_headers", ""),
EXRVersion.const.p("version", ""),
unsigned_char.const.p("memory", ""),
AutoSize("memory")..size_t("size", ""),
Check(1)..charASCII.const.p.p("err", "")
)
int(
"LoadEXRImageFromFile",
"""
Loads single-part OpenEXR image from a file.
Application must setup #ParseEXRHeaderFromFile() before calling this function.
Application can free EXRImage using #FreeEXRImage(). When there was an error message, Application must free {@code err} with #FreeEXRErrorMessage().
""",
EXRImage.p("image", ""),
EXRHeader.const.p("header", ""),
charUTF8.const.p("filename", ""),
Check(1)..charASCII.const.p.p("err", ""),
returnDoc = "negative value and may set error string in {@code err} when there's an error"
)
int(
"LoadEXRImageFromMemory",
"""
Loads single-part OpenEXR image from a memory.
Application must setup ##EXRHeader with #ParseEXRHeaderFromMemory() before calling this function.
Application can free EXRImage using #FreeEXRImage(). When there was an error message, Application must free {@code err} with #FreeEXRErrorMessage().
""",
EXRImage.p("image", ""),
EXRHeader.const.p("header", ""),
unsigned_char.const.p("memory", ""),
AutoSize("memory")..size_t("size", ""),
Check(1)..charASCII.const.p.p("err", ""),
returnDoc = "negative value and may set error string in {@code err} when there's an error"
)
int(
"LoadEXRMultipartImageFromFile",
"""
Loads multi-part OpenEXR image from a file.
Application must setup #ParseEXRMultipartHeaderFromFile() before calling this function.
Application can free EXRImage using #FreeEXRImage(). When there was an error message, Application must free {@code err} with #FreeEXRErrorMessage().
""",
EXRImage.p("images", ""),
EXRHeader.const.p.p("headers", ""),
AutoSize("images", "headers")..unsigned_int("num_parts", ""),
charUTF8.const.p("filename", ""),
Check(1)..charASCII.const.p.p("err", ""),
returnDoc = "negative value and may set error string in {@code err} when there's an error"
)
int(
"LoadEXRMultipartImageFromMemory",
"""
Loads multi-part OpenEXR image from a memory.
Application must setup ##EXRHeader* array with #ParseEXRMultipartHeaderFromMemory() before calling this function.
Application can free EXRImage using #FreeEXRImage(). When there was an error message, Application must free {@code err} with #FreeEXRErrorMessage().
""",
EXRImage.p("images", ""),
EXRHeader.const.p.p("headers", ""),
AutoSize("images", "headers")..unsigned_int("num_parts", ""),
unsigned_char.const.p("memory", ""),
AutoSize("memory")..size_t("size", ""),
Check(1)..charASCII.const.p.p("err", ""),
returnDoc = "negative value and may set error string in {@code err} when there's an error"
)
int(
"SaveEXRImageToFile",
"""
Saves multi-channel, single-frame OpenEXR image to a file.
When there was an error message, Application must free {@code err} with #FreeEXRErrorMessage().
""",
EXRImage.const.p("image", ""),
EXRHeader.const.p("exr_header", ""),
charUTF8.const.p("filename", ""),
Check(1)..charASCII.const.p.p("err", ""),
returnDoc = "negative value and may set error string in {@code err} when there's an error"
)
size_t(
"SaveEXRImageToMemory",
"""
Saves multi-channel, single-frame OpenEXR image to a memory.
Image is compressed using {@code EXRImage.compression} value.
When there was an error message, Application must free {@code err} with #FreeEXRErrorMessage().
""",
EXRImage.const.p("image", ""),
EXRHeader.const.p("exr_header", ""),
Check(1)..unsigned_char.p.p("memory", ""),
Check(1)..charASCII.const.p.p("err", ""),
returnDoc = "the number of bytes if success or zero and may set error string in {@code err} when there's an error"
)
int(
"SaveEXRMultipartImageToFile",
"""
Saves multi-channel, multi-frame OpenEXR image to a file.
Image is compressed using {@code EXRImage.compression} value. File global attributes (eg. {@code display_window}) must be set in the first header.
""",
EXRImage.const.p("images", ""),
EXRHeader.const.p.p("exr_headers", ""),
AutoSize("images", "exr_headers")..unsigned_int("num_parts", ""),
charUTF8.const.p("filename", ""),
Check(1)..charASCII.const.p.p("err", ""),
returnDoc =
"""
negative value and may set error string in {@code err} when there's an error.
When there was an error message, Application must free {@code err} with #FreeEXRErrorMessage().
"""
)
size_t(
"SaveEXRMultipartImageToMemory",
"""
Saves multi-channel, multi-frame OpenEXR image to a memory.
Image is compressed using {@code EXRImage.compression} value. File global attributes (eg. {@code display_window}) must be set in the first header.
""",
EXRImage.const.p("images", ""),
EXRHeader.const.p.p("exr_headers", ""),
AutoSize("images", "exr_headers")..unsigned_int("num_parts", ""),
Check(1)..unsigned_char.p.p("memory", ""),
Check(1)..charASCII.const.p.p("err", ""),
returnDoc =
"""
the number of bytes if success. Return zero and will set error string in {@code err} when there's an error.
When there was an error message, Application must free {@code err} with #FreeEXRErrorMessage().
"""
)
int(
"LoadDeepEXR",
"""
Loads single-frame OpenEXR deep image.
Application must free memory of variables in {@code DeepImage(image, offset_table)}.
When there was an error message, Application must free {@code err} with #FreeEXRErrorMessage().
""",
DeepImage.p("out_image", ""),
charUTF8.const.p("filename", ""),
Check(1)..charASCII.const.p.p("err", ""),
returnDoc = "negative value and may set error string in {@code err} when there's an error"
)
/*int(
"SaveDeepEXR",
"Saves single-frame OpenEXR deep image.",
const..DeepImage_p("in_image", ""),
const..charUTF8_p("filename", ""),
Check(1)..const..charASCII_pp("err", ""),
returnDoc = "negative value and may set error string in {@code err} when there's an error"
)
int(
"LoadMultiPartDeepEXR",
"""
Loads multi-part OpenEXR deep image.
Application must free memory of variables in {@code DeepImage(image, offset_table)}.
""",
DeepImage_p.p("out_image", ""),
AutoSize("out_image")..int("num_parts", ""),
const..charUTF8_p("filename", ""),
Check(1)..const..charASCII_pp("err", "")
)*/
} | bsd-3-clause | 9c180c532622add80b120bb4413b894d | 29.988864 | 173 | 0.578667 | 3.949191 | false | false | false | false |
flesire/ontrack | ontrack-repository-impl/src/main/java/net/nemerosa/ontrack/repository/ProjectLabelJdbcRepository.kt | 1 | 3434 | package net.nemerosa.ontrack.repository
import net.nemerosa.ontrack.model.labels.ProjectLabelForm
import net.nemerosa.ontrack.repository.support.AbstractJdbcRepository
import org.springframework.stereotype.Repository
import javax.sql.DataSource
@Repository
class ProjectLabelJdbcRepository(
private val labelRepository: LabelRepository,
dataSource: DataSource
) : AbstractJdbcRepository(dataSource), ProjectLabelRepository {
override fun getLabelsForProject(project: Int): List<LabelRecord> =
namedParameterJdbcTemplate.queryForList(
"""
SELECT PL.LABEL_ID
FROM PROJECT_LABEL PL
INNER JOIN LABEL L ON L.ID = PL.label_id
WHERE PROJECT_ID = :project
ORDER BY L.category, L.name
""",
params("project", project),
Int::class.java
).map { labelRepository.getLabel(it) }
override fun getProjectsForLabel(label: Int): List<Int> =
namedParameterJdbcTemplate.queryForList(
"""
SELECT PL.project_id
FROM PROJECT_LABEL PL
INNER JOIN PROJECTS p on PL.project_id = p.id
WHERE label_id = :label
ORDER BY p.name
""",
params("label", label),
Integer::class.java
).map { it.toInt() }
override fun associateProjectToLabel(project: Int, label: Int) {
val params = params("project", project).addValue("label", label)
val existing = namedParameterJdbcTemplate.queryForList(
"""
SELECT *
FROM PROJECT_LABEL
WHERE PROJECT_ID = :project
AND LABEL_ID = :label
""",
params
)
if (existing.isEmpty()) {
namedParameterJdbcTemplate.update(
"""
INSERT INTO project_label(PROJECT_ID, LABEL_ID)
VALUES (:project, :label)
""",
params
)
}
}
override fun unassociateProjectToLabel(project: Int, label: Int) {
namedParameterJdbcTemplate.update(
"""
DELETE FROM PROJECT_LABEL
WHERE PROJECT_ID = :project
AND LABEL_ID = :label
""",
params("project", project).addValue("label", label)
)
}
override fun associateProjectToLabels(project: Int, form: ProjectLabelForm) {
// Existing labels
val existingLabels = getLabelsForProject(project).map { it.id }
// For any new label, saves it
form.labels.minus(existingLabels).forEach { label ->
namedParameterJdbcTemplate.update(
"""
INSERT INTO project_label(PROJECT_ID, LABEL_ID)
VALUES (:project, :label)
""",
params("project", project).addValue("label", label)
)
}
// Deletes any leftover
existingLabels.minus(form.labels).forEach { label ->
unassociateProjectToLabel(project, label)
}
}
}
| mit | ed4d79dddb1161205aa6c254b0da2a80 | 36.326087 | 81 | 0.515434 | 5.468153 | false | false | false | false |
google/intellij-community | plugins/kotlin/base/psi/src/org/jetbrains/kotlin/idea/base/psi/KotlinPsiHeuristics.kt | 2 | 9756 | // 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.base.psi
import com.google.common.collect.HashMultimap
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.JvmNames
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.annotations.JVM_STATIC_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.resolve.jvm.annotations.JVM_OVERLOADS_FQ_NAME
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
object KotlinPsiHeuristics {
@JvmStatic
fun unwrapImportAlias(file: KtFile, aliasName: String): Collection<String> {
return file.aliasImportMap[aliasName]
}
@JvmStatic
fun unwrapImportAlias(type: KtUserType, aliasName: String): Collection<String> {
val file = type.containingKotlinFileStub?.psi as? KtFile ?: return emptyList()
return unwrapImportAlias(file, aliasName)
}
@JvmStatic
fun getImportAliases(file: KtFile, names: Set<String>): Set<String> {
val result = LinkedHashSet<String>()
for ((aliasName, name) in file.aliasImportMap.entries()) {
if (name in names) {
result += aliasName
}
}
return result
}
private val KtFile.aliasImportMap by userDataCached("ALIAS_IMPORT_MAP_KEY") { file ->
HashMultimap.create<String, String>().apply {
for (import in file.importList?.imports.orEmpty()) {
val aliasName = import.aliasName ?: continue
val name = import.importPath?.fqName?.shortName()?.asString() ?: continue
put(aliasName, name)
}
}
}
@JvmStatic
fun isProbablyNothing(typeReference: KtTypeReference): Boolean {
val userType = typeReference.typeElement as? KtUserType ?: return false
return isProbablyNothing(userType)
}
@JvmStatic
fun isProbablyNothing(type: KtUserType): Boolean {
val referencedName = type.referencedName
if (referencedName == "Nothing") {
return true
}
// TODO: why don't use PSI-less stub for calculating aliases?
val file = type.containingKotlinFileStub?.psi as? KtFile ?: return false
// TODO: support type aliases
return file.aliasImportMap[referencedName].contains("Nothing")
}
@JvmStatic
fun getJvmName(fqName: FqName): String {
val asString = fqName.asString()
var startIndex = 0
while (startIndex != -1) { // always true
val dotIndex = asString.indexOf('.', startIndex)
if (dotIndex == -1) return asString
startIndex = dotIndex + 1
val charAfterDot = asString.getOrNull(startIndex) ?: return asString
if (!charAfterDot.isLetter()) return asString
if (charAfterDot.isUpperCase()) return buildString {
append(asString.subSequence(0, startIndex))
append(asString.substring(startIndex).replace('.', '$'))
}
}
return asString
}
@JvmStatic
fun getPackageName(file: KtFile): FqName? {
val entry = JvmFileClassUtil.findAnnotationEntryOnFileNoResolve(file, JvmNames.JVM_PACKAGE_NAME_SHORT) ?: return null
val customPackageName = JvmFileClassUtil.getLiteralStringFromAnnotation(entry)
if (customPackageName != null) {
return FqName(customPackageName)
}
return file.packageFqName
}
@JvmStatic
fun getJvmName(declaration: KtClassOrObject): String? {
val classId = declaration.classIdIfNonLocal ?: return null
val jvmClassName = JvmClassName.byClassId(classId)
return jvmClassName.fqNameForTopLevelClassMaybeWithDollars.asString()
}
private fun checkAnnotationUseSiteTarget(annotationEntry: KtAnnotationEntry, useSiteTarget: AnnotationUseSiteTarget?): Boolean {
return useSiteTarget == null || annotationEntry.useSiteTarget?.getAnnotationUseSiteTarget() == useSiteTarget
}
@JvmStatic
fun findAnnotation(declaration: KtAnnotated, shortName: String, useSiteTarget: AnnotationUseSiteTarget? = null): KtAnnotationEntry? {
return declaration.annotationEntries
.firstOrNull { checkAnnotationUseSiteTarget(it, useSiteTarget) && it.shortName?.asString() == shortName }
}
@JvmStatic
fun findAnnotation(declaration: KtAnnotated, fqName: FqName, useSiteTarget: AnnotationUseSiteTarget? = null): KtAnnotationEntry? {
val targetShortName = fqName.shortName().asString()
val targetAliasName = declaration.containingKtFile.findAliasByFqName(fqName)?.name
for (annotationEntry in declaration.annotationEntries) {
if (!checkAnnotationUseSiteTarget(annotationEntry, useSiteTarget)) {
continue
}
val annotationShortName = annotationEntry.shortName?.asString() ?: continue
if (annotationShortName == targetShortName || annotationShortName == targetAliasName) {
return annotationEntry
}
}
return null
}
@JvmStatic
fun hasAnnotation(declaration: KtAnnotated, shortName: String, useSiteTarget: AnnotationUseSiteTarget? = null): Boolean {
return findAnnotation(declaration, shortName, useSiteTarget) != null
}
@JvmStatic
fun hasAnnotation(declaration: KtAnnotated, shortName: Name, useSiteTarget: AnnotationUseSiteTarget? = null): Boolean {
return findAnnotation(declaration, shortName.asString(), useSiteTarget) != null
}
@JvmStatic
fun hasAnnotation(declaration: KtAnnotated, fqName: FqName, useSiteTarget: AnnotationUseSiteTarget? = null): Boolean {
return findAnnotation(declaration, fqName, useSiteTarget) != null
}
@JvmStatic
fun findJvmName(declaration: KtAnnotated, useSiteTarget: AnnotationUseSiteTarget? = null): String? {
val annotation = findAnnotation(declaration, JvmFileClassUtil.JVM_NAME, useSiteTarget) ?: return null
return JvmFileClassUtil.getLiteralStringFromAnnotation(annotation)
}
@JvmStatic
fun findJvmGetterName(declaration: KtValVarKeywordOwner): String? {
return when (declaration) {
is KtProperty -> declaration.getter?.let(::findJvmName) ?: findJvmName(declaration, AnnotationUseSiteTarget.PROPERTY_GETTER)
is KtParameter -> findJvmName(declaration, AnnotationUseSiteTarget.PROPERTY_GETTER)
else -> null
}
}
@JvmStatic
fun findJvmSetterName(declaration: KtValVarKeywordOwner): String? {
return when (declaration) {
is KtProperty -> declaration.setter?.let(::findJvmName) ?: findJvmName(declaration, AnnotationUseSiteTarget.PROPERTY_SETTER)
is KtParameter -> findJvmName(declaration, AnnotationUseSiteTarget.PROPERTY_SETTER)
else -> null
}
}
@JvmStatic
fun findSuppressAnnotation(declaration: KtAnnotated): KtAnnotationEntry? {
return findAnnotation(declaration, StandardNames.FqNames.suppress)
}
@JvmStatic
fun hasSuppressAnnotation(declaration: KtAnnotated): Boolean {
return findSuppressAnnotation(declaration) != null
}
@JvmStatic
fun hasNonSuppressAnnotations(declaration: KtAnnotated): Boolean {
val annotationEntries = declaration.annotationEntries
return annotationEntries.size > 1 || annotationEntries.size == 1 && !hasSuppressAnnotation(declaration)
}
@JvmStatic
fun hasJvmFieldAnnotation(declaration: KtAnnotated): Boolean {
return hasAnnotation(declaration, JvmAbi.JVM_FIELD_ANNOTATION_FQ_NAME)
}
@JvmStatic
fun hasJvmOverloadsAnnotation(declaration: KtAnnotated): Boolean {
return hasAnnotation(declaration, JVM_OVERLOADS_FQ_NAME)
}
@JvmStatic
fun hasJvmStaticAnnotation(declaration: KtAnnotated): Boolean {
return hasAnnotation(declaration, JVM_STATIC_ANNOTATION_FQ_NAME)
}
private val PUBLISHED_API_FQN = FqName("kotlin.PublishedApi")
@JvmStatic
fun hasPublishedApiAnnotation(declaration: KtAnnotated): Boolean {
return hasAnnotation(declaration, PUBLISHED_API_FQN)
}
@JvmStatic
fun getStringValue(argument: ValueArgument): String? {
return argument.getArgumentExpression()
?.safeAs<KtStringTemplateExpression>()
?.entries
?.singleOrNull()
?.safeAs<KtLiteralStringTemplateEntry>()
?.text
}
@JvmStatic
fun findSuppressedEntities(declaration: KtAnnotated): List<String>? {
val entry = findSuppressAnnotation(declaration) ?: return null
return entry.valueArguments.mapNotNull(::getStringValue)
}
@JvmStatic
fun isPossibleOperator(declaration: KtNamedFunction): Boolean {
if (declaration.hasModifier(KtTokens.OPERATOR_KEYWORD)) {
return true
} else if (!declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) {
// Operator modifier could be omitted only for overridden function
return false
}
val name = declaration.name ?: return false
if (!OperatorConventions.isConventionName(Name.identifier(name))) {
return false
}
return true
}
} | apache-2.0 | d55bfb250e18a9a648c1a594c1b4e0ff | 38.028 | 137 | 0.691369 | 5.37817 | false | false | false | false |
RuneSuite/client | plugins-dev/src/main/java/org/runestar/client/plugins/dev/ItemContainersDebug.kt | 1 | 985 | package org.runestar.client.plugins.dev
import org.runestar.client.api.plugins.DisposablePlugin
import org.runestar.client.api.Fonts
import org.runestar.client.api.game.live.ItemContainers
import org.runestar.client.api.game.live.Canvas
import org.runestar.client.api.plugins.PluginSettings
import java.awt.Color
class ItemContainersDebug : DisposablePlugin<PluginSettings>() {
override val defaultSettings = PluginSettings()
override fun onStart() {
add(Canvas.repaints.subscribe { g ->
val x = 5
var y = 40
g.font = Fonts.PLAIN_12
g.color = Color.WHITE
val strings = ArrayList<String>()
ItemContainers.forEach { k, v ->
val vs = v.map { it?.let { "(${it.id}x${it.quantity})" } }
strings.add("$k:$vs")
}
strings.forEach { s ->
g.drawString(s, x, y)
y += g.font.size + 5
}
})
}
} | mit | 1d37b3f01c68089eea16193fd3c39448 | 28.878788 | 74 | 0.588832 | 4.087137 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ConvertCollectionFix.kt | 1 | 4096 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
class ConvertCollectionFix(element: KtExpression, val type: CollectionType) : KotlinQuickFixAction<KtExpression>(element) {
override fun getFamilyName(): String = KotlinBundle.message("convert.to.0", type.displayName)
override fun getText() = KotlinBundle.message("convert.expression.to.0.by.inserting.1", type.displayName, type.functionCall)
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val expression = element ?: return
val psiFactory = KtPsiFactory(project)
val replaced = expression.replaced(psiFactory.createExpressionByPattern("$0.$1", expression, type.functionCall))
editor?.caretModel?.moveToOffset(replaced.endOffset)
}
enum class CollectionType(
val functionCall: String,
val fqName: FqName,
val literalFunctionName: String? = null,
val emptyCollectionFunction: String? = null,
private val nameOverride: String? = null
) {
List("toList()", FqName("kotlin.collections.List"), "listOf", "emptyList"),
Collection("toList()", FqName("kotlin.collections.Collection"), "listOf", "emptyList"),
Iterable("toList()", FqName("kotlin.collections.Iterable"), "listOf", "emptyList"),
MutableList("toMutableList()", FqName("kotlin.collections.MutableList")),
Array("toTypedArray()", FqName("kotlin.Array"), "arrayOf", "emptyArray"),
Sequence("asSequence()", FqName("kotlin.sequences.Sequence"), "sequenceOf", "emptySequence"),
Set("toSet()", FqName("kotlin.collections.Set"), "setOf", "emptySet"),
//specialized types must be last because iteration order is relevant for getCollectionType
ArrayViaList("toList().toTypedArray()", FqName("kotlin.Array"), nameOverride = "Array"),
;
val displayName get() = nameOverride ?: name
fun specializeFor(sourceType: CollectionType) = when {
this == Array && sourceType == Sequence -> ArrayViaList
this == Array && sourceType == Iterable -> ArrayViaList
else -> this
}
}
companion object {
private val TYPES = CollectionType.values()
fun getConversionTypeOrNull(expressionType: KotlinType, expectedType: KotlinType): CollectionType? {
val expressionCollectionType = expressionType.getCollectionType() ?: return null
val expectedCollectionType = expectedType.getCollectionType() ?: return null
if (expressionCollectionType == expectedCollectionType) return null
val expressionTypeArg = expressionType.arguments.singleOrNull()?.type ?: return null
val expectedTypeArg = expectedType.arguments.singleOrNull()?.type ?: return null
if (!expressionTypeArg.isSubtypeOf(expectedTypeArg)) return null
return expectedCollectionType.specializeFor(expressionCollectionType)
}
fun KotlinType.getCollectionType(acceptNullableTypes: Boolean = false): CollectionType? {
if (isMarkedNullable && !acceptNullableTypes) return null
return TYPES.firstOrNull { KotlinBuiltIns.isConstructedFromGivenClass(this, it.fqName) }
}
}
}
| apache-2.0 | 284f5ac852f25f1b1d1c3db5d50b8ff4 | 50.2 | 158 | 0.720215 | 4.964848 | false | false | false | false |
JetBrains/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/orders.kt | 1 | 8155 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import kotlin.jvm.JvmName
import kotlin.jvm.JvmOverloads
import kotlin.jvm.JvmStatic
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
/**
* This entity stores order of facets in iml file. This is needed to ensure that facet tags are saved in the same order to avoid
* unnecessary modifications of iml file.
*/
interface FacetsOrderEntity : WorkspaceEntity {
val orderOfFacets: List<String>
val moduleEntity: ModuleEntity
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : FacetsOrderEntity, WorkspaceEntity.Builder<FacetsOrderEntity>, ObjBuilder<FacetsOrderEntity> {
override var entitySource: EntitySource
override var orderOfFacets: MutableList<String>
override var moduleEntity: ModuleEntity
}
companion object : Type<FacetsOrderEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(orderOfFacets: List<String>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): FacetsOrderEntity {
val builder = builder()
builder.orderOfFacets = orderOfFacets.toMutableWorkspaceList()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: FacetsOrderEntity, modification: FacetsOrderEntity.Builder.() -> Unit) = modifyEntity(
FacetsOrderEntity.Builder::class.java, entity, modification)
//endregion
val ModuleEntity.facetOrder: @Child FacetsOrderEntity?
by WorkspaceEntity.extension()
/**
* This property indicates that external-system-id attribute should be stored in facet configuration to avoid unnecessary modifications
*/
interface FacetExternalSystemIdEntity : WorkspaceEntity {
val externalSystemId: String
val facet: FacetEntity
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : FacetExternalSystemIdEntity, WorkspaceEntity.Builder<FacetExternalSystemIdEntity>, ObjBuilder<FacetExternalSystemIdEntity> {
override var entitySource: EntitySource
override var externalSystemId: String
override var facet: FacetEntity
}
companion object : Type<FacetExternalSystemIdEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(externalSystemId: String,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): FacetExternalSystemIdEntity {
val builder = builder()
builder.externalSystemId = externalSystemId
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: FacetExternalSystemIdEntity,
modification: FacetExternalSystemIdEntity.Builder.() -> Unit) = modifyEntity(
FacetExternalSystemIdEntity.Builder::class.java, entity, modification)
//endregion
val FacetEntity.facetExternalSystemIdEntity: @Child FacetExternalSystemIdEntity?
by WorkspaceEntity.extension()
/**
* This property indicates that external-system-id attribute should be stored in artifact configuration file to avoid unnecessary modifications
*/
interface ArtifactExternalSystemIdEntity : WorkspaceEntity {
val externalSystemId: String
val artifactEntity: ArtifactEntity
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ArtifactExternalSystemIdEntity, WorkspaceEntity.Builder<ArtifactExternalSystemIdEntity>, ObjBuilder<ArtifactExternalSystemIdEntity> {
override var entitySource: EntitySource
override var externalSystemId: String
override var artifactEntity: ArtifactEntity
}
companion object : Type<ArtifactExternalSystemIdEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(externalSystemId: String,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): ArtifactExternalSystemIdEntity {
val builder = builder()
builder.externalSystemId = externalSystemId
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ArtifactExternalSystemIdEntity,
modification: ArtifactExternalSystemIdEntity.Builder.() -> Unit) = modifyEntity(
ArtifactExternalSystemIdEntity.Builder::class.java, entity, modification)
//endregion
val ArtifactEntity.artifactExternalSystemIdEntity: @Child ArtifactExternalSystemIdEntity?
by WorkspaceEntity.extension()
/**
* This property indicates that external-system-id attribute should be stored in library configuration file to avoid unnecessary modifications
*/
interface LibraryExternalSystemIdEntity: WorkspaceEntity {
val externalSystemId: String
val library: LibraryEntity
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : LibraryExternalSystemIdEntity, WorkspaceEntity.Builder<LibraryExternalSystemIdEntity>, ObjBuilder<LibraryExternalSystemIdEntity> {
override var entitySource: EntitySource
override var externalSystemId: String
override var library: LibraryEntity
}
companion object : Type<LibraryExternalSystemIdEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(externalSystemId: String,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): LibraryExternalSystemIdEntity {
val builder = builder()
builder.externalSystemId = externalSystemId
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: LibraryExternalSystemIdEntity,
modification: LibraryExternalSystemIdEntity.Builder.() -> Unit) = modifyEntity(
LibraryExternalSystemIdEntity.Builder::class.java, entity, modification)
//endregion
val LibraryEntity.externalSystemId: @Child LibraryExternalSystemIdEntity?
by WorkspaceEntity.extension()
/**
* This entity stores order of artifacts in ipr file. This is needed to ensure that artifact tags are saved in the same order to avoid
* unnecessary modifications of ipr file.
*/
interface ArtifactsOrderEntity : WorkspaceEntity {
val orderOfArtifacts: List<String>
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ArtifactsOrderEntity, WorkspaceEntity.Builder<ArtifactsOrderEntity>, ObjBuilder<ArtifactsOrderEntity> {
override var entitySource: EntitySource
override var orderOfArtifacts: MutableList<String>
}
companion object : Type<ArtifactsOrderEntity, Builder>() {
@JvmOverloads
@JvmStatic
@JvmName("create")
operator fun invoke(orderOfArtifacts: List<String>,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): ArtifactsOrderEntity {
val builder = builder()
builder.orderOfArtifacts = orderOfArtifacts.toMutableWorkspaceList()
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ArtifactsOrderEntity, modification: ArtifactsOrderEntity.Builder.() -> Unit) = modifyEntity(
ArtifactsOrderEntity.Builder::class.java, entity, modification)
//endregion
| apache-2.0 | bd5f591e6b00e91883b058a113a5f87a | 36.408257 | 155 | 0.751318 | 5.647507 | false | false | false | false |
square/okio | okio/src/commonMain/kotlin/okio/internal/-RealBufferedSource.kt | 1 | 11494 | /*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// TODO move to RealBufferedSource class: https://youtrack.jetbrains.com/issue/KT-20427
@file:Suppress("NOTHING_TO_INLINE")
package okio.internal
import okio.Buffer
import okio.BufferedSource
import okio.ByteString
import okio.EOFException
import okio.Options
import okio.PeekSource
import okio.RealBufferedSource
import okio.Segment
import okio.Sink
import okio.buffer
import okio.checkOffsetAndCount
internal inline fun RealBufferedSource.commonRead(sink: Buffer, byteCount: Long): Long {
require(byteCount >= 0L) { "byteCount < 0: $byteCount" }
check(!closed) { "closed" }
if (buffer.size == 0L) {
val read = source.read(buffer, Segment.SIZE.toLong())
if (read == -1L) return -1L
}
val toRead = minOf(byteCount, buffer.size)
return buffer.read(sink, toRead)
}
internal inline fun RealBufferedSource.commonExhausted(): Boolean {
check(!closed) { "closed" }
return buffer.exhausted() && source.read(buffer, Segment.SIZE.toLong()) == -1L
}
internal inline fun RealBufferedSource.commonRequire(byteCount: Long) {
if (!request(byteCount)) throw EOFException()
}
internal inline fun RealBufferedSource.commonRequest(byteCount: Long): Boolean {
require(byteCount >= 0L) { "byteCount < 0: $byteCount" }
check(!closed) { "closed" }
while (buffer.size < byteCount) {
if (source.read(buffer, Segment.SIZE.toLong()) == -1L) return false
}
return true
}
internal inline fun RealBufferedSource.commonReadByte(): Byte {
require(1)
return buffer.readByte()
}
internal inline fun RealBufferedSource.commonReadByteString(): ByteString {
buffer.writeAll(source)
return buffer.readByteString()
}
internal inline fun RealBufferedSource.commonReadByteString(byteCount: Long): ByteString {
require(byteCount)
return buffer.readByteString(byteCount)
}
internal inline fun RealBufferedSource.commonSelect(options: Options): Int {
check(!closed) { "closed" }
while (true) {
val index = buffer.selectPrefix(options, selectTruncated = true)
when (index) {
-1 -> {
return -1
}
-2 -> {
// We need to grow the buffer. Do that, then try it all again.
if (source.read(buffer, Segment.SIZE.toLong()) == -1L) return -1
}
else -> {
// We matched a full byte string: consume it and return it.
val selectedSize = options.byteStrings[index].size
buffer.skip(selectedSize.toLong())
return index
}
}
}
}
internal inline fun RealBufferedSource.commonReadByteArray(): ByteArray {
buffer.writeAll(source)
return buffer.readByteArray()
}
internal inline fun RealBufferedSource.commonReadByteArray(byteCount: Long): ByteArray {
require(byteCount)
return buffer.readByteArray(byteCount)
}
internal inline fun RealBufferedSource.commonReadFully(sink: ByteArray) {
try {
require(sink.size.toLong())
} catch (e: EOFException) {
// The underlying source is exhausted. Copy the bytes we got before rethrowing.
var offset = 0
while (buffer.size > 0L) {
val read = buffer.read(sink, offset, buffer.size.toInt())
if (read == -1) throw AssertionError()
offset += read
}
throw e
}
buffer.readFully(sink)
}
internal inline fun RealBufferedSource.commonRead(sink: ByteArray, offset: Int, byteCount: Int): Int {
checkOffsetAndCount(sink.size.toLong(), offset.toLong(), byteCount.toLong())
if (buffer.size == 0L) {
val read = source.read(buffer, Segment.SIZE.toLong())
if (read == -1L) return -1
}
val toRead = okio.minOf(byteCount, buffer.size).toInt()
return buffer.read(sink, offset, toRead)
}
internal inline fun RealBufferedSource.commonReadFully(sink: Buffer, byteCount: Long) {
try {
require(byteCount)
} catch (e: EOFException) {
// The underlying source is exhausted. Copy the bytes we got before rethrowing.
sink.writeAll(buffer)
throw e
}
buffer.readFully(sink, byteCount)
}
internal inline fun RealBufferedSource.commonReadAll(sink: Sink): Long {
var totalBytesWritten: Long = 0
while (source.read(buffer, Segment.SIZE.toLong()) != -1L) {
val emitByteCount = buffer.completeSegmentByteCount()
if (emitByteCount > 0L) {
totalBytesWritten += emitByteCount
sink.write(buffer, emitByteCount)
}
}
if (buffer.size > 0L) {
totalBytesWritten += buffer.size
sink.write(buffer, buffer.size)
}
return totalBytesWritten
}
internal inline fun RealBufferedSource.commonReadUtf8(): String {
buffer.writeAll(source)
return buffer.readUtf8()
}
internal inline fun RealBufferedSource.commonReadUtf8(byteCount: Long): String {
require(byteCount)
return buffer.readUtf8(byteCount)
}
internal inline fun RealBufferedSource.commonReadUtf8Line(): String? {
val newline = indexOf('\n'.code.toByte())
return if (newline == -1L) {
if (buffer.size != 0L) {
readUtf8(buffer.size)
} else {
null
}
} else {
buffer.readUtf8Line(newline)
}
}
internal inline fun RealBufferedSource.commonReadUtf8LineStrict(limit: Long): String {
require(limit >= 0) { "limit < 0: $limit" }
val scanLength = if (limit == Long.MAX_VALUE) Long.MAX_VALUE else limit + 1
val newline = indexOf('\n'.code.toByte(), 0, scanLength)
if (newline != -1L) return buffer.readUtf8Line(newline)
if (scanLength < Long.MAX_VALUE &&
request(scanLength) && buffer[scanLength - 1] == '\r'.code.toByte() &&
request(scanLength + 1) && buffer[scanLength] == '\n'.code.toByte()
) {
return buffer.readUtf8Line(scanLength) // The line was 'limit' UTF-8 bytes followed by \r\n.
}
val data = Buffer()
buffer.copyTo(data, 0, okio.minOf(32, buffer.size))
throw EOFException(
"\\n not found: limit=" + minOf(buffer.size, limit) +
" content=" + data.readByteString().hex() + '…'.toString()
)
}
internal inline fun RealBufferedSource.commonReadUtf8CodePoint(): Int {
require(1)
val b0 = buffer[0].toInt()
when {
b0 and 0xe0 == 0xc0 -> require(2)
b0 and 0xf0 == 0xe0 -> require(3)
b0 and 0xf8 == 0xf0 -> require(4)
}
return buffer.readUtf8CodePoint()
}
internal inline fun RealBufferedSource.commonReadShort(): Short {
require(2)
return buffer.readShort()
}
internal inline fun RealBufferedSource.commonReadShortLe(): Short {
require(2)
return buffer.readShortLe()
}
internal inline fun RealBufferedSource.commonReadInt(): Int {
require(4)
return buffer.readInt()
}
internal inline fun RealBufferedSource.commonReadIntLe(): Int {
require(4)
return buffer.readIntLe()
}
internal inline fun RealBufferedSource.commonReadLong(): Long {
require(8)
return buffer.readLong()
}
internal inline fun RealBufferedSource.commonReadLongLe(): Long {
require(8)
return buffer.readLongLe()
}
internal inline fun RealBufferedSource.commonReadDecimalLong(): Long {
require(1)
var pos = 0L
while (request(pos + 1)) {
val b = buffer[pos]
if ((b < '0'.code.toByte() || b > '9'.code.toByte()) && (pos != 0L || b != '-'.code.toByte())) {
// Non-digit, or non-leading negative sign.
if (pos == 0L) {
throw NumberFormatException("Expected a digit or '-' but was 0x${b.toString(16)}")
}
break
}
pos++
}
return buffer.readDecimalLong()
}
internal inline fun RealBufferedSource.commonReadHexadecimalUnsignedLong(): Long {
require(1)
var pos = 0
while (request((pos + 1).toLong())) {
val b = buffer[pos.toLong()]
if ((b < '0'.code.toByte() || b > '9'.code.toByte()) &&
(b < 'a'.code.toByte() || b > 'f'.code.toByte()) &&
(b < 'A'.code.toByte() || b > 'F'.code.toByte())
) {
// Non-digit, or non-leading negative sign.
if (pos == 0) {
throw NumberFormatException("Expected leading [0-9a-fA-F] character but was 0x${b.toString(16)}")
}
break
}
pos++
}
return buffer.readHexadecimalUnsignedLong()
}
internal inline fun RealBufferedSource.commonSkip(byteCount: Long) {
var byteCount = byteCount
check(!closed) { "closed" }
while (byteCount > 0) {
if (buffer.size == 0L && source.read(buffer, Segment.SIZE.toLong()) == -1L) {
throw EOFException()
}
val toSkip = minOf(byteCount, buffer.size)
buffer.skip(toSkip)
byteCount -= toSkip
}
}
internal inline fun RealBufferedSource.commonIndexOf(b: Byte, fromIndex: Long, toIndex: Long): Long {
var fromIndex = fromIndex
check(!closed) { "closed" }
require(fromIndex in 0L..toIndex) { "fromIndex=$fromIndex toIndex=$toIndex" }
while (fromIndex < toIndex) {
val result = buffer.indexOf(b, fromIndex, toIndex)
if (result != -1L) return result
// The byte wasn't in the buffer. Give up if we've already reached our target size or if the
// underlying stream is exhausted.
val lastBufferSize = buffer.size
if (lastBufferSize >= toIndex || source.read(buffer, Segment.SIZE.toLong()) == -1L) return -1L
// Continue the search from where we left off.
fromIndex = maxOf(fromIndex, lastBufferSize)
}
return -1L
}
internal inline fun RealBufferedSource.commonIndexOf(bytes: ByteString, fromIndex: Long): Long {
var fromIndex = fromIndex
check(!closed) { "closed" }
while (true) {
val result = buffer.indexOf(bytes, fromIndex)
if (result != -1L) return result
val lastBufferSize = buffer.size
if (source.read(buffer, Segment.SIZE.toLong()) == -1L) return -1L
// Keep searching, picking up from where we left off.
fromIndex = maxOf(fromIndex, lastBufferSize - bytes.size + 1)
}
}
internal inline fun RealBufferedSource.commonIndexOfElement(targetBytes: ByteString, fromIndex: Long): Long {
var fromIndex = fromIndex
check(!closed) { "closed" }
while (true) {
val result = buffer.indexOfElement(targetBytes, fromIndex)
if (result != -1L) return result
val lastBufferSize = buffer.size
if (source.read(buffer, Segment.SIZE.toLong()) == -1L) return -1L
// Keep searching, picking up from where we left off.
fromIndex = maxOf(fromIndex, lastBufferSize)
}
}
internal inline fun RealBufferedSource.commonRangeEquals(
offset: Long,
bytes: ByteString,
bytesOffset: Int,
byteCount: Int
): Boolean {
check(!closed) { "closed" }
if (offset < 0L ||
bytesOffset < 0 ||
byteCount < 0 ||
bytes.size - bytesOffset < byteCount
) {
return false
}
for (i in 0 until byteCount) {
val bufferOffset = offset + i
if (!request(bufferOffset + 1)) return false
if (buffer[bufferOffset] != bytes[bytesOffset + i]) return false
}
return true
}
internal inline fun RealBufferedSource.commonPeek(): BufferedSource {
return PeekSource(this).buffer()
}
internal inline fun RealBufferedSource.commonClose() {
if (closed) return
closed = true
source.close()
buffer.clear()
}
internal inline fun RealBufferedSource.commonTimeout() = source.timeout()
internal inline fun RealBufferedSource.commonToString() = "buffer($source)"
| apache-2.0 | a38d5a1052f591cd5bc71d0dae0fd871 | 27.874372 | 109 | 0.687783 | 3.80782 | false | false | false | false |
stefanosiano/PowerfulImageView | powerfulimageview_rs/src/main/java/com/stefanosiano/powerful_libraries/imageview/progress/drawers/CircularIndeterminateProgressDrawer.kt | 2 | 7447 | package com.stefanosiano.powerful_libraries.imageview.progress.drawers
import android.animation.Animator
import android.animation.ValueAnimator
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.LinearInterpolator
import com.stefanosiano.powerful_libraries.imageview.progress.ProgressOptions
/** Default animation duration. */
private const val DEFAULT_ANIMATION_DURATION: Long = 800
@Suppress("MagicNumber")
/** ProgressDrawer that shows an indeterminate animated circle as progress indicator. */
internal class CircularIndeterminateProgressDrawer : ProgressDrawer {
/** Paint used to draw the arcs. */
private var mProgressPaint: Paint = Paint()
/** Animator that rotates the whole circle. */
private var mOffsetAnimator: ValueAnimator = ValueAnimator.ofFloat(0f, 1f)
/** Animator that transforms the angles used to draw the progress. */
private var mProgressAnimator: ValueAnimator = ValueAnimator.ofFloat(0f, 1f)
/** Start angle of the arc. */
private var mProgressStartAngle: Int = 0
/** Sweep angle of the arc. */
private var mProgressSweepAngle: Int = 0
/** Whether the progress is shrinking or expanding. Used to adjust behaviour during animation. */
private var isShrinking: Boolean = false
/** Custom animation duration. If it's less then 0, default duration is used. */
private var mProgressAnimationDuration: Long = -1
/** offset of the start angle. It will change linearly continuously. */
private var mOffset: Int = 0
/** Last start angle offset. Used when calling setup(), so it doesn't change angle. */
private var mLastStartAngleOffset: Int = 0
/** Last sweep angle offset. Used when calling setup(), so it doesn't change angle. */
private var mLastSweepAngleOffset: Int = 0
/** Whether to reverse the progress. */
private var mIsProgressReversed: Boolean = false
/** Listener to handle things from the drawer. */
private var listener: ProgressDrawerManager.ProgressDrawerListener? = null
init {
this.mProgressStartAngle = -90
this.mProgressSweepAngle = 180
this.mLastStartAngleOffset = 0
this.mLastSweepAngleOffset = 0
mOffsetAnimator.duration = 3000
mOffsetAnimator.interpolator = LinearInterpolator()
mOffsetAnimator.repeatCount = ValueAnimator.INFINITE
// Using animation.getAnimatedFraction() because animation.getAnimatedValue() leaks memory
mOffsetAnimator.addUpdateListener { mOffset = (360 * it.animatedFraction).toInt() }
mProgressAnimator.duration =
if (mProgressAnimationDuration < 0) DEFAULT_ANIMATION_DURATION else mProgressAnimationDuration
mProgressAnimator.interpolator = AccelerateDecelerateInterpolator()
mProgressAnimator.repeatCount = ValueAnimator.INFINITE
mProgressAnimator.addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator) {}
override fun onAnimationEnd(animation: Animator) {}
override fun onAnimationCancel(animation: Animator) {}
override fun onAnimationRepeat(animation: Animator) { isShrinking = !isShrinking }
})
// Using animation.getAnimatedFraction() because animation.getAnimatedValue() leaks memory
mProgressAnimator.addUpdateListener {
setProgressAngle((360 * it.animatedFraction).toInt(), (290 * it.animatedFraction).toInt())
}
}
override fun setup(progressOptions: ProgressOptions) {
mProgressPaint.color = progressOptions.indeterminateColor
mProgressPaint.strokeWidth = progressOptions.calculatedBorderWidth.toFloat()
mProgressPaint.isAntiAlias = true
mProgressPaint.style = Paint.Style.STROKE
mProgressAnimationDuration = if (progressOptions.animationDuration.toLong() < 0) {
DEFAULT_ANIMATION_DURATION
} else progressOptions.animationDuration.toLong()
if (mProgressAnimator.duration != mProgressAnimationDuration) {
mProgressAnimator.duration = mProgressAnimationDuration
if (mProgressAnimator.isRunning) {
mProgressAnimator.cancel()
mProgressAnimator.start()
}
}
mIsProgressReversed = progressOptions.isProgressReversed
setProgressAngle(mLastStartAngleOffset, mLastSweepAngleOffset)
}
override fun startIndeterminateAnimation() {
mOffsetAnimator.cancel()
mProgressAnimator.cancel()
this.mOffset = 0
this.isShrinking = false
this.mLastStartAngleOffset = 0
this.mLastSweepAngleOffset = 0
setProgressAngle(mLastStartAngleOffset, mLastSweepAngleOffset)
mProgressAnimator.start()
mOffsetAnimator.start()
}
/**
* Set the [startAngleOffset], used when progress is shrinking (summing), and [sweepAngleOffset], used when
* progress is shrinking (subtracting) or expanding (summing), of the angles of the arcs that will be drawn.
*/
private fun setProgressAngle(startAngleOffset: Int, sweepAngleOffset: Int) {
mLastStartAngleOffset = startAngleOffset
mLastSweepAngleOffset = sweepAngleOffset
// mProgressSweepAngle when isShrinking and at the end of animation must be equal to itself when !isShrinking
// and at the beginning of the animation
if (isShrinking) {
// When sweepAngleOffset = 1 * 290 => 50. when sweepAngleOffset = 0 * 290 => 340
this.mProgressStartAngle = -90 + startAngleOffset + mOffset
this.mProgressSweepAngle = 340 - sweepAngleOffset
} else {
// When sweepAngleOffset = 0 * 290 => 50. when sweepAngleOffset = 1 * 290 => 340
this.mProgressStartAngle = -90 + mOffset
this.mProgressSweepAngle = sweepAngleOffset + 50
}
listener?.onRequestInvalidate()
}
override fun draw(canvas: Canvas, progressBounds: RectF) {
if (!mIsProgressReversed) {
canvas.drawArc(
progressBounds,
mProgressStartAngle.toFloat(),
mProgressSweepAngle.toFloat(),
false,
mProgressPaint
)
} else {
canvas.drawArc(
progressBounds,
(-mProgressStartAngle).toFloat(),
(-mProgressSweepAngle).toFloat(),
false,
mProgressPaint
)
}
}
override fun stopIndeterminateAnimation() {
mOffsetAnimator.cancel()
mProgressAnimator.cancel()
}
override fun setProgressPercent(progressPercent: Float) {}
override fun setAnimationEnabled(enabled: Boolean) {}
override fun setAnimationDuration(millis: Long) {
mProgressAnimationDuration = if (millis < 0) DEFAULT_ANIMATION_DURATION else millis
if (mProgressAnimator.duration != mProgressAnimationDuration) {
mProgressAnimator.duration = mProgressAnimationDuration
if (mProgressAnimator.isRunning) {
mProgressAnimator.cancel()
mProgressAnimator.start()
}
}
}
override fun setListener(listener: ProgressDrawerManager.ProgressDrawerListener) { this.listener = listener }
}
| mit | fc00bc6557a40d3c1c8ad1acb9b8f866 | 39.693989 | 117 | 0.685645 | 5.23699 | false | false | false | false |
wangxuxin/SmartHome | SmartHomeAndroid/app/src/main/java/io/github/acedroidx/smarthome/MainActivity.kt | 1 | 3119 | package io.github.acedroidx.smarthome
import android.app.PendingIntent.getActivity
import android.content.DialogInterface
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.content.Intent
import android.widget.Toast
import android.widget.EditText
import android.content.SharedPreferences
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.support.v7.app.AlertDialog
import android.util.Log
import android.view.View
import android.widget.Button
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.dialog_biglight.*
import android.view.LayoutInflater
import kotlinx.android.synthetic.main.dialog_biglight.view.*
class MainActivity : AppCompatActivity() {
lateinit var ip: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (intent.extras != null) ip = intent.extras.getString("ip")
else ip = "error"
var handler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(inputMessage: Message) {
Log.w("wxxDbg", inputMessage.obj.toString())
if (inputMessage.obj == "on" || inputMessage.obj == "off" || inputMessage.obj == "ok") {
Toast.makeText(applicationContext, inputMessage.obj.toString(), Toast.LENGTH_SHORT)
.show()
} else {
Toast.makeText(applicationContext, "error1:" + inputMessage.obj.toString(), Toast.LENGTH_LONG)
.show()
}
}
}
var builder = AlertDialog.Builder(this)
val inflater = this.layoutInflater
var inflate = inflater.inflate(R.layout.dialog_biglight, null)
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflate)
builder.setTitle("输入亮度等级,最高32")
builder.setPositiveButton("确定") { dialog, id ->
if(inflate.editText.text.toString().toInt() in 1..32){
HttpClient("http://" + ip + ":23333/bigLight-set/1000/"+inflate.editText.text, handler).start()
dialog.dismiss()
}else{
Toast.makeText(applicationContext, "输入亮度等级,最高32", Toast.LENGTH_LONG)
.show()
}
}
builder.setNegativeButton("取消") { dialog, id -> dialog.cancel()}
var dialog = builder.create()
door.setOnClickListener { HttpClient("http://" + ip + ":23333/door-switch", handler).start() }
bigLight.setOnClickListener { HttpClient("http://" + ip + ":23333/bigLight-switch", handler).start() }
bigLS.setOnClickListener {dialog.show()}
whiteLight.setOnClickListener { HttpClient("http://" + ip + ":23333/whiteLight-switch", handler).start() }
fan.setOnClickListener { HttpClient("http://" + ip + ":23333/fan-switch", handler).start() }
}
}
| gpl-3.0 | 047d46061af1f16760dac93fb86a9a02 | 44.955224 | 114 | 0.653134 | 4.318373 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/multifileClasses/optimized/deferredStaticInitialization.kt | 2 | 837 | // TARGET_BACKEND: JVM
// IGNORE_LIGHT_ANALYSIS
// WITH_RUNTIME
// KOTLIN_CONFIGURATION_FLAGS: +JVM.INHERIT_MULTIFILE_PARTS
// FILE: box.kt
import a.*
fun box(): String = OK
// FILE: part1.kt
@file:[JvmName("MultifileClass") JvmMultifileClass]
package a
val O = run { "O" }
// FILE: part2.kt
@file:[JvmName("MultifileClass") JvmMultifileClass]
package a
const val K = "K"
// FILE: part3.kt
@file:[JvmName("MultifileClass") JvmMultifileClass]
package a
val OK: String = run { O + K }
// FILE: irrelevantPart.kt
@file:[JvmName("MultifileClass") JvmMultifileClass]
package a
val X1: Nothing =
throw AssertionError("X1 should not be initialized")
// FILE: reallyIrrelevantPart.kt
@file:[JvmName("MultifileClass") JvmMultifileClass]
package a
val X2: Nothing =
throw AssertionError("X2 should not be initialized")
| apache-2.0 | fc0f7698ca8dd2e85cd3bf0ae60ea9f8 | 19.414634 | 60 | 0.713262 | 3.444444 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/multiDecl/ValCapturedInFunctionLiteral.kt | 5 | 212 | class A {
operator fun component1() = 1
operator fun component2() = 2
}
fun box() : String {
val (a, b) = A()
val run = {
a
}
return if (run() == 1 && b == 2) "OK" else "fail"
}
| apache-2.0 | 2dff95dc3e076a1f2a98f574e63f4d38 | 15.307692 | 53 | 0.466981 | 2.985915 | false | false | false | false |
windchopper/password-drop | src/main/kotlin/com/github/windchopper/tools/password/drop/ui/Controller.kt | 1 | 2046 | package com.github.windchopper.tools.password.drop.ui
import com.github.windchopper.common.fx.cdi.form.StageFormController
import com.github.windchopper.tools.password.drop.misc.screen
import javafx.scene.Parent
import javafx.scene.control.Alert
import javafx.scene.image.Image
import javafx.stage.*
abstract class Controller: StageFormController() {
override fun afterLoad(form: Parent, parameters: MutableMap<String, *>, formNamespace: MutableMap<String, *>) {
super.afterLoad(form, parameters, formNamespace)
listOf(
Image("/com/github/windchopper/tools/password/drop/images/keys_16.png"),
Image("/com/github/windchopper/tools/password/drop/images/keys_24.png"),
Image("/com/github/windchopper/tools/password/drop/images/keys_32.png"),
Image("/com/github/windchopper/tools/password/drop/images/keys_48.png"))
.also {
stage.icons.addAll(it)
}
}
open fun <A: Alert> prepareAlert(alert: A, modality: Modality? = Modality.WINDOW_MODAL, centerOnScreen: Screen? = stage.screen()): A {
return with (alert) {
initModality(modality)
initOwner(stage)
dialogPane.scene.window.let { window ->
if (window is Stage) {
window.icons.addAll(stage.icons)
}
centerOnScreen?.let { screen ->
window.addEventHandler(WindowEvent.WINDOW_SHOWN) {
window.x = (screen.visualBounds.width - window.width) / 2
window.y = (screen.visualBounds.height - window.height) / 2
}
}
}
this
}
}
open fun prepareChildStage(childStage: Stage = Stage(), modality: Modality = Modality.NONE, style: StageStyle = StageStyle.UNIFIED): Stage {
return childStage.also {
it.initModality(modality)
it.initStyle(style)
it.initOwner(stage)
}
}
}
| apache-2.0 | 80521bfe82170514813c4f22ee577609 | 36.2 | 144 | 0.604594 | 4.289308 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.