content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.ko.mvp.core
import com.ko.mvp.base.MvpContract
internal class MvpInteractor(
private val repository: MvpContract.Repository
): MvpContract.Interactor {
override suspend fun fetch(): MvpDomain {
//>> you can add more business logic here in the future
return repository.fetch()
}
}
| MVP/app/src/main/java/com/ko/mvp/core/MvpInteractor.kt | 1407432965 |
/*
* Copyright 2013 Maurício Linhares
*
* Maurício Linhares licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.github.mauricio.async.db.util
import java.nio.charset.Charset
import java.nio.ByteOrder
import io.netty.buffer.Unpooled
import io.netty.buffer.ByteBuf
object ByteBufferUtils {
fun writeLength(buffer: ByteBuf) {
val length = buffer.writerIndex() - 1
buffer.markWriterIndex()
buffer.writerIndex(1)
buffer.writeInt(length)
buffer.resetWriterIndex()
}
fun writeCString(content: String, b: ByteBuf, charset: Charset) {
b.writeBytes(content.toByteArray(charset))
b.writeByte(0)
}
fun writeSizedString(content: String, b: ByteBuf, charset: Charset) {
val bytes = content.toByteArray(charset)
b.writeByte(bytes.size)
b.writeBytes(bytes)
}
fun readCString(b: ByteBuf, charset: Charset): String {
b.markReaderIndex()
var byte: Byte = 0
var count = 0
do {
byte = b.readByte()
count += 1
} while (byte != 0.toByte())
b.resetReaderIndex()
val result = b.toString(b.readerIndex(), count - 1, charset)
b.readerIndex(b.readerIndex() + count)
return result
}
fun readUntilEOF(b: ByteBuf, charset: Charset): String {
if (b.readableBytes() == 0) {
return ""
}
b.markReaderIndex()
var byte: Byte = -1
var count = 0
var offset = 1
while (byte != 0.toByte()) {
if (b.readableBytes() > 0) {
byte = b.readByte()
count += 1
} else {
byte = 0
offset = 0
}
}
b.resetReaderIndex()
val result = b.toString(b.readerIndex(), count - offset, charset)
b.readerIndex(b.readerIndex() + count)
return result
}
fun read3BytesInt(b: ByteBuf): Int =
(b.readByte().toInt() and 0xff) or
((b.readByte().toInt() and 0xff) shl 8) or
((b.readByte().toInt() and 0xff) shl 16)
fun write3BytesInt(b: ByteBuf, value: Int) {
b.writeByte(value and 0xff)
b.writeByte(value shl 8)
b.writeByte(value shl 16)
}
fun writePacketLength(buffer: ByteBuf, sequence: Int = 1) {
val length = buffer.writerIndex() - 4
buffer.markWriterIndex()
buffer.writerIndex(0)
write3BytesInt(buffer, length)
buffer.writeByte(sequence)
buffer.resetWriterIndex()
}
fun packetBuffer(estimate: Int = 1024): ByteBuf {
val buffer = mysqlBuffer(estimate)
buffer.writeInt(0)
return buffer
}
fun mysqlBuffer(estimate: Int = 1024): ByteBuf =
Unpooled.buffer(estimate).order(ByteOrder.LITTLE_ENDIAN)
}
| db-async-common/src/main/kotlin/com/github/mauricio/async/db/util/ByteBufferUtils.kt | 1489636359 |
package guideme.volunteers.actions
import guideme.volunteers.domain.Level
import guideme.volunteers.domain.Person
import guideme.volunteers.domain.TravelDestination
import guideme.volunteers.domain.TravelDestinationRepository
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.junit.Before
import org.junit.Test
class TravelActionTest {
private lateinit var travelAction : TravelAction
var travelDestination : TravelDestination = mock()
var travelDestinationRepository : TravelDestinationRepository = mock()
var person : Person = mock()
@Before
fun setUp(){
travelAction = TravelAction(travelDestination, person, travelDestinationRepository)
}
@Test
fun runActionTest(){
whenever(travelDestination.name).thenReturn("Barcelona")
whenever(travelDestination.difficultyLevel).thenReturn(Level())
travelAction.run()
}
} | data_structure/src/test/kotlin/guideme/volunteers/actions/TravelActionTest.kt | 3985174720 |
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gradlebuild.binarycompatibility
import org.junit.Test
/**
* Asserts Kotlin `internal` members are filtered from the comparison.
*/
class KotlinInternalFilteringTest : AbstractBinaryCompatibilityTest() {
private
val internalMembers = """
internal fun foo() {}
internal val bar = "bar"
internal var bazar = "bazar"
internal fun String.fooExt() {}
internal fun Int.fooExt() {}
internal val String.barExt: String
get() = "bar"
internal var Int.bazarExt: String
get() = "bar"
set(value) = Unit
"""
private
val publicMembers = """
fun foo() {}
val bar = "bar"
var bazar = "bazar"
fun String.fooExt() {}
fun Int.fooExt() {}
val String.barExt: String
get() = "bar"
var Int.bazarExt: String
get() = "bar"
set(value) = Unit
"""
private
val existingSource = """
class ExistingClass {
class ExistingNestedClass
}
val valTurnedIntoVar: String
get() = ""
typealias ExistingTypeAlias = String
"""
private
val internalSource = """
$internalMembers
class ExistingClass() {
internal constructor(bar: String) : this()
$internalMembers
class ExistingNestedClass {
$internalMembers
}
}
typealias ExistingTypeAlias = String
var valTurnedIntoVar: String
get() = ""
internal set(value) = Unit
internal const val cathedral = "cathedral"
internal class AddedClass() {
constructor(bar: ExistingTypeAlias) : this()
$publicMembers
}
internal object AddedObject {
$publicMembers
const val cathedral = "cathedral"
}
internal enum class AddedEnum {
FOO;
$publicMembers
}
"""
private
val publicSource = """
$publicMembers
class ExistingClass() {
constructor(bar: String) : this()
$publicMembers
class ExistingNestedClass {
$publicMembers
}
}
typealias ExistingTypeAlias = String
var valTurnedIntoVar: String
get() = ""
set(value) = Unit
const val cathedral = "cathedral"
class AddedClass() {
constructor(bar: ExistingTypeAlias) : this()
$publicMembers
}
object AddedObject {
$publicMembers
const val cathedral = "cathedral"
}
enum class AddedEnum {
FOO;
$publicMembers
}
"""
@Test
fun `added internal members are filtered from the comparison`() {
checkBinaryCompatibleKotlin(
v1 = existingSource,
v2 = internalSource
).assertEmptyReport()
}
@Test
fun `existing internal members made public appear as added`() {
checkNotBinaryCompatibleKotlin(
v1 = internalSource,
v2 = publicSource
).apply {
assertHasErrors(
*reportedMembers.map {
added(it.first, it.second)
}.toTypedArray()
)
assertHasNoWarning()
assertHasNoInformation()
}
}
@Test
fun `existing public members made internal appear as removed`() {
checkNotBinaryCompatibleKotlin(
v1 = publicSource,
v2 = internalSource
).apply {
assertHasErrors(
*reportedMembers.map {
removed(it.first, it.second)
}.toTypedArray()
)
assertHasNoWarning()
assertHasNoInformation()
}
}
private
val reportedMembers = listOf(
"Class" to "AddedClass"
) + reportedMembersFor("AddedClass") + listOf(
"Constructor" to "AddedClass(java.lang.String)",
"Constructor" to "AddedClass()",
"Class" to "AddedEnum",
"Field" to "FOO"
) + reportedMembersFor("AddedEnum") + listOf(
"Method" to "AddedEnum.valueOf(java.lang.String)",
"Method" to "AddedEnum.values()",
"Class" to "AddedObject",
"Field" to "INSTANCE",
"Field" to "cathedral"
) + reportedMembersFor("AddedObject") + reportedMembersFor("ExistingClass") + listOf(
"Constructor" to "ExistingClass(java.lang.String)"
) + reportedMembersFor("ExistingClass${'$'}ExistingNestedClass") + listOf(
"Field" to "cathedral"
) + reportedMembersFor("SourceKt") + listOf(
"Method" to "SourceKt.setValTurnedIntoVar(java.lang.String)"
)
private
fun reportedMembersFor(containingType: String) =
listOf(
"Method" to "$containingType.foo()",
"Method" to "$containingType.fooExt(java.lang.String)",
"Method" to "$containingType.fooExt(int)",
"Method" to "$containingType.getBar()",
"Method" to "$containingType.getBarExt(java.lang.String)",
"Method" to "$containingType.getBazar()",
"Method" to "$containingType.getBazarExt(int)",
"Method" to "$containingType.setBazar(java.lang.String)",
"Method" to "$containingType.setBazarExt(int,java.lang.String)"
)
}
| build-logic/binary-compatibility/src/test/kotlin/gradlebuild/binarycompatibility/KotlinInternalFilteringTest.kt | 4013936786 |
package edu.kit.iti.formal.util
import java.nio.file.Files
import java.nio.file.Path
/**
*
* @author Alexander Weigl
* @version 1 (04.05.19)
*/
fun Path.inputStream() = Files.newInputStream(this)
| util/src/main/kotlin/edu/kit/iti/formal/util/io.kt | 739599050 |
package br.com.bulgasoftwares.feedreader.extensions
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import com.google.firebase.analytics.FirebaseAnalytics
inline fun <reified T : Any> Activity.launchActivity(
requestCode: Int = -1,
options: Bundle? = null,
noinline init: Intent.() -> Unit = {}) {
val intent = newIntent<T>(this)
intent.init()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
startActivityForResult(intent, requestCode, options)
} else {
startActivityForResult(intent, requestCode)
}
}
inline fun <reified T : Any> Context.launchActivity(
options: Bundle? = null,
noinline init: Intent.() -> Unit = {}) {
val intent = newIntent<T>(this)
intent.init()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
startActivity(intent, options)
} else {
startActivity(intent)
}
}
inline fun <reified T : Any> newIntent(context: Context): Intent =
Intent(context, T::class.java)
val Activity.analytics: FirebaseAnalytics
get() {
return FirebaseAnalytics.getInstance(this)
} | app/src/main/java/br/com/bulgasoftwares/feedreader/extensions/ActivityExtensions.kt | 302807760 |
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.cutscene.dialogue
import javafx.beans.property.SimpleStringProperty
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.*
import org.junit.jupiter.api.Test
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class SerializableDialogueGraphTest {
@Test
fun `Serialization to and from`() {
val start = StartNode("test start")
val choice = ChoiceNode("test choice")
val function = FunctionNode("test function")
val end = EndNode("test end")
val text = TextNode("test text")
val branch = BranchNode("test branch")
val subdialogue = SubDialogueNode("test subdialogue")
choice.options[0] = SimpleStringProperty("Option 1")
choice.options[1] = SimpleStringProperty("Option 2")
choice.conditions[0] = SimpleStringProperty("")
choice.conditions[1] = SimpleStringProperty("hasItem 5000")
val graph = DialogueGraph()
// nodes
graph.addNode(start)
graph.addNode(choice)
graph.addNode(function)
graph.addNode(end)
graph.addNode(text)
graph.addNode(branch)
graph.addNode(subdialogue)
// edges
graph.addEdge(start, choice)
graph.addChoiceEdge(choice, 0, function)
graph.addChoiceEdge(choice, 1, end)
graph.addChoiceEdge(branch, 0, text)
graph.addChoiceEdge(branch, 1, end)
graph.addEdge(function, end)
graph.addEdge(text, subdialogue)
graph.addEdge(subdialogue, end)
val sGraph = DialogueGraphSerializer.toSerializable(graph)
assertThat(sGraph.version, greaterThan(0))
sGraph.nodes.forEach {
assertThat(it.value.type, `is`(not(DialogueNodeType.CHOICE)))
}
sGraph.choiceNodes.forEach {
assertThat(it.value.type, `is`(DialogueNodeType.CHOICE))
}
sGraph.version++
val copy = DialogueGraphSerializer.fromSerializable(sGraph)
assertThat(copy.uniqueID, `is`(graph.uniqueID))
assertThat(copy.nodes.mapValues { it.toString() }, `is`(graph.nodes.mapValues { it.toString() }))
val edges1 = graph.edges.map { it.toString() }
val edges2 = copy.edges.map { it.toString() }
assertThat(edges1, containsInAnyOrder(*edges2.toTypedArray()))
}
} | fxgl-gameplay/src/test/kotlin/com/almasb/fxgl/cutscene/dialogue/SerializableDialogueGraphTest.kt | 1568634795 |
package com.example.dummyapp1
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
| DummyApp1/app/src/main/java/com/example/dummyapp1/MainActivity.kt | 429825523 |
package com.binlly.fastpeak.business.test.adapter
import android.content.Context
import android.widget.TextView
import com.binlly.fastpeak.R
import com.binlly.fastpeak.base.adapter.BaseDelegate
import com.binlly.fastpeak.business.test.model.TestModel
import com.chad.library.adapter.base.BaseViewHolder
/**
* Created by binlly on 2017/5/13.
*/
class RouterDelegate(context: Context): BaseDelegate<TestModel>(context) {
override val layoutResId: Int
get() = R.layout.test_item_key_value
override fun childConvert(holder: BaseViewHolder, item: TestModel) {
val key = holder.getView<TextView>(R.id.key)
val value = holder.getView<TextView>(R.id.value)
key.text = item.router.key
value.text = item.router.value
value.setTextColor(item.valueColor)
}
} | app/src/main/java/com/binlly/fastpeak/business/test/adapter/RouterDelegate.kt | 2917058318 |
package io.github.manamiproject.manami.app.inconsistencies.lists.deadentries
import io.github.manamiproject.manami.app.lists.ignorelist.IgnoreListEntry
import io.github.manamiproject.manami.app.lists.watchlist.WatchListEntry
internal data class DeadEntriesInconsistenciesResult(
val watchListResults: List<WatchListEntry> = emptyList(),
val ignoreListResults: List<IgnoreListEntry> = emptyList(),
) | manami-app/src/main/kotlin/io/github/manamiproject/manami/app/inconsistencies/lists/deadentries/DeadEntriesInconsistenciesResult.kt | 399315491 |
package ii_collections
import org.junit.Assert.assertEquals
import org.junit.Test
class _24_Extensions_On_Collections {
@Test fun testCollectionOfOneElement() {
doTest(listOf("a"), listOf("a"))
}
@Test fun testEmptyCollection() {
doTest(null, listOf())
}
@Test fun testSimpleCollection() {
doTest(listOf("a", "c"), listOf("a", "bb", "c"))
}
@Test fun testCollectionWithEmptyStrings() {
doTest(listOf("", "", "", ""), listOf("", "", "", "", "a", "bb", "ccc", "dddd"))
}
@Test fun testCollectionWithTwoGroupsOfMaximalSize() {
doTest(listOf("a", "c"), listOf("a", "bb", "c", "dd"))
}
private fun doTest(expected: Collection<String>?, argument: Collection<String>) {
assertEquals("The function 'doSomethingStrangeWithCollection' should do at least something with a collection:",
expected, doSomethingStrangeWithCollection(argument))
}
} | test/ii_collections/_24_Extensions_On_Collections.kt | 3256363123 |
/*
* Copyright (c) 2020 Giorgio Antonioli
*
* 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.fondesa.recyclerviewdivider
import com.fondesa.recyclerviewdivider.test.dummyGrid
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Tests of [Divider].
*/
class DividerTest {
@Test
fun `init - properties return constructor value`() {
val divider = Divider(
grid = dummyGrid(),
originX = 3,
originY = 4,
orientation = Orientation.VERTICAL
)
assertEquals(3, divider.originX)
assertEquals(4, divider.originY)
assertEquals(Orientation.VERTICAL, divider.orientation)
}
@Test
fun `isTopDivider - divider vertical - returns false`() {
val divider = Divider(
grid = dummyGrid(),
originX = 0,
originY = 0,
orientation = Orientation.VERTICAL
)
assertFalse(divider.isTopDivider)
}
@Test
fun `isTopDivider - divider horizontal, originY not 0 - returns false`() {
val divider = Divider(
grid = dummyGrid(),
originX = 0,
originY = 1,
orientation = Orientation.HORIZONTAL
)
assertFalse(divider.isTopDivider)
}
@Test
fun `isTopDivider - divider horizontal, originY not 0 - returns true`() {
val divider = Divider(
grid = dummyGrid(),
originX = 0,
originY = 0,
orientation = Orientation.HORIZONTAL
)
assertTrue(divider.isTopDivider)
}
@Test
fun `isBottomDivider - divider vertical - returns false`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.VERTICAL, cellsInLines = intArrayOf(1, 1)),
originX = 0,
originY = 2,
orientation = Orientation.VERTICAL
)
assertFalse(divider.isBottomDivider)
}
@Test
fun `isBottomDivider - divider horizontal, grid vertical, originY not equal to lines count - returns false`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.VERTICAL, cellsInLines = intArrayOf(1, 1)),
originX = 0,
originY = 1,
orientation = Orientation.HORIZONTAL
)
assertFalse(divider.isBottomDivider)
}
@Test
fun `isBottomDivider - divider horizontal, grid vertical, originY equal to lines count - returns true`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.VERTICAL, cellsInLines = intArrayOf(1, 1)),
originX = 0,
originY = 2,
orientation = Orientation.HORIZONTAL
)
assertTrue(divider.isBottomDivider)
}
@Test
fun `isBottomDivider - divider horizontal, grid horizontal, originY not equal to cells count in given line - returns false`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.HORIZONTAL, cellsInLines = intArrayOf(3, 2, 3)),
originX = 2,
originY = 2,
orientation = Orientation.HORIZONTAL
)
assertFalse(divider.isBottomDivider)
}
@Test
fun `isBottomDivider - divider horizontal, grid horizontal, originY equal to cells count in line, line not filled - returns false`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.HORIZONTAL, cellsInLines = intArrayOf(3, 2, 2), fillLine = false),
originX = 2,
originY = 2,
orientation = Orientation.HORIZONTAL
)
assertFalse(divider.isBottomDivider)
}
@Test
fun `isBottomDivider - divider horizontal, grid horizontal, originY equal to cells count in given line, line filled - returns true`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.HORIZONTAL, cellsInLines = intArrayOf(3, 2, 2)),
originX = 2,
originY = 2,
orientation = Orientation.HORIZONTAL
)
assertTrue(divider.isBottomDivider)
}
@Test
fun `isStartDivider - divider horizontal - returns false`() {
val divider = Divider(
grid = dummyGrid(),
originX = 0,
originY = 0,
orientation = Orientation.HORIZONTAL
)
assertFalse(divider.isStartDivider)
}
@Test
fun `isStartDivider - divider vertical, originX not 0 - returns false`() {
val divider = Divider(
grid = dummyGrid(),
originX = 1,
originY = 0,
orientation = Orientation.VERTICAL
)
assertFalse(divider.isStartDivider)
}
@Test
fun `isStartDivider - divider vertical, originX 0 - returns true`() {
val divider = Divider(
grid = dummyGrid(),
originX = 0,
originY = 0,
orientation = Orientation.VERTICAL
)
assertTrue(divider.isStartDivider)
}
@Test
fun `isEndDivider - divider horizontal - returns false`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.HORIZONTAL, cellsInLines = intArrayOf(1, 1)),
originX = 2,
originY = 0,
orientation = Orientation.HORIZONTAL
)
assertFalse(divider.isEndDivider)
}
@Test
fun `isEndDivider - divider vertical, grid horizontal, originX not equal to lines count - returns false`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.HORIZONTAL, cellsInLines = intArrayOf(1, 1)),
originX = 1,
originY = 0,
orientation = Orientation.VERTICAL
)
assertFalse(divider.isEndDivider)
}
@Test
fun `isEndDivider - divider vertical, grid horizontal, originX equal to lines count - returns true`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.HORIZONTAL, cellsInLines = intArrayOf(1, 1)),
originX = 2,
originY = 0,
orientation = Orientation.VERTICAL
)
assertTrue(divider.isEndDivider)
}
@Test
fun `isEndDivider - divider vertical, grid vertical, originX not equal to cells count in given line - returns false`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.VERTICAL, cellsInLines = intArrayOf(3, 2, 3)),
originX = 2,
originY = 2,
orientation = Orientation.VERTICAL
)
assertFalse(divider.isEndDivider)
}
@Test
fun `isEndDivider - divider vertical, grid vertical, originX equal to cells count in given line, line not filled - returns false`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.VERTICAL, cellsInLines = intArrayOf(3, 2, 2), fillLine = false),
originX = 2,
originY = 2,
orientation = Orientation.VERTICAL
)
assertFalse(divider.isEndDivider)
}
@Test
fun `isEndDivider - divider vertical, grid vertical, originX equal to cells count in given line, line filled - returns true`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.VERTICAL, cellsInLines = intArrayOf(3, 2, 3)),
originX = 3,
originY = 2,
orientation = Orientation.VERTICAL
)
assertTrue(divider.isEndDivider)
}
@Test
fun `isFirstDivider - divider not top, grid vertical - returns false`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.VERTICAL),
originX = 0,
originY = 0,
orientation = Orientation.VERTICAL
)
assertFalse(divider.isFirstDivider)
}
@Test
fun `isFirstDivider - divider top, grid vertical - returns true`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.VERTICAL),
originX = 0,
originY = 0,
orientation = Orientation.HORIZONTAL
)
assertTrue(divider.isFirstDivider)
}
@Test
fun `isFirstDivider - divider not start, grid horizontal - returns false`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.HORIZONTAL),
originX = 0,
originY = 0,
orientation = Orientation.HORIZONTAL
)
assertFalse(divider.isFirstDivider)
}
@Test
fun `isFirstDivider - divider start, grid horizontal - returns true`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.HORIZONTAL),
originX = 0,
originY = 0,
orientation = Orientation.VERTICAL
)
assertTrue(divider.isFirstDivider)
}
@Test
fun `isLastDivider - divider not bottom, grid vertical - returns false`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.VERTICAL, cellsInLines = intArrayOf(1, 1)),
originX = 0,
originY = 1,
orientation = Orientation.HORIZONTAL
)
assertFalse(divider.isLastDivider)
}
@Test
fun `isLastDivider - divider bottom divider, grid vertical - returns true`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.VERTICAL, cellsInLines = intArrayOf(1, 1)),
originX = 0,
originY = 2,
orientation = Orientation.HORIZONTAL
)
assertTrue(divider.isLastDivider)
}
@Test
fun `isLastDivider - divider not end, grid horizontal - returns false`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.HORIZONTAL, cellsInLines = intArrayOf(1, 1)),
originX = 1,
originY = 0,
orientation = Orientation.VERTICAL
)
assertFalse(divider.isLastDivider)
}
@Test
fun `isLastDivider - divider not end, grid horizontal - returns true`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.HORIZONTAL, cellsInLines = intArrayOf(1, 1)),
originX = 2,
originY = 0,
orientation = Orientation.VERTICAL
)
assertTrue(divider.isLastDivider)
}
@Test
fun `isSideDivider - divider not start or end, grid vertical - returns false`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.VERTICAL),
originX = 0,
originY = 0,
orientation = Orientation.HORIZONTAL
)
assertFalse(divider.isSideDivider)
}
@Test
fun `isSideDivider - divider start, grid vertical - returns true`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.VERTICAL),
originX = 0,
originY = 0,
orientation = Orientation.VERTICAL
)
assertTrue(divider.isSideDivider)
}
@Test
fun `isSideDivider - divider end, grid vertical - returns true`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.VERTICAL, cellsInLines = intArrayOf(3, 2, 3)),
originX = 3,
originY = 2,
orientation = Orientation.VERTICAL
)
assertTrue(divider.isSideDivider)
}
@Test
fun `isSideDivider - divider not top or bottom divider, grid horizontal - returns false`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.HORIZONTAL),
originX = 0,
originY = 0,
orientation = Orientation.VERTICAL
)
assertFalse(divider.isSideDivider)
}
@Test
fun `isSideDivider - divider not top divider, grid horizontal - returns true`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.HORIZONTAL),
originX = 0,
originY = 0,
orientation = Orientation.HORIZONTAL
)
assertTrue(divider.isSideDivider)
}
@Test
fun `isSideDivider - divider not bottom divider, grid horizontal - returns true`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.HORIZONTAL, cellsInLines = intArrayOf(3, 2, 3)),
originX = 2,
originY = 3,
orientation = Orientation.HORIZONTAL
)
assertTrue(divider.isSideDivider)
}
@Test(expected = IllegalArgumentException::class)
fun `accumulatedSpan - divider horizontal, grid vertical - throws exception`() {
Divider(
grid = dummyGrid(orientation = Orientation.VERTICAL),
originX = 0,
originY = 0,
orientation = Orientation.HORIZONTAL
).accumulatedSpan
}
@Test(expected = IllegalArgumentException::class)
fun `accumulatedSpan - divider vertical, grid horizontal - throws exception`() {
Divider(
grid = dummyGrid(orientation = Orientation.HORIZONTAL),
originX = 0,
originY = 0,
orientation = Orientation.VERTICAL
).accumulatedSpan
}
@Test
fun `accumulatedSpan - divider vertical, grid vertical - returns accumulated span`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.VERTICAL, cellsInLines = intArrayOf(3, 2, 3)),
originX = 2,
originY = 1,
orientation = Orientation.VERTICAL
)
assertEquals(3, divider.accumulatedSpan)
}
@Test
fun `accumulatedSpan - divider horizontal, grid horizontal - returns accumulated span`() {
val divider = Divider(
grid = dummyGrid(orientation = Orientation.HORIZONTAL, cellsInLines = intArrayOf(3, 2, 3)),
originX = 1,
originY = 2,
orientation = Orientation.HORIZONTAL
)
assertEquals(3, divider.accumulatedSpan)
}
}
| recycler-view-divider/src/test/kotlin/com/fondesa/recyclerviewdivider/DividerTest.kt | 1699679373 |
/*-
* ========================LICENSE_START=================================
* ids-webconsole
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.webconsole.api
import java.io.IOException
import javax.ws.rs.container.ContainerRequestContext
import javax.ws.rs.container.ContainerResponseContext
import javax.ws.rs.container.ContainerResponseFilter
import javax.ws.rs.ext.Provider
/**
* This filter adds Cross-Origin Resource Sharing (CORS) headers to each response.
*
* @author Christian Banse
*/
@Provider
class CORSResponseFilter : ContainerResponseFilter {
@Throws(IOException::class)
override fun filter(
requestContext: ContainerRequestContext,
responseContext: ContainerResponseContext
) {
val headers = responseContext.headers
// allow AJAX from everywhere
headers.add("Access-Control-Allow-Origin", "*")
headers.add(
"Access-Control-Allow-Headers",
"origin, content-type, accept, authorization, X-Requested-With"
)
headers.add("Access-Control-Allow-Credentials", "true")
headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
}
}
| ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/CORSResponseFilter.kt | 1269963708 |
/*
* Copyright (c) 2020 Giorgio Antonioli
*
* 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.fondesa.recyclerviewdivider
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Tests of SidesAdjacentToCell.kt file.
*/
class SidesAdjacentToCellKtTest {
@Test
fun `sidesAdjacentToCell - vertical LTR grid, 1 column, without fullSpan`() {
mapOf(
StaggeredCell(0, false) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.START, Side.END)
).assertValid(spanCount = 1, orientation = Orientation.VERTICAL, layoutRightToLeft = false)
}
@Test
fun `sidesAdjacentToCell - vertical RTL grid, 1 column, without fullSpan`() {
mapOf(
StaggeredCell(0, false) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.START, Side.END)
).assertValid(spanCount = 1, orientation = Orientation.VERTICAL, layoutRightToLeft = true)
}
@Test
fun `sidesAdjacentToCell - vertical LTR grid, 1 column, with fullSpan`() {
mapOf(
StaggeredCell(0, true) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.START, Side.END),
StaggeredCell(0, true) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.START, Side.END),
StaggeredCell(0, true) to sidesOf(Side.START, Side.END)
).assertValid(spanCount = 1, orientation = Orientation.VERTICAL, layoutRightToLeft = false)
}
@Test
fun `sidesAdjacentToCell - vertical RTL grid, 1 column, with fullSpan`() {
mapOf(
StaggeredCell(0, true) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.START, Side.END),
StaggeredCell(0, true) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.START, Side.END),
StaggeredCell(0, true) to sidesOf(Side.START, Side.END)
).assertValid(spanCount = 1, orientation = Orientation.VERTICAL, layoutRightToLeft = true)
}
@Test
fun `sidesAdjacentToCell - vertical LTR grid, multiple columns, without fullSpan, without white spaces`() {
mapOf(
StaggeredCell(0, false) to sidesOf(Side.START),
StaggeredCell(1, false) to sidesOf(Side.END),
StaggeredCell(0, false) to sidesOf(Side.START),
StaggeredCell(1, false) to sidesOf(Side.END),
StaggeredCell(0, false) to sidesOf(Side.START)
).assertValid(spanCount = 2, orientation = Orientation.VERTICAL, layoutRightToLeft = false)
}
@Test
fun `sidesAdjacentToCell - vertical RTL grid, multiple columns, without fullSpan, without white spaces`() {
mapOf(
StaggeredCell(0, false) to sidesOf(Side.END),
StaggeredCell(1, false) to sidesOf(Side.START),
StaggeredCell(0, false) to sidesOf(Side.END),
StaggeredCell(1, false) to sidesOf(Side.START),
StaggeredCell(0, false) to sidesOf(Side.END)
).assertValid(spanCount = 2, orientation = Orientation.VERTICAL, layoutRightToLeft = true)
}
@Test
fun `sidesAdjacentToCell - vertical LTR grid, multiple columns, with fullSpan, without white spaces`() {
mapOf(
StaggeredCell(0, true) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.START),
StaggeredCell(1, false) to sidesOf(Side.END),
StaggeredCell(0, true) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.START),
StaggeredCell(1, false) to sidesOf(Side.END)
).assertValid(spanCount = 2, orientation = Orientation.VERTICAL, layoutRightToLeft = false)
}
@Test
fun `sidesAdjacentToCell - vertical RTL grid, multiple columns, with fullSpan, without white spaces`() {
mapOf(
StaggeredCell(0, true) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.END),
StaggeredCell(1, false) to sidesOf(Side.START),
StaggeredCell(0, true) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.END),
StaggeredCell(1, false) to sidesOf(Side.START)
).assertValid(spanCount = 2, orientation = Orientation.VERTICAL, layoutRightToLeft = true)
}
@Test
fun `sidesAdjacentToCell - vertical LTR grid, multiple columns, with fullSpan, with white spaces`() {
mapOf(
StaggeredCell(0, true) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.START),
StaggeredCell(0, false) to sidesOf(Side.START),
StaggeredCell(1, false) to sidesOf(Side.END),
StaggeredCell(1, false) to sidesOf(Side.END)
).assertValid(spanCount = 2, orientation = Orientation.VERTICAL, layoutRightToLeft = false)
}
@Test
fun `sidesAdjacentToCell - vertical RTL grid, multiple columns, with fullSpan, with white spaces`() {
mapOf(
StaggeredCell(0, true) to sidesOf(Side.START, Side.END),
StaggeredCell(0, false) to sidesOf(Side.END),
StaggeredCell(0, false) to sidesOf(Side.END),
StaggeredCell(1, false) to sidesOf(Side.START),
StaggeredCell(1, false) to sidesOf(Side.START)
).assertValid(spanCount = 2, orientation = Orientation.VERTICAL, layoutRightToLeft = true)
}
@Test
fun `sidesAdjacentToCell - horizontal LTR grid, 1 column, without fullSpan`() {
mapOf(
StaggeredCell(0, false) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP, Side.BOTTOM)
).assertValid(spanCount = 1, orientation = Orientation.HORIZONTAL, layoutRightToLeft = false)
}
@Test
fun `sidesAdjacentToCell - horizontal RTL grid, 1 column, without fullSpan`() {
mapOf(
StaggeredCell(0, false) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP, Side.BOTTOM)
).assertValid(spanCount = 1, orientation = Orientation.HORIZONTAL, layoutRightToLeft = true)
}
@Test
fun `sidesAdjacentToCell - horizontal LTR grid, 1 column, with fullSpan`() {
mapOf(
StaggeredCell(0, true) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, true) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, true) to sidesOf(Side.TOP, Side.BOTTOM)
).assertValid(spanCount = 1, orientation = Orientation.HORIZONTAL, layoutRightToLeft = false)
}
@Test
fun `sidesAdjacentToCell - horizontal RTL grid, 1 column, with fullSpan`() {
mapOf(
StaggeredCell(0, true) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, true) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, true) to sidesOf(Side.TOP, Side.BOTTOM)
).assertValid(spanCount = 1, orientation = Orientation.HORIZONTAL, layoutRightToLeft = true)
}
@Test
fun `sidesAdjacentToCell - horizontal LTR grid, multiple columns, without fullSpan, without white spaces`() {
mapOf(
StaggeredCell(0, false) to sidesOf(Side.TOP),
StaggeredCell(1, false) to sidesOf(Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP),
StaggeredCell(1, false) to sidesOf(Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP)
).assertValid(spanCount = 2, orientation = Orientation.HORIZONTAL, layoutRightToLeft = false)
}
@Test
fun `sidesAdjacentToCell - horizontal RTL grid, multiple columns, without fullSpan, without white spaces`() {
mapOf(
StaggeredCell(0, false) to sidesOf(Side.TOP),
StaggeredCell(1, false) to sidesOf(Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP),
StaggeredCell(1, false) to sidesOf(Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP)
).assertValid(spanCount = 2, orientation = Orientation.HORIZONTAL, layoutRightToLeft = true)
}
@Test
fun `sidesAdjacentToCell - horizontal LTR grid, multiple columns, with fullSpan, without white spaces`() {
mapOf(
StaggeredCell(0, true) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP),
StaggeredCell(1, false) to sidesOf(Side.BOTTOM),
StaggeredCell(0, true) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP),
StaggeredCell(1, false) to sidesOf(Side.BOTTOM)
).assertValid(spanCount = 2, orientation = Orientation.HORIZONTAL, layoutRightToLeft = false)
}
@Test
fun `sidesAdjacentToCell - horizontal RTL grid, multiple columns, with fullSpan, without white spaces`() {
mapOf(
StaggeredCell(0, true) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP),
StaggeredCell(1, false) to sidesOf(Side.BOTTOM),
StaggeredCell(0, true) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP),
StaggeredCell(1, false) to sidesOf(Side.BOTTOM)
).assertValid(spanCount = 2, orientation = Orientation.HORIZONTAL, layoutRightToLeft = true)
}
@Test
fun `sidesAdjacentToCell - horizontal LTR grid, multiple columns, with fullSpan, with white spaces`() {
mapOf(
StaggeredCell(0, true) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP),
StaggeredCell(0, false) to sidesOf(Side.TOP),
StaggeredCell(1, false) to sidesOf(Side.BOTTOM),
StaggeredCell(1, false) to sidesOf(Side.BOTTOM)
).assertValid(spanCount = 2, orientation = Orientation.HORIZONTAL, layoutRightToLeft = false)
}
@Test
fun `sidesAdjacentToCell - horizontal RTL grid, multiple columns, with fullSpan, with white spaces`() {
mapOf(
StaggeredCell(0, true) to sidesOf(Side.TOP, Side.BOTTOM),
StaggeredCell(0, false) to sidesOf(Side.TOP),
StaggeredCell(0, false) to sidesOf(Side.TOP),
StaggeredCell(1, false) to sidesOf(Side.BOTTOM),
StaggeredCell(1, false) to sidesOf(Side.BOTTOM)
).assertValid(spanCount = 2, orientation = Orientation.HORIZONTAL, layoutRightToLeft = true)
}
private fun Map<StaggeredCell, Sides>.assertValid(spanCount: Int, orientation: Orientation, layoutRightToLeft: Boolean) {
val horizontalDirection = if (layoutRightToLeft) {
LayoutDirection.Horizontal.RIGHT_TO_LEFT
} else {
LayoutDirection.Horizontal.LEFT_TO_RIGHT
}
val grid = StaggeredGrid(
spanCount = spanCount,
orientation = orientation,
layoutDirection = LayoutDirection(horizontal = horizontalDirection, vertical = LayoutDirection.Vertical.TOP_TO_BOTTOM)
)
forEach { cell, expectedSides ->
val actualSides = grid.sidesAdjacentToCell(cell)
assertEquals(expectedSides, actualSides)
}
}
private fun sidesOf(first: Side, vararg others: Side): Sides = sidesOf().apply {
this += first
this += others
}
}
| recycler-view-divider/src/test/kotlin/com/fondesa/recyclerviewdivider/SidesAdjacentToCellKtTest.kt | 3808479929 |
package fr.free.nrw.commons.widget
import android.appwidget.AppWidgetManager
import android.content.Context
import android.widget.RemoteViews
import com.facebook.imagepipeline.core.ImagePipelineFactory
import com.facebook.soloader.SoLoader
import fr.free.nrw.commons.Media
import fr.free.nrw.commons.TestAppAdapter
import fr.free.nrw.commons.TestCommonsApplication
import fr.free.nrw.commons.media.MediaClient
import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
import org.powermock.reflect.Whitebox
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.wikipedia.AppAdapter
import java.lang.reflect.Method
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [21], application = TestCommonsApplication::class)
class PicOfDayAppWidgetUnitTests {
private lateinit var widget: PicOfDayAppWidget
private lateinit var context: Context
@Mock
private lateinit var views: RemoteViews
@Mock
private lateinit var appWidgetManager: AppWidgetManager
@Mock
private lateinit var mediaClient: MediaClient
@Mock
private lateinit var compositeDisposable: CompositeDisposable
@Before
fun setUp() {
AppAdapter.set(TestAppAdapter())
context = RuntimeEnvironment.application.applicationContext
SoLoader.setInTestMode()
ImagePipelineFactory.initialize(context)
MockitoAnnotations.initMocks(this)
widget = PicOfDayAppWidget()
Whitebox.setInternalState(widget, "compositeDisposable", compositeDisposable)
Whitebox.setInternalState(widget, "mediaClient", mediaClient)
}
@Test
@Throws(Exception::class)
fun testWidgetNotNull() {
Assert.assertNotNull(widget)
}
@Test
@Throws(Exception::class)
fun testOnDisabled() {
widget.onDisabled(context)
}
@Test
@Throws(Exception::class)
fun testOnEnabled() {
widget.onEnabled(context)
}
@Test
@Throws(Exception::class)
fun testOnUpdate() {
widget.onUpdate(context, appWidgetManager, intArrayOf(1))
}
@Test
@Throws(Exception::class)
fun testLoadImageFromUrl() {
val method: Method = PicOfDayAppWidget::class.java.getDeclaredMethod(
"loadImageFromUrl",
String::class.java,
Context::class.java,
RemoteViews::class.java,
AppWidgetManager::class.java,
Int::class.java
)
method.isAccessible = true
method.invoke(widget, "", context, views, appWidgetManager, 1)
}
@Test
@Throws(Exception::class)
fun testLoadPictureOfTheDay() {
`when`(mediaClient.getPictureOfTheDay()).thenReturn(Single.just(Media()))
val method: Method = PicOfDayAppWidget::class.java.getDeclaredMethod(
"loadPictureOfTheDay",
Context::class.java,
RemoteViews::class.java,
AppWidgetManager::class.java,
Int::class.java
)
method.isAccessible = true
method.invoke(widget, context, views, appWidgetManager, 1)
}
} | app/src/test/kotlin/fr/free/nrw/commons/widget/PicOfDayAppWidgetUnitTests.kt | 783886847 |
package com.github.shchurov.gitterclient.dagger.modules
import com.github.shchurov.gitterclient.data.database.Database
import com.github.shchurov.gitterclient.data.database.implementation.DatabaseImpl
import com.github.shchurov.gitterclient.data.database.implementation.RealmInitializer
import com.github.shchurov.gitterclient.data.network.api.GitterApi
import com.github.shchurov.gitterclient.data.network.api.implementation.GitterApiImpl
import com.github.shchurov.gitterclient.data.network.api.implementation.retrofit.RetrofitInitializer
import com.github.shchurov.gitterclient.data.preferences.Preferences
import com.github.shchurov.gitterclient.data.preferences.implementation.PreferencesImpl
import com.github.shchurov.gitterclient.domain.interactors.threading.SchedulersProvider
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
open class AppModule() {
@Provides
@Singleton
open fun providePreferences(): Preferences {
return PreferencesImpl("gitter_preferences")
}
@Provides
@Singleton
open fun provideGitterApi(preferences: Preferences): GitterApi {
val gitterService = RetrofitInitializer.initGitterService(preferences)
return GitterApiImpl(gitterService, preferences)
}
@Provides
@Singleton
fun provideRealmInitializer(): RealmInitializer {
return RealmInitializer()
}
@Provides
@Singleton
open fun provideDatabase(realmInitializer: RealmInitializer): Database {
return DatabaseImpl(realmInitializer)
}
@Provides
@Singleton
fun provideSchedulersProvider(): SchedulersProvider {
return SchedulersProvider()
}
} | app/src/main/kotlin/com/github/shchurov/gitterclient/dagger/modules/AppModule.kt | 2515358329 |
package example.dsl_style_kotlin
import org.seasar.doma.jdbc.Config
import org.seasar.doma.jdbc.JdbcLogger
import org.seasar.doma.jdbc.dialect.Dialect
import org.seasar.doma.jdbc.tx.TransactionManager
import javax.sql.DataSource
class DbConfig(
private val dialect: Dialect,
private val dataSource: DataSource,
private val jdbcLogger: JdbcLogger,
private val transactionManager: TransactionManager
) : Config {
override fun getJdbcLogger(): JdbcLogger {
return jdbcLogger
}
override fun getDialect(): Dialect {
return dialect
}
override fun getDataSource(): DataSource {
return dataSource
}
override fun getTransactionManager(): TransactionManager {
return transactionManager
}
}
| dsl-style-kotlin/src/main/kotlin/example/dsl_style_kotlin/DbConfig.kt | 3837306033 |
package io.innofang.singleton.example.kotlin
/**
* Created by Inno Fang on 2017/8/12.
*/
class ThreadSafeStaticInnerClassSingleton {
companion object {
fun getInstance() = Holder.instance
}
private object Holder {
val instance = ThreadSafeStaticInnerClassSingleton()
}
} | src/io/innofang/singleton/example/kotlin/ThreadSafeStaticInnerClassSingleton.kt | 4123495236 |
package ir.iais.utilities.javautils.jackson.serializers
import com.winterbe.expekt.should
import ir.iais.utilities.javautils.println
import ir.iais.utilities.javautils.utils.minutes
import ir.iais.utilities.javautils.utils.seconds
import org.junit.Test
class JSerDurationTest {
@Test
fun `test negative durations`() {
val `-10SecDuration` = JSerDuration((-10).seconds)
`-10SecDuration`.toString().println()
`-10SecDuration`.hours.should.equal(0)
`-10SecDuration`.minutes.should.equal(0)
`-10SecDuration`.seconds.should.equal(10)
`-10SecDuration`.sign.should.equal("-")
`-10SecDuration`.serialize().should.equal("-00:00:10")
`-10SecDuration`.serializeAsHourMinute().should.equal("-")
val `-1Duration` = JSerDuration((-1).minutes)
`-1Duration`.toString().println()
`-1Duration`.hours.should.equal(0)
`-1Duration`.minutes.should.equal(1)
`-1Duration`.seconds.should.equal(0)
`-1Duration`.sign.should.equal("-")
`-1Duration`.serialize().should.equal("-00:01:00")
`-1Duration`.serializeAsHourMinute().should.equal("-00:01")
val `-2h-9min-28sec Duration` = JSerDuration((-128).minutes + (-88).seconds)
`-2h-9min-28sec Duration`.hours.should.equal(2)
`-2h-9min-28sec Duration`.minutes.should.equal(9)
`-2h-9min-28sec Duration`.seconds.should.equal(28)
`-2h-9min-28sec Duration`.toString().println()
`-2h-9min-28sec Duration`.sign.should.equal("-")
`-2h-9min-28sec Duration`.serialize().should.equal("-02:09:28")
`-2h-9min-28sec Duration`.serializeAsHourMinute().should.equal("-02:09")
val ` 2h 9min 28sec Duration` = JSerDuration((128).minutes + (88).seconds)
` 2h 9min 28sec Duration`.hours.should.equal(2)
` 2h 9min 28sec Duration`.minutes.should.equal(9)
` 2h 9min 28sec Duration`.seconds.should.equal(28)
` 2h 9min 28sec Duration`.toString().println()
` 2h 9min 28sec Duration`.sign.should.empty
` 2h 9min 28sec Duration`.serialize().should.equal("02:09:28")
` 2h 9min 28sec Duration`.serializeAsHourMinute().should.equal("02:09")
}
} | src/test/java/ir/iais/utilities/javautils/jackson/serializers/JSerDurationTest.kt | 3836663765 |
package org.biacode.escommons.example.controller.impl
import org.biacode.escommons.core.model.response.DocumentsAndTotalCount
import org.biacode.escommons.example.controller.PersonController
import org.biacode.escommons.example.domain.Person
import org.biacode.escommons.example.filter.PersonFilter
import org.biacode.escommons.example.service.PersonService
import org.springframework.web.bind.annotation.*
/**
* Created by Arthur Asatryan.
* Date: 3/29/18
* Time: 5:25 PM
*/
@RestController
@RequestMapping("persons")
class PersonControllerImpl(val personService: PersonService) : PersonController {
@PostMapping("create")
override fun create(@RequestBody person: Person): Boolean {
return personService.save(person, PERSON_INDEX)
}
@GetMapping("filter")
override fun filter(@RequestParam("firstName") firstName: String): DocumentsAndTotalCount<Person> {
return personService.getByFilter(PersonFilter(firstName, 0, 10), PERSON_INDEX)
}
companion object {
const val PERSON_INDEX: String = "person_index"
}
} | escommons-example/src/main/kotlin/org/biacode/escommons/example/controller/impl/PersonControllerImpl.kt | 1483055697 |
package com.lasthopesoftware.bluewater.client.connection.builder.GivenServerIsFoundViaLookup.AndAnAuthKeyIsProvided
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.connection.builder.UrlScanner
import com.lasthopesoftware.bluewater.client.connection.builder.lookup.LookupServers
import com.lasthopesoftware.bluewater.client.connection.builder.lookup.ServerInfo
import com.lasthopesoftware.bluewater.client.connection.okhttp.OkHttpFactory
import com.lasthopesoftware.bluewater.client.connection.settings.ConnectionSettings
import com.lasthopesoftware.bluewater.client.connection.settings.LookupConnectionSettings
import com.lasthopesoftware.bluewater.client.connection.testing.TestConnections
import com.lasthopesoftware.bluewater.client.connection.url.IUrlProvider
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.BeforeClass
import org.junit.Test
class WhenScanningForUrls {
companion object {
private var urlProvider: IUrlProvider? = null
@BeforeClass
@JvmStatic
fun before() {
val connectionTester = mockk<TestConnections>()
every { connectionTester.promiseIsConnectionPossible(any()) } returns false.toPromise()
every { connectionTester.promiseIsConnectionPossible(match { a -> "http://1.2.3.4:143/MCWS/v1/" == a.urlProvider.baseUrl.toString() && "gooey" == a.urlProvider.authCode }) } returns true.toPromise()
val serverLookup = mockk<LookupServers>()
every { serverLookup.promiseServerInformation(LibraryId(15)) } returns Promise(
ServerInfo(
143,
null,
"1.2.3.4", emptyList(), emptyList(),
null
)
)
val connectionSettingsLookup = mockk<LookupConnectionSettings>()
every { connectionSettingsLookup.lookupConnectionSettings(LibraryId(15)) } returns ConnectionSettings(accessCode = "gooPc", userName = "myuser", password = "myPass").toPromise()
val urlScanner = UrlScanner(
{ "gooey" },
connectionTester,
serverLookup,
connectionSettingsLookup,
OkHttpFactory
)
urlProvider = urlScanner.promiseBuiltUrlProvider(LibraryId(15)).toFuture().get()
}
}
@Test
fun thenTheUrlProviderIsReturned() {
assertThat(urlProvider).isNotNull
}
@Test
fun thenTheBaseUrlIsCorrect() {
assertThat(urlProvider?.baseUrl.toString()).isEqualTo("http://1.2.3.4:143/MCWS/v1/")
}
}
| projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/connection/builder/GivenServerIsFoundViaLookup/AndAnAuthKeyIsProvided/WhenScanningForUrls.kt | 4145410560 |
package com.ryuta46.evalspecmaker.util
class Logger(val tag: String) {
companion object {
val LOG_LEVEL_NONE = 0
val LOG_LEVEL_ERROR = 1
val LOG_LEVEL_WARN = 2
val LOG_LEVEL_INFO = 3
val LOG_LEVEL_DEBUG = 4
val LOG_LEVEL_VERBOSE = 5
var level = LOG_LEVEL_NONE
}
fun e(message: String) {
if (level >= LOG_LEVEL_ERROR) println("|ERR|$tag|$message")
}
fun w(message: String) {
if (level >= LOG_LEVEL_WARN) println("|WRN|$tag|$message")
}
fun i(message: String) {
if (level >= LOG_LEVEL_INFO) println("|INF|$tag|$message")
}
fun d(message: String) {
if (level >= LOG_LEVEL_DEBUG) println("|DBG|$tag|$message")
}
fun v(message: String) {
if (level >= LOG_LEVEL_VERBOSE) println("|VRB|$tag|$message")
}
inline fun <T> trace(body: () -> T): T {
val callerName = if (level >= LOG_LEVEL_DEBUG) {
Throwable().stackTrace[0].methodName
} else {
null
}
try {
callerName?.let {
d("$callerName start")
}
return body()
}
finally {
callerName?.let {
d("$callerName end")
}
}
}
}
| project/src/main/kotlin/com/ryuta46/evalspecmaker/util/Logger.kt | 586114555 |
package com.izeni.rapidocommon.recycler
import android.support.annotation.LayoutRes
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.izeni.rapidocommon.view.inflate
import com.izeni.rapidocommon.recycler.SectionManager.SectionData
/**
* Created by ner on 1/2/17.
*/
//TODO Need to make it so section headers span the recycler view when using a GridLayoutManager
abstract class MultiTypeSectionedAdapter(sections: List<Section<*>>,
private val sectionHeader: SectionedViewHolderData<SectionData>? = null) :
RecyclerView.Adapter<SectionedViewHolder<*>>() {
companion object {
val HEADER = -1
}
private val sectionManager by lazy { SectionManager(this, sections) }
init {
if (sectionHeader == null && sectionManager.hasHeaders())
throw IllegalStateException("One of your sections has a header but there was no SectionedViewHolderData passed for section headers")
}
override fun getItemViewType(position: Int): Int {
return sectionManager.getViewHolderType(position)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SectionedViewHolder<*> {
if (viewType == HEADER)
return sectionHeader!!.createViewHolder(parent)
else
return sectionManager.createViewHolder(parent, viewType)
}
override fun onBindViewHolder(holder: SectionedViewHolder<*>, position: Int) {
val type = getItemViewType(position)
if (type == HEADER)
sectionManager.bindHeader(holder, position)
else
sectionManager.bind(holder, position)
}
override fun getItemCount() = sectionManager.count
fun collapseSection(sectionType: Int) {
sectionManager.collapseSection(sectionType)
}
fun expandSection(sectionType: Int) {
sectionManager.expandSection(sectionType)
}
fun addItem(sectionType: Int, item: Any) {
sectionManager.addItem(sectionType, item)
}
fun addItemAt(index: Int, sectionType: Int, item: Any) {
sectionManager.addItemAt(index, sectionType, item)
}
fun addItems(sectionType: Int, items: List<Any>) {
sectionManager.addItems(sectionType, items)
}
fun removeItem(sectionType: Int, item: Any) {
sectionManager.removeItem(sectionType, item)
}
class SectionedViewHolderData<T>(@LayoutRes val layoutId: Int, val viewHolder: (View) -> SectionedViewHolder<T>) {
fun createViewHolder(parent: ViewGroup): SectionedViewHolder<T> {
return viewHolder(parent.inflate(layoutId))
}
}
@Suppress("UNCHECKED_CAST")
abstract class Section<T>(val type: Int,
private val items: MutableList<T>,
val viewHolderData: SectionedViewHolderData<T>,
val hasHeader: Boolean = false,
val isCollapsible: Boolean = false) {
val count: Int
get() = if (isCollapsed) 0 else items.size
val headerCount = if (hasHeader) 1 else 0
var isCollapsed = false
set(value) { if (isCollapsible) field = value }
fun bind(viewHolder: SectionedViewHolder<*>, position: Int) {
(viewHolder as SectionedViewHolder<T>).bind(items[position])
}
fun bindHeader(viewHolder: SectionedViewHolder<*>) {
(viewHolder as SectionedViewHolder<SectionData>).bind(SectionData(type, items.size, isCollapsed))
}
fun addItem(item: Any) {
items.add(item as T)
}
fun addItemAt(index: Int, item: Any) {
items.add(index, item as T)
}
fun addItems(items: List<Any>) {
this.items.addAll(items as List<T>)
}
fun removeItem(item: Any): Int {
val index = items.indexOf(item as T)
items.removeAt(index)
return index
}
}
} | rapidocommon/src/main/java/com/izeni/rapidocommon/recycler/MultiTypeSectionedAdapter.kt | 2013410117 |
/*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.taskdefs.Checksum
import org.apache.tools.ant.types.ResourceCollection
import org.apache.tools.ant.types.selectors.AndSelector
import org.apache.tools.ant.types.selectors.ContainsRegexpSelector
import org.apache.tools.ant.types.selectors.ContainsSelector
import org.apache.tools.ant.types.selectors.DateSelector
import org.apache.tools.ant.types.selectors.DependSelector
import org.apache.tools.ant.types.selectors.DepthSelector
import org.apache.tools.ant.types.selectors.DifferentSelector
import org.apache.tools.ant.types.selectors.ExtendSelector
import org.apache.tools.ant.types.selectors.FileSelector
import org.apache.tools.ant.types.selectors.FilenameSelector
import org.apache.tools.ant.types.selectors.MajoritySelector
import org.apache.tools.ant.types.selectors.NoneSelector
import org.apache.tools.ant.types.selectors.NotSelector
import org.apache.tools.ant.types.selectors.OrSelector
import org.apache.tools.ant.types.selectors.PresentSelector
import org.apache.tools.ant.types.selectors.SelectSelector
import org.apache.tools.ant.types.selectors.SizeSelector
import org.apache.tools.ant.types.selectors.TypeSelector
import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
fun Ant.checksum(
file: String? = null,
todir: String? = null,
algorithm: String? = null,
provider: String? = null,
fileext: String? = null,
property: String? = null,
totalproperty: String? = null,
verifyproperty: String? = null,
forceoverwrite: Boolean? = null,
readbuffersize: Int? = null,
format: FormatElement? = null,
pattern: String? = null,
includes: String? = null,
excludes: String? = null,
defaultexcludes: Boolean? = null,
includesfile: String? = null,
excludesfile: String? = null,
casesensitive: Boolean? = null,
followsymlinks: Boolean? = null,
nested: (KChecksum.() -> Unit)? = null)
{
Checksum().execute("checksum") { task ->
if (file != null)
task.setFile(project.resolveFile(file))
if (todir != null)
task.setTodir(project.resolveFile(todir))
if (algorithm != null)
task.setAlgorithm(algorithm)
if (provider != null)
task.setProvider(provider)
if (fileext != null)
task.setFileext(fileext)
if (property != null)
task.setProperty(property)
if (totalproperty != null)
task.setTotalproperty(totalproperty)
if (verifyproperty != null)
task.setVerifyproperty(verifyproperty)
if (forceoverwrite != null)
task.setForceOverwrite(forceoverwrite)
if (readbuffersize != null)
task.setReadBufferSize(readbuffersize)
if (format != null)
task.setFormat(Checksum.FormatElement().apply { this.value = format.value })
if (pattern != null)
task.setPattern(pattern)
if (includes != null)
task.setIncludes(includes)
if (excludes != null)
task.setExcludes(excludes)
if (defaultexcludes != null)
task.setDefaultexcludes(defaultexcludes)
if (includesfile != null)
task.setIncludesfile(project.resolveFile(includesfile))
if (excludesfile != null)
task.setExcludesfile(project.resolveFile(excludesfile))
if (casesensitive != null)
task.setCaseSensitive(casesensitive)
if (followsymlinks != null)
task.setFollowSymlinks(followsymlinks)
if (nested != null)
nested(KChecksum(task))
}
}
class KChecksum(override val component: Checksum) :
IFileSelectorNested,
IResourceCollectionNested,
ISelectSelectorNested,
IAndSelectorNested,
IOrSelectorNested,
INotSelectorNested,
INoneSelectorNested,
IMajoritySelectorNested,
IDateSelectorNested,
ISizeSelectorNested,
IFilenameSelectorNested,
IExtendSelectorNested,
IContainsSelectorNested,
IPresentSelectorNested,
IDepthSelectorNested,
IDependSelectorNested,
IContainsRegexpSelectorNested,
IDifferentSelectorNested,
ITypeSelectorNested,
IModifiedSelectorNested
{
fun include(name: String? = null, If: String? = null, unless: String? = null) {
component.createInclude().apply {
_init(name, If, unless)
}
}
fun includesfile(name: String? = null, If: String? = null, unless: String? = null) {
component.createIncludesFile().apply {
_init(name, If, unless)
}
}
fun exclude(name: String? = null, If: String? = null, unless: String? = null) {
component.createExclude().apply {
_init(name, If, unless)
}
}
fun excludesfile(name: String? = null, If: String? = null, unless: String? = null) {
component.createExcludesFile().apply {
_init(name, If, unless)
}
}
fun patternset(includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, nested: (KPatternSet.() -> Unit)? = null) {
component.createPatternSet().apply {
component.project.setProjectReference(this)
_init(includes, excludes, includesfile, excludesfile, nested)
}
}
override fun _addFileSelector(value: FileSelector) = component.add(value)
override fun _addResourceCollection(value: ResourceCollection) = component.add(value)
override fun _addSelectSelector(value: SelectSelector) = component.addSelector(value)
override fun _addAndSelector(value: AndSelector) = component.addAnd(value)
override fun _addOrSelector(value: OrSelector) = component.addOr(value)
override fun _addNotSelector(value: NotSelector) = component.addNot(value)
override fun _addNoneSelector(value: NoneSelector) = component.addNone(value)
override fun _addMajoritySelector(value: MajoritySelector) = component.addMajority(value)
override fun _addDateSelector(value: DateSelector) = component.addDate(value)
override fun _addSizeSelector(value: SizeSelector) = component.addSize(value)
override fun _addFilenameSelector(value: FilenameSelector) = component.addFilename(value)
override fun _addExtendSelector(value: ExtendSelector) = component.addCustom(value)
override fun _addContainsSelector(value: ContainsSelector) = component.addContains(value)
override fun _addPresentSelector(value: PresentSelector) = component.addPresent(value)
override fun _addDepthSelector(value: DepthSelector) = component.addDepth(value)
override fun _addDependSelector(value: DependSelector) = component.addDepend(value)
override fun _addContainsRegexpSelector(value: ContainsRegexpSelector) = component.addContainsRegexp(value)
override fun _addDifferentSelector(value: DifferentSelector) = component.addDifferent(value)
override fun _addTypeSelector(value: TypeSelector) = component.addType(value)
override fun _addModifiedSelector(value: ModifiedSelector) = component.addModified(value)
}
enum class FormatElement(val value: String) { CHECKSUM("CHECKSUM"), MD5SUM("MD5SUM"), SVF("SVF") }
| src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/checksum.kt | 2469758987 |
/*
* Copyright @ 2018 - present 8x8, 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 org.jitsi.nlj.rtp
import org.jitsi.nlj.util.BufferPool
import org.jitsi.rtp.rtp.RtpHeader
class PaddingVideoPacket private constructor(
buffer: ByteArray,
offset: Int,
length: Int
) : VideoRtpPacket(buffer, offset, length) {
override fun clone(): PaddingVideoPacket =
throw NotImplementedError("clone() not supported for padding packets.")
companion object {
/**
* Creating a PaddingVideoPacket by directly grabbing a buffer in its
* ctor is problematic because we cannot clear the buffer we retrieve
* before calling the parent class' constructor. Because the buffer
* may contain invalid data, any attempts to parse it by parent class(es)
* could fail, so we use a helper here instead
*/
fun create(length: Int): PaddingVideoPacket {
val buf = BufferPool.getBuffer(length)
// It's possible we the buffer we pulled from the pool already has
// data in it, and we won't be overwriting it with anything so clear
// out the data
buf.fill(0, 0, length)
return PaddingVideoPacket(buf, 0, length).apply {
// Recalculate the header length now that we've zero'd everything out
// and set the fields
version = RtpHeader.VERSION
headerLength = RtpHeader.getTotalLength(buffer, offset)
paddingSize = payloadLength
}
}
}
}
| jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/rtp/PaddingVideoPacket.kt | 2078605266 |
package mil.nga.giat.mage.observation.sync
import android.content.Context
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.hilt.work.HiltWorker
import androidx.work.*
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import mil.nga.giat.mage.MageApplication
import mil.nga.giat.mage.R
import mil.nga.giat.mage.data.observation.AttachmentRepository
import mil.nga.giat.mage.sdk.datastore.observation.AttachmentHelper
import java.io.IOException
import java.net.HttpURLConnection
import java.util.concurrent.TimeUnit
@HiltWorker
class AttachmentSyncWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val attachmentRepository: AttachmentRepository
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
// Lock to ensure previous running work will complete when cancelled before new work is started.
return mutex.withLock {
val result = try {
syncAttachments()
} catch (e: Exception) {
Log.e(LOG_NAME, "Failed to sync attachments", e)
RESULT_RETRY_FLAG
}
if (result.containsFlag(RESULT_RETRY_FLAG)) Result.retry() else Result.success()
}
}
override suspend fun getForegroundInfo(): ForegroundInfo {
val notification = NotificationCompat.Builder(applicationContext, MageApplication.MAGE_NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_sync_preference_24dp)
.setContentTitle("Sync Attachments")
.setContentText("Pushing attachments to MAGE.")
.setPriority(NotificationCompat.PRIORITY_MAX)
.setAutoCancel(true)
.build()
return ForegroundInfo(ATTACHMENT_SYNC_NOTIFICATION_ID, notification)
}
private suspend fun syncAttachments(): Int {
var result = RESULT_SUCCESS_FLAG
val attachmentHelper = AttachmentHelper.getInstance(applicationContext)
for (attachment in attachmentHelper.dirtyAttachments.filter { !it.observation.remoteId.isNullOrEmpty() && it.url.isNullOrEmpty() }) {
val response = attachmentRepository.syncAttachment(attachment)
result = if (response.isSuccessful) {
Result.success()
} else {
if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
Result.failure()
} else {
Result.retry()
}
}.withFlag(result)
}
return result
}
private fun Result.withFlag(flag: Int): Int {
return when (this) {
is Result.Success -> RESULT_FAILURE_FLAG or flag
is Result.Retry -> RESULT_RETRY_FLAG or flag
else -> RESULT_SUCCESS_FLAG or flag
}
}
private fun Int.containsFlag(flag: Int): Boolean {
return (this or flag) == this
}
companion object {
private val LOG_NAME = AttachmentSyncWorker::class.java.simpleName
private const val RESULT_SUCCESS_FLAG = 0
private const val RESULT_FAILURE_FLAG = 1
private const val RESULT_RETRY_FLAG = 2
private const val ATTACHMENT_SYNC_WORK = "mil.nga.mage.ATTACHMENT_SYNC_WORK"
private const val ATTACHMENT_SYNC_NOTIFICATION_ID = 200
private val mutex = Mutex()
fun scheduleWork(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = OneTimeWorkRequest.Builder(AttachmentSyncWorker::class.java)
.setConstraints(constraints)
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
.setBackoffCriteria(BackoffPolicy.LINEAR, 15, TimeUnit.SECONDS)
.build()
WorkManager
.getInstance(context)
.beginUniqueWork(ATTACHMENT_SYNC_WORK, ExistingWorkPolicy.REPLACE, request)
.enqueue()
}
}
} | mage/src/main/java/mil/nga/giat/mage/observation/sync/AttachmentSyncWorker.kt | 86725799 |
package tileentity.heat
import com.cout970.magneticraft.api.internal.energy.ElectricNode
import com.cout970.magneticraft.api.internal.heat.HeatContainer
import com.cout970.magneticraft.config.Config
import com.cout970.magneticraft.gui.common.DATA_ID_MACHINE_WORKING
import com.cout970.magneticraft.misc.ElectricConstants
import com.cout970.magneticraft.misc.network.IBD
import com.cout970.magneticraft.misc.tileentity.ITileTrait
import com.cout970.magneticraft.misc.tileentity.TraitElectricity
import com.cout970.magneticraft.misc.tileentity.TraitHeat
import com.cout970.magneticraft.tileentity.TileBase
import com.cout970.magneticraft.util.*
import com.teamwizardry.librarianlib.common.util.autoregister.TileRegister
import net.minecraftforge.fml.relauncher.Side
/**
* Created by cout970 on 04/07/2016.
*/
@TileRegister("electric_heater")
class TileElectricHeater : TileBase() {
var mainNode = ElectricNode({ world }, { pos }, capacity = 1.25)
val traitElectricity = TraitElectricity(this, listOf(mainNode))
val heat = HeatContainer(dissipation = 0.0,
specificHeat = COPPER_HEAT_CAPACITY * 3,
maxHeat = COPPER_HEAT_CAPACITY * 3 * COPPER_MELTING_POINT,
conductivity = DEFAULT_CONDUCTIVITY,
worldGetter = { this.world },
posGetter = { this.getPos() })
val traitHeat: TraitHeat = TraitHeat(this, listOf(heat))
override val traits: List<ITileTrait> = listOf(traitHeat, traitElectricity)
override fun update() {
if (worldObj.isServer) {
if (mainNode.voltage >= ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE && heat.heat < heat.maxHeat) {
val power = -Config.electricHeaterMaxConsumption * interpolate(mainNode.voltage, 60.0, 70.0)
val applied = mainNode.applyPower(power, false)
val energy = applied.toFloat()
heat.applyHeat((energy * ENERGY_TO_HEAT).toDouble(), false)
}
}
super.update()
}
override fun receiveSyncData(data: IBD, side: Side) {
super.receiveSyncData(data, side)
if (side == Side.SERVER) {
data.getDouble(DATA_ID_MACHINE_WORKING, { heat.heat = it })
}
}
} | ignore/test/tileentity/heat/TileElectricHeater.kt | 2564848399 |
package com.jetbrains.rider.plugins.unity.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.jetbrains.rider.plugins.unity.run.UnityProcessPickerDialog
class AttachToUnityProcessAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project?: return
val dialog = UnityProcessPickerDialog(project)
dialog.show()
}
} | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/actions/AttachToUnityProcessAction.kt | 2036988887 |
package github.nisrulz.example.usingparcelize
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Person(
val name: String = "",
val address: String = "",
val age: Int = 0,
val occupation: String = ""
) : Parcelable {
override fun toString(): String {
return "Name: $name" +
"\nAge: $age" +
"\nAddress: $address" +
"\nOccupation: $occupation"
}
} | UsingParcelize/app/src/main/java/github/nisrulz/example/usingparcelize/Person.kt | 325658334 |
// Copyright 2020 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.common.testing
import java.time.Clock
import java.time.Instant
import java.time.ZoneId
/**
* An implementation of [Clock] that returns a predetermined underlying [Instant] which may be
* changed. Each change of the [Instant] with this [Clock] is named so it can be referred to in a
* test.
*/
class TestClockWithNamedInstants(start: Instant) : Clock() {
private val ticks = linkedMapOf("start" to start)
override fun instant(): Instant = last()
operator fun get(name: String): Instant = ticks[name] ?: error("No named test instant for $name")
fun last() = ticks.toList().last().second
/** Adds a tick event to the clock and ticks the clock forward by some fixed amount of seconds. */
fun tickSeconds(name: String, seconds: Long = 1) {
require(seconds > 0) { "Must tick by positive seconds" }
require(name !in ticks) { "May not reuse name of instant $name" }
ticks[name] = last().plusSeconds(seconds)
}
override fun withZone(zone: ZoneId?): Clock = error("Not implemented")
override fun getZone() = error("Not implemented")
}
| src/main/kotlin/org/wfanet/measurement/common/testing/TestClockWithNamedInstants.kt | 2365714830 |
package com.waz.zclient.pages.extendedcursor.voicefilter2
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.waz.zclient.R
class WaveBinView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0):
View(context, attrs, defStyleAttr) {
private var duration: Long = 0
private var currentHead: Long = 0
private val activePaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val inactivePaint: Paint
private var levels: FloatArray? = null
private val binWidth: Int
private val binSpaceWidth: Int
init {
activePaint.color = Color.BLUE
inactivePaint = Paint(Paint.ANTI_ALIAS_FLAG)
inactivePaint.color = Color.WHITE
binWidth = resources.getDimensionPixelSize(R.dimen.wave_graph_bin_width)
binSpaceWidth = resources.getDimensionPixelSize(R.dimen.wave_graph_bin_space_width)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (levels == null) {
return
}
val maxNumOfLevels = levels!!.size
val size = levels!!.size
val totalBinWidth = size * binWidth + (size - 1) * binSpaceWidth
val height = canvas.height
val width = canvas.width
var currentX = (width - totalBinWidth) / 2
val breakPoint = (maxNumOfLevels.toFloat() * currentHead.toFloat() * 1.0f / duration).toInt()
for (i in 0 until breakPoint) {
if (i > maxNumOfLevels - 1) {
return
}
var lh = levels!![i] * height
if (lh < binWidth) {
lh = binWidth.toFloat()
}
val top = (height - lh) / 2
canvas.drawRect(
currentX.toFloat(),
top,
(currentX + binWidth).toFloat(),
(top + lh),
activePaint)
currentX += binWidth + binSpaceWidth
}
for (i in breakPoint until maxNumOfLevels) {
var lh = levels!![i] * height
if (lh < binWidth) {
lh = binWidth.toFloat()
}
val top = (height - lh) / 2
canvas.drawRect(
currentX.toFloat(),
top,
(currentX + binWidth).toFloat(),
(top + lh),
inactivePaint)
currentX += binWidth + binSpaceWidth
}
}
fun setAccentColor(accentColor: Int) {
activePaint.color = accentColor
}
fun setAudioLevels(levels: FloatArray) {
this.levels = levels
}
fun setAudioPlayingProgress(current: Long, total: Long) {
this.currentHead = current
this.duration = total
postInvalidate()
}
}
| app/src/main/java/com/waz/zclient/pages/extendedcursor/voicefilter2/WaveBinView.kt | 2900687471 |
package com.github.telegram.domain
import com.google.gson.annotations.SerializedName as Name
/**
* This object represents a message.
*
* @property messageId Unique message identifier.
* @property from Sender, can be empty for messages sent to channels.
* @property date Date the message was sent in Unix time.
* @property chat Conversation the message belongs to.
* @property forwardFrom For forwarded messages, sender of the original message.
* @property forwardFromChat For messages forwarded from a channel, information about the original channel.
* @property forwardDate For forwarded messages, date the original message was sent in Unix time.
* @property replyToMessage For replies, the original message.
* Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply.
* @property editDate the message was last edited in Unix time.
* @property text For text messages, the actual UTF-8 text of the message, 0-4096 characters.
* @property entities List of For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text.
* @property audio Message is an audio file, information about the file.
* @property document Message is a general file, information about the file.
* @property photo List of Message is a photo, available sizes of the photo.
* @property sticker Message is a sticker, information about the sticker.
* @property video Message is a video, information about the video.
* @property voice Message is a voice message, information about the file.
* @property caption Caption for the document, photo or video, 0-200 characters.
* @property contact Message is a shared contact, information about the contact.
* @property location Message is a shared location, information about the location.
* @property venue Message is a venue, information about the venue.
* @property newChatMember A new member was added to the group, information about them (this member may be the bot itself).
* @property leftChatMember A member was removed from the group, information about them (this member may be the bot itself).
* @property newChatTitle A chat title was changed to this value.
* @property newChatPhoto List of A chat photo was change to this value.
* @property deleteChatPhoto Service message: the chat photo was deleted.
* @property groupChatCreated Service message: the group has been created.
* @property supergroupChatCreated Service message: the supergroup has been created.
* This field can‘t be received in a message coming through updates, because bot can’t be a member of a supergroup when it is created.
* It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup.
* @property channelChatCreated Service message: the channel has been created.
* This field can‘t be received in a message coming through updates, because bot can’t be a member of a channel when it is created.
* It can only be found in reply_to_message if someone replies to a very first message in a channel.
* @property migrateToChatId The group has been migrated to a supergroup with the specified identifier.
* @property migrateFromChatId The supergroup has been migrated from a group with the specified identifier.
* @property pinnedMessage Specified message was pinned.
* Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply.
*/
data class Message(
@Name("message_id") val messageId: Long,
@Name("from") val from: User?,
@Name("date") val date: Int,
@Name("chat") val chat: Chat,
@Name("forward_from") val forwardFrom: User?,
@Name("forward_from_chat") val forwardFromChat: Chat?,
@Name("forward_from_message_id") val forwardFromMessageId: Int?,
@Name("forward_signature") val forwardSignature: String?,
@Name("forward_date") val forwardDate: Int?,
@Name("reply_to_message") val replyToMessage: Message?,
@Name("edit_date") val editDate: Int?,
@Name("media_group_id") val mediaGroupId: String?,
@Name("author_signature") val authorSignature: String?,
@Name("text") val text: String?,
@Name("entities") val entities: List<MessageEntity>?,
@Name("caption_entities") val captionEntities: List<MessageEntity>?,
@Name("audio") val audio: Audio?,
@Name("document") val document: Document?,
@Name("photo") val photo: List<PhotoSize>?,
// todo: game
@Name("sticker") val sticker: Sticker?,
@Name("video") val video: Video?,
@Name("voice") val voice: Voice?,
// todo: video_note
@Name("caption") val caption: String?,
@Name("contact") val contact: Contact?,
@Name("location") val location: Location?,
@Name("venue") val venue: Venue?,
@Name("new_chat_member") val newChatMember: User?,
@Name("left_chat_member") val leftChatMember: User?,
@Name("new_chat_title") val newChatTitle: String?,
@Name("new_chat_photo") val newChatPhoto: List<PhotoSize>?,
@Name("delete_chat_photo") val deleteChatPhoto: Boolean,
@Name("group_chat_created") val groupChatCreated: Boolean,
@Name("supergroup_chat_created") val supergroupChatCreated: Boolean,
@Name("channel_chat_created") val channelChatCreated: Boolean,
@Name("migrate_to_chat_id") val migrateToChatId: Int?,
@Name("migrate_from_chat_id") val migrateFromChatId: Int?,
@Name("pinned_message") val pinnedMessage: Message?,
@Name("connected_website") val connectedWebsite: String?) | telegram-bot-api/src/main/kotlin/com/github/telegram/domain/Message.kt | 2560257665 |
package com.freaklius.kotlin.algorithms.sort
import java.util.LinkedList
/**
* Bucket sort algorithm
* Average performance = O(n)
*/
class BucketSort : SortAlgorithm {
override fun sort(arr: Array<Long>): Array<Long> {
//Number of buckets can depend on input array size
val numberOfBuckets = if (arr.size > 100) Math.floor(arr.size / 10.0).toInt() else 10
val outputArray = arr
val sortArray = Array<LinkedList<Long>>(numberOfBuckets, { i -> LinkedList()}) //We need to store digits in range 0..9
val maxArrayValue = maximum(arr)
for (i in 0..arr.size - 1){
val value = arr[i]
var valueIndex = Math.floor((numberOfBuckets * (value / maxArrayValue)).toDouble()).toInt() // It's a number in range 0..9
if (valueIndex == arr.size){
valueIndex = arr.size - 1 //Maximum values go to the last bucket
}
sortArray[valueIndex].add(value)
}
var outputArrayIndex = 0
for (list in sortArray){
if (list.size > 0){
val arrayFromList = Array<Long>(list.size, { i -> list.get(i)})
for (value in InsertionSort().sort(arrayFromList)){
outputArray[outputArrayIndex] = value
outputArrayIndex++
}
}
}
return outputArray
}
override fun getName(): String {
return "BucketSort"
}
} | src/com/freaklius/kotlin/algorithms/sort/BucketSort.kt | 3859886663 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rustSlowTests
import org.rust.cargo.RustWithToolchainTestBase
import org.rust.cargo.project.model.cargoProjects
import org.rust.fileTree
import org.rust.openapiext.pathAsPath
import java.util.concurrent.TimeUnit
class CargoProjectServiceTest : RustWithToolchainTestBase() {
fun `test finds project for file`() {
val testProject = fileTree {
dir("a") {
toml("Cargo.toml", """
[package]
name = "a"
version = "0.1.0"
authors = []
""")
dir("src") {
rust("lib.rs", "")
}
}
dir("b") {
toml("Cargo.toml", """
[package]
name = "b"
version = "0.1.0"
authors = []
[workspace]
members = ["../c"]
[dependencies]
a = { path = "../a" }
d = { path = "../d" }
""")
dir("src") {
rust("lib.rs", "")
}
}
dir("c") {
toml("Cargo.toml", """
[package]
name = "c"
version = "0.1.0"
authors = []
workspace = "../b"
""")
dir("src") {
rust("lib.rs", "")
}
}
dir("d") {
toml("Cargo.toml", """
[package]
name = "d"
version = "0.1.0"
authors = []
""")
dir("src") {
rust("lib.rs", "")
}
}
}.create(project, cargoProjectDirectory)
val rootPath = testProject.root.pathAsPath
val projects = project.cargoProjects.apply {
attachCargoProject(rootPath.resolve("a/Cargo.toml"))
attachCargoProject(rootPath.resolve("b/Cargo.toml"))
attachCargoProject(rootPath.resolve("d/Cargo.toml"))
refreshAllProjects().get(1, TimeUnit.MINUTES)
}
fun checkFile(relpath: String, projectName: String?) {
val vFile = testProject.root.findFileByRelativePath(relpath)!!
val project = projects.findProjectForFile(vFile)
if (project?.presentableName != projectName) {
error("Expected $projectName, found $project for $relpath")
}
}
checkFile("a/src/lib.rs", "a")
checkFile("b/src/lib.rs", "b")
checkFile("c/src/lib.rs", "b")
checkFile("d/src/lib.rs", "d")
}
}
| src/test/kotlin/org/rustSlowTests/CargoProjectServiceTest.kt | 3655910209 |
package org.jetbrains.dokka.allModulesPage.templates
import org.jetbrains.dokka.DokkaConfiguration.DokkaModuleDescription
import org.jetbrains.dokka.base.renderers.html.SearchRecord
import org.jetbrains.dokka.base.templating.AddToSearch
import org.jetbrains.dokka.base.templating.parseJson
import org.jetbrains.dokka.base.templating.toJsonString
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.templates.TemplateProcessingStrategy
import java.io.File
import java.util.concurrent.ConcurrentHashMap
abstract class BaseJsonNavigationTemplateProcessingStrategy(val context: DokkaContext) : TemplateProcessingStrategy {
abstract val navigationFileNameWithoutExtension: String
abstract val path: String
private val fragments = ConcurrentHashMap<String, List<SearchRecord>>()
open fun canProcess(file: File): Boolean =
file.extension == "json" && file.nameWithoutExtension == navigationFileNameWithoutExtension
override fun process(input: File, output: File, moduleContext: DokkaModuleDescription?): Boolean {
val canProcess = canProcess(input)
if (canProcess) {
runCatching { parseJson<AddToSearch>(input.readText()) }.getOrNull()?.let { command ->
moduleContext?.relativePathToOutputDirectory
?.relativeToOrSelf(context.configuration.outputDir)
?.let { key ->
fragments[key.toString()] = command.elements
}
} ?: fallbackToCopy(input, output)
}
return canProcess
}
override fun finish(output: File) {
if (fragments.isNotEmpty()) {
val content = toJsonString(fragments.entries.flatMap { (moduleName, navigation) ->
navigation.map { it.withResolvedLocation(moduleName) }
})
output.resolve(path).mkdirs()
output.resolve("$path/$navigationFileNameWithoutExtension.json").writeText(content)
}
}
private fun fallbackToCopy(input: File, output: File) {
context.logger.warn("Falling back to just copying ${input.name} file even though it should have been processed")
input.copyTo(output)
}
private fun SearchRecord.withResolvedLocation(moduleName: String): SearchRecord =
copy(location = "$moduleName/$location")
}
class PagesSearchTemplateStrategy(val dokkaContext: DokkaContext) :
BaseJsonNavigationTemplateProcessingStrategy(dokkaContext) {
override val navigationFileNameWithoutExtension: String = "pages"
override val path: String = "scripts"
}
| plugins/templating/src/main/kotlin/templates/JsonElementBasedTemplateProcessingStrategy.kt | 3676550833 |
package com.artfable.telegram.api
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
/**
* @author aveselov
* @since 18/07/19
*/
@JsonIgnoreProperties(ignoreUnknown = true)
data class CallbackQuery(
@JsonProperty("id") val id: Long,
@JsonProperty("from") val from: User? = null,
@JsonProperty("data") val data: String? = null,
@JsonProperty("message") val message: Message? = null
) | src/main/kotlin/com/artfable/telegram/api/CallbackQuery.kt | 2655217451 |
package me.mrkirby153.KirBot.server.data
enum class CommandType {
JS,
TEXT
} | src/main/kotlin/me/mrkirby153/KirBot/server/data/CommandType.kt | 1692093866 |
package com.google.devtools.ksp.processor
import com.google.devtools.ksp.KspExperimental
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSNode
import com.google.devtools.ksp.symbol.KSPropertyDeclaration
import com.google.devtools.ksp.symbol.Modifier
import com.google.devtools.ksp.visitor.KSTopDownVisitor
class ConstPropertiesProcessor : AbstractTestProcessor() {
private val visitor = Visitor()
override fun toResult(): List<String> {
return visitor.constPropertiesNames.sorted()
}
@OptIn(KspExperimental::class)
override fun process(resolver: Resolver): List<KSAnnotated> {
resolver.getDeclarationsFromPackage("foo.compiled").forEach {
it.accept(visitor, Unit)
}
resolver.getNewFiles().forEach { it.accept(visitor, Unit) }
return emptyList()
}
private class Visitor : KSTopDownVisitor<Unit, Unit>() {
val constPropertiesNames = arrayListOf<String>()
override fun defaultHandler(node: KSNode, data: Unit) {
}
override fun visitPropertyDeclaration(property: KSPropertyDeclaration, data: Unit) {
if (Modifier.CONST in property.modifiers) {
constPropertiesNames += property.simpleName.asString()
}
}
}
}
| test-utils/src/main/kotlin/com/google/devtools/ksp/processor/ConstPropertiesProcessor.kt | 1387811722 |
import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.*
class NormalProcessor : SymbolProcessor {
lateinit var codeGenerator: CodeGenerator
lateinit var logger: KSPLogger
var rounds = 0
override fun onError() {
logger.error("NormalProcessor called error on $rounds")
}
fun init(
options: Map<String, String>,
kotlinVersion: KotlinVersion,
codeGenerator: CodeGenerator,
logger: KSPLogger
) {
this.logger = logger
this.codeGenerator = codeGenerator
}
override fun process(resolver: Resolver): List<KSAnnotated> {
rounds++
if (rounds == 1) {
codeGenerator.createNewFile(Dependencies.ALL_FILES, "test", "normal", "log")
}
return emptyList()
}
}
class TestProcessorProvider2 : SymbolProcessorProvider {
override fun create(
env: SymbolProcessorEnvironment
): SymbolProcessor {
return NormalProcessor().apply {
init(env.options, env.kotlinVersion, env.codeGenerator, env.logger)
}
}
}
| integration-tests/src/test/resources/on-error/on-error-processor/src/main/kotlin/NormalProcessor.kt | 3155442662 |
package org.ozinger.ika.definition
import kotlinx.serialization.Serializable
@Serializable
sealed class IMode
@Serializable
data class Mode(
val mode: Char,
val param: String? = null,
) : IMode()
@Serializable
data class MemberMode(
val target: UniversalUserId,
val mode: Char? = null,
) : IMode() {
constructor(target: String, mode: Char? = null) : this(UniversalUserId(target), mode)
}
@Serializable
data class EphemeralMemberMode(
val target: String,
val mode: Char? = null,
) : IMode()
typealias MutableModes = MutableSet<IMode>
typealias Modes = Set<IMode>
@Serializable
data class ModeChangelist<T : IMode>(
val adding: Set<T> = setOf(),
val removing: Set<T> = setOf(),
)
data class ModeDefinition(
val stackable: List<Char>,
val parameterized: List<Char>,
val parameterizedAdd: List<Char>,
val general: List<Char>,
) {
constructor(modeDefs: List<String>) : this(
modeDefs[0].toList(),
modeDefs[1].toList(),
modeDefs[2].toList(),
modeDefs[3].toList(),
)
constructor(modeDefString: String) : this(modeDefString.split(","))
}
| app/src/main/kotlin/org/ozinger/ika/definition/Mode.kt | 77828892 |
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.psi.element
import com.intellij.psi.stubs.StubElement
import com.vladsch.md.nav.psi.util.MdTypes
class MdReferenceStubImpl(parent: StubElement<*>, linkRefWithAnchor: String) :
MdLinkElementStubImpl<MdReference, MdReferenceStub>(parent, MdTypes.REFERENCE, linkRefWithAnchor),
MdReferenceStub
| src/main/java/com/vladsch/md/nav/psi/element/MdReferenceStubImpl.kt | 2049896755 |
package com.github.javiersantos.piracychecker.utils
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.content.pm.Signature
import android.opengl.GLES20
import android.os.Build
import android.os.Environment
import android.util.Base64
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import com.github.javiersantos.piracychecker.R
import com.github.javiersantos.piracychecker.enums.AppType
import com.github.javiersantos.piracychecker.enums.InstallerID
import com.github.javiersantos.piracychecker.enums.PirateApp
import java.io.File
import java.security.MessageDigest
import java.util.ArrayList
internal fun Context.buildUnlicensedDialog(title: String, content: String): AlertDialog? {
return (this as? Activity)?.let {
if (isFinishing) return null
AlertDialog.Builder(this)
.setCancelable(false)
.setTitle(title)
.setMessage(content)
.setPositiveButton(
getString(R.string.app_unlicensed_close),
DialogInterface.OnClickListener { _, _ ->
if (isFinishing)
return@OnClickListener
finish()
})
.create()
}
}
@Deprecated(
"Deprecated in favor of apkSignatures, which returns all valid signing signatures",
ReplaceWith("apkSignatures"))
val Context.apkSignature: Array<String>
get() = apkSignatures
val Context.apkSignatures: Array<String>
get() = currentSignatures
@Suppress("DEPRECATION", "RemoveExplicitTypeArguments")
private val Context.currentSignatures: Array<String>
get() {
val actualSignatures = ArrayList<String>()
val signatures: Array<Signature> = try {
val packageInfo =
packageManager.getPackageInfo(
packageName,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
PackageManager.GET_SIGNING_CERTIFICATES
else PackageManager.GET_SIGNATURES)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
if (packageInfo.signingInfo.hasMultipleSigners())
packageInfo.signingInfo.apkContentsSigners
else packageInfo.signingInfo.signingCertificateHistory
} else packageInfo.signatures
} catch (e: Exception) {
arrayOf<Signature>()
}
signatures.forEach { signature ->
val messageDigest = MessageDigest.getInstance("SHA")
messageDigest.update(signature.toByteArray())
try {
actualSignatures.add(
Base64.encodeToString(messageDigest.digest(), Base64.DEFAULT).trim())
} catch (e: Exception) {
}
}
return actualSignatures.filter { it.isNotEmpty() && it.isNotBlank() }.toTypedArray()
}
private fun Context.verifySigningCertificate(appSignature: String?): Boolean =
appSignature?.let { appSign -> currentSignatures.any { it == appSign } } ?: false
internal fun Context.verifySigningCertificates(appSignatures: Array<String>): Boolean {
var validCount = 0
appSignatures.forEach { if (verifySigningCertificate(it)) validCount += 1 }
return validCount >= appSignatures.size
}
internal fun Context.verifyInstallerId(installerID: List<InstallerID>): Boolean {
val validInstallers = ArrayList<String>()
val installer = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
packageManager.getInstallSourceInfo(packageName).installingPackageName
} else {
packageManager.getInstallerPackageName(packageName)
}
for (id in installerID) {
validInstallers.addAll(id.toIDs())
}
return installer != null && validInstallers.contains(installer)
}
@Suppress("DEPRECATION")
@SuppressLint("SdCardPath")
internal fun Context.getPirateApp(
lpf: Boolean,
stores: Boolean,
folders: Boolean,
apks: Boolean,
extraApps: ArrayList<PirateApp>
): PirateApp? {
if (!lpf && !stores && extraApps.isEmpty()) return null
val apps = getApps(extraApps)
var installed = false
var theApp: PirateApp? = null
try {
val pm = packageManager
val list = pm?.getInstalledApplications(PackageManager.GET_META_DATA)
for (app in apps) {
val checkLPF = lpf && app.type == AppType.PIRATE
val checkStore = stores && app.type == AppType.STORE
val checkOther = app.type == AppType.OTHER
if (checkLPF || checkStore || checkOther) {
installed = list?.any { it.packageName.contains(app.packageName) } ?: false
if (!installed) {
installed = isIntentAvailable(pm.getLaunchIntentForPackage(app.packageName))
}
}
if (installed) {
theApp = app
break
}
}
} catch (e: Exception) {
}
if ((folders || apks) && theApp == null) {
if (hasPermissions()) {
var apkExist = false
var foldersExist = false
var containsFolder = false
for (app in apps) {
val pack = app.packageName
try {
if (apks) {
val file1 = File("/data/app/$pack-1/base.apk")
val file2 = File("/data/app/$pack-2/base.apk")
val file3 = File("/data/app/$pack.apk")
val file4 = File("/data/data/$pack.apk")
apkExist = file1.exists() || file2.exists() ||
file3.exists() || file4.exists()
}
if (folders) {
val file5 = File("/data/data/$pack")
val file6 =
File(
"${Environment.getExternalStorageDirectory()}/Android/data/$pack")
foldersExist = file5.exists() || file6.exists()
val appsContainer = File("/data/app/")
if (appsContainer.exists()) {
for (f in appsContainer.listFiles().orEmpty()) {
if (f.name.startsWith(pack))
containsFolder = true
}
}
}
} catch (e: Exception) {
}
if (containsFolder || apkExist || foldersExist) {
theApp = app
break
}
}
}
}
return theApp
}
/**
* 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.
*
*
* Copyright (C) 2013, Vladislav Gingo Skoumal (http://www.skoumal.net)
*/
@Suppress("DEPRECATION")
internal fun isInEmulator(deepCheck: Boolean = false): Boolean {
var ratingCheckEmulator = 0
val product = try {
Build.PRODUCT
} catch (e: Exception) {
""
}
if (product.containsIgnoreCase("sdk") || product.containsIgnoreCase("Andy") ||
product.containsIgnoreCase("ttVM_Hdragon") || product.containsIgnoreCase("google_sdk") ||
product.containsIgnoreCase("Droid4X") || product.containsIgnoreCase("nox") ||
product.containsIgnoreCase("sdk_x86") || product.containsIgnoreCase("sdk_google") ||
product.containsIgnoreCase("vbox86p")) {
ratingCheckEmulator++
}
val manufacturer = try {
Build.MANUFACTURER
} catch (e: Exception) {
""
}
if (manufacturer.equalsIgnoreCase("unknown") || manufacturer.equalsIgnoreCase("Genymotion") ||
manufacturer.containsIgnoreCase("Andy") || manufacturer.containsIgnoreCase("MIT") ||
manufacturer.containsIgnoreCase("nox") || manufacturer.containsIgnoreCase("TiantianVM")) {
ratingCheckEmulator++
}
val brand = try {
Build.BRAND
} catch (e: Exception) {
""
}
if (brand.equalsIgnoreCase("generic") || brand.equalsIgnoreCase("generic_x86") ||
brand.equalsIgnoreCase("TTVM") || brand.containsIgnoreCase("Andy")) {
ratingCheckEmulator++
}
val device = try {
Build.DEVICE
} catch (e: Exception) {
""
}
if (device.containsIgnoreCase("generic") || device.containsIgnoreCase("generic_x86") ||
device.containsIgnoreCase("Andy") || device.containsIgnoreCase("ttVM_Hdragon") ||
device.containsIgnoreCase("Droid4X") || device.containsIgnoreCase("nox") ||
device.containsIgnoreCase("generic_x86_64") || device.containsIgnoreCase("vbox86p")) {
ratingCheckEmulator++
}
val model = try {
Build.MODEL
} catch (e: Exception) {
""
}
if (model.equalsIgnoreCase("sdk") || model.equalsIgnoreCase("google_sdk") ||
model.containsIgnoreCase("Droid4X") || model.containsIgnoreCase("TiantianVM") ||
model.containsIgnoreCase("Andy") || model.equalsIgnoreCase(
"Android SDK built for x86_64") ||
model.equalsIgnoreCase("Android SDK built for x86")) {
ratingCheckEmulator++
}
val hardware = try {
Build.HARDWARE
} catch (e: Exception) {
""
}
if (hardware.equalsIgnoreCase("goldfish") || hardware.equalsIgnoreCase("vbox86") ||
hardware.containsIgnoreCase("nox") || hardware.containsIgnoreCase("ttVM_x86")) {
ratingCheckEmulator++
}
val fingerprint = try {
Build.FINGERPRINT
} catch (e: Exception) {
""
}
if (fingerprint.containsIgnoreCase("generic") ||
fingerprint.containsIgnoreCase("generic/sdk/generic") ||
fingerprint.containsIgnoreCase("generic_x86/sdk_x86/generic_x86") ||
fingerprint.containsIgnoreCase("Andy") || fingerprint.containsIgnoreCase("ttVM_Hdragon") ||
fingerprint.containsIgnoreCase("generic_x86_64") ||
fingerprint.containsIgnoreCase("generic/google_sdk/generic") ||
fingerprint.containsIgnoreCase("vbox86p") ||
fingerprint.containsIgnoreCase("generic/vbox86p/vbox86p")) {
ratingCheckEmulator++
}
if (deepCheck) {
try {
GLES20.glGetString(GLES20.GL_RENDERER)?.let {
if (it.containsIgnoreCase("Bluestacks") || it.containsIgnoreCase("Translator"))
ratingCheckEmulator += 10
}
} catch (e: Exception) {
}
try {
val sharedFolder = File(
"${Environment.getExternalStorageDirectory()}${File.separatorChar}windows" +
"${File.separatorChar}BstSharedFolder")
if (sharedFolder.exists())
ratingCheckEmulator += 10
} catch (e: Exception) {
}
}
return ratingCheckEmulator > 3
}
internal fun Context.isDebug(): Boolean =
applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
private fun getApps(extraApps: ArrayList<PirateApp>): ArrayList<PirateApp> {
val apps = ArrayList<PirateApp>()
apps.add(
PirateApp(
"LuckyPatcher",
arrayOf(
"c", "o", "m", ".", "c", "h", "e", "l", "p", "u", "s", ".", "l", "a", "c", "k", "y",
"p", "a", "t", "c", "h"),
AppType.PIRATE))
apps.add(
PirateApp(
"LuckyPatcher",
arrayOf(
"c", "o", "m", ".", "d", "i", "m", "o", "n", "v", "i", "d", "e", "o", ".", "l", "u",
"c", "k", "y", "p", "a", "t", "c", "h", "e", "r"),
AppType.PIRATE))
apps.add(
PirateApp(
"LuckyPatcher",
arrayOf("c", "o", "m", ".", "f", "o", "r", "p", "d", "a", ".", "l", "p"),
AppType.PIRATE))
apps.add(
PirateApp(
"LuckyPatcher",
arrayOf(
"c", "o", "m", ".", "a", "n", "d", "r", "o", "i", "d", ".", "v", "e", "n", "d", "i",
"n", "g", ".", "b", "i", "l", "l", "i", "n", "g", ".", "I", "n", "A", "p", "p", "B",
"i", "l", "l", "i", "n", "g", "S", "e", "r", "v", "i", "c", "e"),
AppType.PIRATE))
apps.add(
PirateApp(
"LuckyPatcher",
arrayOf(
"c", "o", "m", ".", "a", "n", "d", "r", "o", "i", "d", ".", "v", "e", "n", "d", "i",
"n", "g", ".", "b", "i", "l", "l", "i", "n", "g", ".", "I", "n", "A", "p", "p", "B",
"i", "l", "l", "i", "n", "g", "S", "o", "r", "v", "i", "c", "e"),
AppType.PIRATE))
apps.add(
PirateApp(
"LuckyPatcher",
arrayOf(
"c", "o", "m", ".", "a", "n", "d", "r", "o", "i", "d", ".", "v", "e", "n", "d", "i",
"n", "c"),
AppType.PIRATE))
apps.add(
PirateApp(
"UretPatcher",
arrayOf(
"u", "r", "e", "t", ".", "j", "a", "s", "i", "2", "1", "6", "9", ".", "p", "a", "t",
"c", "h", "e", "r"),
AppType.PIRATE))
apps.add(
PirateApp(
"UretPatcher",
arrayOf(
"z", "o", "n", "e", ".", "j", "a", "s", "i", "2", "1", "6", "9", ".", "u", "r", "e",
"t", "p", "a", "t", "c", "h", "e", "r"),
AppType.PIRATE))
apps.add(
PirateApp(
"ActionLauncherPatcher",
arrayOf("p", ".", "j", "a", "s", "i", "2", "1", "6", "9", ".", "a", "l", "3"),
AppType.PIRATE))
apps.add(
PirateApp(
"Freedom",
arrayOf(
"c", "c", ".", "m", "a", "d", "k", "i", "t", "e", ".", "f", "r", "e", "e", "d", "o",
"m"),
AppType.PIRATE))
apps.add(
PirateApp(
"Freedom",
arrayOf(
"c", "c", ".", "c", "z", ".", "m", "a", "d", "k", "i", "t", "e", ".", "f", "r", "e",
"e", "d", "o", "m"),
AppType.PIRATE))
apps.add(
PirateApp(
"CreeHack",
arrayOf(
"o", "r", "g", ".", "c", "r", "e", "e", "p", "l", "a", "y", "s", ".", "h", "a", "c",
"k"),
AppType.PIRATE))
apps.add(
PirateApp(
"HappyMod",
arrayOf("c", "o", "m", ".", "h", "a", "p", "p", "y", "m", "o", "d", ".", "a", "p", "k"),
AppType.PIRATE))
apps.add(
PirateApp(
"Game Hacker",
arrayOf(
"o", "r", "g", ".", "s", "b", "t", "o", "o", "l", "s", ".", "g", "a", "m", "e", "h",
"a", "c", "k"),
AppType.PIRATE))
apps.add(
PirateApp(
"Game Killer Cheats",
arrayOf(
"c", "o", "m", ".", "z", "u", "n", "e", ".", "g", "a", "m", "e", "k", "i", "l", "l",
"e", "r"),
AppType.PIRATE))
apps.add(
PirateApp(
"AGK - App Killer",
arrayOf("c", "o", "m", ".", "a", "a", "g", ".", "k", "i", "l", "l", "e", "r"),
AppType.PIRATE))
apps.add(
PirateApp(
"Game Killer",
arrayOf(
"c", "o", "m", ".", "k", "i", "l", "l", "e", "r", "a", "p", "p", ".", "g", "a", "m",
"e", "k", "i", "l", "l", "e", "r"),
AppType.PIRATE))
apps.add(
PirateApp(
"Game Killer", arrayOf("c", "n", ".", "l", "m", ".", "s", "q"),
AppType.PIRATE))
apps.add(
PirateApp(
"Game CheatIng Hacker",
arrayOf(
"n", "e", "t", ".", "s", "c", "h", "w", "a", "r", "z", "i", "s", ".", "g", "a", "m",
"e", "_", "c", "i", "h"),
AppType.PIRATE))
apps.add(
PirateApp(
"Game Hacker",
arrayOf(
"c", "o", "m", ".", "b", "a", "s", "e", "a", "p", "p", "f", "u", "l", "l", ".", "f",
"w", "d"),
AppType.PIRATE))
apps.add(
PirateApp(
"Content Guard Disabler",
arrayOf(
"c", "o", "m", ".", "g", "i", "t", "h", "u", "b", ".", "o", "n", "e", "m", "i", "n",
"u", "s", "o", "n", "e", ".", "d", "i", "s", "a", "b", "l", "e", "c", "o", "n", "t",
"e", "n", "t", "g", "u", "a", "r", "d"),
AppType.PIRATE))
apps.add(
PirateApp(
"Content Guard Disabler",
arrayOf(
"c", "o", "m", ".", "o", "n", "e", "m", "i", "n", "u", "s", "o", "n", "e", ".", "d",
"i", "s", "a", "b", "l", "e", "c", "o", "n", "t", "e", "n", "t", "g", "u", "a", "r",
"d"),
AppType.PIRATE))
apps.add(
PirateApp(
"Aptoide", arrayOf("c", "m", ".", "a", "p", "t", "o", "i", "d", "e", ".", "p", "t"),
AppType.STORE))
apps.add(
PirateApp(
"BlackMart",
arrayOf(
"o", "r", "g", ".", "b", "l", "a", "c", "k", "m", "a", "r", "t", ".", "m", "a", "r",
"k", "e", "t"),
AppType.STORE))
apps.add(
PirateApp(
"BlackMart",
arrayOf(
"c", "o", "m", ".", "b", "l", "a", "c", "k", "m", "a", "r", "t", "a", "l", "p", "h",
"a"),
AppType.STORE))
apps.add(
PirateApp(
"Mobogenie",
arrayOf("c", "o", "m", ".", "m", "o", "b", "o", "g", "e", "n", "i", "e"),
AppType.STORE))
apps.add(
PirateApp(
"1Mobile",
arrayOf(
"m", "e", ".", "o", "n", "e", "m", "o", "b", "i", "l", "e", ".", "a", "n", "d", "r",
"o", "i", "d"),
AppType.STORE))
apps.add(
PirateApp(
"GetApk", arrayOf(
"c", "o", "m", ".", "r", "e", "p", "o", "d", "r", "o", "i", "d", ".", "a", "p", "p"),
AppType.STORE))
apps.add(
PirateApp(
"GetJar",
arrayOf(
"c", "o", "m", ".", "g", "e", "t", "j", "a", "r", ".", "r", "e", "w", "a", "r", "d",
"s"),
AppType.STORE))
apps.add(
PirateApp(
"SlideMe",
arrayOf(
"c", "o", "m", ".", "s", "l", "i", "d", "e", "m", "e", ".", "s", "a", "m", ".", "m",
"a", "n", "a", "g", "e", "r"),
AppType.STORE))
apps.add(
PirateApp(
"ACMarket",
arrayOf("n", "e", "t", ".", "a", "p", "p", "c", "a", "k", "e"),
AppType.STORE))
apps.add(
PirateApp(
"ACMarket",
arrayOf("a", "c", ".", "m", "a", "r", "k", "e", "t", ".", "s", "t", "o", "r", "e"),
AppType.STORE))
apps.add(
PirateApp(
"AppCake",
arrayOf("c", "o", "m", ".", "a", "p", "p", "c", "a", "k", "e"),
AppType.STORE))
apps.add(
PirateApp(
"Z Market",
arrayOf("c", "o", "m", ".", "z", "m", "a", "p", "p"),
AppType.STORE))
apps.add(
PirateApp(
"Modded Play Store",
arrayOf(
"c", "o", "m", ".", "d", "v", ".", "m", "a", "r", "k", "e", "t", "m", "o", "d", ".",
"i", "n", "s", "t", "a", "l", "l", "e", "r"),
AppType.STORE))
apps.add(
PirateApp(
"Mobilism Market",
arrayOf(
"o", "r", "g", ".", "m", "o", "b", "i", "l", "i", "s", "m", ".", "a", "n", "d", "r",
"o", "i", "d"),
AppType.STORE))
apps.add(
PirateApp(
"All-in-one Downloader", arrayOf(
"c", "o", "m", ".", "a", "l", "l", "i", "n", "o", "n", "e", ".", "f", "r", "e", "e"),
AppType.STORE))
apps.addAll(extraApps)
return ArrayList(apps.distinctBy { it.packageName })
}
private fun Context.isIntentAvailable(intent: Intent?): Boolean {
intent ?: return false
return try {
packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
.orEmpty().isNotEmpty()
} catch (e: Exception) {
false
}
}
private fun Context.hasPermissions(): Boolean {
return try {
Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN ||
!shouldAskPermission(Manifest.permission.READ_EXTERNAL_STORAGE) ||
!ActivityCompat.shouldShowRequestPermissionRationale(
this as Activity, Manifest.permission.READ_EXTERNAL_STORAGE)
} catch (e: Exception) {
false
}
}
private fun shouldAskPermission(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
private fun Context.shouldAskPermission(permission: String): Boolean {
if (shouldAskPermission()) {
val permissionResult = ActivityCompat.checkSelfPermission(this, permission)
return permissionResult != PackageManager.PERMISSION_GRANTED
}
return false
}
private fun String.equalsIgnoreCase(other: String) = this.equals(other, true)
private fun String.containsIgnoreCase(other: String) = this.contains(other, true) | library/src/main/java/com/github/javiersantos/piracychecker/utils/LibraryUtils.kt | 1424127605 |
import akka.util.ByteString
import com.amazonaws.services.rekognition.AmazonRekognitionAsyncClient
import com.amazonaws.services.rekognition.model.DetectModerationLabelsRequest
import com.amazonaws.services.rekognition.model.DetectModerationLabelsResult
import com.amazonaws.services.rekognition.model.Image
import org.apache.log4j.Logger
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletionStage
import java.util.concurrent.ExecutionException
import java.util.concurrent.Future
import javax.inject.Inject
class ModerationClient @Inject constructor(val asyncClient: AmazonRekognitionAsyncClient) {
private val logger = Logger.getLogger(ModerationClient::class.java)
fun callModerationService(bytes: ByteString): CompletionStage<DetectModerationLabelsResult> {
val moderationRequest = DetectModerationLabelsRequest()
.withImage(Image().withBytes(bytes.asByteBuffer()))
val resultFuture = asyncClient.detectModerationLabelsAsync(moderationRequest)
val completableFutureResult = makeCompletableFuture(resultFuture)
return completableFutureResult
}
//From https://stackoverflow.com/questions/23301598/transform-java-future-into-a-completablefuture
fun <T> makeCompletableFuture(future: Future<T>): CompletableFuture<T> {
return CompletableFuture.supplyAsync<T> {
try {
val startTime = System.currentTimeMillis()
return@supplyAsync future.get()
.apply { logger.info("Time to call moderation service:${System.currentTimeMillis() - startTime}") }
} catch (e: InterruptedException) {
throw RuntimeException(e)
} catch (e: ExecutionException) {
throw RuntimeException(e)
}
}
}
} | src/main/kotlin/ModerationClient.kt | 2069528060 |
package org.http4k.lens
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.throws
import org.http4k.cloudnative.env.Authority
import org.http4k.cloudnative.env.Host
import org.http4k.cloudnative.env.Port
import org.http4k.cloudnative.env.Secret
import org.http4k.cloudnative.env.Timeout
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.core.with
import org.http4k.lens.BiDiLensContract.checkContract
import org.http4k.lens.BiDiLensContract.spec
import org.junit.jupiter.api.Test
import java.time.Duration
class CloudNativeExtTest {
@Test
fun port() = checkContract(spec.port(), Port(123), "123", "", "invalid", "o", "o123", "o123123")
@Test
fun host() = checkContract(spec.host(), Host("localhost.com"), "localhost.com", "", null, "o", "olocalhost.com", "olocalhost.comlocalhost.com")
@Test
fun authority() = checkContract(spec.authority(), Authority(Host.localhost, Port(80)), "localhost:80", "", null, "o", "olocalhost:80", "olocalhost:80localhost:80")
@Test
fun timeout() = checkContract(spec.timeout(), Timeout(Duration.ofSeconds(35)), "PT35S", "", "invalid", "o", "oPT35S", "oPT35SPT35S")
@Test
fun secret() {
val requiredLens = spec.secret().required("hello")
assertThat(requiredLens("123"), equalTo(Secret("123".toByteArray())))
assertThat({ requiredLens("") }, throws(lensFailureWith<String>(Missing(requiredLens.meta), overallType = Failure.Type.Missing)))
}
@Test
fun `host header`() {
fun assertFormat(input: Authority) {
val reqWithHeader = Request(GET, "").with(Header.HOST of input)
assertThat(reqWithHeader.header("Host"), equalTo(input.toString()))
assertThat(Header.HOST(reqWithHeader), equalTo(input))
}
assertFormat(Authority(Host.localhost, Port(443)))
assertFormat(Authority(Host.localhost))
}
}
| http4k-cloudnative/src/test/kotlin/org/http4k/lens/CloudNativeExtTest.kt | 312656291 |
package me.retty.reduxkt.sample.redux.reducer
import me.retty.reduxkt.sample.redux.Reducer
import me.retty.reduxkt.sample.redux.action.TodoAction
/**
* Created by atsukofukui on 2017/08/23.
*/
class RootReducerSet {
companion object {
val aggregatedReducer: Reducer = { action, state ->
when (action) {
is TodoAction -> TodoReducerSet.aggregatedReducer(action, state)
else -> state
}
}
}
} | sample/app/src/main/kotlin/me/retty/reduxkt/sample/redux/reducer/RootReducerSet.kt | 2508748897 |
package org.http4k
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.http4k.core.Method.GET
import org.http4k.core.Method.POST
import org.http4k.core.Request
import org.http4k.core.body.toBody
import org.http4k.core.toCurl
import org.junit.jupiter.api.Test
class CurlTest {
@Test
fun `generates for simple get request`() {
val curl = Request(GET, "http://httpbin.org").toCurl()
assertThat(curl, equalTo("curl -X GET \"http://httpbin.org\""))
}
@Test
fun `generates for request with query`() {
val curl = Request(GET, "http://httpbin.org").query("a", "one two three").toCurl()
assertThat(curl, equalTo("""curl -X GET "http://httpbin.org?a=one+two+three""""))
}
@Test
fun `includes headers`() {
val curl = Request(GET, "http://httpbin.org").header("foo", "my header").toCurl()
assertThat(curl, equalTo("""curl -X GET -H "foo:my header" "http://httpbin.org""""))
}
@Test
fun `deals with headers with quotes`() {
val curl = Request(GET, "http://httpbin.org").header("foo", "my \"quoted\" header").toCurl()
assertThat(curl, equalTo("""curl -X GET -H "foo:my \"quoted\" header" "http://httpbin.org""""))
}
@Test
fun `includes body data`() {
val curl = Request(POST, "http://httpbin.org/post").body(listOf("foo" to "bar").toBody()).toCurl()
assertThat(curl, equalTo("""curl -X POST --data "foo=bar" "http://httpbin.org/post""""))
}
@Test
fun `escapes body form`() {
val curl = Request(GET, "http://httpbin.org").body(listOf("foo" to "bar \"quoted\"").toBody()).toCurl()
assertThat(curl, equalTo("""curl -X GET --data "foo=bar+%22quoted%22" "http://httpbin.org""""))
}
@Test
fun `escapes body string`() {
val curl = Request(GET, "http://httpbin.org").body("my \"quote\"").toCurl()
assertThat(curl, equalTo("""curl -X GET --data "my \"quote\"" "http://httpbin.org""""))
}
@Test
fun `does not realise stream body`() {
val request = Request(POST, "http://httpbin.org").body("any stream".byteInputStream())
val curl = request.toCurl()
assertThat(curl, equalTo("""curl -X POST --data "<<stream>>" "http://httpbin.org""""))
assertThat(String(request.body.stream.readBytes()), equalTo("any stream"))
}
@Test
fun `limits the entity if it's too large`() {
val largeBody = (0..500).joinToString(" ")
val curl = Request(GET, "http://httpbin.org").body(largeBody).toCurl(256)
val data = "data \"([^\"]+)\"".toRegex().find(curl)?.groupValues?.get(1)!!
assertThat(data.length, equalTo(256 + "[truncated]".length))
}
}
| http4k-core/src/test/kotlin/org/http4k/CurlTest.kt | 1137105659 |
package com.github.nukc.stateview
import android.content.Context
import android.os.Build
import android.util.DisplayMetrics
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.*
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.NestedScrollingChild
import androidx.core.view.NestedScrollingParent
import androidx.core.view.ScrollingView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
/**
* @author Nukc.
*/
internal object Injector {
val constraintLayoutAvailable = try {
null != Class.forName("androidx.constraintlayout.widget.ConstraintLayout")
} catch (e: Throwable) {
false
}
val swipeRefreshLayoutAvailable = try {
Class.forName("androidx.swiperefreshlayout.widget.SwipeRefreshLayout") != null
} catch (e: Throwable) {
false
}
/**
* Create a new FrameLayout (wrapper), let parent's remove children views, and add to the wrapper,
* stateVew add to wrapper, wrapper add to parent
*
* @param parent target
* @return [StateView]
*/
fun wrapChild(parent: ViewGroup): StateView {
// If there are other complex needs, maybe you can use stateView in layout(.xml)
var screenHeight = 0
// create a new FrameLayout to wrap StateView and parent's childView
val wrapper = FrameLayout(parent.context)
val layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
)
wrapper.layoutParams = layoutParams
if (parent is LinearLayout) {
// create a new LinearLayout to wrap parent's childView
val wrapLayout = LinearLayout(parent.context)
wrapLayout.layoutParams = parent.layoutParams ?: layoutParams
wrapLayout.orientation = parent.orientation
var i = 0
val childCount: Int = parent.getChildCount()
while (i < childCount) {
val childView: View = parent.getChildAt(0)
parent.removeView(childView)
wrapLayout.addView(childView)
i++
}
wrapper.addView(wrapLayout)
} else if (parent is ScrollView || parent is ScrollingView) {
// not recommended to inject Scrollview/NestedScrollView
if (parent.childCount != 1) {
throw IllegalStateException("the ScrollView does not have one direct child")
}
val directView = parent.getChildAt(0)
parent.removeView(directView)
wrapper.addView(directView)
val wm = parent.context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val metrics = DisplayMetrics()
wm.defaultDisplay.getMetrics(metrics)
screenHeight = metrics.heightPixels
} else if (parent is NestedScrollingParent && parent is NestedScrollingChild) {
if (parent.childCount == 2) {
val targetView = parent.getChildAt(1)
parent.removeView(targetView)
wrapper.addView(targetView)
} else if (parent.childCount > 2) {
throw IllegalStateException("the view is not refresh layout? view = $parent")
}
} else {
throw IllegalStateException("the view does not have parent, view = $parent")
}
// parent add wrapper
parent.addView(wrapper)
// StateView will be added to wrapper
val stateView = StateView(parent.context)
if (screenHeight > 0) {
// let StateView be shown in the center
val params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, screenHeight)
wrapper.addView(stateView, params)
} else {
wrapper.addView(stateView)
}
return stateView
}
/**
* Set StateView to be the same size and position as the target view,
* layoutParams should be use [ConstraintLayout.LayoutParams] (android.view.ViewGroup.LayoutParams)
*
* @param parent view's parent, [ConstraintLayout]
* @param view target view
* @return [StateView]
*/
fun matchViewIfParentIsConstraintLayout(parent: ConstraintLayout, view: View): StateView {
val stateView = StateView(parent.context)
val lp = ConstraintLayout.LayoutParams(view.layoutParams as ViewGroup.LayoutParams)
lp.leftToLeft = view.id
lp.rightToRight = view.id
lp.topToTop = view.id
lp.bottomToBottom = view.id
parent.addView(stateView, lp)
return stateView
}
/**
* Set StateView to be the same size and position as the target view, If parent is RelativeLayout
*
* @param parent view's parent, [RelativeLayout]
* @param view target view
* @return [StateView]
*/
fun matchViewIfParentIsRelativeLayout(parent: RelativeLayout, view: View): StateView {
val stateView = StateView(parent.context)
val lp = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
RelativeLayout.LayoutParams(view.layoutParams as RelativeLayout.LayoutParams)
} else {
RelativeLayout.LayoutParams(view.layoutParams)
}
parent.addView(stateView, lp)
setStateListAnimator(stateView, view)
return stateView
}
/**
* In order to display on the button top
*/
fun setStateListAnimator(stateView: StateView, target: View) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && target is Button) {
Log.i(
StateView.TAG,
"for normal display, stateView.stateListAnimator = view.stateListAnimator"
)
stateView.stateListAnimator = target.stateListAnimator
}
}
/**
* fix bug: if someone injects SwipeRefreshLayout's child after SwipeRefreshLayout is resumed,
* this child will be hidden.
*/
fun injectIntoSwipeRefreshLayout(layout: SwipeRefreshLayout) {
try {
val mTargetField = SwipeRefreshLayout::class.java.getDeclaredField("mTarget")
mTargetField.isAccessible = true
mTargetField.set(layout, null)
// we replace the mTarget field with 'null', then the SwipeRefreshLayout
// will look for it's real child again.
} catch (e: Throwable) {
e.printStackTrace()
}
}
} | kotlin/src/main/java/com/github/nukc/stateview/Injector.kt | 2793349178 |
package sx.blah.discord.kotlin
import sx.blah.discord.api.IDiscordClient
import sx.blah.discord.modules.IModule
/**
* This represents the base Discord4K module. This does nothing, it's only for show.
*/
class Discord4K : IModule {
override fun getName() = "Discord4k"
override fun enable(client: IDiscordClient?) = true
override fun getVersion() = "1.0.0-SNAPSHOT"
override fun getMinimumDiscord4JVersion() = "2.5.1"
override fun getAuthor() = "austinv11"
override fun disable() {
throw UnsupportedOperationException()
}
}
| src/main/kotlin/sx/blah/discord/kotlin/Discord4K.kt | 461551655 |
package v_collections
fun example7() {
val result = listOf("a", "b", "ba", "ccc", "ad").groupBy { it.length() }
result == mapOf(1 to listOf("a", "b"), 2 to listOf("ba", "ad"), 3 to listOf("ccc"))
}
fun Shop.groupCustomersByCity(): Map<City, List<Customer>> {
// Return the map of the customers living in each city
todoCollectionTask()
}
| src/v_collections/H_GroupBy.kt | 596197805 |
package io.gitlab.arturbosch.detekt.rules.exceptions
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.test.TestConfig
import io.gitlab.arturbosch.detekt.test.compileAndLint
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatExceptionOfType
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.util.regex.PatternSyntaxException
class TooGenericExceptionCaughtSpec : Spek({
describe("a file with many caught exceptions") {
it("should find one of each kind") {
val rule = TooGenericExceptionCaught(Config.empty)
val findings = rule.compileAndLint(tooGenericExceptionCode)
assertThat(findings).hasSize(caughtExceptionDefaults.size)
}
}
describe("a file with a caught exception which is ignored") {
val code = """
class MyTooGenericException : RuntimeException()
fun f() {
try {
throw Throwable()
} catch (myIgnore: MyTooGenericException) {
throw Error()
}
}
"""
it("should not report an ignored catch blocks because of its exception name") {
val config = TestConfig(mapOf(TooGenericExceptionCaught.ALLOWED_EXCEPTION_NAME_REGEX to "myIgnore"))
val rule = TooGenericExceptionCaught(config)
val findings = rule.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not report an ignored catch blocks because of its exception type") {
val config = TestConfig(mapOf(TooGenericExceptionCaught.CAUGHT_EXCEPTIONS_PROPERTY to "[MyException]"))
val rule = TooGenericExceptionCaught(config)
val findings = rule.compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should not fail when disabled with invalid regex on allowed exception names") {
val configRules = mapOf(
"active" to "false",
TooGenericExceptionCaught.ALLOWED_EXCEPTION_NAME_REGEX to "*MyException"
)
val config = TestConfig(configRules)
val rule = TooGenericExceptionCaught(config)
val findings = rule.compileAndLint(tooGenericExceptionCode)
assertThat(findings).isEmpty()
}
it("should fail with invalid regex on allowed exception names") {
val config = TestConfig(mapOf(TooGenericExceptionCaught.ALLOWED_EXCEPTION_NAME_REGEX to "*Foo"))
val rule = TooGenericExceptionCaught(config)
assertThatExceptionOfType(PatternSyntaxException::class.java).isThrownBy {
rule.compileAndLint(tooGenericExceptionCode)
}
}
}
})
| detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/TooGenericExceptionCaughtSpec.kt | 286773246 |
package io.gitlab.arturbosch.detekt.rules.empty
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.test.assertThat
import io.gitlab.arturbosch.detekt.test.lint
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class EmptyConstructorSpec : Spek({
describe("EmptyDefaultConstructor rule") {
it("should not report empty constructors for annotation classes with expect or actual keyword - #1362") {
val code = """
expect annotation class NeedsConstructor()
actual annotation class NeedsConstructor actual constructor()
@NeedsConstructor
fun annotatedFunction() = Unit
"""
val findings = EmptyDefaultConstructor(Config.empty).lint(code)
assertThat(findings).isEmpty()
}
}
})
| detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/empty/EmptyConstructorSpec.kt | 347335999 |
package com.yuyashuai.frameanimation.io
import android.graphics.Bitmap
import com.yuyashuai.frameanimation.FrameAnimation
/**
* @author yuyashuai 2019-04-24.
* responsible for decoding picture
*/
interface BitmapDecoder {
/**
* decoding the bitmap from the specified path
* @param path the bitmap path
* @param inBitmap the reuse bitmap
* @return null when decode fails
*/
fun decodeBitmap(path: FrameAnimation.PathData, inBitmap: Bitmap?): Bitmap?
/**
* @see decodeBitmap
*/
fun decodeBitmap(path: FrameAnimation.PathData): Bitmap?
} | frameanimation/src/main/java/com/yuyashuai/frameanimation/io/BitmapDecoder.kt | 1472291589 |
/*
* Copyright 2020 Intershop Communications AG.
*
* 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.intershop.gradle.scm.utils
/**
* This is the configuration class for the necessary prefixes
* on special branches, so that it is possible to identify the
* relevant branches and tags for version calculation.
*/
interface IPrefixConfig {
companion object {
/**
* Search pattern for stabilization branches with version information.
*/
const val stabilizationBranchPattern = "(\\d+(\\.\\d+)?(\\.\\d+)?(\\.\\d+)?)"
}
/**
* Prefix for stabilization branches.
*
* @property stabilizationPrefix
*/
var stabilizationPrefix: String
/**
* Prefix for feature branches.
*
* @property featurePrefix
*/
var featurePrefix: String
/**
* Prefix for hotfix branches.
*
* @property hotfixPrefix
*/
var hotfixPrefix: String
/**
* Prefix for bugfix branches.
*
* @property bugfixPrefix
*/
var bugfixPrefix: String
/**
* Prefix for release tags.
*
* @property tagPrefix
*/
var tagPrefix: String
/**
* Separator between prefix and version.
*
* @property prefixSeperator
*/
var prefixSeperator: String
/**
* Separator between prefix and version for branches.
*
* @property branchPrefixSeperator
*/
var branchPrefixSeperator: String?
/**
* Separator between prefix and version for tags.
*
* @property tagPrefixSeperator
*/
var tagPrefixSeperator: String?
/**
* Creates a search pattern for feature branches.
*
* @property featureBranchPattern Search pattern for feature branches.
*/
val featureBranchPattern: String
get() {
return if(branchPrefixSeperator != null) {
"${featurePrefix}${branchPrefixSeperator}(.*)"
} else {
"${featurePrefix}${prefixSeperator}(.*)"
}
}
/**
* Creates a search pattern for hotfix branches.
*
* @property hotfixBranchPattern Search pattern for hotfix branches.
*/
val hotfixBranchPattern : String
get() {
if(branchPrefixSeperator != null) {
return "${hotfixPrefix}${branchPrefixSeperator}(.*)"
}
return "${hotfixPrefix}${prefixSeperator}(.*)"
}
/**
* Creates a search pattern for bugfix branches.
*
* @property bugfixBranchPattern Search pattern for bugfix branches.
*/
val bugfixBranchPattern: String
get() {
if(branchPrefixSeperator != null) {
return "${bugfixPrefix}${branchPrefixSeperator}(.*)"
}
return "${bugfixPrefix}${prefixSeperator}(.*)"
}
/**
* Creates a search pattern for stabilization branches.
*
* @property stabilizationBranchPattern Search pattern for stabilization branches.
*/
val stabilizationBranchPattern: String
get() {
if(branchPrefixSeperator != null) {
return "${stabilizationPrefix}${branchPrefixSeperator}(.*)"
}
return "${stabilizationPrefix}${prefixSeperator}(.*)"
}
/**
* Returns the prefix for the special branch.
*
* @param type branch type
* @return the prefix for the specified branch type
*/
fun getPrefix(type: BranchType): String {
return when (type) {
BranchType.BRANCH -> stabilizationPrefix
BranchType.FEATUREBRANCH -> featurePrefix
BranchType.HOTFIXBBRANCH -> hotfixPrefix
BranchType.BUGFIXBRANCH -> bugfixPrefix
else -> tagPrefix
}
}
}
| src/main/kotlin/com/intershop/gradle/scm/utils/IPrefixConfig.kt | 266475852 |
/*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.processModel
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import nl.adaptivity.serialutil.DelegatingSerializer
import nl.adaptivity.xmlutil.Namespace
import nl.adaptivity.xmlutil.XmlReader
@Serializable(with = IXmlResultType.Serializer::class)
interface IXmlResultType {
val content: CharArray?
/**
* The value of the name property.
*/
fun getName(): String
fun setName(value: String)
/**
* Gets the value of the path property.
*
* @return possible object is [String]
*/
fun getPath(): String?
/**
* Sets the value of the path property.
*
* @param namespaceContext
*
* @param value allowed object is [String]
*/
fun setPath(namespaceContext: Iterable<Namespace>, value: String?)
/**
* A reader for the underlying body stream.
*/
val bodyStreamReader: XmlReader
/**
* Get the namespace context for evaluating the xpath expression.
* @return the context
*/
val originalNSContext: Iterable<Namespace>
companion object Serializer : DelegatingSerializer<IXmlResultType, XmlResultType>(XmlResultType.serializer()) {
fun serializer(): Serializer = this
override fun fromDelegate(delegate: XmlResultType): IXmlResultType = delegate
override fun IXmlResultType.toDelegate(): XmlResultType {
return this as? XmlResultType ?: XmlResultType(this)
}
}
}
val IXmlResultType.path: String?
inline get() = getPath()
var IXmlResultType.name: String
inline get(): String = getName()
inline set(value) {
setName(value)
}
fun IXmlResultType.getOriginalNSContext(): Iterable<Namespace> = originalNSContext
object IXmlResultTypeListSerializer : KSerializer<List<IXmlResultType>> {
val delegate = ListSerializer(XmlResultType)
override val descriptor: SerialDescriptor = delegate.descriptor
override fun deserialize(decoder: Decoder): List<IXmlResultType> {
return delegate.deserialize(decoder)
}
override fun serialize(encoder: Encoder, value: List<IXmlResultType>) {
delegate.serialize(encoder, value.map(::XmlResultType))
}
}
| PE-common/src/commonMain/kotlin/nl/adaptivity/process/processModel/IXmlResultType.kt | 4242356054 |
package de.westnordost.streetcomplete.settings
import androidx.preference.PreferenceDialogFragmentCompat
import android.view.View
import android.widget.NumberPicker
import de.westnordost.streetcomplete.R
/** Preference dialog where user should pick a number */
class NumberPickerPreferenceDialog : PreferenceDialogFragmentCompat() {
private lateinit var picker: NumberPicker
private lateinit var values: Array<String>
private val pref: NumberPickerPreference
get() = preference as NumberPickerPreference
override fun onBindDialogView(view: View) {
super.onBindDialogView(view)
picker = view.findViewById(R.id.numberPicker)
val intValues = (pref.minValue..pref.maxValue step pref.step).toList()
values = intValues.map { "$it" }.toTypedArray()
var index = values.indexOf(pref.value.toString())
if(index == -1) {
do ++index while(index < intValues.lastIndex && intValues[index] < pref.value)
}
picker.apply {
displayedValues = values
minValue = 0
maxValue = values.size - 1
value = index
wrapSelectorWheel = false
}
}
override fun onDialogClosed(positiveResult: Boolean) {
// hackfix: The Android number picker accepts input via soft keyboard (which makes sense
// from a UX viewpoint) but is not designed for that. By default, it does not apply the
// input there. See http://stackoverflow.com/questions/18944997/numberpicker-doesnt-work-with-keyboard
// A workaround is to clear the focus before saving.
picker.clearFocus()
if (positiveResult) {
pref.value = values[picker.value].toInt()
}
}
}
| app/src/main/java/de/westnordost/streetcomplete/settings/NumberPickerPreferenceDialog.kt | 2756896883 |
/*
* Copyright (c) 2019.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine.impl.dom
import nl.adaptivity.process.engine.impl.Result
import nl.adaptivity.process.engine.impl.Source
import nl.adaptivity.xmlutil.NamespaceContext
import nl.adaptivity.xmlutil.QName
import nl.adaptivity.xmlutil.XmlReader
import nl.adaptivity.xmlutil.XmlWriter
import nl.adaptivity.xmlutil.util.ICompactFragment
expect class DOMResult : Result {
constructor(node: Node)
}
expect fun Result.newWriter(): XmlWriter
expect fun Source.newReader(): XmlReader
expect class DOMSource : Source {
constructor(node: Node)
}
expect interface NodeList {
fun getLength(): Int
}
expect interface Text : CharacterData
expect interface CharacterData : Node
expect interface Node {
fun getOwnerDocument(): Document
fun getFirstChild(): Node?
fun getNextSibling(): Node?
fun appendChild(child: Node): Node
}
expect interface Element : Node
expect interface Document {
fun createTextNode(text: String): Text
fun createDocumentFragment(): DocumentFragment
fun createElement(tagname: String): Element
fun adoptNode(source: Node): Node
}
expect interface DocumentFragment : Node {
}
expect abstract class DocumentBuilder {
abstract fun newDocument(): Document
}
expect abstract class DocumentBuilderFactory {
fun isNamespaceAware(): Boolean
fun setNamespaceAware(value: Boolean)
abstract fun newDocumentBuilder(): DocumentBuilder
}
var DocumentBuilderFactory.isNamespaceAware
inline get() = isNamespaceAware()
inline set(value) {
setNamespaceAware(value)
}
expect fun newDocumentBuilderFactory(): DocumentBuilderFactory
expect class InputSource
expect interface XPathExpression {
fun evaluate(source: Any, returnType: QName):Any
fun evaluate(source: InputSource, returnType: QName):Any
}
expect interface XPath {
fun getNamespaceContext(): NamespaceContext
fun setNamespaceContext(context: NamespaceContext)
fun compile(expression: String): XPathExpression
}
expect fun newXPath(): XPath
expect object XPathConstants {
val NUMBER: QName
val STRING: QName
val BOOLEAN: QName
val NODESET: QName
val NODE: QName
val DOM_OBJECT_MODEL: String
}
expect fun NodeList.toFragment(): ICompactFragment
expect fun Node.toFragment(): ICompactFragment
expect fun ICompactFragment.toDocumentFragment(): DocumentFragment
| ProcessEngine/core/src/commonMain/kotlin/nl/adaptivity/process/engine/impl/dom/dom.kt | 2981800936 |
/*
* Copyright 2020 Alex Almeida Tavella
*
* 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 br.com.core.tmdb
import android.content.Context
import br.com.core.tmdb.api.TmdbApiKeyStore
import br.com.core.tmdb.image.ImageConfigurationApi
import br.com.moov.core.di.AppScope
import com.squareup.anvil.annotations.ContributesTo
import dagger.Module
import dagger.Provides
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Qualifier
@Qualifier
private annotation class BaseUrl
@Module(
includes = [
TmdbInternalModule::class
]
)
@ContributesTo(AppScope::class)
interface TmdbModule
private const val CACHE_SIZE: Long = 10 * 1024 * 1024
@Module
internal object TmdbInternalModule {
@[Provides BaseUrl]
fun providesBaseUrl(): String = "https://api.themoviedb.org"
@Provides
fun providesApiKey(apiKeyStore: TmdbApiKeyStore): String = apiKeyStore.getApiKey()
@Provides
fun providesCacheDuration(): Long = TimeUnit.DAYS.toSeconds(1)
@Provides
fun providesCache(context: Context): Cache = Cache(context.cacheDir, CACHE_SIZE)
@Provides
fun providesOkHttpClient(
cache: Cache,
interceptor: Interceptor
): OkHttpClient {
val builder = OkHttpClient().newBuilder()
if (BuildConfig.DEBUG) {
builder.addInterceptor(
HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT)
.setLevel(HttpLoggingInterceptor.Level.BODY)
)
}
return builder
.cache(cache)
.addInterceptor(interceptor)
.build()
}
@Provides
fun providesRetrofit(
okHttpClient: OkHttpClient,
@BaseUrl baseUrl: String
): Retrofit {
return Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(MoshiConverterFactory.create())
.build()
}
@Provides
fun providesImageConfigurationApi(retrofit: Retrofit): ImageConfigurationApi {
return retrofit.create(ImageConfigurationApi::class.java)
}
}
| core-lib/tmdb/src/main/java/br/com/core/tmdb/TmdbModule.kt | 338169284 |
package org.wordpress.android.fluxc.network.rest.wpcom.wc.addons
import android.content.Context
import com.android.volley.RequestQueue
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.generated.endpoint.WOOCOMMERCE
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.network.UserAgent
import org.wordpress.android.fluxc.network.rest.wpcom.BaseWPComRestClient
import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackError
import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackSuccess
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload
import org.wordpress.android.fluxc.network.rest.wpcom.wc.addons.dto.AddOnGroupDto
import org.wordpress.android.fluxc.network.rest.wpcom.wc.toWooError
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
@Singleton
class AddOnsRestClient @Inject constructor(
appContext: Context,
dispatcher: Dispatcher,
@Named("regular") requestQueue: RequestQueue,
accessToken: AccessToken,
userAgent: UserAgent,
private val requestBuilder: JetpackTunnelGsonRequestBuilder
) : BaseWPComRestClient(appContext, dispatcher, requestQueue, accessToken, userAgent) {
suspend fun fetchGlobalAddOnGroups(site: SiteModel): WooPayload<List<AddOnGroupDto>> {
val url = WOOCOMMERCE.product_add_ons.pathV1Addons
val response = requestBuilder.syncGetRequest(
restClient = this,
site = site,
url = url,
params = emptyMap(),
clazz = Array<AddOnGroupDto>::class.java
)
return when (response) {
is JetpackSuccess -> WooPayload(response.data?.toList())
is JetpackError -> WooPayload(response.error.toWooError())
}
}
}
| plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/addons/AddOnsRestClient.kt | 1116514711 |
package org.wordpress.android.fluxc.model
sealed class LocalOrRemoteId {
data class LocalId(val value: Int) : LocalOrRemoteId()
data class RemoteId(val value: Long) : LocalOrRemoteId()
}
| fluxc/src/main/java/org/wordpress/android/fluxc/model/LocalOrRemoteId.kt | 3642570862 |
package moe.tlaster.openween.core.model.user
import com.fasterxml.jackson.annotation.JsonProperty
import moe.tlaster.openween.core.model.BaseListModel
/**
* Created by Tlaster on 2016/9/2.
*/
class UserListModel : BaseListModel() {
@field:JsonProperty("users")
var users: List<UserModel>? = null
}
| app/src/main/java/moe/tlaster/openween/core/model/user/UserListModel.kt | 856672356 |
package kotlinx.serialization.properties
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
class SealedClassSerializationFromPropertiesTest {
@Serializable
sealed class BaseClass {
abstract val firstProperty: Long
abstract val secondProperty: String
}
@SerialName("FIRSTCHILD")
@Serializable
data class FirstChild(override val firstProperty: Long, override val secondProperty: String) : BaseClass()
@SerialName("SECONDCHILD")
@Serializable
data class SecondChild(override val firstProperty: Long, override val secondProperty: String) : BaseClass()
@Test
fun testPropertiesDeserialization() {
val props = mapOf(
"type" to "FIRSTCHILD",
"firstProperty" to 1L,
"secondProperty" to "one"
)
val instance: BaseClass = Properties.decodeFromMap(props)
assertIs<FirstChild>(instance)
assertEquals(instance.firstProperty, 1)
assertEquals(instance.secondProperty, "one")
}
@Test
fun testPropertiesSerialization() {
val instance: BaseClass = FirstChild(
firstProperty = 1L, secondProperty = "one"
)
val instanceProperties = Properties.encodeToMap(instance)
assertEquals(1L, instanceProperties["firstProperty"])
assertEquals("one", instanceProperties["secondProperty"])
}
} | formats/properties/commonTest/src/kotlinx/serialization/properties/SealedClassSerializationFromPropertiesTest.kt | 3938192839 |
/*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.protobuf.internal
import kotlinx.serialization.*
import kotlin.jvm.*
/*
* In ProtoBuf spec, ids from 19000 to 19999 are reserved for protocol use,
* thus we are leveraging it here and use 19_500 as a marker no one us allowed to use.
* It does not leak to the resulting output.
*/
internal const val MISSING_TAG = 19_500L
internal abstract class ProtobufTaggedBase {
private var tagsStack = LongArray(8)
@JvmField
protected var stackSize = -1
protected val currentTag: ProtoDesc
get() = tagsStack[stackSize]
protected val currentTagOrDefault: ProtoDesc
get() = if (stackSize == -1) MISSING_TAG else tagsStack[stackSize]
protected fun popTagOrDefault(): ProtoDesc = if (stackSize == -1) MISSING_TAG else tagsStack[stackSize--]
protected fun pushTag(tag: ProtoDesc) {
if (tag == MISSING_TAG) return // Missing tag is never added
val idx = ++stackSize
if (stackSize >= tagsStack.size) {
expand()
}
tagsStack[idx] = tag
}
private fun expand() {
tagsStack = tagsStack.copyOf(tagsStack.size * 2)
}
protected fun popTag(): ProtoDesc {
if (stackSize >= 0) return tagsStack[stackSize--]
// Unreachable
throw SerializationException("No tag in stack for requested element")
}
protected inline fun <E> tagBlock(tag: ProtoDesc, block: () -> E): E {
pushTag(tag)
return block()
}
}
| formats/protobuf/commonMain/src/kotlinx/serialization/protobuf/internal/ProtobufTaggedBase.kt | 1619496547 |
package kotlinx.serialization.json
import kotlinx.serialization.*
class JsonImplicitNullsTest: AbstractJsonImplicitNullsTest() {
override fun <T> Json.encode(value: T, serializer: KSerializer<T>): String {
return encodeToString(serializer, value)
}
override fun <T> Json.decode(json: String, serializer: KSerializer<T>): T {
return decodeFromString(serializer, json)
}
}
| formats/json-tests/commonTest/src/kotlinx/serialization/json/JsonImplicitNullsTest.kt | 3772813777 |
package avenwu.net.filelocker.activity
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
/**
* Created by aven on 1/12/16.
*/
public abstract class BaseToolbarActivity : AppCompatActivity() {
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item?.itemId == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item)
}
} | app/src/main/kotlin/avenwu/net/filelocker/activity/BaseToolbarActivity.kt | 2968266104 |
package name.kropp.intellij.makefile
import com.intellij.execution.actions.*
import com.intellij.execution.configurations.*
import com.intellij.openapi.components.*
import com.intellij.openapi.util.*
import com.intellij.psi.*
import name.kropp.intellij.makefile.psi.*
import java.io.*
class MakefileRunConfigurationProducer : LazyRunConfigurationProducer<MakefileRunConfiguration>() {
override fun setupConfigurationFromContext(configuration: MakefileRunConfiguration, context: ConfigurationContext, sourceElement: Ref<PsiElement>): Boolean {
if (context.psiLocation?.containingFile !is MakefileFile) {
return false
}
val macroManager = PathMacroManager.getInstance(context.project)
val path = context.location?.virtualFile?.path
configuration.filename = macroManager.collapsePath(path) ?: ""
configuration.target = findTarget(context)?.name ?: ""
if (configuration.target.isNotEmpty()) {
configuration.name = configuration.target
} else {
configuration.name = File(path).name
}
return true
}
override fun isConfigurationFromContext(configuration: MakefileRunConfiguration, context: ConfigurationContext): Boolean {
val macroManager = PathMacroManager.getInstance(context.project)
return macroManager.expandPath(configuration.filename) == context.location?.virtualFile?.path &&
configuration.target == findTarget(context)?.name
}
private fun findTarget(context: ConfigurationContext): MakefileTarget? {
var element = context.psiLocation
while (element != null && element !is MakefileTarget) {
element = element.parent
}
val target = element as? MakefileTarget
if (target?.isSpecialTarget == false) {
return target
}
return null
}
override fun getConfigurationFactory(): ConfigurationFactory = MakefileRunConfigurationFactory(MakefileRunConfigurationType)
} | src/main/kotlin/name/kropp/intellij/makefile/MakefileRunConfigurationProducer.kt | 3334831326 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.block.property
data class FlammableInfo(
val encouragement: Int,
val flammability: Int
) : Comparable<FlammableInfo> {
override fun compareTo(other: FlammableInfo): Int {
val result = this.encouragement.compareTo(other.encouragement)
return if (result != 0) result else this.flammability.compareTo(other.flammability)
}
}
| src/main/kotlin/org/lanternpowered/server/block/property/FlammableInfo.kt | 73676126 |
package com.github.feed.sample.ui.eventlist
import com.github.feed.sample.ui.BasePresenterTest
import com.github.feed.sample.ui.eventlist.EventViewModel
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import io.reactivex.android.plugins.RxAndroidPlugins
import io.reactivex.schedulers.Schedulers
import org.junit.BeforeClass
import org.junit.Test
import org.mockito.Mockito.verify
class EventListPresenterTest : BasePresenterTest<EventListContract.View, EventListPresenter, EventViewModel>() {
override var view: EventListContract.View = mock()
override fun createPresenter() = EventListPresenter()
companion object {
@JvmStatic
@BeforeClass
fun setupClass() {
RxAndroidPlugins.setInitMainThreadSchedulerHandler { _ -> Schedulers.trampoline() }
}
}
@Test
fun getEvents_successful() {
// Arrange
setViewModel(EventViewModel(EventViewModel.Config.SUCCESSFUL))
// Act
// presenter.onViewActive() is called automatically
// Assert
verify(view).showEvents(any())
}
@Test
fun getEvents_failureLimitExceeded() {
// Arrange
setViewModel(EventViewModel(EventViewModel.Config.RATE_LIMIT_EXCEEDED))
// Act
// presenter.onViewActive() is called automatically
// Assert
verify(view).showLimitErrorMessage()
}
@Test(expected = RuntimeException::class)
fun getEvents_failureGenericError() {
// Arrange
setViewModel(EventViewModel(EventViewModel.Config.GENERIC_ERROR))
// Act
// presenter.onViewActive() is called automatically
// Assert
verify(view).showGenericError()
}
}
| app/src/test/kotlin/com/github/feed/sample/ui/eventlist/EventListPresenterTest.kt | 3515226034 |
package de.entera.riker.suite
import org.junit.Test
import kotlin.test.expect
class SuiteTest {
@Test
fun `transform() test test`() {
// given:
val source = Node("suite",
Node("test"),
Node("test")
)
val expected = Node("suite",
Node("testCase",
Node("test")
),
Node("testCase",
Node("test")
)
)
// expect:
expect(expected) { transform(source) }
}
@Test
fun `transform() testSetup test test`() {
// given:
val source = Node("suite",
Node("testSetup"),
Node("test"),
Node("test")
)
val expected = Node("suite",
Node("testCase",
Node("testSetup"),
Node("test")
),
Node("testCase",
Node("testSetup"),
Node("test")
)
)
// expect:
expect(expected) { transform(source) }
}
}
data class Node<T>(val data: T,
val children: MutableList<Node<T>> = arrayListOf()) {
constructor(data: T,
vararg children: Node<T>) : this(data) {
this.children.addAll(children)
}
}
fun transform(node: Node<String>): Node<String> {
val target = Node(node.data)
// collect setups and cleanups.
val testSetups = node.children.filter { it.data == "testSetup" }
val testCleanups = node.children.filter { it.data == "testCleanup" }
// populate test cases.
val testCases = node.children.filter { it.data == "test" }
.map { Node("testCase", (testSetups + it + testCleanups).toArrayList() ) }
target.children.addAll(testCases)
return target
}
| projects/riker-core/src/test/kotlin/de/entera/riker/suite/SuiteTest.kt | 3079650034 |
package io.rover.sdk.example.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
) | example-app/src/main/java/io/rover/sdk/example/ui/theme/Shape.kt | 3043798138 |
package com.habitrpg.android.habitica.ui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebChromeClient
import com.habitrpg.android.habitica.BuildConfig
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.AppComponent
import kotlinx.android.synthetic.main.fragment_news.*
class NewsFragment : BaseMainFragment() {
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
return inflater?.inflate(R.layout.fragment_news, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val address = if (BuildConfig.DEBUG) BuildConfig.BASE_URL else context.getString(R.string.base_url)
newsWebview.webChromeClient = WebChromeClient()
newsWebview.loadUrl(address + "/static/new-stuff")
}
override fun injectFragment(component: AppComponent) {
component.inject(this)
}
override fun customTitle(): String {
return if (!isAdded) {
""
} else getString(R.string.sidebar_news)
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/NewsFragment.kt | 488455871 |
package net.detunized.unfuckjs
import com.intellij.lang.javascript.psi.JSBinaryExpression
public class ConvertAndToIf: ConvertBooleanToIf("&&") {
override fun getCondition(expression: JSBinaryExpression) =
expression.getLOperand().getText()
override fun getThen(expression: JSBinaryExpression) =
expression.getROperand().getText()
}
| src/net/detunized/unfuckjs/ConvertAndToIf.kt | 360052661 |
/*****************************************************************************
* TvChannels.kt
*****************************************************************************
* Copyright © 2018 VLC authors, VideoLAN and VideoLabs
* Author: Geoffrey Métais
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
package org.videolan.vlc.util
import android.content.ComponentName
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.tvprovider.media.tv.TvContractCompat
import androidx.tvprovider.media.tv.WatchNextProgram
import kotlinx.coroutines.*
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.resources.util.getFromMl
import org.videolan.tools.AppScope
import org.videolan.tools.Settings
import org.videolan.vlc.BuildConfig
import org.videolan.vlc.PreviewVideoInputService
import org.videolan.vlc.R
import org.videolan.vlc.getFileUri
import videolan.org.commontools.*
private const val TAG = "VLC/TvChannels"
private const val MAX_RECOMMENDATIONS = 3
@ExperimentalCoroutinesApi
@RequiresApi(Build.VERSION_CODES.O)
fun setChannel(context: Context) = GlobalScope.launch(start = CoroutineStart.UNDISPATCHED) {
val channelId = withContext(Dispatchers.IO) {
val prefs = Settings.getInstance(context)
val name = context.getString(R.string.tv_my_new_videos)
createOrUpdateChannel(prefs, context, name, R.drawable.ic_channel_icon, BuildConfig.APP_ID)
}
if (Permissions.canReadStorage(context)) updatePrograms(context, channelId)
}
private suspend fun updatePrograms(context: Context, channelId: Long) {
if (channelId == -1L) return
val videoList = context.getFromMl { recentVideos }
val programs = withContext(Dispatchers.IO) { existingPrograms(context, channelId) }
if (videoList.isNullOrEmpty()) return
val cn = ComponentName(context, PreviewVideoInputService::class.java)
for ((count, mw) in videoList.withIndex()) {
if (mw == null) continue
val index = programs.indexOfId(mw.id)
if (index != -1) {
programs.removeAt(index)
continue
}
if (mw.isThumbnailGenerated) {
if (mw.artworkMrl === null) continue
} else if (withContext(Dispatchers.IO) { ThumbnailsProvider.getMediaThumbnail(mw, 272.toPixel()) } === null
|| mw.artworkMrl === null) {
continue
}
val desc = ProgramDesc(channelId, mw.id, mw.title, mw.description,
mw.artUri(), mw.length.toInt(), mw.time.toInt(),
mw.width, mw.height, BuildConfig.APP_ID)
val program = buildProgram(cn, desc)
GlobalScope.launch(Dispatchers.IO) {
context.contentResolver.insert(TvContractCompat.PreviewPrograms.CONTENT_URI, program.toContentValues())
}
if (count - programs.size >= MAX_RECOMMENDATIONS) break
}
for (program in programs) {
withContext(Dispatchers.IO) { context.contentResolver.delete(TvContractCompat.buildPreviewProgramUri(program.programId), null, null) }
}
}
fun Context.launchChannelUpdate() = AppScope.launch {
val id = withContext(Dispatchers.IO) { Settings.getInstance(this@launchChannelUpdate).getLong(KEY_TV_CHANNEL_ID, -1L) }
updatePrograms(this@launchChannelUpdate, id)
}
suspend fun setResumeProgram(context: Context, mw: MediaWrapper) {
var cursor: Cursor? = null
var isProgramPresent = false
val mw = context.getFromMl { findMedia(mw) }
try {
cursor = context.contentResolver.query(
TvContractCompat.WatchNextPrograms.CONTENT_URI, WATCH_NEXT_MAP_PROJECTION, null,
null, null)
cursor?.let {
while (it.moveToNext()) {
if (!it.isNull(1) && TextUtils.equals(mw.id.toString(), cursor.getString(1))) {
// Found a row that contains the matching ID
val watchNextProgramId = cursor.getLong(0)
if (it.getInt(2) == 0 || mw.time == 0L) { //Row removed by user or progress null
if (deleteWatchNext(context, watchNextProgramId) < 1) {
Log.e(TAG, "Delete program failed")
return
}
} else { // Update the program
val existingProgram = WatchNextProgram.fromCursor(cursor)
updateWatchNext(context, existingProgram, mw.time, watchNextProgramId)
isProgramPresent = true
}
break
}
}
}
if (!isProgramPresent && mw.time != 0L) {
val desc = ProgramDesc(0L, mw.id, mw.title, mw.description,
mw.artUri(), mw.length.toInt(), mw.time.toInt(),
mw.width, mw.height, BuildConfig.APP_ID)
val cn = ComponentName(context, PreviewVideoInputService::class.java)
val program = buildWatchNextProgram(cn, desc)
val watchNextProgramUri = context.contentResolver.insert(TvContractCompat.WatchNextPrograms.CONTENT_URI, program.toContentValues())
if (watchNextProgramUri == null || watchNextProgramUri == Uri.EMPTY) Log.e(TAG, "Insert watch next program failed")
}
} finally {
cursor?.close()
}
}
private suspend fun MediaWrapper.artUri() : Uri {
if (!isThumbnailGenerated) {
withContext(Dispatchers.IO) { ThumbnailsProvider.getVideoThumbnail(this@artUri, 512) }
}
val mrl = artworkMrl
?: return Uri.parse("android.resource://${BuildConfig.APP_ID}/${R.drawable.ic_browser_video_big_normal}")
return try {
getFileUri(mrl)
} catch (ex: IllegalArgumentException) {
Uri.parse("android.resource://${BuildConfig.APP_ID}/${R.drawable.ic_browser_video_big_normal}")
}
} | application/vlc-android/src/org/videolan/vlc/util/TvChannels.kt | 2875084373 |
package com.flexpoker.table.command.aggregate.generic
import com.flexpoker.table.command.aggregate.DefaultRandomNumberGenerator
import com.flexpoker.table.command.aggregate.eventproducers.createTable
import com.flexpoker.table.command.aggregate.testhelpers.TestRandomNumberGenerator
import com.flexpoker.table.command.commands.CreateTableCommand
import com.flexpoker.table.command.events.TableCreatedEvent
import com.flexpoker.test.util.CommonAssertions.verifyNewEvents
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
import java.util.HashSet
import java.util.UUID
class CreateNewTableTest {
@Test
fun testCreateNewTestSuccess() {
val tableId = UUID.randomUUID()
val playerIds = setOf(UUID.randomUUID(), UUID.randomUUID())
val command = CreateTableCommand(tableId, UUID.randomUUID(), playerIds, 6)
val events = createTable(command.tableId, command.gameId, command.numberOfPlayersPerTable,
command.playerIds, TestRandomNumberGenerator(2))
verifyNewEvents(tableId, events, TableCreatedEvent::class.java)
assertEquals(setOf(2, 3),
(events[0] as TableCreatedEvent).seatPositionToPlayerMap.filterValues { it != null }.keys.toSet())
}
@Test
fun testPlayerListExactSucceeds() {
val tableId = UUID.randomUUID()
val playerIds = setOf(UUID.randomUUID(), UUID.randomUUID())
val command = CreateTableCommand(tableId, UUID.randomUUID(), playerIds, 2)
val events = createTable(command.tableId, command.gameId, command.numberOfPlayersPerTable,
command.playerIds, TestRandomNumberGenerator(0))
verifyNewEvents(tableId, events, TableCreatedEvent::class.java)
assertEquals(setOf(0, 1),
(events[0] as TableCreatedEvent).seatPositionToPlayerMap.filterValues { it != null }.keys.toSet())
}
@Test
fun testCantCreateATableGreaterThanMaxSize() {
val playerIds = setOf(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())
val command = CreateTableCommand(UUID.randomUUID(), UUID.randomUUID(), playerIds, 2)
assertThrows(IllegalArgumentException::class.java) {
createTable(command.tableId, command.gameId, command.numberOfPlayersPerTable,
command.playerIds, DefaultRandomNumberGenerator())
}
}
@Test
fun testCantCreateATableWithOnlyOnePlayer() {
val tableId = UUID.randomUUID()
val playerIds = HashSet<UUID>()
playerIds.add(UUID.randomUUID())
val command = CreateTableCommand(tableId, UUID.randomUUID(), playerIds, 2)
assertThrows(IllegalArgumentException::class.java) {
createTable(command.tableId, command.gameId, command.numberOfPlayersPerTable,
command.playerIds, DefaultRandomNumberGenerator())
}
}
} | src/test/kotlin/com/flexpoker/table/command/aggregate/generic/CreateNewTableTest.kt | 808485566 |
/*
* Copyright 2016-2021 Adrian Cotfas
*
* 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.apps.adrcotfas.goodtime.settings
import com.apps.adrcotfas.goodtime.util.BatteryUtils.Companion.isIgnoringBatteryOptimizations
import com.apps.adrcotfas.goodtime.util.UpgradeDialogHelper.Companion.launchUpgradeDialog
import androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback
import android.os.Bundle
import com.apps.adrcotfas.goodtime.R
import android.view.LayoutInflater
import android.view.ViewGroup
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.annotation.TargetApi
import android.app.NotificationManager
import android.content.Context
import android.media.RingtoneManager
import android.net.Uri
import android.provider.Settings
import android.text.format.DateFormat
import android.view.View
import androidx.preference.*
import com.apps.adrcotfas.goodtime.ui.common.TimePickerDialogBuilder
import com.apps.adrcotfas.goodtime.util.*
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint
import xyz.aprildown.ultimateringtonepicker.RingtonePickerDialog
import xyz.aprildown.ultimateringtonepicker.UltimateRingtonePicker
import java.time.DayOfWeek
import java.time.LocalTime
import javax.inject.Inject
@AndroidEntryPoint
class SettingsFragment : PreferenceFragmentCompat(), OnRequestPermissionsResultCallback {
private lateinit var prefDisableSoundCheckbox: CheckBoxPreference
private lateinit var prefDndMode: CheckBoxPreference
@Inject
lateinit var preferenceHelper: PreferenceHelper
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.settings, rootKey)
setupReminderPreference()
setupStartOfDayPreference()
prefDisableSoundCheckbox = findPreference(PreferenceHelper.DISABLE_SOUND_AND_VIBRATION)!!
prefDndMode = findPreference(PreferenceHelper.DND_MODE)!!
}
private fun setupTimePickerPreference(
preference: Preference,
getTimeAction: () -> Int,
setTimeAction: (Int) -> Unit
) {
preference.setOnPreferenceClickListener {
val dialog = TimePickerDialogBuilder(requireContext())
.buildDialog(LocalTime.ofSecondOfDay(getTimeAction().toLong()))
dialog.addOnPositiveButtonClickListener {
val newValue = LocalTime.of(dialog.hour, dialog.minute).toSecondOfDay()
setTimeAction(newValue)
updateTimePickerPreferenceSummary(preference, getTimeAction())
}
dialog.showOnce(parentFragmentManager, "MaterialTimePicker")
true
}
updateTimePickerPreferenceSummary(preference, getTimeAction())
}
private fun setupReminderPreference() {
// restore from preferences
val dayOfWeekPref = findPreference<DayOfWeekPreference>(PreferenceHelper.REMINDER_DAYS)
dayOfWeekPref!!.setCheckedDays(
preferenceHelper.getBooleanArray(
PreferenceHelper.REMINDER_DAYS, DayOfWeek.values().size
)
)
val timePickerPref: Preference = findPreference(PreferenceHelper.REMINDER_TIME)!!
setupTimePickerPreference(
timePickerPref,
{ preferenceHelper.getReminderTime() },
{ preferenceHelper.setReminderTime(it) })
}
private fun setupStartOfDayPreference() {
val pref: Preference = findPreference(PreferenceHelper.WORK_DAY_START)!!
setupTimePickerPreference(
pref,
{ preferenceHelper.getStartOfDay() },
{ preferenceHelper.setStartOfDay(it) })
}
private fun updateTimePickerPreferenceSummary(pref: Preference, secondOfDay: Int) {
pref.summary = secondsOfDayToTimerFormat(
secondOfDay, DateFormat.is24HourFormat(context)
)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val view = super.onCreateView(inflater, container, savedInstanceState)
view!!.alpha = 0f
view.animate().alpha(1f).duration = 100
return view
}
@SuppressLint("BatteryLife")
override fun onResume() {
super.onResume()
requireActivity().title = getString(R.string.settings)
setupTheme()
setupRingtone()
setupScreensaver()
setupAutoStartSessionVsInsistentNotification()
setupDisableSoundCheckBox()
setupDnDCheckBox()
setupFlashingNotificationPref()
setupOneMinuteLeftNotificationPref()
val disableBatteryOptimizationPref =
findPreference<Preference>(PreferenceHelper.DISABLE_BATTERY_OPTIMIZATION)
if (!isIgnoringBatteryOptimizations(requireContext())) {
disableBatteryOptimizationPref!!.isVisible = true
disableBatteryOptimizationPref.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
val intent = Intent()
intent.action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
intent.data = Uri.parse("package:" + requireActivity().packageName)
startActivity(intent)
true
}
} else {
disableBatteryOptimizationPref!!.isVisible = false
}
findPreference<Preference>(PreferenceHelper.DISABLE_WIFI)!!.isVisible =
Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
prefDndMode.isVisible = true
}
override fun onDisplayPreferenceDialog(preference: Preference) {
when (preference.key) {
PreferenceHelper.TIMER_STYLE -> {
super.onDisplayPreferenceDialog(preference)
}
PreferenceHelper.VIBRATION_TYPE -> {
val dialog = VibrationPreferenceDialogFragment.newInstance(preference.key)
dialog.setTargetFragment(this, 0)
dialog.showOnce(parentFragmentManager, "VibrationType")
}
else -> {
super.onDisplayPreferenceDialog(preference)
}
}
}
private fun setupAutoStartSessionVsInsistentNotification() {
// Continuous mode versus insistent notification
val autoWork = findPreference<CheckBoxPreference>(PreferenceHelper.AUTO_START_WORK)
autoWork!!.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _: Preference?, newValue: Any ->
val pref = findPreference<CheckBoxPreference>(PreferenceHelper.INSISTENT_RINGTONE)
if (newValue as Boolean) {
pref!!.isChecked = false
}
true
}
val autoBreak = findPreference<CheckBoxPreference>(PreferenceHelper.AUTO_START_BREAK)
autoBreak!!.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _: Preference?, newValue: Any ->
val pref = findPreference<CheckBoxPreference>(PreferenceHelper.INSISTENT_RINGTONE)
if (newValue as Boolean) {
pref!!.isChecked = false
}
true
}
val insistentRingPref =
findPreference<CheckBoxPreference>(PreferenceHelper.INSISTENT_RINGTONE)
insistentRingPref!!.onPreferenceClickListener =
if (preferenceHelper.isPro()) null else Preference.OnPreferenceClickListener {
launchUpgradeDialog(requireActivity().supportFragmentManager)
insistentRingPref.isChecked = false
true
}
insistentRingPref.onPreferenceChangeListener =
if (preferenceHelper.isPro()) Preference.OnPreferenceChangeListener { _, newValue: Any ->
val p1 = findPreference<CheckBoxPreference>(PreferenceHelper.AUTO_START_BREAK)
val p2 = findPreference<CheckBoxPreference>(PreferenceHelper.AUTO_START_WORK)
if (newValue as Boolean) {
p1!!.isChecked = false
p2!!.isChecked = false
}
true
} else null
}
private fun handleRingtonePrefClick(preference: Preference) {
if (preference.key == PreferenceHelper.RINGTONE_BREAK_FINISHED && !preferenceHelper.isPro()) {
launchUpgradeDialog(requireActivity().supportFragmentManager)
} else {
val selectedUri =
Uri.parse(toRingtone(preferenceHelper.getNotificationSoundFinished(preference.key)!!).uri)
val settings = UltimateRingtonePicker.Settings(
preSelectUris = listOf(selectedUri),
systemRingtonePicker = UltimateRingtonePicker.SystemRingtonePicker(
customSection = UltimateRingtonePicker.SystemRingtonePicker.CustomSection(),
defaultSection = UltimateRingtonePicker.SystemRingtonePicker.DefaultSection(
showSilent = false
),
ringtoneTypes = listOf(
RingtoneManager.TYPE_NOTIFICATION,
)
),
deviceRingtonePicker = UltimateRingtonePicker.DeviceRingtonePicker(
alwaysUseSaf = true
)
)
val dialog = RingtonePickerDialog.createEphemeralInstance(
settings = settings,
dialogTitle = preference.title,
listener = object : UltimateRingtonePicker.RingtonePickerListener {
override fun onRingtonePicked(ringtones: List<UltimateRingtonePicker.RingtoneEntry>) {
preference.apply {
val ringtone = if (ringtones.isNotEmpty()) {
Ringtone(ringtones.first().uri.toString(), ringtones.first().name)
} else {
Ringtone("", resources.getString(R.string.pref_ringtone_summary))
}
val json = Gson().toJson(ringtone)
preferenceHelper.setNotificationSoundFinished(preference.key, json)
summary = ringtone.name
callChangeListener(ringtone)
}
}
}
)
dialog.showOnce(parentFragmentManager, "RingtonePref")
}
}
private fun setupRingtone() {
val prefWork = findPreference<Preference>(PreferenceHelper.RINGTONE_WORK_FINISHED)
val prefBreak = findPreference<Preference>(PreferenceHelper.RINGTONE_BREAK_FINISHED)
val defaultSummary = resources.getString(
R.string.pref_ringtone_summary
)
prefWork!!.summary =
toRingtone(preferenceHelper.getNotificationSoundWorkFinished()!!, defaultSummary).name
prefBreak!!.summary =
toRingtone(preferenceHelper.getNotificationSoundBreakFinished()!!, defaultSummary).name
prefWork.setOnPreferenceClickListener {
handleRingtonePrefClick(prefWork)
true
}
prefBreak.setOnPreferenceClickListener {
handleRingtonePrefClick(prefBreak)
true
}
if (preferenceHelper.isPro()) {
prefWork.onPreferenceChangeListener = null
} else {
preferenceHelper.setNotificationSoundBreakFinished(preferenceHelper.getNotificationSoundWorkFinished()!!)
prefWork.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _, newValue: Any? ->
preferenceHelper.setNotificationSoundBreakFinished(Gson().toJson(newValue))
prefBreak.summary = prefWork.summary
true
}
}
val prefEnableRingtone =
findPreference<SwitchPreferenceCompat>(PreferenceHelper.ENABLE_RINGTONE)
toggleEnableRingtonePreference(prefEnableRingtone!!.isChecked)
prefEnableRingtone.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _, newValue: Any ->
toggleEnableRingtonePreference(newValue as Boolean)
true
}
}
private fun setupScreensaver() {
val screensaverPref =
findPreference<CheckBoxPreference>(PreferenceHelper.ENABLE_SCREENSAVER_MODE)
findPreference<Preference>(PreferenceHelper.ENABLE_SCREENSAVER_MODE)!!.onPreferenceClickListener =
if (preferenceHelper.isPro()) null else Preference.OnPreferenceClickListener {
launchUpgradeDialog(requireActivity().supportFragmentManager)
screensaverPref!!.isChecked = false
true
}
findPreference<Preference>(PreferenceHelper.ENABLE_SCREEN_ON)!!.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _: Preference?, newValue: Any ->
if (!(newValue as Boolean)) {
if (screensaverPref!!.isChecked) {
screensaverPref.isChecked = false
}
}
true
}
}
private fun setupTheme() {
val prefAmoled = findPreference<SwitchPreferenceCompat>(PreferenceHelper.AMOLED)
prefAmoled!!.onPreferenceClickListener =
if (preferenceHelper.isPro()) null else Preference.OnPreferenceClickListener {
launchUpgradeDialog(requireActivity().supportFragmentManager)
prefAmoled.isChecked = true
true
}
prefAmoled.onPreferenceChangeListener =
if (preferenceHelper.isPro()) Preference.OnPreferenceChangeListener { _, _ ->
ThemeHelper.setTheme(activity as SettingsActivity, preferenceHelper.isAmoledTheme())
requireActivity().recreate()
true
} else null
}
private fun updateDisableSoundCheckBoxSummary(
pref: CheckBoxPreference?,
notificationPolicyAccessGranted: Boolean
) {
if (notificationPolicyAccessGranted) {
pref!!.summary = ""
} else {
pref!!.setSummary(R.string.settings_grant_permission)
}
}
private fun setupDisableSoundCheckBox() {
if (isNotificationPolicyAccessDenied) {
updateDisableSoundCheckBoxSummary(prefDisableSoundCheckbox, false)
prefDisableSoundCheckbox.isChecked = false
prefDisableSoundCheckbox.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
requestNotificationPolicyAccess()
false
}
} else {
updateDisableSoundCheckBoxSummary(prefDisableSoundCheckbox, true)
prefDisableSoundCheckbox.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
if (prefDndMode.isChecked) {
prefDndMode.isChecked = false
true
} else {
false
}
}
}
}
private fun setupFlashingNotificationPref() {
val pref =
findPreference<SwitchPreferenceCompat>(PreferenceHelper.ENABLE_FLASHING_NOTIFICATION)
pref!!.onPreferenceClickListener =
if (preferenceHelper.isPro()) null else Preference.OnPreferenceClickListener {
launchUpgradeDialog(requireActivity().supportFragmentManager)
pref.isChecked = false
true
}
}
private fun setupOneMinuteLeftNotificationPref() {
val pref =
findPreference<SwitchPreferenceCompat>(PreferenceHelper.ENABLE_ONE_MINUTE_BEFORE_NOTIFICATION)
pref!!.onPreferenceClickListener =
if (preferenceHelper.isPro()) null else Preference.OnPreferenceClickListener {
launchUpgradeDialog(requireActivity().supportFragmentManager)
pref.isChecked = false
true
}
}
private fun setupDnDCheckBox() {
if (isNotificationPolicyAccessDenied) {
updateDisableSoundCheckBoxSummary(prefDndMode, false)
prefDndMode.isChecked = false
prefDndMode.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
requestNotificationPolicyAccess()
false
}
} else {
updateDisableSoundCheckBoxSummary(prefDndMode, true)
prefDndMode.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
if (prefDisableSoundCheckbox.isChecked) {
prefDisableSoundCheckbox.isChecked = false
true
} else {
false
}
}
}
}
private fun requestNotificationPolicyAccess() {
if (isNotificationPolicyAccessDenied) {
val intent = Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS)
startActivity(intent)
}
}
@get:TargetApi(Build.VERSION_CODES.M)
private val isNotificationPolicyAccessDenied: Boolean
get() {
val notificationManager =
requireActivity().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
return !notificationManager.isNotificationPolicyAccessGranted
}
private fun toggleEnableRingtonePreference(newValue: Boolean) {
findPreference<Preference>(PreferenceHelper.RINGTONE_WORK_FINISHED)!!.isVisible =
newValue
findPreference<Preference>(PreferenceHelper.RINGTONE_BREAK_FINISHED)!!.isVisible =
newValue
findPreference<Preference>(PreferenceHelper.PRIORITY_ALARM)!!.isVisible =
newValue
}
companion object {
private const val TAG = "SettingsFragment"
}
} | app/src/main/java/com/apps/adrcotfas/goodtime/settings/SettingsFragment.kt | 2466834995 |
package coconautti.sql
import org.joda.time.DateTime
import java.sql.Connection
import kotlin.reflect.KClass
abstract class Statement(private val database: Database) {
fun execute(): Any? = database.execute(this)
fun execute(conn: Connection): Any? = database.execute(conn, this)
abstract fun values(): List<Value>
}
abstract class Query(val database: Database) : Statement(database) {
fun query(): List<Record> = database.query(this)
fun <T> fetch(klass: KClass<*>): List<T> = database.fetch(this, klass)
abstract fun columns(): List<Column>
}
abstract class BatchStatement(private val database: Database) {
fun execute(): List<Any> = database.execute(this)
fun execute(conn: Connection): List<Any> = database.execute(conn, this)
abstract fun values(): List<List<Value>>
}
class Column(private val name: String) {
override fun toString(): String = name
}
class Value(internal val value: Any?) {
override fun toString(): String = when (value) {
null -> "NULL"
is String -> if (isFunction(value)) value else "'$value'"
is Boolean -> if (value) "TRUE" else "FALSE"
is DateTime -> value.toString("YYYY-mm-dd hh:mm:ss.sss")
else -> value.toString()
}
private fun isFunction(value: String): Boolean = (value.contains("(") && value.endsWith(")"))
}
| src/main/kotlin/coconautti/sql/Statement.kt | 795824126 |
package net.nemerosa.ontrack.extension.indicators.ui.graphql
import net.nemerosa.ontrack.extension.indicators.AbstractIndicatorsTestSupport
import net.nemerosa.ontrack.extension.indicators.model.Rating
import net.nemerosa.ontrack.extension.indicators.support.Percentage
import net.nemerosa.ontrack.test.assertJsonNull
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class GQLTypeIndicatorCategoryReportIT : AbstractIndicatorsTestSupport() {
@Test
fun `Getting report for a category filtered on rate`() {
// Creating a view with 1 category
val category = category()
val types = (1..3).map { no ->
category.percentageType(id = "${category.id}-$no", threshold = 100) // Percentage == Compliance
}
// Projects with indicator values for this category
val projects = (1..3).map { project() }
projects.forEachIndexed { pi, project ->
types.forEachIndexed { ti, type ->
project.indicator(type, Percentage((pi * 3 + ti) * 10))
/**
* List of values
*
* Project 0
* Type 0 Value = 0 Rating = F
* Type 1 Value = 10 Rating = F
* Type 2 Value = 20 Rating = F
* Project 1
* Type 0 Value = 30 Rating = E
* Type 1 Value = 40 Rating = D
* Type 2 Value = 50 Rating = D
* Project 2
* Type 0 Value = 60 Rating = C
* Type 1 Value = 70 Rating = C
* Type 2 Value = 80 Rating = B
*/
}
}
// Getting the view report for different rates
val expectedRates = mapOf(
Rating.A to (0..2),
Rating.B to (0..2),
Rating.C to (0..2),
Rating.D to (0..1),
Rating.E to (0..1),
Rating.F to (0..0),
)
expectedRates.forEach { (rating, expectedProjects) ->
run("""
{
indicatorCategories {
categories(id: "${category.id}") {
report {
projectReport(rate: "$rating") {
project {
name
}
indicators {
rating
}
}
}
}
}
}
""").let { data ->
val reports = data.path("indicatorCategories").path("categories").first()
.path("report").path("projectReport")
val projectNames = reports.map { it.path("project").path("name").asText() }
val expectedProjectNames = expectedProjects.map { index ->
projects[index].name
}
println("---- Checking for rate $rating")
println("Expecting: $expectedProjectNames")
println("Actual : $projectNames")
assertEquals(
expectedProjectNames,
projectNames,
"Expecting ${expectedProjectNames.size} projects having rating worse or equal than $rating"
)
}
}
}
@Test
fun `Getting indicator values for all types in a category for all projects`() {
val category = category()
val types = (1..3).map { no ->
category.integerType(id = "${category.id}-$no")
}
val projects = (1..3).map { project() }
projects.forEach { project ->
types.forEach { type ->
project.indicator(type, project.id())
}
}
val unsetProjects = (1..2).map { project() }
run(
"""
{
indicatorCategories {
categories(id: "${category.id}") {
report {
projectReport {
project {
name
}
indicators {
type {
id
}
value
}
}
typeReport {
type {
id
}
projectIndicators {
project {
name
}
indicator {
value
}
}
}
}
}
}
}
"""
).let { data ->
val report = data.path("indicatorCategories").path("categories").first().path("report")
/**
* Report indexed by project
*/
val projectReports = report.path("projectReport").associate { projectReport ->
projectReport.path("project").path("name").asText() to
projectReport.path("indicators")
}
// Projects with values
projects.forEach { project ->
val projectReport = projectReports[project.name]
assertNotNull(projectReport) {
val indicators = it.associate { indicator ->
indicator.path("type").path("id").asText() to
indicator.path("value").path("value")
}
types.forEach { type ->
val value = indicators[type.id]
assertNotNull(value) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
}
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectReport = projectReports[project.name]
assertNotNull(projectReport) {
val indicators = it.associate { indicator ->
indicator.path("type").path("id").asText() to
indicator.path("value").path("value")
}
types.forEach { type ->
val value = indicators[type.id]
assertNotNull(value) { actualValue ->
assertTrue(actualValue.isNull || actualValue.isMissingNode)
}
}
}
}
/**
* Report indexed by type
*/
val typeReports = report.path("typeReport").associate { typeReport ->
typeReport.path("type").path("id").asText() to
typeReport.path("projectIndicators")
}
// For each type
types.forEach { type ->
val typeReport = typeReports[type.id]
assertNotNull(typeReport) { actualTypeReport ->
val projectIndicators = actualTypeReport.associate { projectIndicator ->
projectIndicator.path("project").path("name").asText() to
projectIndicator.path("indicator").path("value").path("value")
}
// Projects with values
projects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
assertNotNull(projectIndicator) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
assertNotNull(projectIndicator) { actualValue ->
assertTrue(actualValue.isNull || actualValue.isMissingNode)
}
}
}
}
}
}
@Test
fun `Getting indicator values for all types in a category only for projects having an indicator`() {
val category = category()
val types = (1..3).map { no ->
category.integerType(id = "${category.id}-$no")
}
val projects = (1..3).map { project() }
projects.forEach { project ->
types.forEach { type ->
project.indicator(type, project.id())
}
}
val unsetProjects = (1..2).map { project() }
run(
"""
{
indicatorCategories {
categories(id: "${category.id}") {
report(filledOnly: true) {
projectReport {
project {
name
}
indicators {
type {
id
}
value
}
}
typeReport {
type {
id
}
projectIndicators {
project {
name
}
indicator {
value
}
}
}
}
}
}
}
"""
).let { data ->
val report = data.path("indicatorCategories").path("categories").first().path("report")
/**
* Report indexed by project
*/
val projectReports = report.path("projectReport").associate { projectReport ->
projectReport.path("project").path("name").asText() to
projectReport.path("indicators")
}
// Projects with values
projects.forEach { project ->
val projectReport = projectReports[project.name]
assertNotNull(projectReport) {
val indicators = it.associate { indicator ->
indicator.path("type").path("id").asText() to
indicator.path("value").path("value")
}
types.forEach { type ->
val value = indicators[type.id]
assertNotNull(value) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
}
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectReport = projectReports[project.name]
assertJsonNull(projectReport)
}
/**
* Report indexed by type
*/
val typeReports = report.path("typeReport").associate { typeReport ->
typeReport.path("type").path("id").asText() to
typeReport.path("projectIndicators")
}
// For each type
types.forEach { type ->
val typeReport = typeReports[type.id]
assertNotNull(typeReport) { actualTypeReport ->
val projectIndicators = actualTypeReport.associate { projectIndicator ->
projectIndicator.path("project").path("name").asText() to
projectIndicator.path("indicator").path("value").path("value")
}
// Projects with values
projects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
assertNotNull(projectIndicator) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
assertJsonNull(projectIndicator)
}
}
}
}
}
@Test
fun `Getting indicator values for all types in a category for a project identified by name`() {
val category = category()
val types = (1..3).map { no ->
category.integerType(id = "${category.id}-$no")
}
val projects = (1..3).map { project() }
projects.forEach { project ->
types.forEach { type ->
project.indicator(type, project.id())
}
}
val unsetProjects = (1..2).map { project() }
run(
"""
{
indicatorCategories {
categories(id: "${category.id}") {
report(projectName: "${projects[0].name}") {
projectReport {
project {
name
}
indicators {
type {
id
}
value
}
}
typeReport {
type {
id
}
projectIndicators {
project {
name
}
indicator {
value
}
}
}
}
}
}
}
"""
).let { data ->
val report = data.path("indicatorCategories").path("categories").first().path("report")
/**
* Report indexed by project
*/
val projectReports = report.path("projectReport").associate { projectReport ->
projectReport.path("project").path("name").asText() to
projectReport.path("indicators")
}
// Projects with values
projects.forEach { project ->
val projectReport = projectReports[project.name]
if (project.name == projects[0].name) {
assertNotNull(projectReport) {
val indicators = it.associate { indicator ->
indicator.path("type").path("id").asText() to
indicator.path("value").path("value")
}
types.forEach { type ->
val value = indicators[type.id]
assertNotNull(value) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
}
}
} else {
assertJsonNull(projectReport)
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectReport = projectReports[project.name]
assertJsonNull(projectReport)
}
/**
* Report indexed by type
*/
val typeReports = report.path("typeReport").associate { typeReport ->
typeReport.path("type").path("id").asText() to
typeReport.path("projectIndicators")
}
// For each type
types.forEach { type ->
val typeReport = typeReports[type.id]
assertNotNull(typeReport) { actualTypeReport ->
val projectIndicators = actualTypeReport.associate { projectIndicator ->
projectIndicator.path("project").path("name").asText() to
projectIndicator.path("indicator").path("value").path("value")
}
// Projects with values
projects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
if (project.name == projects[0].name) {
assertNotNull(projectIndicator) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
} else {
assertJsonNull(projectIndicator)
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
assertJsonNull(projectIndicator)
}
}
}
}
}
@Test
fun `Getting indicator values for all types in a category for a project identified by ID`() {
val category = category()
val types = (1..3).map { no ->
category.integerType(id = "${category.id}-$no")
}
val projects = (1..3).map { project() }
projects.forEach { project ->
types.forEach { type ->
project.indicator(type, project.id())
}
}
val unsetProjects = (1..2).map { project() }
run(
"""
{
indicatorCategories {
categories(id: "${category.id}") {
report(projectId: ${projects[0].id}) {
projectReport {
project {
name
}
indicators {
type {
id
}
value
}
}
typeReport {
type {
id
}
projectIndicators {
project {
name
}
indicator {
value
}
}
}
}
}
}
}
"""
).let { data ->
val report = data.path("indicatorCategories").path("categories").first().path("report")
/**
* Report indexed by project
*/
val projectReports = report.path("projectReport").associate { projectReport ->
projectReport.path("project").path("name").asText() to
projectReport.path("indicators")
}
// Projects with values
projects.forEach { project ->
val projectReport = projectReports[project.name]
if (project.name == projects[0].name) {
assertNotNull(projectReport) {
val indicators = it.associate { indicator ->
indicator.path("type").path("id").asText() to
indicator.path("value").path("value")
}
types.forEach { type ->
val value = indicators[type.id]
assertNotNull(value) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
}
}
} else {
assertJsonNull(projectReport)
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectReport = projectReports[project.name]
assertJsonNull(projectReport)
}
/**
* Report indexed by type
*/
val typeReports = report.path("typeReport").associate { typeReport ->
typeReport.path("type").path("id").asText() to
typeReport.path("projectIndicators")
}
// For each type
types.forEach { type ->
val typeReport = typeReports[type.id]
assertNotNull(typeReport) { actualTypeReport ->
val projectIndicators = actualTypeReport.associate { projectIndicator ->
projectIndicator.path("project").path("name").asText() to
projectIndicator.path("indicator").path("value").path("value")
}
// Projects with values
projects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
if (project.name == projects[0].name) {
assertNotNull(projectIndicator) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
} else {
assertJsonNull(projectIndicator)
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
assertJsonNull(projectIndicator)
}
}
}
}
}
@Test
fun `Getting indicator values for all types in a category for projects identified by a portfolio`() {
val category = category()
val types = (1..3).map { no ->
category.integerType(id = "${category.id}-$no")
}
val projects = (1..3).map { project() }
projects.forEach { project ->
types.forEach { type ->
project.indicator(type, project.id())
}
}
val unsetProjects = (1..2).map { project() }
val label = label()
val portfolio = portfolio(categories = listOf(category), label = label)
projects[0].labels = listOf(label)
run(
"""
{
indicatorCategories {
categories(id: "${category.id}") {
report(portfolio: "${portfolio.id}") {
projectReport {
project {
name
}
indicators {
type {
id
}
value
}
}
typeReport {
type {
id
}
projectIndicators {
project {
name
}
indicator {
value
}
}
}
}
}
}
}
"""
).let { data ->
val report = data.path("indicatorCategories").path("categories").first().path("report")
/**
* Report indexed by project
*/
val projectReports = report.path("projectReport").associate { projectReport ->
projectReport.path("project").path("name").asText() to
projectReport.path("indicators")
}
// Projects with values
projects.forEach { project ->
val projectReport = projectReports[project.name]
if (project.name == projects[0].name) {
assertNotNull(projectReport) {
val indicators = it.associate { indicator ->
indicator.path("type").path("id").asText() to
indicator.path("value").path("value")
}
types.forEach { type ->
val value = indicators[type.id]
assertNotNull(value) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
}
}
} else {
assertJsonNull(projectReport)
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectReport = projectReports[project.name]
assertJsonNull(projectReport)
}
/**
* Report indexed by type
*/
val typeReports = report.path("typeReport").associate { typeReport ->
typeReport.path("type").path("id").asText() to
typeReport.path("projectIndicators")
}
// For each type
types.forEach { type ->
val typeReport = typeReports[type.id]
assertNotNull(typeReport) { actualTypeReport ->
val projectIndicators = actualTypeReport.associate { projectIndicator ->
projectIndicator.path("project").path("name").asText() to
projectIndicator.path("indicator").path("value").path("value")
}
// Projects with values
projects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
if (project.name == projects[0].name) {
assertNotNull(projectIndicator) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
} else {
assertJsonNull(projectIndicator)
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
assertJsonNull(projectIndicator)
}
}
}
}
}
@Test
fun `Getting indicator values for all types in a category for projects identified by a label`() {
val category = category()
val types = (1..3).map { no ->
category.integerType(id = "${category.id}-$no")
}
val projects = (1..3).map { project() }
projects.forEach { project ->
types.forEach { type ->
project.indicator(type, project.id())
}
}
val unsetProjects = (1..2).map { project() }
val label = label()
projects[0].labels = listOf(label)
run(
"""
{
indicatorCategories {
categories(id: "${category.id}") {
report(label: "${label.getDisplay()}") {
projectReport {
project {
name
}
indicators {
type {
id
}
value
}
}
typeReport {
type {
id
}
projectIndicators {
project {
name
}
indicator {
value
}
}
}
}
}
}
}
"""
).let { data ->
val report = data.path("indicatorCategories").path("categories").first().path("report")
/**
* Report indexed by project
*/
val projectReports = report.path("projectReport").associate { projectReport ->
projectReport.path("project").path("name").asText() to
projectReport.path("indicators")
}
// Projects with values
projects.forEach { project ->
val projectReport = projectReports[project.name]
if (project.name == projects[0].name) {
assertNotNull(projectReport) {
val indicators = it.associate { indicator ->
indicator.path("type").path("id").asText() to
indicator.path("value").path("value")
}
types.forEach { type ->
val value = indicators[type.id]
assertNotNull(value) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
}
}
} else {
assertJsonNull(projectReport)
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectReport = projectReports[project.name]
assertJsonNull(projectReport)
}
/**
* Report indexed by type
*/
val typeReports = report.path("typeReport").associate { typeReport ->
typeReport.path("type").path("id").asText() to
typeReport.path("projectIndicators")
}
// For each type
types.forEach { type ->
val typeReport = typeReports[type.id]
assertNotNull(typeReport) { actualTypeReport ->
val projectIndicators = actualTypeReport.associate { projectIndicator ->
projectIndicator.path("project").path("name").asText() to
projectIndicator.path("indicator").path("value").path("value")
}
// Projects with values
projects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
if (project.name == projects[0].name) {
assertNotNull(projectIndicator) { actualValue ->
assertTrue(actualValue.isInt)
assertEquals(project.id(), actualValue.asInt())
}
} else {
assertJsonNull(projectIndicator)
}
}
// Projects without value
unsetProjects.forEach { project ->
val projectIndicator = projectIndicators[project.name]
assertJsonNull(projectIndicator)
}
}
}
}
}
} | ontrack-extension-indicators/src/test/java/net/nemerosa/ontrack/extension/indicators/ui/graphql/GQLTypeIndicatorCategoryReportIT.kt | 3995191703 |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.serialization
import org.jetbrains.kotlin.backend.common.LoggingContext
import org.jetbrains.kotlin.backend.common.overrides.FakeOverrideBuilder
import org.jetbrains.kotlin.backend.common.overrides.PlatformFakeOverrideClassFilter
import org.jetbrains.kotlin.backend.common.serialization.*
import org.jetbrains.kotlin.backend.common.serialization.encodings.BinarySymbolData
import org.jetbrains.kotlin.backend.common.serialization.signature.IdSignatureSerializer
import org.jetbrains.kotlin.backend.konan.CachedLibraries
import org.jetbrains.kotlin.backend.konan.descriptors.isInteropLibrary
import org.jetbrains.kotlin.backend.konan.descriptors.konanLibrary
import org.jetbrains.kotlin.backend.konan.ir.interop.IrProviderForCEnumAndCStructStubs
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.konan.isNativeStdlib
import org.jetbrains.kotlin.descriptors.konan.kotlinLibrary
import org.jetbrains.kotlin.ir.builders.TranslationPluginContext
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrFileImpl
import org.jetbrains.kotlin.ir.declarations.impl.IrModuleFragmentImpl
import org.jetbrains.kotlin.ir.descriptors.IrAbstractFunctionFactory
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
import org.jetbrains.kotlin.ir.symbols.IrSymbol
import org.jetbrains.kotlin.ir.symbols.impl.IrFileSymbolImpl
import org.jetbrains.kotlin.ir.symbols.impl.IrPublicSymbolBase
import org.jetbrains.kotlin.ir.types.classOrNull
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.library.IrLibrary
import org.jetbrains.kotlin.library.KotlinLibrary
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.module
object KonanFakeOverrideClassFilter : PlatformFakeOverrideClassFilter {
private fun IdSignature.isInteropSignature(): Boolean = with(this) {
IdSignature.Flags.IS_NATIVE_INTEROP_LIBRARY.test()
}
// This is an alternative to .isObjCClass that doesn't need to walk up all the class heirarchy,
// rather it only looks at immediate super class symbols.
private fun IrClass.hasInteropSuperClass() = this.superTypes
.mapNotNull { it.classOrNull }
.filter { it is IrPublicSymbolBase<*> }
.any { it.signature.isInteropSignature() }
override fun constructFakeOverrides(clazz: IrClass): Boolean {
return !clazz.hasInteropSuperClass()
}
}
internal class KonanIrLinker(
private val currentModule: ModuleDescriptor,
override val functionalInterfaceFactory: IrAbstractFunctionFactory,
override val translationPluginContext: TranslationPluginContext?,
logger: LoggingContext,
builtIns: IrBuiltIns,
symbolTable: SymbolTable,
private val forwardModuleDescriptor: ModuleDescriptor?,
private val stubGenerator: DeclarationStubGenerator,
private val cenumsProvider: IrProviderForCEnumAndCStructStubs,
exportedDependencies: List<ModuleDescriptor>,
deserializeFakeOverrides: Boolean,
private val cachedLibraries: CachedLibraries
) : KotlinIrLinker(currentModule, logger, builtIns, symbolTable, exportedDependencies, deserializeFakeOverrides) {
companion object {
private val C_NAMES_NAME = Name.identifier("cnames")
private val OBJC_NAMES_NAME = Name.identifier("objcnames")
val FORWARD_DECLARATION_ORIGIN = object : IrDeclarationOriginImpl("FORWARD_DECLARATION_ORIGIN") {}
const val offset = SYNTHETIC_OFFSET
}
override fun isBuiltInModule(moduleDescriptor: ModuleDescriptor): Boolean = moduleDescriptor.isNativeStdlib()
override val fakeOverrideBuilder = FakeOverrideBuilder(symbolTable, IdSignatureSerializer(KonanManglerIr), builtIns, KonanFakeOverrideClassFilter)
private val forwardDeclarationDeserializer = forwardModuleDescriptor?.let { KonanForwardDeclarationModuleDeserializer(it) }
override fun createModuleDeserializer(moduleDescriptor: ModuleDescriptor, klib: IrLibrary?, strategy: DeserializationStrategy): IrModuleDeserializer {
if (moduleDescriptor === forwardModuleDescriptor) {
return forwardDeclarationDeserializer ?: error("forward declaration deserializer expected")
}
if (klib is KotlinLibrary && klib.isInteropLibrary()) {
val isCached = cachedLibraries.isLibraryCached(klib)
return KonanInteropModuleDeserializer(moduleDescriptor, isCached)
}
return KonanModuleDeserializer(moduleDescriptor, klib ?: error("Expecting kotlin library"), strategy)
}
private inner class KonanModuleDeserializer(moduleDescriptor: ModuleDescriptor, klib: IrLibrary, strategy: DeserializationStrategy):
KotlinIrLinker.BasicIrModuleDeserializer(moduleDescriptor, klib, strategy)
private inner class KonanInteropModuleDeserializer(
moduleDescriptor: ModuleDescriptor,
private val isLibraryCached: Boolean
) : IrModuleDeserializer(moduleDescriptor) {
init {
assert(moduleDescriptor.kotlinLibrary.isInteropLibrary())
}
private val descriptorByIdSignatureFinder = DescriptorByIdSignatureFinder(
moduleDescriptor, KonanManglerDesc,
DescriptorByIdSignatureFinder.LookupMode.MODULE_ONLY
)
private fun IdSignature.isInteropSignature(): Boolean = IdSignature.Flags.IS_NATIVE_INTEROP_LIBRARY.test()
override fun contains(idSig: IdSignature): Boolean {
if (idSig.isPublic) {
if (idSig.isInteropSignature()) {
// TODO: add descriptor cache??
return descriptorByIdSignatureFinder.findDescriptorBySignature(idSig) != null
}
}
return false
}
private fun DeclarationDescriptor.isCEnumsOrCStruct(): Boolean = cenumsProvider.isCEnumOrCStruct(this)
private val fileMap = mutableMapOf<PackageFragmentDescriptor, IrFile>()
private fun getIrFile(packageFragment: PackageFragmentDescriptor): IrFile = fileMap.getOrPut(packageFragment) {
IrFileImpl(NaiveSourceBasedFileEntryImpl(IrProviderForCEnumAndCStructStubs.cTypeDefinitionsFileName), packageFragment).also {
moduleFragment.files.add(it)
}
}
private fun resolveCEnumsOrStruct(descriptor: DeclarationDescriptor, idSig: IdSignature, symbolKind: BinarySymbolData.SymbolKind): IrSymbol {
val file = getIrFile(descriptor.findPackage())
return cenumsProvider.getDeclaration(descriptor, idSig, file, symbolKind).symbol
}
override fun deserializeIrSymbol(idSig: IdSignature, symbolKind: BinarySymbolData.SymbolKind): IrSymbol {
val descriptor = descriptorByIdSignatureFinder.findDescriptorBySignature(idSig) ?: error("Expecting descriptor for $idSig")
// If library is cached we don't need to create an IrClass for struct or enum.
if (!isLibraryCached && descriptor.isCEnumsOrCStruct()) return resolveCEnumsOrStruct(descriptor, idSig, symbolKind)
val symbolOwner = stubGenerator.generateMemberStub(descriptor) as IrSymbolOwner
return symbolOwner.symbol
}
override val moduleFragment: IrModuleFragment = IrModuleFragmentImpl(moduleDescriptor, builtIns)
override val moduleDependencies: Collection<IrModuleDeserializer> = listOfNotNull(forwardDeclarationDeserializer)
}
private inner class KonanForwardDeclarationModuleDeserializer(moduleDescriptor: ModuleDescriptor) : IrModuleDeserializer(moduleDescriptor) {
init {
assert(moduleDescriptor.isForwardDeclarationModule)
}
private val declaredDeclaration = mutableMapOf<IdSignature, IrClass>()
private fun IdSignature.isForwardDeclarationSignature(): Boolean {
if (isPublic) {
return packageFqName().run {
startsWith(C_NAMES_NAME) || startsWith(OBJC_NAMES_NAME)
}
}
return false
}
override fun contains(idSig: IdSignature): Boolean = idSig.isForwardDeclarationSignature()
private fun resolveDescriptor(idSig: IdSignature): ClassDescriptor =
with(idSig as IdSignature.PublicSignature) {
val classId = ClassId(packageFqName(), FqName(declarationFqName), false)
moduleDescriptor.findClassAcrossModuleDependencies(classId) ?: error("No declaration found with $idSig")
}
private fun buildForwardDeclarationStub(descriptor: ClassDescriptor): IrClass {
return stubGenerator.generateClassStub(descriptor).also {
it.origin = FORWARD_DECLARATION_ORIGIN
}
}
override fun deserializeIrSymbol(idSig: IdSignature, symbolKind: BinarySymbolData.SymbolKind): IrSymbol {
assert(symbolKind == BinarySymbolData.SymbolKind.CLASS_SYMBOL) { "Only class could be a Forward declaration $idSig (kind $symbolKind)" }
val descriptor = resolveDescriptor(idSig)
val actualModule = descriptor.module
if (actualModule !== moduleDescriptor) {
val moduleDeserializer = deserializersForModules[actualModule] ?: error("No module deserializer for $actualModule")
moduleDeserializer.addModuleReachableTopLevel(idSig)
return symbolTable.referenceClassFromLinker(descriptor, idSig)
}
return declaredDeclaration.getOrPut(idSig) { buildForwardDeclarationStub(descriptor) }.symbol
}
override val moduleFragment: IrModuleFragment = IrModuleFragmentImpl(moduleDescriptor, builtIns)
override val moduleDependencies: Collection<IrModuleDeserializer> = emptyList()
}
val modules: Map<String, IrModuleFragment>
get() = mutableMapOf<String, IrModuleFragment>().apply {
deserializersForModules
.filter { !it.key.isForwardDeclarationModule && it.value.moduleDescriptor !== currentModule }
.forEach { this.put(it.key.konanLibrary!!.libraryName, it.value.moduleFragment) }
}
class KonanPluginContext(
override val moduleDescriptor: ModuleDescriptor,
override val bindingContext: BindingContext,
override val symbolTable: ReferenceSymbolTable,
override val typeTranslator: TypeTranslator,
override val irBuiltIns: IrBuiltIns
):TranslationPluginContext
}
| backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/serialization/KonanIrlinker.kt | 62815570 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.debugOrInfoIfTestMode
import com.intellij.openapi.fileEditor.impl.LoadTextUtil
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.ArrayUtil
import com.intellij.util.LineSeparator
import com.intellij.util.io.readChars
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.loadElement
import org.jdom.Element
import org.jdom.JDOMException
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.nio.file.attribute.BasicFileAttributes
open class FileBasedStorage(file: Path,
fileSpec: String,
rootElementName: String?,
pathMacroManager: TrackingPathMacroSubstitutor? = null,
roamingType: RoamingType? = null,
provider: StreamProvider? = null) :
XmlElementStorage(fileSpec, rootElementName, pathMacroManager, roamingType, provider) {
@Volatile private var cachedVirtualFile: VirtualFile? = null
protected var lineSeparator: LineSeparator? = null
protected var blockSavingTheContent = false
@Volatile var file = file
private set
init {
if (ApplicationManager.getApplication().isUnitTestMode && file.toString().startsWith('$')) {
throw AssertionError("It seems like some macros were not expanded for path: $file")
}
}
protected open val isUseXmlProlog = false
protected open val isUseVfsForWrite = true
private val isUseUnixLineSeparator: Boolean
// only ApplicationStore doesn't use xml prolog
get() = !isUseXmlProlog
// we never set io file to null
fun setFile(virtualFile: VirtualFile?, ioFileIfChanged: Path?) {
cachedVirtualFile = virtualFile
if (ioFileIfChanged != null) {
file = ioFileIfChanged
}
}
override fun createSaveSession(states: StateMap) = FileSaveSession(states, this)
protected open class FileSaveSession(storageData: StateMap, storage: FileBasedStorage) :
XmlElementStorage.XmlElementStorageSaveSession<FileBasedStorage>(storageData, storage) {
override fun save() {
if (storage.blockSavingTheContent) {
LOG.info("Save blocked for ${storage.fileSpec}")
}
else {
super.save()
}
}
override fun saveLocally(dataWriter: DataWriter?) {
var lineSeparator = storage.lineSeparator
if (lineSeparator == null) {
lineSeparator = if (storage.isUseUnixLineSeparator) LineSeparator.LF else LineSeparator.getSystemLineSeparator()
storage.lineSeparator = lineSeparator
}
val isUseVfs = storage.isUseVfsForWrite
val virtualFile = if (isUseVfs) storage.virtualFile else null
if (dataWriter == null) {
if (isUseVfs && virtualFile == null) {
LOG.warn("Cannot find virtual file $virtualFile")
}
deleteFile(storage.file, this, virtualFile)
storage.cachedVirtualFile = null
}
else if (!isUseVfs) {
val file = storage.file
LOG.debugOrInfoIfTestMode { "Save $file" }
dataWriter.writeTo(file, lineSeparator.separatorString)
}
else {
storage.cachedVirtualFile = writeFile(storage.file, this, virtualFile, dataWriter, lineSeparator, storage.isUseXmlProlog)
}
}
}
val virtualFile: VirtualFile?
get() {
var result = cachedVirtualFile
if (result == null) {
result = LocalFileSystem.getInstance().findFileByPath(file.systemIndependentPath)
// otherwise virtualFile.contentsToByteArray() will query expensive FileTypeManager.getInstance()).getByFile()
result?.charset = StandardCharsets.UTF_8
cachedVirtualFile = result
}
return cachedVirtualFile
}
protected inline fun <T> runAndHandleExceptions(task: () -> T): T? {
try {
return task()
}
catch (e: JDOMException) {
processReadException(e)
}
catch (e: IOException) {
processReadException(e)
}
return null
}
fun preloadStorageData(isEmpty: Boolean) {
if (isEmpty) {
storageDataRef.set(StateMap.EMPTY)
}
else {
getStorageData()
}
}
override fun loadLocalData(): Element? {
blockSavingTheContent = false
return runAndHandleExceptions { loadLocalDataUsingIo() }
}
private fun loadLocalDataUsingIo(): Element? {
val attributes: BasicFileAttributes?
try {
attributes = Files.readAttributes(file, BasicFileAttributes::class.java)
}
catch (e: NoSuchFileException) {
LOG.debug { "Document was not loaded for $fileSpec, doesn't exist" }
return null
}
if (!attributes.isRegularFile) {
LOG.debug { "Document was not loaded for $fileSpec, not a file" }
}
else if (attributes.size() == 0L) {
processReadException(null)
}
else if (isUseUnixLineSeparator) {
// do not load the whole data into memory if no need to detect line separator
lineSeparator = LineSeparator.LF
return loadElement(file)
}
else {
val data = file.readChars()
lineSeparator = detectLineSeparators(data, if (isUseXmlProlog) null else LineSeparator.LF)
return loadElement(data)
}
return null
}
protected fun processReadException(e: Exception?) {
val contentTruncated = e == null
blockSavingTheContent = !contentTruncated &&
(PROJECT_FILE == fileSpec || fileSpec.startsWith(PROJECT_CONFIG_DIR) ||
fileSpec == StoragePathMacros.MODULE_FILE || fileSpec == StoragePathMacros.WORKSPACE_FILE)
if (e != null) {
LOG.warn(e)
}
val app = ApplicationManager.getApplication()
if (!app.isUnitTestMode && !app.isHeadlessEnvironment) {
val reason = if (contentTruncated) "content truncated" else e!!.message
val action = if (blockSavingTheContent) "Please correct the file content" else "File content will be recreated"
Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID,
"Load Settings",
"Cannot load settings from file '$file': $reason\n$action",
NotificationType.WARNING)
.notify(null)
}
}
override fun toString(): String = file.systemIndependentPath
}
internal fun writeFile(file: Path?,
requestor: Any,
virtualFile: VirtualFile?,
dataWriter: DataWriter,
lineSeparator: LineSeparator,
prependXmlProlog: Boolean): VirtualFile {
val result = if (file != null && (virtualFile == null || !virtualFile.isValid)) {
getOrCreateVirtualFile(requestor, file)
}
else {
virtualFile!!
}
if ((LOG.isDebugEnabled || ApplicationManager.getApplication().isUnitTestMode) && !FileUtilRt.isTooLarge(result.length)) {
val content = dataWriter.toBufferExposingByteArray(lineSeparator)
if (isEqualContent(result, lineSeparator, content, prependXmlProlog)) {
val contentString = content.toByteArray().toString(StandardCharsets.UTF_8)
LOG.warn("Content equals, but it must be handled not on this level: file ${result.name}, content:\n$contentString")
}
else if (DEBUG_LOG != null && ApplicationManager.getApplication().isUnitTestMode) {
DEBUG_LOG = "${result.path}:\n$content\nOld Content:\n${LoadTextUtil.loadText(result)}"
}
}
doWrite(requestor, result, dataWriter, lineSeparator, prependXmlProlog)
return result
}
internal val XML_PROLOG = """<?xml version="1.0" encoding="UTF-8"?>""".toByteArray()
private fun isEqualContent(result: VirtualFile,
lineSeparator: LineSeparator,
content: BufferExposingByteArrayOutputStream,
prependXmlProlog: Boolean): Boolean {
val headerLength = if (!prependXmlProlog) 0 else XML_PROLOG.size + lineSeparator.separatorBytes.size
if (result.length.toInt() != (headerLength + content.size())) {
return false
}
val oldContent = result.contentsToByteArray()
if (prependXmlProlog && (!ArrayUtil.startsWith(oldContent, XML_PROLOG) ||
!ArrayUtil.startsWith(oldContent, XML_PROLOG.size, lineSeparator.separatorBytes))) {
return false
}
return (headerLength until oldContent.size).all { oldContent[it] == content.internalBuffer[it - headerLength] }
}
private fun doWrite(requestor: Any, file: VirtualFile, dataWriterOrByteArray: Any, lineSeparator: LineSeparator, prependXmlProlog: Boolean) {
LOG.debugOrInfoIfTestMode { "Save ${file.presentableUrl}" }
if (!file.isWritable) {
// may be element is not long-lived, so, we must write it to byte array
val byteArray = when (dataWriterOrByteArray) {
is DataWriter -> dataWriterOrByteArray.toBufferExposingByteArray(lineSeparator)
else -> dataWriterOrByteArray as BufferExposingByteArrayOutputStream
}
throw ReadOnlyModificationException(file, object : StateStorage.SaveSession {
override fun save() {
doWrite(requestor, file, byteArray, lineSeparator, prependXmlProlog)
}
})
}
runUndoTransparentWriteAction {
file.getOutputStream(requestor).use { output ->
if (prependXmlProlog) {
output.write(XML_PROLOG)
output.write(lineSeparator.separatorBytes)
}
if (dataWriterOrByteArray is DataWriter) {
dataWriterOrByteArray.write(output, lineSeparator.separatorString)
}
else {
(dataWriterOrByteArray as BufferExposingByteArrayOutputStream).writeTo(output)
}
}
}
}
internal fun detectLineSeparators(chars: CharSequence, defaultSeparator: LineSeparator? = null): LineSeparator {
for (c in chars) {
if (c == '\r') {
return LineSeparator.CRLF
}
else if (c == '\n') {
// if we are here, there was no \r before
return LineSeparator.LF
}
}
return defaultSeparator ?: LineSeparator.getSystemLineSeparator()
}
private fun deleteFile(file: Path, requestor: Any, virtualFile: VirtualFile?) {
if (virtualFile == null) {
try {
Files.delete(file)
}
catch (ignored: NoSuchFileException) {
}
}
else if (virtualFile.exists()) {
if (virtualFile.isWritable) {
deleteFile(requestor, virtualFile)
}
else {
throw ReadOnlyModificationException(virtualFile, object : StateStorage.SaveSession {
override fun save() {
deleteFile(requestor, virtualFile)
}
})
}
}
}
internal fun deleteFile(requestor: Any, virtualFile: VirtualFile) {
runUndoTransparentWriteAction { virtualFile.delete(requestor) }
}
internal class ReadOnlyModificationException(val file: VirtualFile, val session: StateStorage.SaveSession?) : RuntimeException("File is read-only: $file") | platform/configuration-store-impl/src/FileBasedStorage.kt | 1498170738 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.intellij.build.images
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.LineSeparator
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.diff.Diff
import org.jetbrains.jps.model.JpsSimpleElement
import org.jetbrains.jps.model.java.JavaSourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.util.JpsPathUtil
import java.io.File
import java.nio.charset.StandardCharsets
import java.nio.file.*
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
data class ModifiedClass(val module: JpsModule, val file: Path, val result: CharSequence)
class IconsClassGenerator(private val projectHome: File, val util: JpsModule, private val writeChangesToDisk: Boolean = true) {
private val processedClasses = AtomicInteger()
private val processedIcons = AtomicInteger()
private val processedPhantom = AtomicInteger()
private val modifiedClasses = ContainerUtil.createConcurrentList<ModifiedClass>()
fun processModule(module: JpsModule) {
val customLoad: Boolean
val packageName: String
val className: String
val outFile: Path
if ("intellij.platform.icons" == module.name) {
customLoad = false
packageName = "com.intellij.icons"
className = "AllIcons"
val dir = util.getSourceRoots(JavaSourceRootType.SOURCE).first().file.absolutePath + "/com/intellij/icons"
outFile = Paths.get(dir, "AllIcons.java")
}
else {
customLoad = true
packageName = "icons"
val firstRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).firstOrNull() ?: return
val firstRootDir = firstRoot.file.toPath().resolve("icons")
var oldClassName: String?
// this is added to remove unneeded empty directories created by previous version of this script
if (Files.isDirectory(firstRootDir)) {
try {
Files.delete(firstRootDir)
println("deleting empty directory $firstRootDir")
}
catch (ignore: DirectoryNotEmptyException) {
}
oldClassName = findIconClass(firstRootDir)
}
else {
oldClassName = null
}
val generatedRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).find { it.properties.isForGeneratedSources }
val targetRoot = (generatedRoot ?: firstRoot).file.toPath().resolve("icons")
if (generatedRoot != null && oldClassName != null) {
val oldFile = firstRootDir.resolve("$oldClassName.java")
println("deleting $oldFile from source root which isn't marked as 'generated'")
Files.delete(oldFile)
}
if (oldClassName == null) {
try {
oldClassName = findIconClass(targetRoot)
}
catch (ignored: NoSuchFileException) {
}
}
className = oldClassName ?: directoryName(module) + "Icons"
outFile = targetRoot.resolve("$className.java")
}
val oldText = if (Files.exists(outFile)) Files.readAllBytes(outFile).toString(StandardCharsets.UTF_8) else null
val newText = generate(module, className, packageName, customLoad, getCopyrightComment(oldText))
val oldLines = oldText?.lines() ?: emptyList()
val newLines = newText?.lines() ?: emptyList()
if (newLines.isNotEmpty()) {
processedClasses.incrementAndGet()
if (oldLines != newLines) {
if (writeChangesToDisk) {
val separator = getSeparators(oldText)
Files.createDirectories(outFile.parent)
Files.write(outFile, newLines.joinToString(separator = separator.separatorString).toByteArray())
println("Updated icons class: ${outFile.fileName}")
}
else {
val sb = StringBuilder()
var ch = Diff.buildChanges(oldLines.toTypedArray(), newLines.toTypedArray())
while (ch != null) {
val deleted = oldLines.subList(ch.line0, ch.line0 + ch.deleted)
val inserted = newLines.subList(ch.line1, ch.line1 + ch.inserted)
if (sb.isNotEmpty()) sb.append("=".repeat(20)).append("\n")
deleted.forEach { sb.append("-").append(it).append("\n") }
inserted.forEach { sb.append("+").append(it).append("\n") }
ch = ch.link
}
modifiedClasses.add(ModifiedClass(module, outFile, sb))
}
}
}
}
fun printStats() {
println()
println("Generated classes: ${processedClasses.get()}. Processed icons: ${processedIcons.get()}. Phantom icons: ${processedPhantom.get()}")
}
fun getModifiedClasses(): List<ModifiedClass> = modifiedClasses
private fun findIconClass(dir: Path): String? {
Files.newDirectoryStream(dir).use { stream ->
for (it in stream) {
val name = it.fileName.toString()
if (name.endsWith("Icons.java")) {
return name.substring(0, name.length - ".java".length)
}
}
}
return null
}
private fun getCopyrightComment(text: String?): String {
if (text == null) return ""
val i = text.indexOf("package ")
if (i == -1) return ""
val comment = text.substring(0, i)
return if (comment.trim().endsWith("*/") || comment.trim().startsWith("//")) comment else ""
}
private fun getSeparators(text: String?): LineSeparator {
if (text == null) return LineSeparator.LF
return StringUtil.detectSeparators(text) ?: LineSeparator.LF
}
private fun generate(module: JpsModule, className: String, packageName: String, customLoad: Boolean, copyrightComment: String): String? {
val imageCollector = ImageCollector(projectHome.toPath(), iconsOnly = true, className = className)
val images = imageCollector.collect(module, includePhantom = true)
if (images.isEmpty()) {
return null
}
imageCollector.printUsedIconRobots()
val answer = StringBuilder()
answer.append(copyrightComment)
append(answer, "package $packageName;\n", 0)
append(answer, "import com.intellij.openapi.util.IconLoader;", 0)
append(answer, "", 0)
append(answer, "import javax.swing.*;", 0)
append(answer, "", 0)
// IconsGeneratedSourcesFilter depends on following comment, if you going to change the text
// please do corresponding changes in IconsGeneratedSourcesFilter as well
append(answer, "/**", 0)
append(answer, " * NOTE THIS FILE IS AUTO-GENERATED", 0)
append(answer, " * DO NOT EDIT IT BY HAND, run \"Generate icon classes\" configuration instead", 0)
append(answer, " */", 0)
append(answer, "public class $className {", 0)
if (customLoad) {
append(answer, "private static Icon load(String path) {", 1)
append(answer, "return IconLoader.getIcon(path, ${className}.class);", 2)
append(answer, "}", 1)
append(answer, "", 0)
val customExternalLoad = images.any { it.deprecation?.replacementContextClazz != null }
if (customExternalLoad) {
append(answer, "private static Icon load(String path, Class<?> clazz) {", 1)
append(answer, "return IconLoader.getIcon(path, clazz);", 2)
append(answer, "}", 1)
append(answer, "", 0)
}
}
val inners = StringBuilder()
processIcons(images, inners, customLoad, 0)
if (inners.isEmpty()) return null
answer.append(inners)
append(answer, "}", 0)
return answer.toString()
}
private fun processIcons(images: List<ImagePaths>, answer: StringBuilder, customLoad: Boolean, depth: Int) {
val level = depth + 1
val (nodes, leafs) = images.partition { getImageId(it, depth).contains('/') }
val nodeMap = nodes.groupBy { getImageId(it, depth).substringBefore('/') }
val leafMap = ContainerUtil.newMapFromValues(leafs.iterator()) { getImageId(it, depth) }
fun getWeight(key: String): Int {
val image = leafMap[key]
if (image == null) {
return 0
}
return if (image.deprecated) 1 else 0
}
val sortedKeys = (nodeMap.keys + leafMap.keys)
.sortedWith(NAME_COMPARATOR)
.sortedWith(kotlin.Comparator(function = { o1, o2 ->
getWeight(o1) - getWeight(o2)
}))
for (key in sortedKeys) {
val group = nodeMap[key]
val image = leafMap[key]
if (group != null) {
val inners = StringBuilder()
processIcons(group, inners, customLoad, depth + 1)
if (inners.isNotEmpty()) {
append(answer, "", level)
append(answer, "public static class " + className(key) + " {", level)
append(answer, inners.toString(), 0)
append(answer, "}", level)
}
}
if (image != null) {
appendImage(image, answer, level, customLoad)
}
}
}
private fun appendImage(image: ImagePaths,
answer: StringBuilder,
level: Int,
customLoad: Boolean) {
val file = image.file ?: return
if (!image.phantom && !isIcon(file)) {
return
}
processedIcons.incrementAndGet()
if (image.phantom) {
processedPhantom.incrementAndGet()
}
if (image.used || image.deprecated) {
val deprecationComment = image.deprecation?.comment
append(answer, "", level)
if (deprecationComment != null) {
append(answer, "/** @deprecated $deprecationComment */", level)
}
append(answer, "@SuppressWarnings(\"unused\")", level)
}
if (image.deprecated) {
append(answer, "@Deprecated", level)
}
val sourceRoot = image.sourceRoot
var rootPrefix = "/"
if (sourceRoot.rootType == JavaSourceRootType.SOURCE) {
@Suppress("UNCHECKED_CAST")
val packagePrefix = (sourceRoot.properties as JpsSimpleElement<JavaSourceRootProperties>).data.packagePrefix
if (!packagePrefix.isEmpty()) {
rootPrefix += packagePrefix.replace('.', '/') + "/"
}
}
val iconName = iconName(file)
val deprecation = image.deprecation
if (deprecation?.replacementContextClazz != null) {
val method = if (customLoad) "load" else "IconLoader.getIcon"
append(answer,
"public static final Icon $iconName = $method(\"${deprecation.replacement}\", ${deprecation.replacementContextClazz}.class);",
level)
return
}
else if (deprecation?.replacementReference != null) {
append(answer, "public static final Icon $iconName = ${deprecation.replacementReference};", level)
return
}
val sourceRootFile = Paths.get(JpsPathUtil.urlToPath(sourceRoot.url))
val imageFile: Path
if (deprecation?.replacement == null) {
imageFile = file
}
else {
imageFile = sourceRootFile.resolve(deprecation.replacement.removePrefix("/").removePrefix(File.separator))
assert(isIcon(imageFile)) { "Overriding icon should be valid: $iconName - $imageFile" }
}
val size = if (Files.exists(imageFile)) imageSize(imageFile) else null
val comment: String
when {
size != null -> comment = " // ${size.width}x${size.height}"
image.phantom -> comment = ""
else -> error("Can't get icon size: $imageFile")
}
val method = if (customLoad) "load" else "IconLoader.getIcon"
val relativePath = rootPrefix + FileUtilRt.toSystemIndependentName(sourceRootFile.relativize(imageFile).toString())
append(answer,
"public static final Icon $iconName = $method(\"$relativePath\");$comment",
level)
}
private fun append(answer: StringBuilder, text: String, level: Int) {
if (text.isNotBlank()) answer.append(" ".repeat(level))
answer.append(text).append("\n")
}
private fun getImageId(image: ImagePaths, depth: Int): String {
val path = image.id.removePrefix("/").split("/")
if (path.size < depth) {
throw IllegalArgumentException("Can't get image ID - ${image.id}, $depth")
}
return path.drop(depth).joinToString("/")
}
private fun directoryName(module: JpsModule): String {
return directoryNameFromConfig(module) ?: className(module.name)
}
private fun directoryNameFromConfig(module: JpsModule): String? {
val rootUrl = getFirstContentRootUrl(module) ?: return null
val rootDir = File(JpsPathUtil.urlToPath(rootUrl))
if (!rootDir.isDirectory) return null
val file = File(rootDir, ROBOTS_FILE_NAME)
if (!file.exists()) return null
val prefix = "name:"
var moduleName: String? = null
file.forEachLine {
if (it.startsWith(prefix)) {
val name = it.substring(prefix.length).trim()
if (name.isNotEmpty()) moduleName = name
}
}
return moduleName
}
private fun getFirstContentRootUrl(module: JpsModule): String? {
return module.contentRootsList.urls.firstOrNull()
}
private fun className(name: String): String {
val answer = StringBuilder()
name.removePrefix("intellij.").split("-", "_", ".").forEach {
answer.append(capitalize(it))
}
return toJavaIdentifier(answer.toString())
}
private fun iconName(file: Path): String {
val name = capitalize(file.fileName.toString().substringBeforeLast('.'))
return toJavaIdentifier(name)
}
private fun toJavaIdentifier(id: String): String {
val sb = StringBuilder()
id.forEach {
if (Character.isJavaIdentifierPart(it)) {
sb.append(it)
}
else {
sb.append('_')
}
}
if (Character.isJavaIdentifierStart(sb.first())) {
return sb.toString()
}
else {
return "_" + sb.toString()
}
}
private fun capitalize(name: String): String {
if (name.length == 2) return name.toUpperCase()
return name.capitalize()
}
// legacy ordering
private val NAME_COMPARATOR: Comparator<String> = compareBy { it.toLowerCase() + "." }
}
| platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/IconsClassGenerator.kt | 1786611085 |
package graphql.language
class VariableDefinition : AbstractNode {
val name: String
var type: Type? = null
var defaultValue: Value? = null
constructor(name: String) {
this.name = name
}
constructor(name: String, type: Type) : this(name){
this.type = type
}
constructor(name: String, type: Type, defaultValue: Value) : this(name, type){
this.defaultValue = defaultValue
}
override val children: List<Node>
get() {
val result = mutableListOf<Node>()
type?.let { result.add(it) }
defaultValue?.let { result.add(it) }
return result
}
override fun isEqualTo(node: Node): Boolean {
if (this === node) return true
if (javaClass != node.javaClass) return false
val that = node as VariableDefinition
return name == that.name
}
override fun toString(): String {
return "VariableDefinition{" +
"name='" + name + '\'' +
", type=" + type +
", defaultValue=" + defaultValue +
'}'
}
}
| src/main/kotlin/graphql/language/VariableDefinition.kt | 1216005059 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.liteloader
import com.demonwav.mcdev.MinecraftSettings
import com.demonwav.mcdev.facet.MinecraftFacet
import com.intellij.ide.FileIconProvider
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import javax.swing.Icon
class LiteLoaderFileIconProvider : FileIconProvider {
override fun getIcon(file: VirtualFile, flags: Int, project: Project?): Icon? {
project ?: return null
if (!MinecraftSettings.instance.isShowProjectPlatformIcons) {
return null
}
val module = ModuleUtilCore.findModuleForFile(file, project) ?: return null
val liteloaderModule = MinecraftFacet.getInstance(module, LiteLoaderModuleType) ?: return null
if (file == liteloaderModule.litemodJson) {
return liteloaderModule.icon
}
return null
}
}
| src/main/kotlin/platform/liteloader/LiteLoaderFileIconProvider.kt | 994426154 |
package de.axelrindle.broadcaster.command
import de.axelrindle.broadcaster.BroadcastingThread
import de.axelrindle.broadcaster.plugin
import de.axelrindle.pocketknife.PocketCommand
import de.axelrindle.pocketknife.util.sendMessageF
import org.bukkit.command.Command
import org.bukkit.command.CommandSender
/**
* Starts the broadcasting thread.
*
* @see BroadcastingThread
*/
class StartCommand : PocketCommand() {
override fun getName(): String {
return "start"
}
override fun getDescription(): String {
return plugin.localization.localize("CommandHelp.Start")!!
}
override fun getUsage(): String {
return "/brc start"
}
override fun getPermission(): String {
return "broadcaster.start"
}
override fun handle(sender: CommandSender, command: Command, args: Array<out String>): Boolean {
try {
BroadcastingThread.start()
sender.sendMessageF(plugin.localization.localize("Started")!!)
} catch (e: RuntimeException) {
sender.sendMessageF(plugin.localization.localize(e.message!!)!!)
}
return true
}
override fun sendHelp(sender: CommandSender) {
sender.sendMessageF("&9${getUsage()} &f- &3${getDescription()}")
}
} | src/main/kotlin/de/axelrindle/broadcaster/command/StartCommand.kt | 1299949627 |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.materialstudies.owl.ui.learn
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.materialstudies.owl.databinding.RelatedCourseItemBinding
import com.materialstudies.owl.model.Course
import com.materialstudies.owl.model.CourseDiff
class RelatedAdapter : ListAdapter<Course, RelatedViewHolder>(CourseDiff) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RelatedViewHolder {
val binding = RelatedCourseItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return RelatedViewHolder(binding)
}
override fun onBindViewHolder(holder: RelatedViewHolder, position: Int) {
holder.bind(getItem(position))
}
}
class RelatedViewHolder(
private val binding: RelatedCourseItemBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(course: Course) {
binding.run {
this.course = course
executePendingBindings()
}
}
} | Owl/app/src/main/java/com/materialstudies/owl/ui/learn/RelatedAdapter.kt | 3218991005 |
/*
* Copyright 2020 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.materialstudies.reply.ui.nav
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.ListAdapter
import com.materialstudies.reply.data.Account
import com.materialstudies.reply.data.AccountDiffCallback
import com.materialstudies.reply.databinding.AccountItemLayoutBinding
/**
* An adapter which holds a list of selectable accounts owned by the current user.
*/
class AccountAdapter(
private val listener: AccountAdapterListener
) : ListAdapter<Account, AccountViewHolder>(AccountDiffCallback) {
interface AccountAdapterListener {
fun onAccountClicked(account: Account)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AccountViewHolder {
return AccountViewHolder(
AccountItemLayoutBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
),
listener
)
}
override fun onBindViewHolder(holder: AccountViewHolder, position: Int) {
holder.bind(getItem(position))
}
} | app/src/main/java/com/materialstudies/reply/ui/nav/AccountAdapter.kt | 4197837613 |
package siarhei.luskanau.example.workmanager.monitor
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout.VERTICAL
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DividerItemDecoration
import siarhei.luskanau.example.workmanager.databinding.FragmentWorkManagerMonitorBinding
class WorkManagerMonitorFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentWorkManagerMonitorBinding.inflate(inflater, container, false)
val adapter = WorkInfoAdapter()
binding.recyclerView.adapter = adapter
binding.recyclerView.addItemDecoration(
DividerItemDecoration(
binding.recyclerView.context,
VERTICAL
)
)
val workManagerMonitorViewModel =
ViewModelProvider(this).get(WorkManagerMonitorViewModel::class.java)
workManagerMonitorViewModel.getWorkStatusListLiveData(requireContext())
.observe(viewLifecycleOwner, Observer { adapter.submitList(it) })
return binding.root
}
}
| workmanager/src/main/java/siarhei/luskanau/example/workmanager/monitor/WorkManagerMonitorFragment.kt | 3945303015 |
/*
* Copyright (c) 2017 Michał Bączkowski
*
* 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.mibac138.argparser.binder
import com.github.mibac138.argparser.named.name
import com.github.mibac138.argparser.syntax.autoIndex
import com.github.mibac138.argparser.syntax.dsl.SyntaxElementDSL
/**
* Annotation used to [automagically][CallableBoundMethod] generate [named][SyntaxElement.name] syntax elements
*/
@Target(AnnotationTarget.VALUE_PARAMETER)
@Retention(AnnotationRetention.RUNTIME)
annotation class Name(
/**
* The name you want the parameter to have
*/
val value: String,
/**
* if true (auto) assigns an index to the parameter.
* <b>Do not use this and [@Index][Index] simultaneously</b>
*/
val ordered: Boolean = false)
/**
* Generates [named][SyntaxElement.name] syntax by using the [`@Name`][Name] annotation
*/
class NameSyntaxGenerator : AnnotationBasedSyntaxGenerator<Name>(Name::class.java) {
override fun generate(dsl: SyntaxElementDSL, annotation: Name) {
dsl.name = annotation.value
if (annotation.ordered)
dsl.autoIndex()
}
} | binder/src/main/kotlin/com/github/mibac138/argparser/binder/Name.kt | 4186227586 |
package com.soywiz.korge3d
@Experimental(Experimental.Level.WARNING)
annotation class Korge3DExperimental
| korge/src/commonMain/kotlin/com/soywiz/korge3d/Korge3DExperimental.kt | 2954537770 |
package me.ztiany.operators
import java.time.LocalDate
operator fun ClosedRange<LocalDate>.iterator(): Iterator<LocalDate> =
object : Iterator<LocalDate> {
var current = start
override fun hasNext() =
current <= endInclusive
override fun next() = current.apply {
current = plusDays(1)
}
}
fun main(args: Array<String>) {
val newYear = LocalDate.ofYearDay(2017, 1)
val daysOff = newYear.minusDays(1)..newYear
for (dayOff in daysOff) {
println(dayOff)
}
}
| Kotlin/Kotlin-Basic/src/main/kotlin/me/ztiany/operators/IteratorOperator.kt | 92470285 |
/*
* adb-nmap: An ADB network device discovery and connection library
* Copyright (C) 2017-present Arav Singhal and adb-nmap contributors
*
* 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.
*
* The full license can be found in LICENSE.md.
*/
package net.eviltak.adbnmap.net
import net.eviltak.adbnmap.net.protocol.Protocol
import java.net.Socket
import java.net.SocketAddress
import java.util.concurrent.Callable
import java.util.concurrent.Executors
/**
* Scans networks for devices which use the specified protocol.
*
* @param P The type of protocol devices are expected to use.
*
* @property protocolFactory Creates an instance of the protocol of type [P] from the socket to be used
* to connect to the host.
*/
class NetworkMapper<out P : Protocol<*>>(val socketConnector: SocketConnector,
val protocolFactory: (Socket) -> P) {
/**
* Pings the host at [socketAddress] if such a host exists to check whether it supports the
* specified protocol.
*
* @param socketAddress The socket address of the host to ping.
* @return True if the host at [socketAddress] exists and supports the specified protocol.
*/
fun ping(socketAddress: SocketAddress): Boolean {
return socketConnector.tryConnect(socketAddress) {
protocolFactory(it).hostUsesProtocol()
}
}
/**
* Pings all hosts in [network] and returns the address of all devices that support the
* protocol [P].
*
* @param network A collection of addresses representing the network.
* @return A [List] containing the addresses of all devices in [network] that support the
* protocol [P].
*/
fun getDevicesInNetwork(network: Iterable<SocketAddress>): List<SocketAddress> {
val executor = Executors.newCachedThreadPool()
val futures = executor.invokeAll(network.map { Callable { if (ping(it)) it else null } })
return futures.map { it.get() }.filterNotNull()
}
}
| src/main/kotlin/net/eviltak/adbnmap/net/NetworkMapper.kt | 3288797195 |
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.preference
import android.content.Context
import android.content.SharedPreferences
import android.support.v7.preference.Preference
import android.text.TextUtils
import android.util.AttributeSet
import org.mariotaku.abstask.library.AbstractTask
import org.mariotaku.abstask.library.TaskStarter
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.TwittnukerConstants.*
import de.vanita5.twittnuker.constant.SharedPreferenceConstants
import de.vanita5.twittnuker.push.PushBackendServer
class PushNotificationStatusPreference @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = R.attr.preferenceStyle
) : Preference(context, attrs, defStyle) {
private val preferences: SharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
init {
setTitle(R.string.push_status_title)
if (preferences.getBoolean(SharedPreferenceConstants.GCM_TOKEN_SENT, false)) {
setSummary(R.string.push_status_connected)
} else {
setSummary(R.string.push_status_disconnected)
}
}
override fun onClick() {
setSummary(R.string.push_status_disconnecting)
super.onClick()
val task = object : AbstractTask<Any?, Unit, PushNotificationStatusPreference>() {
override fun afterExecute(pushNotificationStatusPreference: PushNotificationStatusPreference?, result: Unit?) {
pushNotificationStatusPreference!!.setSummary(R.string.push_status_disconnected)
}
override fun doLongOperation(param: Any?) {
val currentToken = preferences.getString(SharedPreferenceConstants.GCM_CURRENT_TOKEN, null)
if (!TextUtils.isEmpty(currentToken)) {
val backend = PushBackendServer(context)
backend.remove(currentToken)
preferences.edit().putBoolean(SharedPreferenceConstants.GCM_TOKEN_SENT, false).apply()
preferences.edit().putString(SharedPreferenceConstants.GCM_CURRENT_TOKEN, null).apply()
}
}
}
task.callback = this
TaskStarter.execute(task)
}
}
| twittnuker/src/main/kotlin/de/vanita5/twittnuker/preference/PushNotificationStatusPreference.kt | 550946500 |
package com.anyaku.crypt.combined
import com.anyaku.crypt.asymmetric.EncryptedData as AsymmetricEncryptedData
import com.anyaku.crypt.symmetric.EncryptedData as SymmetricEncryptedData
trait EncryptedData {
val key: AsymmetricEncryptedData
val data: SymmetricEncryptedData
}
| src/main/kotlin/com/anyaku/crypt/combined/EncryptedData.kt | 3315111609 |
package ch.schulealtendorf.psa.service.core.github
data class VersionResponse(
val version: String
)
| app/psa-core-service/src/main/kotlin/ch/schulealtendorf/psa/service/core/github/VersionResponse.kt | 3436418792 |
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.loader.users
import android.content.Context
import de.vanita5.microblog.library.MicroBlog
import de.vanita5.microblog.library.MicroBlogException
import de.vanita5.microblog.library.twitter.model.Paging
import de.vanita5.microblog.library.twitter.model.ResponseList
import de.vanita5.microblog.library.twitter.model.User
import de.vanita5.twittnuker.extension.model.api.microblog.mapToPaginated
import de.vanita5.twittnuker.extension.model.api.toParcelable
import de.vanita5.twittnuker.extension.model.newMicroBlogInstance
import de.vanita5.twittnuker.model.AccountDetails
import de.vanita5.twittnuker.model.ParcelableUser
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.pagination.PaginatedList
class GroupMembersLoader(
context: Context,
accountKey: UserKey?,
private val groupId: String?,
private val groupName: String?,
data: List<ParcelableUser>?,
fromUser: Boolean
) : AbsRequestUsersLoader(context, accountKey, data, fromUser) {
@Throws(MicroBlogException::class)
override fun getUsers(details: AccountDetails, paging: Paging): PaginatedList<ParcelableUser> {
return getMicroBlogUsers(details, paging).mapToPaginated(pagination) {
it.toParcelable(details, profileImageSize = profileImageSize)
}
}
private fun getMicroBlogUsers(details: AccountDetails, paging: Paging): ResponseList<User> {
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
when {
groupId != null -> return microBlog.getGroupMembers(groupId, paging)
groupName != null -> return microBlog.getGroupMembersByName(groupName, paging)
else -> throw MicroBlogException("groupId or groupName required")
}
}
} | twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/users/GroupMembersLoader.kt | 3207209683 |
package com.stripe.android
import android.app.Activity
import android.os.Parcelable
import androidx.annotation.IntRange
import com.stripe.android.stripe3ds2.init.ui.ButtonCustomization
import com.stripe.android.stripe3ds2.init.ui.LabelCustomization
import com.stripe.android.stripe3ds2.init.ui.StripeButtonCustomization
import com.stripe.android.stripe3ds2.init.ui.StripeLabelCustomization
import com.stripe.android.stripe3ds2.init.ui.StripeTextBoxCustomization
import com.stripe.android.stripe3ds2.init.ui.StripeToolbarCustomization
import com.stripe.android.stripe3ds2.init.ui.StripeUiCustomization
import com.stripe.android.stripe3ds2.init.ui.TextBoxCustomization
import com.stripe.android.stripe3ds2.init.ui.ToolbarCustomization
import com.stripe.android.stripe3ds2.init.ui.UiCustomization
import kotlinx.parcelize.Parcelize
/**
* Configuration for authentication mechanisms via [StripePaymentController]
*/
class PaymentAuthConfig private constructor(
internal val stripe3ds2Config: Stripe3ds2Config
) {
class Builder : ObjectBuilder<PaymentAuthConfig> {
private var stripe3ds2Config: Stripe3ds2Config? = null
fun set3ds2Config(stripe3ds2Config: Stripe3ds2Config): Builder = apply {
this.stripe3ds2Config = stripe3ds2Config
}
override fun build(): PaymentAuthConfig {
return PaymentAuthConfig(requireNotNull(stripe3ds2Config))
}
}
@Parcelize
data class Stripe3ds2Config internal constructor(
@IntRange(from = 5, to = 99) internal val timeout: Int,
internal val uiCustomization: Stripe3ds2UiCustomization
) : Parcelable {
init {
checkValidTimeout(timeout)
}
private fun checkValidTimeout(timeout: Int) {
require(!(timeout < 5 || timeout > 99)) {
"Timeout value must be between 5 and 99, inclusive"
}
}
class Builder : ObjectBuilder<Stripe3ds2Config> {
private var timeout = DEFAULT_TIMEOUT
private var uiCustomization =
Stripe3ds2UiCustomization.Builder().build()
/**
* The 3DS2 challenge flow timeout, in minutes.
*
* If the timeout is reached, the challenge screen will close, control will return to
* the launching Activity/Fragment, payment authentication will not succeed, and the
* outcome will be represented as [StripeIntentResult.Outcome.TIMEDOUT].
*
* Must be a value between 5 and 99, inclusive.
*/
fun setTimeout(@IntRange(from = 5, to = 99) timeout: Int): Builder = apply {
this.timeout = timeout
}
fun setUiCustomization(uiCustomization: Stripe3ds2UiCustomization): Builder = apply {
this.uiCustomization = uiCustomization
}
override fun build(): Stripe3ds2Config {
return Stripe3ds2Config(
timeout = timeout,
uiCustomization = uiCustomization
)
}
}
internal companion object {
internal const val DEFAULT_TIMEOUT = 5
}
}
/**
* Customization for 3DS2 buttons
*/
data class Stripe3ds2ButtonCustomization internal constructor(
internal val buttonCustomization: ButtonCustomization
) {
class Builder : ObjectBuilder<Stripe3ds2ButtonCustomization> {
private val buttonCustomization: ButtonCustomization = StripeButtonCustomization()
/**
* Set the button's background color
*
* @param hexColor The button's background color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setBackgroundColor(hexColor: String): Builder = apply {
buttonCustomization.backgroundColor = hexColor
}
/**
* Set the corner radius of the button
*
* @param cornerRadius The radius of the button in pixels
* @throws RuntimeException If the corner radius is less than 0
*/
@Throws(RuntimeException::class)
fun setCornerRadius(cornerRadius: Int): Builder = apply {
buttonCustomization.cornerRadius = cornerRadius
}
/**
* Set the button's text font
*
* @param fontName The name of the font. If not found, default system font used
* @throws RuntimeException If font name is null or empty
*/
@Throws(RuntimeException::class)
fun setTextFontName(fontName: String): Builder = apply {
buttonCustomization.textFontName = fontName
}
/**
* Set the button's text color
*
* @param hexColor The button's text color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setTextColor(hexColor: String): Builder = apply {
buttonCustomization.textColor = hexColor
}
/**
* Set the button's text size
*
* @param fontSize The size of the font in scaled-pixels (sp)
* @throws RuntimeException If the font size is 0 or less
*/
@Throws(RuntimeException::class)
fun setTextFontSize(fontSize: Int): Builder = apply {
buttonCustomization.textFontSize = fontSize
}
/**
* Build the button customization
*
* @return The built button customization
*/
override fun build(): Stripe3ds2ButtonCustomization {
return Stripe3ds2ButtonCustomization(buttonCustomization)
}
}
}
/**
* Customization for 3DS2 labels
*/
data class Stripe3ds2LabelCustomization internal constructor(
internal val labelCustomization: LabelCustomization
) {
class Builder : ObjectBuilder<Stripe3ds2LabelCustomization> {
private val labelCustomization: LabelCustomization = StripeLabelCustomization()
/**
* Set the text color for heading labels
*
* @param hexColor The heading labels's text color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setHeadingTextColor(hexColor: String): Builder = apply {
labelCustomization.headingTextColor = hexColor
}
/**
* Set the heading label's font
*
* @param fontName The name of the font. Defaults to system font if not found
* @throws RuntimeException If the font name is null or empty
*/
@Throws(RuntimeException::class)
fun setHeadingTextFontName(fontName: String): Builder = apply {
labelCustomization.headingTextFontName = fontName
}
/**
* Set the heading label's text size
*
* @param fontSize The size of the heading label in scaled-pixels (sp).
* @throws RuntimeException If the font size is 0 or less
*/
@Throws(RuntimeException::class)
fun setHeadingTextFontSize(fontSize: Int): Builder = apply {
labelCustomization.headingTextFontSize = fontSize
}
/**
* Set the label's font
*
* @param fontName The name of the font. Defaults to system font if not found
* @throws RuntimeException If the font name is null or empty
*/
@Throws(RuntimeException::class)
fun setTextFontName(fontName: String): Builder = apply {
labelCustomization.textFontName = fontName
}
/**
* Set the label's text color
*
* @param hexColor The labels's text color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setTextColor(hexColor: String): Builder = apply {
labelCustomization.textColor = hexColor
}
/**
* Set the label's text size
*
* @param fontSize The label's font size in scaled-pixels (sp)
* @throws RuntimeException If the font size is 0 or less
*/
@Throws(RuntimeException::class)
fun setTextFontSize(fontSize: Int): Builder = apply {
labelCustomization.textFontSize = fontSize
}
/**
* Build the configured label customization
*
* @return The built label customization
*/
override fun build(): Stripe3ds2LabelCustomization {
return Stripe3ds2LabelCustomization(labelCustomization)
}
}
}
/**
* Customization for 3DS2 text entry
*/
data class Stripe3ds2TextBoxCustomization internal constructor(
internal val textBoxCustomization: TextBoxCustomization
) {
class Builder : ObjectBuilder<Stripe3ds2TextBoxCustomization> {
private val textBoxCustomization: TextBoxCustomization = StripeTextBoxCustomization()
/**
* Set the width of the border around the text entry box
*
* @param borderWidth Width of the border in pixels
* @throws RuntimeException If the border width is less than 0
*/
@Throws(RuntimeException::class)
fun setBorderWidth(borderWidth: Int): Builder = apply {
textBoxCustomization.borderWidth = borderWidth
}
/**
* Set the color of the border around the text entry box
*
* @param hexColor The border's color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setBorderColor(hexColor: String): Builder = apply {
textBoxCustomization.borderColor = hexColor
}
/**
* Set the corner radius of the text entry box
*
* @param cornerRadius The corner radius in pixels
* @throws RuntimeException If the corner radius is less than 0
*/
@Throws(RuntimeException::class)
fun setCornerRadius(cornerRadius: Int): Builder = apply {
textBoxCustomization.cornerRadius = cornerRadius
}
/**
* Set the font for text entry
*
* @param fontName The name of the font. The system default is used if not found.
* @throws RuntimeException If the font name is null or empty.
*/
@Throws(RuntimeException::class)
fun setTextFontName(fontName: String): Builder = apply {
textBoxCustomization.textFontName = fontName
}
/**
* Set the text color for text entry
*
* @param hexColor The text color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setTextColor(hexColor: String): Builder = apply {
textBoxCustomization.textColor = hexColor
}
/**
* Set the text entry font size
*
* @param fontSize The font size in scaled-pixels (sp)
* @throws RuntimeException If the font size is 0 or less
*/
@Throws(RuntimeException::class)
fun setTextFontSize(fontSize: Int): Builder = apply {
textBoxCustomization.textFontSize = fontSize
}
/**
* Build the text box customization
*
* @return The text box customization
*/
override fun build(): Stripe3ds2TextBoxCustomization {
return Stripe3ds2TextBoxCustomization(textBoxCustomization)
}
}
}
/**
* Customization for the 3DS2 toolbar
*/
data class Stripe3ds2ToolbarCustomization internal constructor(
internal val toolbarCustomization: ToolbarCustomization
) {
class Builder : ObjectBuilder<Stripe3ds2ToolbarCustomization> {
private val toolbarCustomization: ToolbarCustomization = StripeToolbarCustomization()
/**
* Set the toolbar's background color
*
* @param hexColor The background color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setBackgroundColor(hexColor: String): Builder = apply {
toolbarCustomization.backgroundColor = hexColor
}
/**
* Set the status bar color, if not provided a darkened version of the background
* color will be used.
*
* @param hexColor The status bar color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setStatusBarColor(hexColor: String): Builder = apply {
toolbarCustomization.statusBarColor = hexColor
}
/**
* Set the toolbar's title
*
* @param headerText The toolbar's title text
* @throws RuntimeException if the title is null or empty
*/
@Throws(RuntimeException::class)
fun setHeaderText(headerText: String): Builder = apply {
toolbarCustomization.headerText = headerText
}
/**
* Set the toolbar's cancel button text
*
* @param buttonText The cancel button's text
* @throws RuntimeException If the button text is null or empty
*/
@Throws(RuntimeException::class)
fun setButtonText(buttonText: String): Builder = apply {
toolbarCustomization.buttonText = buttonText
}
/**
* Set the font for the title text
*
* @param fontName The name of the font. System default is used if not found
* @throws RuntimeException If the font name is null or empty
*/
@Throws(RuntimeException::class)
fun setTextFontName(fontName: String): Builder = apply {
toolbarCustomization.textFontName = fontName
}
/**
* Set the color of the title text
*
* @param hexColor The title's text color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setTextColor(hexColor: String): Builder = apply {
toolbarCustomization.textColor = hexColor
}
/**
* Set the title text's font size
*
* @param fontSize The size of the title text in scaled-pixels (sp)
* @throws RuntimeException If the font size is 0 or less
*/
@Throws(RuntimeException::class)
fun setTextFontSize(fontSize: Int): Builder = apply {
toolbarCustomization.textFontSize = fontSize
}
/**
* Build the toolbar customization
*
* @return The built toolbar customization
*/
override fun build(): Stripe3ds2ToolbarCustomization {
return Stripe3ds2ToolbarCustomization(toolbarCustomization)
}
}
}
/**
* Customizations for the 3DS2 UI
*/
@Parcelize
data class Stripe3ds2UiCustomization internal constructor(
val uiCustomization: StripeUiCustomization
) : Parcelable {
/**
* The type of button for which customization can be set
*/
enum class ButtonType {
SUBMIT,
CONTINUE,
NEXT,
CANCEL,
RESEND,
SELECT
}
class Builder private constructor(
private val uiCustomization: StripeUiCustomization
) : ObjectBuilder<Stripe3ds2UiCustomization> {
constructor() : this(StripeUiCustomization())
private constructor(activity: Activity) : this(
StripeUiCustomization.createWithAppTheme(activity)
)
@Throws(RuntimeException::class)
private fun getUiButtonType(buttonType: ButtonType): UiCustomization.ButtonType {
return when (buttonType) {
ButtonType.SUBMIT ->
UiCustomization.ButtonType.SUBMIT
ButtonType.CONTINUE ->
UiCustomization.ButtonType.CONTINUE
ButtonType.NEXT ->
UiCustomization.ButtonType.NEXT
ButtonType.CANCEL ->
UiCustomization.ButtonType.CANCEL
ButtonType.RESEND ->
UiCustomization.ButtonType.RESEND
ButtonType.SELECT ->
UiCustomization.ButtonType.SELECT
}
}
/**
* Set the customization for a particular button
*
* @param buttonCustomization The button customization data
* @param buttonType The type of button to customize
* @throws RuntimeException If any customization data is invalid
*/
@Throws(RuntimeException::class)
fun setButtonCustomization(
buttonCustomization: Stripe3ds2ButtonCustomization,
buttonType: ButtonType
): Builder = apply {
uiCustomization.setButtonCustomization(
buttonCustomization.buttonCustomization,
getUiButtonType(buttonType)
)
}
/**
* Set the customization data for the 3DS2 toolbar
*
* @param toolbarCustomization Toolbar customization data
* @throws RuntimeException If any customization data is invalid
*/
@Throws(RuntimeException::class)
fun setToolbarCustomization(
toolbarCustomization: Stripe3ds2ToolbarCustomization
): Builder = apply {
uiCustomization
.setToolbarCustomization(toolbarCustomization.toolbarCustomization)
}
/**
* Set the 3DS2 label customization
*
* @param labelCustomization Label customization data
* @throws RuntimeException If any customization data is invalid
*/
@Throws(RuntimeException::class)
fun setLabelCustomization(
labelCustomization: Stripe3ds2LabelCustomization
): Builder = apply {
uiCustomization.setLabelCustomization(labelCustomization.labelCustomization)
}
/**
* Set the 3DS2 text box customization
*
* @param textBoxCustomization Text box customization data
* @throws RuntimeException If any customization data is invalid
*/
@Throws(RuntimeException::class)
fun setTextBoxCustomization(
textBoxCustomization: Stripe3ds2TextBoxCustomization
): Builder = apply {
uiCustomization
.setTextBoxCustomization(textBoxCustomization.textBoxCustomization)
}
/**
* Set the accent color
*
* @param hexColor The accent color in the format #RRGGBB or #AARRGGBB
* @throws RuntimeException If the color cannot be parsed
*/
@Throws(RuntimeException::class)
fun setAccentColor(hexColor: String): Builder = apply {
uiCustomization.setAccentColor(hexColor)
}
/**
* Build the UI customization
*
* @return the built UI customization
*/
override fun build(): Stripe3ds2UiCustomization {
return Stripe3ds2UiCustomization(uiCustomization)
}
companion object {
@JvmStatic
fun createWithAppTheme(activity: Activity): Builder {
return Builder(activity)
}
}
}
}
companion object {
private var instance: PaymentAuthConfig? = null
private val DEFAULT = Builder()
.set3ds2Config(Stripe3ds2Config.Builder().build())
.build()
@JvmStatic
fun init(config: PaymentAuthConfig) {
instance = config
}
@JvmStatic
fun get(): PaymentAuthConfig {
return instance ?: DEFAULT
}
@JvmSynthetic
internal fun reset() {
instance = null
}
}
}
| payments-core/src/main/java/com/stripe/android/PaymentAuthConfig.kt | 3756930186 |
package com.stripe.android.test.core
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.UiDevice
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
/**
* BrowserStack does not offer an API for Espresso tests to disable animations. This rule allows
* certain tests to disable animations on the device.
*/
class DisableAnimationsRule : TestRule {
private val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
private val commandsToSetupTestEnvironment = listOf(
"settings put global transition_animation_scale 0.0",
"settings put global animator_duration_scale 0.0",
"settings put global window_animation_scale 0.0",
"settings put secure long_press_timeout 1500",
"settings put secure show_ime_with_hard_keyboard 0"
)
private fun setDevicePreferences(commands : List<String>) {
with(device) {
commands.forEach {
executeShellCommand(it)
}
}
}
override fun apply(base: Statement, description: Description): Statement {
return object : Statement() {
override fun evaluate() {
setDevicePreferences(commandsToSetupTestEnvironment)
base.evaluate()
}
}
}
}
| paymentsheet-example/src/androidTestDebug/java/com/stripe/android/test/core/DisableAnimationsRule.kt | 3458701344 |
package de.reiss.bible2net.theword.note.export
import androidx.lifecycle.MutableLiveData
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import de.reiss.bible2net.theword.R
import de.reiss.bible2net.theword.note.export.NoteExportStatus.ExportError
import de.reiss.bible2net.theword.note.export.NoteExportStatus.ExportSuccess
import de.reiss.bible2net.theword.note.export.NoteExportStatus.Exporting
import de.reiss.bible2net.theword.note.export.NoteExportStatus.NoNotes
import de.reiss.bible2net.theword.note.export.NoteExportStatus.NoPermission
import de.reiss.bible2net.theword.testutil.FragmentTest
import de.reiss.bible2net.theword.testutil.assertDisabled
import de.reiss.bible2net.theword.testutil.assertDisplayed
import de.reiss.bible2net.theword.testutil.assertEnabled
import de.reiss.bible2net.theword.testutil.assertNotDisplayed
import de.reiss.bible2net.theword.testutil.assertTextInSnackbar
import org.junit.Before
import org.junit.Test
class NoteExportFragmentTest : FragmentTest<NoteExportFragment>() {
private val exportLiveData = MutableLiveData<NoteExportStatus>()
private val mockedViewModel = mock<NoteExportViewModel> {
on { exportLiveData() } doReturn exportLiveData
}
override fun createFragment(): NoteExportFragment = NoteExportFragment.createInstance()
.apply {
viewModelProvider = mock {
on { get(any<Class<NoteExportViewModel>>()) } doReturn mockedViewModel
}
}
@Before
fun setUp() {
launchFragment()
}
@Test
fun whenExportingThenShowLoadingAndDisableStartButton() {
exportLiveData.postValue(Exporting)
assertDisplayed(R.id.note_export_loading)
assertDisabled(R.id.note_export_start)
}
@Test
fun whenNoPermissionThenShowNoPermissionMessage() {
exportLiveData.postValue(NoPermission)
assertNotDisplayed(R.id.note_export_loading)
assertEnabled(R.id.note_export_start)
assertTextInSnackbar(activity.getString(R.string.can_not_write_to_sdcard))
}
@Test
fun whenNoNotesToExportThenShowNoNotesToExportMessage() {
exportLiveData.postValue(NoNotes)
assertNotDisplayed(R.id.note_export_loading)
assertEnabled(R.id.note_export_start)
assertTextInSnackbar(activity.getString(R.string.notes_export_no_notes))
}
@Test
fun whenExportErrorThenShowExportErrorMessage() {
val fileName = "testFileName"
exportLiveData.postValue(ExportError(fileName))
assertNotDisplayed(R.id.note_export_loading)
assertEnabled(R.id.note_export_start)
assertTextInSnackbar(activity.getString(R.string.notes_export_error, fileName))
}
@Test
fun whenExportSuccessThenShowExportSuccessMessage() {
val fileName = "testFileName"
exportLiveData.postValue(ExportSuccess(fileName))
assertNotDisplayed(R.id.note_export_loading)
assertEnabled(R.id.note_export_start)
assertTextInSnackbar(activity.getString(R.string.notes_export_success, fileName))
}
}
| app/src/androidTest/java/de/reiss/bible2net/theword/note/export/NoteExportFragmentTest.kt | 2948744763 |
package expo.modules.permissions.requesters
import android.Manifest
import android.os.Bundle
import expo.modules.interfaces.permissions.PermissionsResponse
import expo.modules.interfaces.permissions.PermissionsStatus
class ForegroundLocationRequester : PermissionRequester {
override fun getAndroidPermissions() = listOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)
override fun parseAndroidPermissions(permissionsResponse: Map<String, PermissionsResponse>): Bundle {
return parseBasicLocationPermissions(permissionsResponse).apply {
val accessFineLocation = permissionsResponse.getValue(Manifest.permission.ACCESS_FINE_LOCATION)
val accessCoarseLocation = permissionsResponse.getValue(Manifest.permission.ACCESS_COARSE_LOCATION)
val accuracy = when {
accessFineLocation.status == PermissionsStatus.GRANTED -> {
"fine"
}
accessCoarseLocation.status == PermissionsStatus.GRANTED -> {
"coarse"
}
else -> {
"none"
}
}
putBundle(
"android",
Bundle().apply {
putString("accuracy", accuracy)
}
)
}
}
}
| packages/expo-permissions/android/src/main/java/expo/modules/permissions/requesters/ForegroundLocationRequester.kt | 3986238627 |
package expo.modules.application
import android.app.Activity
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager.NameNotFoundException
import android.os.Build
import android.os.RemoteException
import android.provider.Settings
import android.util.Log
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import expo.modules.core.ExportedModule
import expo.modules.core.ModuleRegistry
import expo.modules.core.Promise
import expo.modules.core.interfaces.ActivityProvider
import expo.modules.core.interfaces.ExpoMethod
import expo.modules.core.interfaces.RegistryLifecycleListener
import java.util.*
private const val NAME = "ExpoApplication"
private val TAG = ApplicationModule::class.java.simpleName
class ApplicationModule(private val mContext: Context) : ExportedModule(mContext), RegistryLifecycleListener {
private var mModuleRegistry: ModuleRegistry? = null
private var mActivityProvider: ActivityProvider? = null
private var mActivity: Activity? = null
override fun getName(): String {
return NAME
}
override fun onCreate(moduleRegistry: ModuleRegistry) {
mModuleRegistry = moduleRegistry
mActivityProvider = moduleRegistry.getModule(ActivityProvider::class.java)
mActivity = mActivityProvider?.currentActivity
}
override fun getConstants(): Map<String, Any?> {
val constants = HashMap<String, Any?>()
val applicationName = mContext.applicationInfo.loadLabel(mContext.packageManager).toString()
val packageName = mContext.packageName
constants["applicationName"] = applicationName
constants["applicationId"] = packageName
val packageManager = mContext.packageManager
try {
val pInfo = packageManager.getPackageInfo(packageName, 0)
constants["nativeApplicationVersion"] = pInfo.versionName
val versionCode = getLongVersionCode(pInfo).toInt()
constants["nativeBuildVersion"] = versionCode.toString()
} catch (e: NameNotFoundException) {
Log.e(TAG, "Exception: ", e)
}
constants["androidId"] = Settings.Secure.getString(mContext.contentResolver, Settings.Secure.ANDROID_ID)
return constants
}
@ExpoMethod
fun getInstallationTimeAsync(promise: Promise) {
val packageManager = mContext.packageManager
val packageName = mContext.packageName
try {
val info = packageManager.getPackageInfo(packageName, 0)
promise.resolve(info.firstInstallTime.toDouble())
} catch (e: NameNotFoundException) {
Log.e(TAG, "Exception: ", e)
promise.reject("ERR_APPLICATION_PACKAGE_NAME_NOT_FOUND", "Unable to get install time of this application. Could not get package info or package name.", e)
}
}
@ExpoMethod
fun getLastUpdateTimeAsync(promise: Promise) {
val packageManager = mContext.packageManager
val packageName = mContext.packageName
try {
val info = packageManager.getPackageInfo(packageName, 0)
promise.resolve(info.lastUpdateTime.toDouble())
} catch (e: NameNotFoundException) {
Log.e(TAG, "Exception: ", e)
promise.reject("ERR_APPLICATION_PACKAGE_NAME_NOT_FOUND", "Unable to get last update time of this application. Could not get package info or package name.", e)
}
}
@ExpoMethod
fun getInstallReferrerAsync(promise: Promise) {
val installReferrer = StringBuilder()
val referrerClient = InstallReferrerClient.newBuilder(mContext).build()
referrerClient.startConnection(object : InstallReferrerStateListener {
override fun onInstallReferrerSetupFinished(responseCode: Int) {
when (responseCode) {
InstallReferrerClient.InstallReferrerResponse.OK -> {
// Connection established and response received
try {
val response = referrerClient.installReferrer
installReferrer.append(response.installReferrer)
} catch (e: RemoteException) {
Log.e(TAG, "Exception: ", e)
promise.reject("ERR_APPLICATION_INSTALL_REFERRER_REMOTE_EXCEPTION", "RemoteException getting install referrer information. This may happen if the process hosting the remote object is no longer available.", e)
}
promise.resolve(installReferrer.toString())
}
InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> // API not available in the current Play Store app
promise.reject("ERR_APPLICATION_INSTALL_REFERRER_UNAVAILABLE", "The current Play Store app doesn't provide the installation referrer API, or the Play Store may not be installed.")
InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE -> // Connection could not be established
promise.reject("ERR_APPLICATION_INSTALL_REFERRER_CONNECTION", "Could not establish a connection to Google Play")
else -> promise.reject("ERR_APPLICATION_INSTALL_REFERRER", "General error retrieving the install referrer: response code $responseCode")
}
referrerClient.endConnection()
}
override fun onInstallReferrerServiceDisconnected() {
promise.reject("ERR_APPLICATION_INSTALL_REFERRER_SERVICE_DISCONNECTED", "Connection to install referrer service was lost.")
}
})
}
companion object {
private fun getLongVersionCode(info: PackageInfo): Long {
return if (Build.VERSION.SDK_INT >= 28) {
info.longVersionCode
} else {
info.versionCode.toLong()
}
}
}
}
| packages/expo-application/android/src/main/java/expo/modules/application/ApplicationModule.kt | 1149562466 |
/*
* The MIT License
*
* Copyright 2014 Alexander Alexeev.
*
*/
package org.mumidol.logicgames.ui
import javafx.application.Application
import java.util.concurrent.Executors
import org.mumidol.logicgames.MultiPlayerGame
import org.mumidol.logicgames.Player
import org.mumidol.logicgames.IllegalTurnException
import javafx.stage.Stage
import org.mumidol.logicgames.Game
import javafx.concurrent.Task
import kotlin.util.measureTimeMillis
import java.util.concurrent.locks.ReentrantLock
import kotlin.properties.Delegates
/**
* Created on 27.11.2014.
*/
class PlayerTurnTask<G : MultiPlayerGame>(val game: G, val player: Player<G>, val onSuccess: (Game.Turn<G>) -> Unit):
Task<Game.Turn<G>>() {
override fun call(): Game.Turn<G>? {
var t: Game.Turn<G>? = null
val time = measureTimeMillis { t = player.turn(game) }
println("Time: $time")
return t
}
override fun failed() {
super<Task>.failed()
println("Failure :-(. ${ getException()?.toString() ?: ""}")
getException()?.printStackTrace()
}
override fun succeeded() {
super<Task>.succeeded()
onSuccess(get())
}
}
trait GameObserver<G : MultiPlayerGame> {
public fun started(game: G)
public fun turn(game: G)
public fun gameOver(game: G)
}
public fun play<G : MultiPlayerGame>(start: G, o: GameObserver<G>, vararg players: Player<G>) {
// var game = start
// val pool = Executors.newFixedThreadPool(1)
fun submit(game: G) {
Thread(PlayerTurnTask(game, players[game.currPlayer], { turn ->
if (turn.game == game) {
val g = turn.move()
if (g.isOver) {
// pool.shutdown()
o.gameOver(g)
} else {
o.turn(g)
submit(turn.move())
}
} else {
throw IllegalTurnException()
}
})).start()
}
o.started(start)
submit(start)
}
public abstract class AsyncHumanPlayer<G : MultiPlayerGame> : Player<G> {
val lock = ReentrantLock()
val waiting = lock.newCondition()
var turn: Game.Turn<G> by Delegates.notNull()
public override fun turn(game: G): Game.Turn<G> {
lock.lock()
try {
startWaiting(game)
waiting.await()
return turn
} finally {
lock.unlock()
}
}
public fun moved(turn: Game.Turn<G>) {
lock.lock()
try {
this.turn = turn
waiting.signal()
} finally {
lock.unlock()
}
}
public fun interrupt() {
lock.lock()
try {
waiting.signal()
} finally {
lock.unlock()
}
}
public abstract fun startWaiting(game: G)
}
| src/logicgames/ui/FXBasic.kt | 171549474 |
/*
* Copyright (C) 2016 Mantas Varnagiris.
*
* 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.
*/
package com.mvcoding.billing
import com.google.gson.Gson
import com.google.gson.JsonObject
import java.io.Serializable
data class Product(
val productId: ProductId,
val productType: ProductType,
val type: String,
val title: String,
val description: String,
val price: Price) : Serializable {
companion object {
fun fromJson(productType: ProductType, json: String) = Gson().fromJson(json, JsonObject::class.java).let {
Product(
ProductId(it.get("productId").asString),
productType,
it.get("type").asString,
it.get("title").asString,
it.get("description").asString,
Price(it.get("price").asString, it.get("price_amount_micros").asLong, it.get("price_currency_code").asString))
}
}
}
data class Price(val price: String, val priceAmountMicros: Long, val currencyCode: String) : Serializable | billing/src/main/kotlin/com/mvcoding/billing/Product.kt | 2034641838 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.