repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
dropbox/dropbox-sdk-java | examples/android/src/main/java/com/dropbox/core/examples/android/DropboxAndroidSampleApplication.kt | 1 | 308 | package com.dropbox.core.examples.android
import android.app.Application
import com.dropbox.core.examples.android.internal.di.AppGraph
import com.dropbox.core.examples.android.internal.di.AppGraphImpl
class DropboxAndroidSampleApplication : Application() {
val appGraph: AppGraph = AppGraphImpl(this)
} | mit |
Cardstock/Cardstock | src/main/kotlin/xyz/cardstock/cardstock/configuration/Server.kt | 1 | 1308 | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package xyz.cardstock.cardstock.configuration
/**
* A data class representing a server to connect to.
*/
data class Server(
/**
* The hostname of this server.
*/
val host: String,
/**
* The port of this server.
*/
val port: Int,
/**
* If this server should be connected to over SSL.
*/
val secure: Boolean,
/**
* The nickname that the bot should use on this server.
*/
val nickname: String,
/**
* The prefix for commands on this server.
*/
val prefix: Char,
/**
* The user of the bot on this server. If null, defaults to [nickname].
*/
val user: String? = null,
/**
* The real name of the bot on this server. If null, defaults to [nickname].
*/
val realName: String? = null,
/**
* The password to use to connect to this server. If null, use no password.
*/
val password: String? = null,
/**
* The channels to join on connection to this server. If null or empty, join no channels on connection.
*/
val channels: List<String>? = null
)
| mpl-2.0 |
wax911/android-emojify | emojify/src/androidTest/java/io/wax911/emojify/EmojiParseTest.kt | 1 | 16143 | package io.wax911.emojify
import androidx.startup.AppInitializer
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import androidx.test.platform.app.InstrumentationRegistry
import io.wax911.emojify.initializer.EmojiInitializer
import io.wax911.emojify.model.Emoji
import io.wax911.emojify.parser.*
import io.wax911.emojify.parser.action.FitzpatrickAction
import io.wax911.emojify.util.Fitzpatrick
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumentation test, which will execute on an Android device.
*
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
@RunWith(AndroidJUnit4ClassRunner::class)
class EmojiParseTest {
private val context by lazy { InstrumentationRegistry.getInstrumentation().context }
private val emojiManager by lazy {
AppInitializer.getInstance(context)
.initializeComponent(EmojiInitializer::class.java)
}
@Before
fun testApplicationContext() {
Assert.assertNotNull(context)
}
@Before
fun testEmojiLoading() {
Assert.assertNotNull(emojiManager)
Assert.assertTrue(emojiManager.emojiList.isNotEmpty())
}
@Test
fun parseToAliases_replaces_the_emojis_by_one_of_their_aliases() {
// GIVEN
val str = "An 😀awesome 😃string with a few 😉emojis!"
// WHEN
val result = emojiManager.parseToAliases(str)
// THEN
Assert.assertEquals(
"An :grinning:awesome :smiley:string with a few :wink:emojis!",
result
)
}
@Test
@Throws(Exception::class)
fun replaceAllEmojis_replace_the_emojis_by_string() {
// GIVEN
val str = "An 😀awesome 😃string with a few 😉emojis!"
// WHEN
val result = emojiManager.replaceAllEmojis(str, ":)")
// THEN
Assert.assertEquals(
"An :)awesome :)string with a few :)emojis!",
result
)
}
@Test
fun parseToAliases_REPLACE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToAliases(str)
// THEN
Assert.assertEquals(":boy|type_6:", result)
}
@Test
fun parseToAliases_REMOVE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToAliases(str, FitzpatrickAction.REMOVE)
// THEN
Assert.assertEquals(":boy:", result)
}
@Test
fun parseToAliases_REMOVE_without_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66"
// WHEN
val result = emojiManager.parseToAliases(str, FitzpatrickAction.REMOVE)
// THEN
Assert.assertEquals(":boy:", result)
}
@Test
fun parseToAliases_IGNORE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToAliases(str, FitzpatrickAction.IGNORE)
// THEN
Assert.assertEquals(":boy:\uD83C\uDFFF", result)
}
@Test
fun parseToAliases_IGNORE_without_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66"
// WHEN
val result = emojiManager.parseToAliases(str, FitzpatrickAction.IGNORE)
// THEN
Assert.assertEquals(":boy:", result)
}
@Test
fun parseToAliases_with_long_overlapping_emoji() {
// GIVEN
val str = "\uD83D\uDC68\u200D\uD83D\uDC69\u200D\uD83D\uDC66"
// WHEN
val result = emojiManager.parseToAliases(str)
//With greedy parsing, this will give :man::woman::boy:
//THEN
Assert.assertEquals(":family_man_woman_boy:", result)
}
@Test
fun parseToAliases_continuous_non_overlapping_emojis() {
// GIVEN
val str = "\uD83D\uDC69\uD83D\uDC68\uD83D\uDC66"
// WHEN
val result = emojiManager.parseToAliases(str)
//THEN
Assert.assertEquals(":woman::man::boy:", result)
}
@Test
fun parseToHtmlDecimal_replaces_the_emojis_by_their_html_decimal_representation() {
// GIVEN
val str = "An 😀awesome 😃string with a few 😉emojis!"
// WHEN
val result = emojiManager.parseToHtmlDecimal(str)
// THEN
Assert.assertEquals(
"An 😀awesome 😃string with a few 😉emojis!",
result
)
}
@Test
fun parseToHtmlDecimal_PARSE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToHtmlDecimal(
str,
FitzpatrickAction.PARSE
)
// THEN
Assert.assertEquals("👦", result)
}
@Test
fun parseToHtmlDecimal_REMOVE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToHtmlDecimal(
str,
FitzpatrickAction.REMOVE
)
// THEN
Assert.assertEquals("👦", result)
}
@Test
fun parseToHtmlDecimal_IGNORE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToHtmlDecimal(
str,
FitzpatrickAction.IGNORE
)
// THEN
Assert.assertEquals("👦\uD83C\uDFFF", result)
}
@Test
fun parseToHtmlHexadecimal_replaces_the_emojis_by_their_htm_hex_representation() {
// GIVEN
val str = "An 😀awesome 😃string with a few 😉emojis!"
// WHEN
val result = emojiManager.parseToHtmlHexadecimal(str)
// THEN
Assert.assertEquals(
"An 😀awesome 😃string with a few 😉emojis!",
result
)
}
@Test
fun parseToHtmlHexadecimal_PARSE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToHtmlHexadecimal(
str,
FitzpatrickAction.PARSE
)
// THEN
Assert.assertEquals("👦", result)
}
@Test
fun parseToHtmlHexadecimal_REMOVE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToHtmlHexadecimal(
str,
FitzpatrickAction.REMOVE
)
// THEN
Assert.assertEquals("👦", result)
}
@Test
fun parseToHtmlHexadecimal_IGNORE_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "\uD83D\uDC66\uD83C\uDFFF"
// WHEN
val result = emojiManager.parseToHtmlHexadecimal(
str,
FitzpatrickAction.IGNORE
)
// THEN
Assert.assertEquals("👦\uD83C\uDFFF", result)
}
@Test
fun parseToUnicode_replaces_the_aliases_and_the_html_by_their_emoji() {
// GIVEN
val str = "An :grinning:awesome :smiley:string " + "😄with a few 😉emojis!"
// WHEN
val result = emojiManager.parseToUnicode(str)
// THEN
Assert.assertEquals("An 😀awesome 😃string 😄with a few 😉emojis!", result)
}
@Test
fun parseToUnicode_with_the_thumbs_up_emoji_replaces_the_alias_by_the_emoji() {
// GIVEN
val str = "An :+1:awesome :smiley:string " + "😄with a few :wink:emojis!"
// WHEN
val result = emojiManager.parseToUnicode(str)
// THEN
Assert.assertEquals(
"An \uD83D\uDC4Dawesome 😃string 😄with a few 😉emojis!",
result
)
}
@Test
fun parseToUnicode_with_the_thumbsdown_emoji_replaces_the_alias_by_the_emoji() {
// GIVEN
val str = "An :-1:awesome :smiley:string 😄" + "with a few :wink:emojis!"
// WHEN
val result = emojiManager.parseToUnicode(str)
// THEN
Assert.assertEquals(
"An \uD83D\uDC4Eawesome 😃string 😄with a few 😉emojis!",
result
)
}
@Test
fun parseToUnicode_with_the_thumbs_up_emoji_in_hex_replaces_the_alias_by_the_emoji() {
// GIVEN
val str = "An :+1:awesome :smiley:string 😄" + "with a few :wink:emojis!"
// WHEN
val result = emojiManager.parseToUnicode(str)
// THEN
Assert.assertEquals(
"An \uD83D\uDC4Dawesome 😃string 😄with a few 😉emojis!",
result
)
}
@Test
fun parseToUnicode_with_a_fitzpatrick_modifier() {
// GIVEN
val str = ":boy|type_6:"
// WHEN
val result = emojiManager.parseToUnicode(str)
// THEN
Assert.assertEquals("\uD83D\uDC66\uD83C\uDFFF", result)
}
@Test
fun parseToUnicode_with_an_unsupported_fitzpatrick_modifier_does_not_replace() {
// GIVEN
val str = ":grinning|type_6:"
// WHEN
val result = emojiManager.parseToUnicode(str)
// THEN
Assert.assertEquals(str, result)
}
@Test
fun getAliasCanditates_with_one_alias() {
// GIVEN
val str = "test :candidate: test"
// WHEN
val candidates = getAliasCandidates(str)
// THEN
Assert.assertEquals(1, candidates.size)
Assert.assertEquals("candidate", candidates.first().alias)
Assert.assertNull(candidates.first().fitzpatrick)
}
@Test
fun getAliasCanditates_with_one_alias_an_another_colon_after() {
// GIVEN
val str = "test :candidate: test:"
// WHEN
val candidates = getAliasCandidates(str)
// THEN
Assert.assertEquals(1, candidates.size)
Assert.assertEquals("candidate", candidates.first().alias)
Assert.assertNull(candidates.first().fitzpatrick)
}
@Test
fun getAliasCanditates_with_one_alias_an_another_colon_right_after() {
// GIVEN
val str = "test :candidate::test"
// WHEN
val candidates = getAliasCandidates(str)
// THEN
Assert.assertEquals(1, candidates.size)
Assert.assertEquals("candidate", candidates.first().alias)
Assert.assertNull(candidates.first().fitzpatrick)
}
@Test
fun getAliasCanditates_with_one_alias_an_another_colon_before_after() {
// GIVEN
val str = "test ::candidate: test"
// WHEN
val candidates = getAliasCandidates(str)
// THEN
Assert.assertEquals(1, candidates.size)
Assert.assertEquals("candidate", candidates.first().alias)
Assert.assertNull(candidates.first().fitzpatrick)
}
@Test
fun getAliasCanditates_with_two_aliases() {
// GIVEN
val str = "test :candi: :candidate: test"
// WHEN
val candidates = getAliasCandidates(str)
// THEN
Assert.assertEquals(2, candidates.size)
Assert.assertEquals("candi", candidates.first().alias)
Assert.assertNull(candidates.first().fitzpatrick)
Assert.assertEquals("candidate", candidates[1].alias)
Assert.assertNull(candidates[1].fitzpatrick)
}
@Test
fun getAliasCanditates_with_two_aliases_sharing_a_colon() {
// GIVEN
val str = "test :candi:candidate: test"
// WHEN
val candidates = getAliasCandidates(str)
// THEN
Assert.assertEquals(2, candidates.size)
Assert.assertEquals("candi", candidates.first().alias)
Assert.assertNull(candidates.first().fitzpatrick)
Assert.assertEquals("candidate", candidates[1].alias)
Assert.assertNull(candidates[1].fitzpatrick)
}
@Test
fun getAliasCanditates_with_a_fitzpatrick_modifier() {
// GIVEN
val str = "test :candidate|type_3: test"
// WHEN
val candidates = getAliasCandidates(str)
// THEN
Assert.assertEquals(1, candidates.size)
Assert.assertEquals("candidate", candidates.first().alias)
Assert.assertEquals(Fitzpatrick.TYPE_3, candidates.first().fitzpatrick)
}
@Test
fun test_with_a_new_flag() {
val input = "Cuba has a new flag! :cu:"
val expected = "Cuba has a new flag! \uD83C\uDDE8\uD83C\uDDFA"
Assert.assertEquals(expected, emojiManager.parseToUnicode(input))
Assert.assertEquals(input, emojiManager.parseToAliases(expected))
}
@Test
fun removeAllEmojis_removes_all_the_emojis_from_the_string() {
// GIVEN
val input = "An 😀awesome 😃string 😄with " + "a \uD83D\uDC66\uD83C\uDFFFfew 😉emojis!"
// WHEN
val result = emojiManager.removeAllEmojis(input)
// THEN
val expected = "An awesome string with a few emojis!"
Assert.assertEquals(expected, result)
}
@Test
fun removeEmojis_only_removes_the_emojis_in_the_iterable_from_the_string() {
// GIVEN
val input = "An\uD83D\uDE03 awesome\uD83D\uDE04 string" + "\uD83D\uDC4D\uD83C\uDFFF with\uD83D\uDCAA\uD83C\uDFFD a few emojis!"
val emojis = ArrayList<Emoji>()
val smile = emojiManager.getForAlias("smile")
val onePlus = emojiManager.getForAlias("+1")
Assert.assertNotNull(smile)
Assert.assertNotNull(onePlus)
emojis.add(smile!!)
emojis.add(onePlus!!)
// WHEN
val result = emojiManager.removeEmojis(input, emojis)
// THEN
val expected = "An\uD83D\uDE03 awesome string with" + "\uD83D\uDCAA\uD83C\uDFFD a few emojis!"
Assert.assertEquals(expected, result)
}
@Test
fun removeAllEmojisExcept_removes_all_the_emojis_from_the_string_except_those_in_the_iterable() {
// GIVEN
val input = "An\uD83D\uDE03 awesome\uD83D\uDE04 string" + "\uD83D\uDC4D\uD83C\uDFFF with\uD83D\uDCAA\uD83C\uDFFD a few emojis!"
val emojis = ArrayList<Emoji>()
val smile = emojiManager.getForAlias("smile")
val onePlus = emojiManager.getForAlias("+1")
Assert.assertNotNull(smile)
Assert.assertNotNull(onePlus)
emojis.add(smile!!)
emojis.add(onePlus!!)
// WHEN
val result = emojiManager.removeAllEmojisExcept(input, emojis)
// THEN
val expected = "An awesome\uD83D\uDE04 string\uD83D\uDC4D\uD83C\uDFFF " + "with a few emojis!"
Assert.assertEquals(expected, result)
}
@Test
fun parseToUnicode_with_the_keycap_asterisk_emoji_replaces_the_alias_by_the_emoji() {
// GIVEN
val str = "Let's test the :keycap_asterisk: emoji and " + "its other alias :star_keycap:"
// WHEN
val result = emojiManager.parseToUnicode(str)
// THEN
Assert.assertEquals("Let's test the *⃣ emoji and its other alias *⃣", result)
}
@Test
fun parseToAliases_NG_and_nigeria() {
// GIVEN
val str = "Nigeria is 🇳🇬, NG is 🆖"
// WHEN
val result = emojiManager.parseToAliases(str)
// THEN
Assert.assertEquals("Nigeria is :ng:, NG is :squared_ng:", result)
}
@Test
fun parseToAliases_couplekiss_woman_woman() {
// GIVEN
val str = "👩❤️💋👩"
// WHEN
val result = emojiManager.parseToAliases(str)
// THEN
Assert.assertEquals(":couplekiss_woman_woman:", result)
}
@Test
fun extractEmojis() {
// GIVEN
val str = "An 😀awesome 😃string with a few 😉emojis!"
// WHEN
val result = emojiManager.extractEmojis(str)
// THEN
Assert.assertEquals("😀", result[0])
Assert.assertEquals("😃", result[1])
Assert.assertEquals("😉", result[2])
}
} | mit |
nhaarman/expect.kt | expect.kt/src/test/kotlin/com/nhaarman/expect/MatcherTest.kt | 1 | 5730 | /*
* Copyright 2016 Niek Haarman
*
* 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.nhaarman.expect
import org.junit.Test
class MatcherTest {
@Test
fun example_toBeTheSameAs() {
val a = Any()
expect(a).toBeTheSameAs(a)
}
@Test
fun example_toBe() {
val actual = Data(1)
val expected = Data(1)
expect(actual).toBe(expected)
}
@Test
fun example_toBeNull() {
val actual: Int? = null
expect(actual).toBeNull()
}
@Test
fun toBeTheSameAs_withEqualReferences_accepts() {
/* Given */
val a = Any()
val matcher = Matcher(a)
/* When */
matcher.toBeTheSameAs(a)
/* Then */
awesome()
}
@Test
fun toBeTheSameAs_withUnequalReferences_fails() {
/* Given */
val actual = Data(1)
val expected = Data(1)
val matcher = Matcher(actual)
/* Then */
expectErrorWithMessage("but was") when_ {
matcher.toBeTheSameAs(expected)
}
}
@Test
fun toNotBeTheSameAs_withEqualReferences_fails() {
/* Given */
val a = Any()
val matcher = Matcher(a)
/* Then */
expectErrorWithMessage("not to be") on {
matcher.toNotBeTheSameAs(a)
}
}
@Test
fun toNotBeTheSameAs_withUnequalReferences_accepts() {
/* Given */
val actual = Data(1)
val expected = Data(1)
val matcher = Matcher(actual)
/* Then */
matcher.toNotBeTheSameAs(expected)
/* Then */
awesome()
}
@Test
fun toBe_withEqualReferences_areAccepted() {
/* Given */
val data = Data(1)
val matcher = Matcher(data)
/* When */
matcher.toBe(data)
/* Then */
awesome()
}
@Test
fun toBe_withEqualItems_areAccepted() {
/* Given */
val first = Data(1)
val second = Data(1)
val matcher = Matcher(first)
/* When */
matcher.toBe(second)
/* Then */
awesome()
}
@Test
fun toBe_withSubtype_isNotAccepted() {
/* Given */
val first = Data(1)
val second = Subdata(1)
val matcher = Matcher(first)
/* Then */
expectErrorWithMessage("but was") on {
matcher.toBe(second)
}
}
@Test
fun toBe_withUnequalItems_isNotAccepted() {
/* Given */
val first = 1
val second = 2
val matcher = Matcher(first)
/* Then */
expectErrorWithMessage("but was") on {
matcher.toBe(second)
}
}
@Test
fun toBe_withNullValue_isNotAccepted() {
/* Given */
val matcher = Matcher<Int>(null)
/* Then */
expectErrorWithMessage("but was").when_ {
matcher.toBe(1)
}
}
@Test
fun toBeNull_withNullValue_accepts() {
/* Given */
val matcher = Matcher<Int>(null)
/* When */
matcher.toBeNull()
/* Then */
awesome()
}
@Test
fun toBeNull_withNonNullValue_fails() {
/* Given */
val matcher = Matcher(3)
/* Then */
expectErrorWithMessage("Expected 3 to be null.") on {
matcher.toBeNull()
}
}
@Test
fun toNotBeNull_withNullValue_fails() {
/* Given */
val matcher = Matcher<Int>(null)
/* When */
expectErrorWithMessage("to not be null") on {
matcher.toNotBeNull()
}
/* Then */
awesome()
}
@Test
fun toNotBeNull_withNonNullValue_accepts() {
/* Given */
val matcher = Matcher(3)
/* When */
matcher.toNotBeNull()
/* Then */
awesome()
}
@Test
fun toBeInstanceOf_withSameClass_accepts() {
/* Given */
val matcher = Matcher(3)
/* When */
matcher.toBeInstanceOf<Int>()
/* Then */
awesome()
}
@Test
fun toBeInstanceOf_withSubclass_accepts() {
/* Given */
val matcher = Matcher(Subdata(4))
/* When */
matcher.toBeInstanceOf<Data>()
/* Then */
awesome()
}
@Test
fun toBeInstanceOf_notAnInstanceOf_fails() {
/* Given */
val matcher = Matcher(Data(4))
/* Then */
expectErrorWithMessage("to be an instance of") on {
/* When */
matcher.toBeInstanceOf<Subdata>()
}
}
open class Data(val value: Int) {
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
} else if (other != null && this.javaClass == other.javaClass) {
val data = other as Data
return this.value == data.value
} else {
return false
}
}
override fun hashCode(): Int {
return value
}
override fun toString() = "Data(value=$value)"
}
class Subdata(value: Int) : Data(value) {
override fun toString() = "Subdata(value=$value)"
}
}
| apache-2.0 |
iarchii/trade_app | app/src/main/java/xyz/thecodeside/tradeapp/helpers/ViewExtensions.kt | 1 | 826 | package xyz.thecodeside.tradeapp.helpers
import android.util.DisplayMetrics
import android.view.View
import android.widget.EditText
fun View.hide() {
this.visibility = View.GONE
}
fun View.show() {
this.visibility = View.VISIBLE
}
fun View.invisible() {
this.visibility = View.INVISIBLE
}
fun View.convertDpToPixel(dp: Int): Int{
val resources = context.resources
val metrics = resources.displayMetrics
val px = dp * (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
return px.toInt()
}
fun View.convertPixelsToDp(px: Int): Int {
val resources = context.resources
val metrics = resources.displayMetrics
val dp = px / (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
return dp.toInt()
}
fun EditText.getStringText(): String = this.text.toString() | apache-2.0 |
MaibornWolff/codecharta | analysis/import/GitLogParser/src/test/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/input/metrics/WeeksWithCommitsTest.kt | 1 | 2376 | package de.maibornwolff.codecharta.importer.gitlogparser.input.metrics
import de.maibornwolff.codecharta.importer.gitlogparser.input.Commit
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.time.OffsetDateTime
import java.time.ZoneOffset
class WeeksWithCommitsTest {
private val zoneOffset = ZoneOffset.UTC
@Test
fun initial_value_zero() {
// when
val metric = WeeksWithCommits()
// then
assertThat(metric.value()).isEqualTo(0)
}
@Test
fun single_modification() {
// given
val metric = WeeksWithCommits()
// when
val date = OffsetDateTime.of(2016, 4, 2, 12, 0, 0, 0, zoneOffset)
metric.registerCommit(Commit("author", emptyList(), date))
// then
assertThat(metric.value()).isEqualTo(1)
}
@Test
fun additional_modification_in_same_calendar_week() {
// given
val metric = WeeksWithCommits()
// when
val date1 = OffsetDateTime.of(2016, 4, 2, 12, 0, 0, 0, zoneOffset)
metric.registerCommit(Commit("author", emptyList(), date1))
val date2 = OffsetDateTime.of(2016, 4, 3, 12, 0, 0, 0, zoneOffset)
metric.registerCommit(Commit("author", emptyList(), date2))
// then
assertThat(metric.value()).isEqualTo(1)
}
@Test
fun additional_modification_in_successive_calendar_week() {
// given
val metric = WeeksWithCommits()
// when
val date1 = OffsetDateTime.of(2016, 4, 3, 12, 0, 0, 0, zoneOffset)
metric.registerCommit(Commit("author", emptyList(), date1))
val date2 = OffsetDateTime.of(2016, 4, 4, 12, 0, 0, 0, zoneOffset)
metric.registerCommit(Commit("author", emptyList(), date2))
// then
assertThat(metric.value()).isEqualTo(2)
}
@Test
fun additional_modification_in_non_successive_calendar_week() {
// given
val metric = WeeksWithCommits()
// when
val date1 = OffsetDateTime.of(2016, 4, 3, 12, 0, 0, 0, zoneOffset)
metric.registerCommit(Commit("author", emptyList(), date1))
val date2 = OffsetDateTime.of(2016, 4, 11, 12, 0, 0, 0, zoneOffset)
metric.registerCommit(Commit("author", emptyList(), date2))
// then
assertThat(metric.value()).isEqualTo(2)
}
}
| bsd-3-clause |
wayfair/brickkit-android | BrickKit/bricks/src/androidTest/java/com/wayfair/brickkit/size/ThirdWidthBrickSizeTest.kt | 1 | 252 | /*
* Copyright © 2020 Wayfair. All rights reserved.
*/
package com.wayfair.brickkit.size
import org.junit.Test
class ThirdWidthBrickSizeTest {
@Test
fun testGetSpans() {
ThirdWidthBrickSize().verifyGetSpans(80, 80, 80, 80)
}
}
| apache-2.0 |
googlecodelabs/odml-pathways | TextClassificationOnMobile/Android/TextClassificationStep2/app/src/androidTest/java/com/google/devrel/textclassificationstep2/ExampleInstrumentedTest.kt | 2 | 1299 | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devrel.textclassificationstep2
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.google.devrel.textclassificationstep1", appContext.packageName)
}
} | apache-2.0 |
esafirm/android-image-picker | sample/src/androidTest/java/com/esafirm/sample/matchers/DrawableMatcher.kt | 2 | 803 | package com.esafirm.sample.matchers
import android.view.View
import android.widget.ImageView
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.TypeSafeMatcher
class DrawableMatcher(private val expected: Int) : TypeSafeMatcher<View>() {
override fun matchesSafely(target: View): Boolean {
val imageView = target as ImageView
if (expected == EMPTY) {
return imageView.drawable == null
}
if (expected == ANY) {
return imageView.drawable != null
}
return false
}
override fun describeTo(description: Description) {}
companion object {
const val EMPTY = -1
const val ANY = -2
}
}
fun hasDrawable(): Matcher<View> {
return DrawableMatcher(DrawableMatcher.ANY)
} | mit |
googlemaps/codelab-places-101-android-kotlin | starter/app/src/main/java/com/google/codelabs/maps/placesdemo/MainActivity.kt | 2 | 2581 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.codelabs.maps.placesdemo
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// List the available demos
val listView = ListView(this).also {
it.layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
it.adapter = DemoAdapter(this, Demo.values())
it.onItemClickListener = AdapterView.OnItemClickListener { parent, _, position, _ ->
val demo = parent.adapter.getItem(position) as? Demo
demo?.let {
startActivity(Intent(this, demo.activity))
}
}
}
setContentView(listView)
}
private class DemoAdapter(context: Context, demos: Array<Demo>) :
ArrayAdapter<Demo>(context, R.layout.item_demo, demos) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val demoView = (convertView as? DemoItemView) ?: DemoItemView(context)
return demoView.also {
val demo = getItem(position)
it.title.setText(demo?.title ?: 0)
it.description.setText(demo?.description ?: 0)
}
}
}
private class DemoItemView(context: Context) : LinearLayout(context) {
val title: TextView by lazy { findViewById(R.id.textViewTitle) }
val description: TextView by lazy { findViewById(R.id.textViewDescription) }
init {
LayoutInflater.from(context)
.inflate(R.layout.item_demo, this)
}
}
} | apache-2.0 |
moraleTeam/morale-core | src/main/kotlin/team/morale/core/domain/service/notification/NotificationRequest.kt | 1 | 117 | package team.morale.core.domain.service.notification;
class NotificationRequest(val email: String, val body: String) | mit |
christophpickl/kpotpourri | common4k/src/test/kotlin/com/github/christophpickl/kpotpourri/common/string/transform_to_test.kt | 1 | 1888 | package com.github.christophpickl.kpotpourri.common.string
import com.github.christophpickl.kpotpourri.common.KPotpourriException
import com.github.christophpickl.kpotpourri.test4k.assertThrown
import com.github.christophpickl.kpotpourri.test4k.hamkrest_matcher.nullValue
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
@Test class TransformToTest {
@DataProvider
fun provideValid(): Array<Array<out Any>> = arrayOf(
arrayOf("1", true),
arrayOf("y", true),
arrayOf("Y", true),
arrayOf("yes", true),
arrayOf("Yes", true),
arrayOf("YES", true),
arrayOf("on", true),
arrayOf("ON", true),
arrayOf("0", false),
arrayOf("n", false),
arrayOf("N", false),
arrayOf("no", false),
arrayOf("No", false),
arrayOf("NO", false),
arrayOf("off", false),
arrayOf("off", false)
)
@Test(dataProvider = "provideValid")
fun `toBooleanLenient2 and toBooleanLenient2OrNull provide valid`(input: String, expected: Boolean) {
assertThat(input.toBooleanLenient2(), equalTo(expected))
assertThat(input.toBooleanLenient2OrNull(), equalTo(expected))
}
@DataProvider
fun provideInvalid(): Array<Array<out Any>> = arrayOf(
arrayOf(""),
arrayOf(" "),
arrayOf("a"),
arrayOf("2"),
arrayOf("ja")
)
@Test(dataProvider = "provideInvalid")
fun `toBooleanLenient2 and toBooleanLenient2OrNull provide invalid`(input: String) {
assertThrown<KPotpourriException> {
input.toBooleanLenient2()
}
assertThat(input.toBooleanLenient2OrNull(), nullValue())
}
}
| apache-2.0 |
vanniktech/Emoji | emoji/src/androidMain/kotlin/com/vanniktech/emoji/internal/EmojiSearchDialog.kt | 1 | 7581 | /*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.vanniktech.emoji.internal
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.content.res.ColorStateList
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.SpannableString
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.Px
import androidx.appcompat.app.AlertDialog
import androidx.core.view.ViewCompat
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.vanniktech.emoji.Emoji
import com.vanniktech.emoji.EmojiTextView
import com.vanniktech.emoji.EmojiTheming
import com.vanniktech.emoji.R
import com.vanniktech.emoji.search.SearchEmoji
import com.vanniktech.emoji.search.SearchEmojiResult
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
internal fun interface EmojiSearchDialogDelegate {
fun onSearchEmojiClick(emoji: Emoji)
}
internal class EmojiSearchDialog : DialogFragment() {
private var delegate: EmojiSearchDialogDelegate? = null
private var searchEmoji: SearchEmoji? = null
private val handler = Handler(Looper.getMainLooper())
private var future: ScheduledFuture<*>? = null
private val executorService = Executors.newSingleThreadScheduledExecutor()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val activity = requireActivity()
val dialog = AlertDialog.Builder(activity, theme)
.setView(R.layout.emoji_dialog_search)
.show()
val root = dialog.findViewById<View>(R.id.root)
val arguments = requireArguments()
val theming = arguments.parcelable<EmojiTheming>(ARG_THEMING)!!
root?.setBackgroundColor(theming.backgroundColor)
val editText = dialog.findViewById<EditText>(R.id.editText)!!
editText.setTextColor(theming.textColor)
val secondaryColor = theming.secondaryColor
editText.setCursorDrawableColor(secondaryColor)
editText.setHandlesColor(secondaryColor)
editText.highlightColor = secondaryColor
ViewCompat.setBackgroundTintList(editText, ColorStateList.valueOf(secondaryColor))
val recyclerView = dialog.findViewById<MaxHeightSearchRecyclerView>(R.id.recyclerView)
val adapter = EmojiAdapter(
theming = theming,
emojiSearchDialogDelegate = {
delegate?.onSearchEmojiClick(it)
dismiss()
},
)
recyclerView?.tint(theming)
recyclerView?.adapter = adapter
editText.addTextChangedListener(
object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
override fun afterTextChanged(s: Editable) {
val query = s.toString()
future?.cancel(true)
handler.removeCallbacksAndMessages(null)
future = executorService.schedule({
val emojis = searchEmoji?.search(query).orEmpty()
handler.post {
adapter.update(emojis, marginStart = null)
}
}, 300, TimeUnit.MILLISECONDS,)
}
},
)
editText.postDelayed({
editText.showKeyboardAndFocus()
}, 300L,)
return dialog
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
future?.cancel(true)
executorService?.shutdownNow()
handler.removeCallbacksAndMessages(null)
delegate = null
}
internal companion object {
private const val TAG = "EmojiSearchDialog"
private const val ARG_THEMING = "arg-theming"
fun show(
context: Context,
delegate: EmojiSearchDialogDelegate,
searchEmoji: SearchEmoji,
theming: EmojiTheming,
) {
EmojiSearchDialog().apply {
arguments = Bundle(1).apply {
putParcelable(ARG_THEMING, theming)
}
this.delegate = delegate
this.searchEmoji = searchEmoji
show((Utils.asActivity(context) as FragmentActivity).supportFragmentManager, TAG)
}
}
}
}
internal class EmojiAdapter(
private val theming: EmojiTheming,
private val emojiSearchDialogDelegate: EmojiSearchDialogDelegate?,
) : RecyclerView.Adapter<EmojiViewHolder>() {
@Px private var marginStart: Int? = null
private var items = emptyList<SearchEmojiResult>()
init {
setHasStableIds(true)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = EmojiViewHolder(parent)
override fun onBindViewHolder(holder: EmojiViewHolder, position: Int) {
val context = holder.textView.context
val item = items[position]
holder.textView.setTextColor(theming.textColor) // This is just in case there's a glyph shown.
holder.textView.text = item.emoji.unicode
(holder.textView.layoutParams as LinearLayout.LayoutParams).marginStart = marginStart ?: context.resources.getDimensionPixelSize(R.dimen.emoji_search_spacing)
val shortCode = item.shortcode
holder.shortCodes.text = SpannableString(shortCode).apply {
setSpan(ForegroundColorSpan(theming.textSecondaryColor), 0, shortCode.length, 0)
setSpan(ForegroundColorSpan(theming.secondaryColor), item.range.first, item.range.last + 1, 0)
}
holder.itemView.setOnClickListener {
emojiSearchDialogDelegate?.onSearchEmojiClick(item.emoji)
}
}
override fun getItemCount() = items.size
fun update(
new: List<SearchEmojiResult>,
@Px marginStart: Int?,
) {
val old = ArrayList(items)
items = new
this.marginStart = marginStart
DiffUtil.calculateDiff(DiffUtilHelper(old, items) { it.hashCode() })
.dispatchUpdatesTo(this)
}
}
internal class EmojiViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.emoji_adapter_item_emoji_search, parent, false)) {
val textView: EmojiTextView by lazy(LazyThreadSafetyMode.NONE) { itemView.findViewById(R.id.textView) }
val shortCodes: TextView by lazy(LazyThreadSafetyMode.NONE) { itemView.findViewById(R.id.shortCodes) }
}
internal class DiffUtilHelper<T>(
private val old: List<T>,
private val new: List<T>,
private val id: (T) -> Int,
) : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
id(old[oldItemPosition]) == id(new[newItemPosition])
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
old[oldItemPosition] == new[newItemPosition]
override fun getOldListSize() = old.size
override fun getNewListSize() = new.size
}
| apache-2.0 |
kotlintest/kotlintest | kotest-assertions/kotest-assertions-jsoup/src/jvmMain/kotlin/io/kotest/assertions/jsoup/ElementMatchers.kt | 1 | 3062 | package io.kotest.assertions.jsoup
import io.kotest.matchers.Matcher
import io.kotest.matchers.MatcherResult
import io.kotest.matchers.should
import io.kotest.matchers.shouldNot
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
fun Elements.shouldBePresent() = this should bePresent()
fun Elements.shouldNotBePresent() = this shouldNot bePresent()
fun bePresent() = object : Matcher<Elements> {
override fun test(value: Elements) = MatcherResult(
value.isNotEmpty(),
"Element should be present",
"Element should not be present"
)
}
infix fun Elements.shouldBePresent(times: Int) = this should bePresent(times)
infix fun Elements.shouldNotBePresent(times: Int) = this shouldNot bePresent(times)
fun bePresent(times: Int) = object : Matcher<Elements> {
override fun test(value: Elements) = MatcherResult(
value.size == times,
"Element should be present $times times",
"Element should not be present $times times"
)
}
infix fun Element.shouldHaveChildWithTag(tag: String) = this should haveChildWithTag(tag)
infix fun Element.shouldNotHaveChildWithTag(tag: String) = this shouldNot haveChildWithTag(tag)
fun haveChildWithTag(tag: String) = object : Matcher<Element> {
override fun test(value: Element) = MatcherResult(
value.getElementsByTag(tag).isNotEmpty(),
"Document should have at least one child with tag $tag",
"Document should not have child with tag $tag"
)
}
infix fun Element.shouldHaveText(expectedText: String) = this should haveText(expectedText)
infix fun Element.shouldNotHaveText(expectedText: String) = this shouldNot haveText(expectedText)
fun haveText(expectedText: String) = object : Matcher<Element> {
override fun test(value: Element) = MatcherResult(
value.text() == expectedText,
"Element ${value.tagName()} should have text $expectedText. But instead was $expectedText",
"Element ${value.tagName()} should not have text $expectedText"
)
}
infix fun Element.shouldHaveAttribute(attrName: String) = this should haveAttribute(attrName)
infix fun Element.shouldNotHaveAttribute(attrName: String) = this shouldNot haveAttribute(attrName)
fun haveAttribute(attrName: String) = object : Matcher<Element> {
override fun test(value: Element) = MatcherResult(
value.hasAttr(attrName),
"Element ${value.tagName()} should have attribute $attrName.",
"Element ${value.tagName()} should not have attribute $attrName."
)
}
fun Element.shouldHaveAttributeValue(attr: String, expectedValue: String) =
this should haveAttrValue(attr, expectedValue)
fun Element.shouldNotHaveAttributeValue(attr: String, expectedValue: String) =
this shouldNot haveAttrValue(attr, expectedValue)
fun haveAttrValue(attr: String, expectedValue: String) = object : Matcher<Element> {
override fun test(value: Element) = MatcherResult(
value.attr(attr) == expectedValue,
"Element should have attribute $attr with value $expectedValue",
"Element should not have attribute $attr with value $expectedValue"
)
}
| apache-2.0 |
bassaer/ChatMessageView | chatmessageview/src/test/kotlin/com/github/bassaer/chatmessageview/util/MessageDateComparatorTest.kt | 1 | 1958 | package com.github.bassaer.chatmessageview.util
import com.github.bassaer.chatmessageview.model.Message
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.*
/**
* <p>MessageDateComparator Test</p>
* Created by nakayama on 2017/11/11.
*/
internal class MessageDateComparatorTest {
private val newMessage = Message()
private val oldMessage = Message()
private val newCalendar = Calendar.getInstance()
private val oldCalendar = Calendar.getInstance()
private val messageDateComparator = MessageDateComparator()
@Test
fun compareDifferentDays() {
newCalendar.set(2017, 10, 11)
oldCalendar.set(2017, 10, 12)
newMessage.sendTime = newCalendar
oldMessage.sendTime = oldCalendar
assertEquals(messageDateComparator.compare(newMessage, oldMessage), -1)
newCalendar.set(2017, 10, 11)
oldCalendar.set(2017, 9, 12)
newMessage.sendTime = newCalendar
oldMessage.sendTime = oldCalendar
assertEquals(messageDateComparator.compare(newMessage, oldMessage), 1)
}
@Test
fun compareSameDaysDifferentHour() {
newCalendar.set(2017, 10, 11, 10,1)
oldCalendar.set(2017, 10, 11, 22,1)
newMessage.sendTime = newCalendar
oldMessage.sendTime = oldCalendar
assertEquals(messageDateComparator.compare(newMessage, oldMessage), -1)
newCalendar.set(2017, 10, 11, 23,2)
oldCalendar.set(2017, 10, 11, 23,1)
newMessage.sendTime = newCalendar
oldMessage.sendTime = oldCalendar
assertEquals(messageDateComparator.compare(newMessage, oldMessage), 1)
}
@Test
fun compareSameDaySameHour() {
newCalendar.set(2017, 10, 10, 20,45)
oldCalendar.set(2017, 10, 10,20,45)
newMessage.sendTime = newCalendar
oldMessage.sendTime = oldCalendar
assertEquals(messageDateComparator.compare(newMessage, oldMessage), 0)
}
} | apache-2.0 |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/gui/components/bars/CallbackBarProvider.kt | 2 | 1404 | package com.cout970.magneticraft.systems.gui.components.bars
import com.cout970.magneticraft.misc.clamp
import com.cout970.magneticraft.misc.crafting.TimedCraftingProcess
import com.cout970.magneticraft.misc.ensureNonZero
import com.cout970.magneticraft.misc.gui.ValueAverage
val ZERO = { 0.0 }
open class CallbackBarProvider(val callback: () -> Number, val max: () -> Number,
val min: () -> Number) : IBarProvider {
override fun getLevel(): Float {
val min = min.invoke().toDouble()
val max = max.invoke().toDouble()
val value = callback.invoke().toDouble()
return clamp((value - min) / ensureNonZero(max - min), 1.0, 0.0).toFloat()
}
}
class StaticBarProvider(val minVal: Double, val maxVal: Double, callback: () -> Number)
: CallbackBarProvider(callback = callback, max = { maxVal }, min = { minVal })
fun TimedCraftingProcess.toBarProvider() = CallbackBarProvider(this::timer, this::limit, ZERO)
fun ValueAverage.toBarProvider(max: Number) = CallbackBarProvider(this::storage, { max }, ZERO)
fun CallbackBarProvider.toPercentText(prefix: String = "", postfix: String = "%"): () -> List<String> = {
listOf("$prefix${(getLevel() * 100.0).toInt()}$postfix")
}
fun CallbackBarProvider.toIntText(prefix: String = "", postfix: String = ""): () -> List<String> = {
listOf("$prefix${callback().toInt()}$postfix")
} | gpl-2.0 |
Shynixn/PetBlocks | petblocks-api/src/main/kotlin/com/github/shynixn/petblocks/api/persistence/entity/GuiPlayerCache.kt | 1 | 1804 | package com.github.shynixn.petblocks.api.persistence.entity
import com.github.shynixn.petblocks.api.business.service.LoggingService
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
interface GuiPlayerCache {
/**
* Allocated gui items path.
*/
var path: String
/**
* Off set x axe.
*/
var offsetX: Int
/**
* Off set Y axe.
*/
var offsetY: Int
/**
* Parent.
*/
var parent: GuiPlayerCache?
/**
* Last time the advertising message was played.
*/
var advertisingMessageTime: Long
/**
* Gets the inventory.
*/
fun <I> getInventory(): I
} | apache-2.0 |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/box/BoxAuthFlow.kt | 1 | 1552 | package com.baulsupp.okurl.services.box
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.SimpleWebServer
import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token
import com.baulsupp.okurl.credentials.NoToken
import com.baulsupp.okurl.kotlin.queryMap
import com.baulsupp.okurl.kotlin.requestBuilder
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Response
import java.net.URLEncoder
object BoxAuthFlow {
suspend fun login(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
clientId: String,
clientSecret: String,
scopes: List<String>
): Oauth2Token {
SimpleWebServer.forCode().use { s ->
val scopesString = URLEncoder.encode(scopes.joinToString(" "), "UTF-8")
val loginUrl =
"https://account.box.com/api/oauth2/authorize?client_id=$clientId&scope=$scopesString&response_type=code&state=x&redirect_uri=${s.redirectUri}"
outputHandler.openLink(loginUrl)
val code = s.waitForCode()
val body = FormBody.Builder().add("grant_type", "authorization_code").add("code", code).add("client_id", clientId)
.add("client_secret", clientSecret).build()
val request = requestBuilder(
"https://api.box.com/oauth2/token",
NoToken
)
.post(body)
.build()
val responseMap = client.queryMap<Any>(request)
return Oauth2Token(
responseMap["access_token"] as String,
responseMap["refresh_token"] as String, clientId, clientSecret
)
}
}
}
| apache-2.0 |
lttng/lttng-scope | lttng-scope-ui/src/main/kotlin/org/lttng/scope/views/timeline/widgets/xychart/XYChartFullRangeWidget.kt | 1 | 10828 | /*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.views.timeline.widgets.xychart
import com.efficios.jabberwocky.common.TimeRange
import com.efficios.jabberwocky.context.ViewGroupContext
import com.efficios.jabberwocky.project.TraceProject
import com.efficios.jabberwocky.views.xychart.control.XYChartControl
import com.efficios.jabberwocky.views.xychart.model.render.XYChartRender
import javafx.application.Platform
import javafx.beans.binding.Bindings
import javafx.beans.value.ChangeListener
import javafx.collections.FXCollections
import javafx.geometry.Insets
import javafx.scene.chart.XYChart
import javafx.scene.layout.BorderPane
import javafx.scene.layout.Pane
import javafx.scene.layout.StackPane
import javafx.scene.paint.Color
import javafx.scene.shape.Rectangle
import javafx.scene.shape.StrokeLineCap
import org.lttng.scope.common.jfx.TimeAxis
import org.lttng.scope.views.timeline.NavigationAreaWidget
import org.lttng.scope.views.timeline.TimelineWidget
import org.lttng.scope.views.timeline.widgets.xychart.layer.XYChartDragHandlers
import org.lttng.scope.views.timeline.widgets.xychart.layer.XYChartScrollHandlers
import org.lttng.scope.views.timeline.widgets.xychart.layer.XYChartSelectionLayer
/**
* Widget for the timeline view showing data in a XY-Chart. The chart will
* display data representing the whole trace, and will display highlighted
* rectangles representing the current visible and selection time ranges.
*/
class XYChartFullRangeWidget(control: XYChartControl, override val weight: Int) : XYChartWidget(control), NavigationAreaWidget {
companion object {
/* Number of data poins we request to the backend */
private const val NB_DATA_POINTS = 200
private const val CHART_HEIGHT = 50.0
private val VISIBLE_RANGE_STROKE_WIDTH = 4.0
private val VISIBLE_RANGE_ARC = 5.0
private val VISIBLE_RANGE_STROKE_COLOR = Color.GRAY
private val VISIBLE_RANGE_FILL_COLOR = Color.LIGHTGRAY.deriveColor(0.0, 1.2, 1.0, 0.6)
}
override val rootNode = BorderPane()
override val selectionLayer = XYChartSelectionLayer.build(this, -10.0)
override val dragHandlers = XYChartDragHandlers(this)
override val scrollHandlers = XYChartScrollHandlers(this)
private val visibleRangeRect = object : Rectangle() {
private val projectChangeListener = object : ViewGroupContext.ProjectChangeListener(this@XYChartFullRangeWidget) {
override fun newProjectCb(newProject: TraceProject<*, *>?) {
isVisible = (newProject != null)
}
}
init {
stroke = VISIBLE_RANGE_STROKE_COLOR
strokeWidth = VISIBLE_RANGE_STROKE_WIDTH
strokeLineCap = StrokeLineCap.ROUND
fill = VISIBLE_RANGE_FILL_COLOR
arcHeight = VISIBLE_RANGE_ARC
arcWidth = VISIBLE_RANGE_ARC
y = 0.0
heightProperty().bind(Bindings.subtract(chart.heightProperty(), VISIBLE_RANGE_STROKE_WIDTH))
val initialProject = viewContext.registerProjectChangeListener(projectChangeListener)
isVisible = (initialProject != null)
}
@Suppress("ProtectedInFinal", "Unused")
protected fun finalize() {
viewContext.deregisterProjectChangeListener(projectChangeListener)
}
}
init {
/* Hide the axes in the full range chart */
with(xAxis) {
isTickLabelsVisible = false
opacity = 0.0
}
with(yAxis) {
isTickLabelsVisible = false
opacity = 0.0
}
with(chart) {
// setTitle(getName())
padding = Insets(-10.0, -10.0, -10.0, -10.0)
// setStyle("-fx-padding: 1px;")
minHeight = CHART_HEIGHT
prefHeight = CHART_HEIGHT
maxHeight = CHART_HEIGHT
}
rootNode.center = StackPane(chart,
Pane(visibleRangeRect).apply { isMouseTransparent = true },
selectionLayer)
rootNode.widthProperty().addListener { _, _, _ ->
drawSelection(viewContext.selectionTimeRange)
seekVisibleRange(viewContext.visibleTimeRange)
timelineWidgetUpdateTask.run()
}
}
override fun dispose() {
}
override fun getWidgetTimeRange() = viewContext.getCurrentProjectFullRange()
override fun mapXPositionToTimestamp(x: Double): Long {
val project = viewContext.traceProject ?: return 0L
val viewWidth = chartPlotArea.width
if (viewWidth < 1.0) return project.startTime
val posRatio = x / viewWidth
val ts = (project.startTime + posRatio * project.fullRange.duration).toLong()
/* Clamp the result to the trace project's range. */
return ts.coerceIn(project.fullRange.startTime, project.fullRange.endTime)
}
// ------------------------------------------------------------------------
// TimelineWidget
// ------------------------------------------------------------------------
override val name = control.renderProvider.providerName
override val timelineWidgetUpdateTask: TimelineWidget.TimelineWidgetUpdateTask = RedrawTask()
/** Not applicable to this widget */
override val splitPane = null
/* Not applicable to this widget */
override val timeBasedScrollPane = null
// TODO Bind the selection rectangles with the other timeline ones?
override val selectionRectangle = null
override val ongoingSelectionRectangle = null
// ------------------------------------------------------------------------
// XYChartView
// ------------------------------------------------------------------------
override fun clear() {
/* Nothing to do, the redraw task will remove all series if the trace is null. */
}
override fun seekVisibleRange(newVisibleRange: TimeRange) {
/* Needs + 10 to be properly aligned, not sure why... */
val xStart = xAxis.getDisplayPosition(newVisibleRange.startTime) + 10.0
val xEnd = xAxis.getDisplayPosition(newVisibleRange.endTime) + 10.0
if (xStart == Double.NaN || xEnd == Double.NaN) return
with(visibleRangeRect) {
x = xStart
width = xEnd - xStart
}
}
private inner class RedrawTask : TimelineWidget.TimelineWidgetUpdateTask {
private var lastTraceProject: TraceProject<*, *>? = null
override fun run() {
/* Skip redraws if we are in a project-switching operation. */
if (viewContext.listenerFreeze) return
var newTraceProject = viewContext.traceProject
if (newTraceProject == lastTraceProject) return
if (newTraceProject == null) {
/* Replace the list of series with an empty list */
Platform.runLater { chart.data = FXCollections.observableArrayList() }
} else {
val painted = repaintChart(newTraceProject)
if (!painted) {
newTraceProject = null
}
}
lastTraceProject = newTraceProject
}
/**
* Repaint the whole chart. Should only be necessary if the active trace
* changes.
*
* @return If we have produced a "real" render or not. If not, it might be
* because the trace is still being initialized, so we should not
* consider it painted.
*/
private fun repaintChart(traceProject: TraceProject<*, *>): Boolean {
val traceFullRange = TimeRange.of(traceProject.startTime, traceProject.endTime)
val renders = control.renderProvider.generateSeriesRenders(traceFullRange, NB_DATA_POINTS, null)
if (renders.isEmpty()) return false
val outSeries = mutableListOf<XYChart.Series<Number, Number>>()
for (render: XYChartRender in renders) {
val outPoints = mutableListOf<XYChart.Data<Number, Number>>()
// Width of a single bar in nanoseconds
val step = (render.data[1].x - render.data[0].x)
/*
* A data point indicates the count difference between the data
* points's timestamp and the next data point's timestamp.
*
* Hack: simulate a bar chart with an area chart here.
*/
for (renderDp: XYChartRender.DataPoint in render.data) {
outPoints.add(XYChart.Data(renderDp.x, 0.0))
outPoints.add(XYChart.Data(renderDp.x, renderDp.y))
outPoints.add(XYChart.Data(renderDp.x + step, renderDp.y))
outPoints.add(XYChart.Data(renderDp.x + step, 0.0))
}
outSeries.add(XYChart.Series(render.series.name, FXCollections.observableList(outPoints)))
}
/* Determine start and end times of the display range. */
val start = renders.map { it.range.startTime }.min()!!
val end = renders.map { it.range.endTime }.max()!!
val range = TimeRange.of(start, end)
xAxis.setTickStep(renders.first().resolutionX)
Platform.runLater {
chart.data = FXCollections.observableArrayList()
outSeries.forEach { chart.data.add(it) }
chart.createSymbols = false
with(chart.xAxis as TimeAxis) {
tickUnit = range.duration.toDouble()
lowerBound = range.startTime.toDouble()
upperBound = range.endTime.toDouble()
}
}
/*
* On project-switching, the whole project time range should be the new visible range.
*
* Unfortunately, we cannot use the normal facilities here to redraw the visible range
* rectangle because the data has not yet been rendered, so the axis does not yet
* have its real width
*
* Instead use this ugly but working hack to artificially draw a rectangle that covers
* the whole widget.
*/
Platform.runLater {
visibleRangeRect.apply {
isVisible = true
x = 10.0
width = chart.width - 10.0
}
}
return true
}
}
}
| epl-1.0 |
MaTriXy/PermissionsDispatcher | test/src/test/java/permissions/dispatcher/test/ActivityWithAllAnnotationsPermissionsDispatcherTest.kt | 1 | 7616 | package permissions.dispatcher.test
import android.content.pm.PackageManager
import android.os.Process
import android.support.v4.app.ActivityCompat
import android.support.v4.app.AppOpsManagerCompat
import android.support.v4.content.PermissionChecker
import org.junit.After
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Matchers.any
import org.mockito.Mockito
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
import permissions.dispatcher.PermissionRequest
@Suppress("IllegalIdentifier")
@RunWith(PowerMockRunner::class)
@PrepareForTest(ActivityCompat::class, PermissionChecker::class, AppOpsManagerCompat::class, Process::class)
class ActivityWithAllAnnotationsPermissionsDispatcherTest {
private lateinit var activity: ActivityWithAllAnnotations
companion object {
private var requestCode = 0
@BeforeClass
@JvmStatic
fun setUpForClass() {
requestCode = getRequestCameraConstant(ActivityWithAllAnnotationsPermissionsDispatcher::class.java)
}
}
@Before
fun setUp() {
activity = Mockito.mock(ActivityWithAllAnnotations::class.java)
PowerMockito.mockStatic(ActivityCompat::class.java)
PowerMockito.mockStatic(PermissionChecker::class.java)
PowerMockito.mockStatic(Process::class.java)
PowerMockito.mockStatic(AppOpsManagerCompat::class.java)
}
@After
fun tearDown() {
clearCustomManufacture()
clearCustomSdkInt()
}
@Test
fun `already granted call the method`() {
mockCheckSelfPermission(true)
ActivityWithAllAnnotationsPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(1)).showCamera()
}
@Test
fun `not granted does not call the method`() {
mockCheckSelfPermission(false)
mockActivityCompatShouldShowRequestPermissionRationale(true)
ActivityWithAllAnnotationsPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(0)).showCamera()
}
@Test
fun `not granted permission and show rationale is true then call the rationale method`() {
mockCheckSelfPermission(false)
mockActivityCompatShouldShowRequestPermissionRationale(true)
ActivityWithAllAnnotationsPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(1)).showRationaleForCamera(any(PermissionRequest::class.java))
}
@Test
fun `not granted permission and show rationale is false then does not call the rationale method`() {
mockCheckSelfPermission(false)
mockActivityCompatShouldShowRequestPermissionRationale(false)
ActivityWithAllAnnotationsPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(0)).showRationaleForCamera(any(PermissionRequest::class.java))
}
@Test
fun `the method is called if verifyPermission is true`() {
ActivityWithAllAnnotationsPermissionsDispatcher.onRequestPermissionsResult(activity, requestCode, intArrayOf(PackageManager.PERMISSION_GRANTED))
Mockito.verify(activity, Mockito.times(1)).showCamera()
}
@Test
fun `the method is not called if verifyPermission is false`() {
ActivityWithAllAnnotationsPermissionsDispatcher.onRequestPermissionsResult(activity, requestCode, intArrayOf(PackageManager.PERMISSION_DENIED))
Mockito.verify(activity, Mockito.times(0)).showCamera()
}
@Test
fun `show never ask method is call if verifyPermission is false and shouldShowRequestPermissionRationale is false`() {
mockActivityCompatShouldShowRequestPermissionRationale(false)
ActivityWithAllAnnotationsPermissionsDispatcher.onRequestPermissionsResult(activity, requestCode, intArrayOf(PackageManager.PERMISSION_DENIED))
Mockito.verify(activity, Mockito.times(1)).showNeverAskForCamera()
}
@Test
fun `show deny method is call if verifyPermission is false and shouldShowRequestPermissionRationale is true`() {
mockActivityCompatShouldShowRequestPermissionRationale(true)
ActivityWithAllAnnotationsPermissionsDispatcher.onRequestPermissionsResult(activity, requestCode, intArrayOf(PackageManager.PERMISSION_DENIED))
Mockito.verify(activity, Mockito.times(1)).showDeniedForCamera()
}
@Test
fun `no the method call if request code is not related to the library`() {
ActivityWithAllAnnotationsPermissionsDispatcher.onRequestPermissionsResult(activity, requestCode + 1000, null)
Mockito.verify(activity, Mockito.times(0)).showCamera()
}
@Test
fun `no denied method call if request code is not related to the library`() {
ActivityWithAllAnnotationsPermissionsDispatcher.onRequestPermissionsResult(activity, requestCode + 1000, null)
Mockito.verify(activity, Mockito.times(0)).showDeniedForCamera()
}
@Test
fun `no never ask method call if request code is not related to the library`() {
ActivityWithAllAnnotationsPermissionsDispatcher.onRequestPermissionsResult(activity, requestCode + 1000, null)
Mockito.verify(activity, Mockito.times(0)).showNeverAskForCamera()
}
@Test
fun `xiaomi device permissionToOp returns null grant permission`() {
testForXiaomi()
mockPermissionToOp(null)
ActivityWithAllAnnotationsPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(1)).showCamera()
}
@Test
fun `xiaomi device grant permission`() {
testForXiaomi()
mockPermissionToOp("")
mockNoteOp(AppOpsManagerCompat.MODE_ALLOWED)
mockCheckSelfPermission(true)
ActivityWithAllAnnotationsPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(1)).showCamera()
}
@Test
fun `xiaomi noteOp returns not allowed value should not call the method`() {
testForXiaomi()
mockPermissionToOp("")
mockNoteOp(AppOpsManagerCompat.MODE_IGNORED)
mockCheckSelfPermission(true)
ActivityWithAllAnnotationsPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(0)).showCamera()
}
@Test
fun `xiaomi noteOp returns allowed but checkSelfPermission not allowed value should not call the method`() {
testForXiaomi()
mockPermissionToOp("")
mockNoteOp(AppOpsManagerCompat.MODE_ALLOWED)
mockCheckSelfPermission(false)
ActivityWithAllAnnotationsPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(0)).showCamera()
}
@Test
fun `blow M follows checkSelfPermissions result false`() {
overwriteCustomSdkInt(22)
mockCheckSelfPermission(false)
ActivityWithAllAnnotationsPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(0)).showCamera()
}
@Test
fun `blow M follows checkSelfPermissions result true`() {
overwriteCustomSdkInt(22)
mockCheckSelfPermission(true)
ActivityWithAllAnnotationsPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(1)).showCamera()
}
}
| apache-2.0 |
robinverduijn/gradle | buildSrc/subprojects/binary-compatibility/src/main/kotlin/org/gradle/binarycompatibility/BinaryCompatibilityRepository.kt | 1 | 3842 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.binarycompatibility
import japicmp.model.JApiClass
import japicmp.model.JApiCompatibility
import japicmp.model.JApiMethod
import javassist.bytecode.SourceFileAttribute
import org.gradle.binarycompatibility.sources.ApiSourceFile
import org.gradle.binarycompatibility.sources.JavaSourceQueries
import org.gradle.binarycompatibility.sources.KotlinSourceQueries
import org.gradle.binarycompatibility.sources.SourcesRepository
import com.google.common.annotations.VisibleForTesting
import java.io.File
/**
* Repository of sources for binary compatibility checks.
*
* `WARN` Holds resources open for performance, must be closed after use.
*/
class BinaryCompatibilityRepository internal constructor(
private
val sources: SourcesRepository
) : AutoCloseable {
companion object {
@JvmStatic
fun openRepositoryFor(sourceRoots: List<File>, compilationClasspath: List<File>) =
BinaryCompatibilityRepository(SourcesRepository(sourceRoots, compilationClasspath))
}
@VisibleForTesting
fun emptyCaches() =
sources.close()
override fun close() =
emptyCaches()
fun isOverride(method: JApiMethod): Boolean =
apiSourceFileFor(method).let { apiSourceFile ->
when (apiSourceFile) {
is ApiSourceFile.Java -> sources.executeQuery(apiSourceFile, JavaSourceQueries.isOverrideMethod(method))
is ApiSourceFile.Kotlin -> sources.executeQuery(apiSourceFile, KotlinSourceQueries.isOverrideMethod(method))
}
}
fun isSince(version: String, member: JApiCompatibility): Boolean =
apiSourceFileFor(member).let { apiSourceFile ->
when (apiSourceFile) {
is ApiSourceFile.Java -> sources.executeQuery(apiSourceFile, JavaSourceQueries.isSince(version, member))
is ApiSourceFile.Kotlin -> sources.executeQuery(apiSourceFile, KotlinSourceQueries.isSince(version, member))
}
}
private
fun apiSourceFileFor(member: JApiCompatibility): ApiSourceFile =
member.jApiClass.let { declaringClass ->
sources.sourceFileAndSourceRootFor(declaringClass.sourceFilePath).let { (sourceFile, sourceRoot) ->
if (declaringClass.isKotlin) ApiSourceFile.Kotlin(sourceFile, sourceRoot)
else ApiSourceFile.Java(sourceFile, sourceRoot)
}
}
private
val JApiClass.sourceFilePath: String
get() = if (isKotlin) kotlinSourceFilePath else javaSourceFilePath
private
val JApiClass.javaSourceFilePath: String
get() = fullyQualifiedName
.replace(".", "/")
.replace(innerClassesPartRegex, "") + ".java"
private
val innerClassesPartRegex =
"\\$.*".toRegex()
private
val JApiClass.kotlinSourceFilePath: String
get() = "$packagePath/$bytecodeSourceFilename"
private
val JApiClass.bytecodeSourceFilename: String
get() = newClass.orNull()?.classFile?.getAttribute("SourceFile")?.let { it as? SourceFileAttribute }?.fileName
?: throw java.lang.IllegalStateException("Bytecode for $fullyQualifiedName is missing the 'SourceFile' attribute")
}
| apache-2.0 |
Ph1b/MaterialAudiobookPlayer | data/src/test/kotlin/de/ph1b/audiobook/data/repo/internals/BookStorageTest.kt | 1 | 1856 | package de.ph1b.audiobook.data.repo.internals
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import de.ph1b.audiobook.data.Book
import de.ph1b.audiobook.data.BookFactory
import kotlinx.coroutines.runBlocking
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
import java.util.UUID
@RunWith(AndroidJUnit4::class)
@Config(sdk = [28])
class BookStorageTest {
private val db = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), AppDb::class.java)
.allowMainThreadQueries()
.build()
private val storage = BookStorage(db.chapterDao(), db.bookMetadataDao(), db.bookSettingsDao(), db)
private val bookA: Book
private val bookB: Book
init {
val bookAId = UUID.randomUUID()
val bookBId = UUID.randomUUID()
val books = runBlocking {
storage.addOrUpdate(BookFactory.create(name = "Name A", lastPlayedAtMillis = 5, id = bookAId))
storage.addOrUpdate(BookFactory.create(name = "Name B", lastPlayedAtMillis = 10, id = bookBId))
storage.books()
}
bookA = books.single { it.id == bookAId }
bookB = books.single { it.id == bookBId }
}
@Test
fun updateName() {
runBlocking {
storage.updateBookName(bookA.id, "Name A2")
val books = storage.books()
val updatedBook = bookA.updateMetaData { copy(name = "Name A2") }
assertThat(books).containsExactly(updatedBook, bookB)
}
}
@Test
fun updateLastPlayedAt() {
runBlocking {
storage.updateLastPlayedAt(bookA.id, 500)
val books = storage.books()
val updatedBook = bookA.update(updateSettings = { copy(lastPlayedAtMillis = 500) })
assertThat(books).containsExactly(updatedBook, bookB)
}
}
}
| lgpl-3.0 |
EZTEQ/rbtv-firetv | app/src/test/java/de/markhaehnel/rbtv/rocketbeanstv/util/InstantAppExecutors.kt | 1 | 292 | package de.markhaehnel.rbtv.rocketbeanstv.util
import de.markhaehnel.rbtv.rocketbeanstv.AppExecutors
import java.util.concurrent.Executor
class InstantAppExecutors : AppExecutors(instant, instant, instant) {
companion object {
private val instant = Executor { it.run() }
}
} | mit |
robinverduijn/gradle | .teamcity/Gradle_Check/configurations/StagePasses.kt | 1 | 5592 | package configurations
import common.applyDefaultSettings
import common.gradleWrapper
import jetbrains.buildServer.configs.kotlin.v2018_2.AbsoluteId
import jetbrains.buildServer.configs.kotlin.v2018_2.BuildStep
import jetbrains.buildServer.configs.kotlin.v2018_2.FailureAction
import jetbrains.buildServer.configs.kotlin.v2018_2.buildSteps.script
import jetbrains.buildServer.configs.kotlin.v2018_2.triggers.ScheduleTrigger
import jetbrains.buildServer.configs.kotlin.v2018_2.triggers.VcsTrigger
import jetbrains.buildServer.configs.kotlin.v2018_2.triggers.schedule
import jetbrains.buildServer.configs.kotlin.v2018_2.triggers.vcs
import model.CIBuildModel
import model.Stage
import model.TestType
import model.Trigger
import projects.FunctionalTestProject
class StagePasses(model: CIBuildModel, stage: Stage, prevStage: Stage?, containsDeferredTests: Boolean) : BaseGradleBuildType(model, init = {
uuid = stageTriggerUuid(model, stage)
id = stageTriggerId(model, stage)
name = stage.stageName.stageName + " (Trigger)"
applyDefaultSettings()
artifactRules = "build/build-receipt.properties"
val triggerExcludes = """
-:.idea
-:.github
-:.teamcity
-:.teamcityTest
-:subprojects/docs/src/docs/release
""".trimIndent()
val masterReleaseFilter = model.masterAndReleaseBranches.joinToString(prefix = "+:", separator = "\n+:")
features {
publishBuildStatusToGithub(model)
}
if (stage.trigger == Trigger.eachCommit) {
triggers.vcs {
quietPeriodMode = VcsTrigger.QuietPeriodMode.USE_CUSTOM
quietPeriod = 90
triggerRules = triggerExcludes
branchFilter = masterReleaseFilter
}
} else if (stage.trigger != Trigger.never) {
triggers.schedule {
if (stage.trigger == Trigger.weekly) {
schedulingPolicy = weekly {
dayOfWeek = ScheduleTrigger.DAY.Saturday
hour = 1
}
} else {
schedulingPolicy = daily {
hour = 0
minute = 30
}
}
triggerBuild = always()
withPendingChangesOnly = true
param("revisionRule", "lastFinished")
param("branchFilter", masterReleaseFilter)
}
}
params {
param("env.JAVA_HOME", buildJavaHome)
}
steps {
gradleWrapper {
name = "GRADLE_RUNNER"
tasks = "createBuildReceipt"
gradleParams = "-PtimestampedVersion --daemon"
}
script {
name = "CHECK_CLEAN_M2"
executionMode = BuildStep.ExecutionMode.ALWAYS
scriptContent = m2CleanScriptUnixLike
}
if (model.tagBuilds) {
gradleWrapper {
name = "TAG_BUILD"
executionMode = BuildStep.ExecutionMode.ALWAYS
tasks = "tagBuild"
gradleParams = "-PteamCityUsername=%teamcity.username.restbot% -PteamCityPassword=%teamcity.password.restbot% -PteamCityBuildId=%teamcity.build.id% -PgithubToken=%github.ci.oauth.token% ${buildScanTag("StagePasses")} --daemon"
}
}
}
dependencies {
if (!stage.runsIndependent && prevStage != null) {
dependency(stageTriggerId(model, prevStage)) {
snapshot {
onDependencyFailure = FailureAction.ADD_PROBLEM
}
}
}
stage.specificBuilds.forEach {
dependency(it.create(model, stage)) {
snapshot {}
}
}
stage.performanceTests.forEach { performanceTest ->
dependency(AbsoluteId(performanceTest.asId(model))) {
snapshot {}
}
}
stage.functionalTests.forEach { testCoverage ->
val isSplitIntoBuckets = testCoverage.testType != TestType.soak
if (isSplitIntoBuckets) {
model.buildTypeBuckets.filter { bucket ->
!bucket.shouldBeSkipped(testCoverage) && !bucket.shouldBeSkippedInStage(stage)
}.forEach { subProjectBucket ->
if (subProjectBucket.hasTestsOf(testCoverage.testType)) {
subProjectBucket.forTestType(testCoverage.testType).forEach {
dependency(AbsoluteId(testCoverage.asConfigurationId(model, it.name))) { snapshot {} }
}
}
}
} else {
dependency(AbsoluteId(testCoverage.asConfigurationId(model))) {
snapshot {}
}
}
}
if (containsDeferredTests) {
model.buildTypeBuckets.forEach { bucket ->
if (bucket.containsSlowTests()) {
FunctionalTestProject.missingTestCoverage.filter {
bucket.hasTestsOf(it.testType)
}.forEach { testConfig ->
bucket.forTestType(testConfig.testType).forEach {
dependency(AbsoluteId(testConfig.asConfigurationId(model, it.name))) { snapshot {} }
}
}
}
}
}
}
})
fun stageTriggerUuid(model: CIBuildModel, stage: Stage) = "${model.projectPrefix}Stage_${stage.stageName.uuid}_Trigger"
fun stageTriggerId(model: CIBuildModel, stage: Stage) = AbsoluteId("${model.projectPrefix}Stage_${stage.stageName.id}_Trigger")
| apache-2.0 |
chenxyu/android-banner | bannerlibrary/src/main/java/com/chenxyu/bannerlibrary/indicator/DrawableIndicator.kt | 1 | 7658 | package com.chenxyu.bannerlibrary.indicator
import android.graphics.drawable.StateListDrawable
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.chenxyu.bannerlibrary.BannerView2
import com.chenxyu.bannerlibrary.R
import com.chenxyu.bannerlibrary.extend.az
import com.chenxyu.bannerlibrary.extend.dpToPx
import com.chenxyu.bannerlibrary.extend.getDrawable2
/**
* @Author: ChenXingYu
* @CreateDate: 2020/8/19 15:49
* @Description: Drawable指示器(支持XML设置)
* @Version: 1.0
* @param overlap 指示器是否重叠在Banner上
* @param normalDrawable 默认Indicator
* @param selectedDrawable 选中Indicator
* @param margin 指示器外边距,间隔(DP)
* @param gravity 指示器的位置
*/
class DrawableIndicator(overlap: Boolean? = true,
@DrawableRes normalDrawable: Int? = R.drawable.indicator_gray,
@DrawableRes selectedDrawable: Int? = R.drawable.indicator_white,
margin: Int? = 4,
gravity: Int? = Gravity.CENTER
) : Indicator() {
/**
* 指示器集
*/
private var mIndicators: MutableList<View> = mutableListOf()
/**
* 指示器外边距,间隔(DP)
*/
var indicatorMargin: Int = 4
/**
* 指示器宽(DP)
*/
var indicatorWidth: Int = 7
/**
* 指示器高(DP)
*/
var indicatorHeight: Int = 7
/**
* 选中时指示器宽(DP)
*/
var indicatorSelectedW: Int = 7
/**
* 选中时指示器高(DP)
*/
var indicatorSelectedH: Int = 7
/**
* 默认Indicator Drawable
*/
@DrawableRes
var indicatorNormalDrawable: Int = R.drawable.indicator_gray
/**
* 选中Indicator Drawable
*/
@DrawableRes
var indicatorSelectedDrawable: Int = R.drawable.indicator_white
/**
* 默认指示器LayoutParams
*/
lateinit var normalParams: LinearLayout.LayoutParams
/**
* 选中的指示器LayoutParams
*/
lateinit var selectedParams: LinearLayout.LayoutParams
init {
overlap?.let { this.overlap = it }
normalDrawable?.let { indicatorNormalDrawable = it }
selectedDrawable?.let { indicatorSelectedDrawable = it }
margin?.let { indicatorMargin = it }
gravity?.let { indicatorGravity = it }
}
override fun registerOnPageChangeCallback(viewPager2: ViewPager2?) {
if (mVp2PageChangeCallback == null) {
mVp2PageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
toggleIndicator(null, viewPager2)
}
}
viewPager2?.registerOnPageChangeCallback(mVp2PageChangeCallback!!)
}
}
override fun addOnScrollListener(recyclerView: RecyclerView?) {
if (mRvScrollListener == null) {
mRvScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
when (newState) {
// 闲置
RecyclerView.SCROLL_STATE_IDLE -> {
toggleIndicator(recyclerView, null)
}
// 拖拽中
RecyclerView.SCROLL_STATE_DRAGGING -> {
}
// 惯性滑动中
RecyclerView.SCROLL_STATE_SETTLING -> {
toggleIndicator(recyclerView, null)
}
}
}
}
recyclerView?.addOnScrollListener(mRvScrollListener!!)
}
}
override fun initIndicator(container: LinearLayout, count: Int, orientation: Int) {
mIndicators.clear()
normalParams = LinearLayout.LayoutParams(
indicatorWidth.dpToPx(container.context),
indicatorHeight.dpToPx(container.context))
selectedParams = LinearLayout.LayoutParams(
indicatorSelectedW.dpToPx(container.context),
indicatorSelectedH.dpToPx(container.context))
if (orientation == RecyclerView.HORIZONTAL) {
normalParams.setMargins(indicatorMargin.dpToPx(container.context), 0,
indicatorMargin.dpToPx(container.context), 0)
selectedParams.setMargins(indicatorMargin.dpToPx(container.context), 0,
indicatorMargin.dpToPx(container.context), 0)
} else {
normalParams.setMargins(0, indicatorMargin.dpToPx(container.context),
0, indicatorMargin.dpToPx(container.context))
selectedParams.setMargins(0, indicatorMargin.dpToPx(container.context),
0, indicatorMargin.dpToPx(container.context))
}
repeat(count) {
val indicators = View(container.context)
val drawable = StateListDrawable()
drawable.addState(IntArray(0).plus(android.R.attr.state_selected),
container.context.getDrawable2(indicatorSelectedDrawable))
drawable.addState(IntArray(0), container.context.getDrawable2(indicatorNormalDrawable))
indicators.background = drawable
indicators.isSelected = false
indicators.layoutParams = normalParams
container.addView(indicators)
mIndicators.add(indicators)
}
mIndicators[0].isSelected = true
mIndicators[0].layoutParams = selectedParams
}
/**
* 切换指示器位置
*/
private fun toggleIndicator(recyclerView: RecyclerView?, viewPager2: ViewPager2?) {
val currentPosition = viewPager2?.currentItem ?: recyclerView?.getChildAt(0)
?.layoutParams?.az<RecyclerView.LayoutParams>()?.viewAdapterPosition
val itemCount = viewPager2?.adapter?.itemCount
?: recyclerView?.adapter?.az<BannerView2.Adapter<*, *>>()?.itemCount ?: return
for (indicator in mIndicators) {
indicator.isSelected = false
indicator.layoutParams = normalParams
}
if (isLoop) {
when (currentPosition) {
0 -> {
mIndicators[mIndicators.size - 1].isSelected = true
mIndicators[mIndicators.size - 1].layoutParams = selectedParams
return
}
itemCount.minus(1) -> {
mIndicators[0].isSelected = true
mIndicators[0].layoutParams = selectedParams
return
}
itemCount.minus(2) -> {
mIndicators[mIndicators.size - 1].isSelected = true
mIndicators[mIndicators.size - 1].layoutParams = selectedParams
return
}
}
for (i in mIndicators.indices) {
if (currentPosition == i) {
mIndicators[i - 1].isSelected = true
mIndicators[i - 1].layoutParams = selectedParams
return
}
}
} else {
currentPosition?.let {
mIndicators[it].isSelected = true
mIndicators[it].layoutParams = selectedParams
}
}
}
} | mit |
proxer/ProxerLibJava | library/src/main/kotlin/me/proxer/library/internal/adapter/ConferenceInfoAdapter.kt | 1 | 1910 | package me.proxer.library.internal.adapter
import com.squareup.moshi.FromJson
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.squareup.moshi.ToJson
import me.proxer.library.entity.messenger.ConferenceInfo
import me.proxer.library.entity.messenger.ConferenceParticipant
import java.util.Date
/**
* @author Ruben Gees
*/
internal class ConferenceInfoAdapter {
@FromJson
fun fromJson(json: IntermediateConferenceInfoContainer): ConferenceInfo {
return ConferenceInfo(
json.info.topic,
json.info.participantAmount,
json.info.firstMessageTime,
json.info.lastMessageTime,
json.info.leaderId,
json.participants
)
}
@ToJson
fun toJson(value: ConferenceInfo): IntermediateConferenceInfoContainer {
return IntermediateConferenceInfoContainer(
IntermediateConferenceInfoContainer.IntermediateConferenceInfo(
value.topic,
value.participantAmount,
value.firstMessageTime,
value.lastMessageTime,
value.leaderId
),
value.participants
)
}
@JsonClass(generateAdapter = true)
internal data class IntermediateConferenceInfoContainer(
@Json(name = "conference") internal val info: IntermediateConferenceInfo,
@Json(name = "users") internal val participants: List<ConferenceParticipant>
) {
@JsonClass(generateAdapter = true)
internal data class IntermediateConferenceInfo(
@Json(name = "topic") val topic: String,
@Json(name = "count") val participantAmount: Int,
@Json(name = "timestamp_start") val firstMessageTime: Date,
@Json(name = "timestamp_end") val lastMessageTime: Date,
@Json(name = "leader") val leaderId: String
)
}
}
| mit |
owncloud/android | owncloudApp/src/main/java/com/owncloud/android/providers/cursors/RootCursor.kt | 1 | 2552 | /**
* ownCloud Android client application
*
* @author Bartosz Przybylski
* @author Abel García de Prada
* Copyright (C) 2015 Bartosz Przybylski
* Copyright (C) 2020 ownCloud GmbH.
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.providers.cursors
import android.accounts.Account
import android.content.Context
import android.database.MatrixCursor
import android.provider.DocumentsContract.Root
import com.owncloud.android.R
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
class RootCursor(projection: Array<String>?) : MatrixCursor(projection ?: DEFAULT_ROOT_PROJECTION) {
fun addRoot(account: Account, context: Context) {
val manager = FileDataStorageManager(context, account, context.contentResolver)
val mainDir = manager.getFileByPath(OCFile.ROOT_PATH)
val flags = Root.FLAG_SUPPORTS_SEARCH or Root.FLAG_SUPPORTS_CREATE
newRow()
.add(Root.COLUMN_ROOT_ID, account.name)
.add(Root.COLUMN_DOCUMENT_ID, mainDir?.fileId)
.add(Root.COLUMN_SUMMARY, account.name)
.add(Root.COLUMN_TITLE, context.getString(R.string.app_name))
.add(Root.COLUMN_ICON, R.mipmap.icon)
.add(Root.COLUMN_FLAGS, flags)
}
fun addProtectedRoot(context: Context) {
newRow()
.add(
Root.COLUMN_SUMMARY,
context.getString(R.string.document_provider_locked)
)
.add(Root.COLUMN_TITLE, context.getString(R.string.app_name))
.add(Root.COLUMN_ICON, R.mipmap.icon)
}
companion object {
private val DEFAULT_ROOT_PROJECTION = arrayOf(
Root.COLUMN_ROOT_ID,
Root.COLUMN_FLAGS,
Root.COLUMN_ICON,
Root.COLUMN_TITLE,
Root.COLUMN_DOCUMENT_ID,
Root.COLUMN_AVAILABLE_BYTES,
Root.COLUMN_SUMMARY,
Root.COLUMN_FLAGS
)
}
}
| gpl-2.0 |
square/leakcanary | leakcanary-android-core/src/main/java/leakcanary/internal/friendly/Friendly.kt | 2 | 615 | @file:Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER", "NOTHING_TO_INLINE")
@file:JvmName("leakcanary-android-core_Friendly")
package leakcanary.internal.friendly
internal inline val mainHandler
get() = leakcanary.internal.mainHandler
internal inline fun checkMainThread() = leakcanary.internal.checkMainThread()
internal inline fun checkNotMainThread() = leakcanary.internal.checkNotMainThread()
internal inline fun <reified T : Any> noOpDelegate(): T = leakcanary.internal.noOpDelegate()
internal inline fun measureDurationMillis(block: () -> Unit) =
leakcanary.internal.measureDurationMillis(block)
| apache-2.0 |
CarrotCodes/Warren | src/main/kotlin/chat/willow/warren/registration/RFC1459RegistrationExtension.kt | 1 | 1014 | package chat.willow.warren.registration
import chat.willow.kale.irc.message.rfc1459.NickMessage
import chat.willow.kale.irc.message.rfc1459.PassMessage
import chat.willow.kale.irc.message.rfc1459.UserMessage
import chat.willow.warren.IMessageSink
class RFC1459RegistrationExtension(private val sink: IMessageSink, private val nickname: String, private val username: String, private val password: String? = null, private val registrationManager: IRegistrationManager): IRegistrationExtension {
override fun startRegistration() {
if (password != null) {
sink.write(PassMessage.Command(password = password))
}
sink.write(NickMessage.Command(nickname = nickname))
sink.write(UserMessage.Command(username = username, mode = "8", realname = username))
}
override fun onRegistrationSucceeded() {
registrationManager.onExtensionSuccess(this)
}
override fun onRegistrationFailed() {
registrationManager.onExtensionFailure(this)
}
}
| isc |
jdinkla/groovy-java-ray-tracer | src/main/kotlin/net/dinkla/raytracer/objects/GeometricObject.kt | 1 | 614 | package net.dinkla.raytracer.objects
import net.dinkla.raytracer.hits.Hit
import net.dinkla.raytracer.hits.ShadowHit
import net.dinkla.raytracer.materials.IMaterial
import net.dinkla.raytracer.math.BBox
import net.dinkla.raytracer.math.Ray
open abstract class GeometricObject {
open var isShadows = true
open var material: IMaterial? = null
var isInitialized: Boolean = false
open var boundingBox: BBox = BBox()
abstract fun hit(ray: Ray, sr: Hit): Boolean
abstract fun shadowHit(ray: Ray, tmin: ShadowHit): Boolean
open fun initialize() {
isInitialized = true
}
}
| apache-2.0 |
kory33/SignVote | src/main/kotlin/com/github/kory33/signvote/manager/vote/UUIDToPlayerVotesCacheMap.kt | 1 | 533 | package com.github.kory33.signvote.manager.vote
import com.github.kory33.signvote.utils.collection.CachingMap
import java.util.UUID
/**
* A map collection class that has [UUID] as keys and [VoteScoreToVotePointCacheMap] as values.
* This map automatically creates empty value upon call of [.get] method where value is `null`
* @see com.github.kory33.signvote.utils.collection.CachingMap
*/
internal class UUIDToPlayerVotesCacheMap :
CachingMap<UUID, VoteScoreToVotePointCacheMap>({ VoteScoreToVotePointCacheMap() })
| gpl-3.0 |
Ekito/koin | koin-projects/koin-androidx-fragment/src/main/java/org/koin/androidx/fragment/android/KoinFragmentFactory.kt | 1 | 794 | package org.koin.androidx.fragment.android
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentFactory
import org.koin.core.component.KoinApiExtension
import org.koin.core.component.KoinComponent
import org.koin.core.scope.Scope
/**
* FragmentFactory for Koin
*/
@OptIn(KoinApiExtension::class)
class KoinFragmentFactory(private val scope: Scope? = null) : FragmentFactory(), KoinComponent {
override fun instantiate(classLoader: ClassLoader, className: String): Fragment {
val clazz = Class.forName(className).kotlin
val instance = if (scope != null) {
scope.getOrNull(clazz)
} else {
getKoin().getOrNull(clazz)
}
return (instance ?: super.instantiate(classLoader, className)) as Fragment
}
} | apache-2.0 |
Ekito/koin | koin-projects/koin-android-viewmodel/src/main/java/org/koin/android/viewmodel/factory/DefaultViewModelFactory.kt | 1 | 522 | package org.koin.android.viewmodel.factory
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import org.koin.android.viewmodel.ViewModelParameter
import org.koin.core.scope.Scope
class DefaultViewModelFactory<T : ViewModel>(val scope: Scope,
val parameters: ViewModelParameter<T>) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return scope.get(parameters.clazz, parameters.qualifier, parameters.parameters) as T
}
} | apache-2.0 |
mayuki/AgqrPlayer4Tv | AgqrPlayer4Tv/app/src/main/java/org/misuzilla/agqrplayer4tv/model/Schedules.kt | 1 | 220 | package org.misuzilla.agqrplayer4tv.model
import java.io.Serializable
/**
* Created by Tomoyo on 1/11/2017.
*/
class Schedules : Serializable {
val version = 1
val schedules = mutableListOf<ScheduleEntry>()
} | mit |
google/ksp | compiler-plugin/src/main/kotlin/com/google/devtools/ksp/DualLookupTracker.kt | 1 | 2006 | /*
* Copyright 2021 Google LLC
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp
import org.jetbrains.kotlin.incremental.LookupTrackerImpl
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.incremental.components.Position
import org.jetbrains.kotlin.incremental.components.ScopeKind
class DualLookupTracker : LookupTracker {
val symbolTracker = LookupTrackerImpl(LookupTracker.DO_NOTHING)
val classTracker = LookupTrackerImpl(LookupTracker.DO_NOTHING)
override val requiresPosition: Boolean
get() = symbolTracker.requiresPosition || classTracker.requiresPosition
override fun record(filePath: String, position: Position, scopeFqName: String, scopeKind: ScopeKind, name: String) {
symbolTracker.record(filePath, position, scopeFqName, scopeKind, name)
if (scopeKind == ScopeKind.CLASSIFIER) {
val className = scopeFqName.substringAfterLast('.')
val outerScope = scopeFqName.substringBeforeLast('.', "<anonymous>")
// DO NOT USE: ScopeKind is meaningless
classTracker.record(filePath, position, outerScope, scopeKind, className)
}
}
override fun clear() {
// Do not clear symbolTracker and classTracker.
// LookupTracker.clear() is called in repeatAnalysisIfNeeded, but we need records across all rounds.
}
}
| apache-2.0 |
talhacohen/android | app/src/main/java/com/etesync/syncadapter/ui/setup/LoginCredentials.kt | 1 | 1768 | /*
* Copyright © 2013 – 2016 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.ui.setup
import android.os.Parcel
import android.os.Parcelable
import com.etesync.syncadapter.App
import com.etesync.syncadapter.Constants
import java.net.URI
import java.net.URISyntaxException
class LoginCredentials(_uri: URI?, val userName: String, val password: String) : Parcelable {
val uri: URI?
init {
var uri = _uri
if (uri == null) {
try {
uri = URI(Constants.serviceUrl.toString())
} catch (e: URISyntaxException) {
App.log.severe("Should never happen, it's a constant")
}
}
this.uri = uri
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeSerializable(uri)
dest.writeString(userName)
dest.writeString(password)
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<*> = object : Parcelable.Creator<LoginCredentials> {
override fun createFromParcel(source: Parcel): LoginCredentials {
return LoginCredentials(
source.readSerializable() as URI,
source.readString()!!, source.readString()!!
)
}
override fun newArray(size: Int): Array<LoginCredentials?> {
return arrayOfNulls(size)
}
}
}
}
| gpl-3.0 |
y2k/ProjectCaerus | app/src/test/kotlin/com/projectcaerus/samples/SampleTest.kt | 1 | 1480 | package com.projectcaerus.samples
import android.app.Activity
import android.content.res.ContextFactory
import android.graphics.Canvas
import com.android.internal.policy.impl.PhoneLayoutInflater
import com.projectcaerus.Size
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.mockito.Mockito
import org.mockito.stubbing.Answer
import java.io.File
import java.net.URLClassLoader
/**
* Created by y2k on 13/06/16.
*/
class SampleTest {
@Test
fun test() {
val appPath = File("../samples/hello-world/app")
val resPath = File(appPath, "src/main/res")
val classPath = File(appPath, "build/intermediates/classes/debug")
assertTrue(classPath.exists())
val loader = URLClassLoader(arrayOf(classPath.toURI().toURL()))
val context = ContextFactory().makeNoPowerMock(loader, resPath)
val mainClass = loader.loadClass("com.example.helloworld.MainActivity")
assertNotNull(mainClass)
val mainActivity = mainClass.newInstance() as Activity
mainActivity.inflater = PhoneLayoutInflater(context)
mainActivity.onCreate(null)
mainActivity.dump(Size(320, 480))
// mainActivity.dumpTo(Size(320, 480), mockCanvas())
}
private fun mockCanvas(): Canvas {
return Mockito.mock(Canvas::class.java, Answer {
println("called = " + it)
if (it.method.name == "save") 1 else null
})
}
} | gpl-3.0 |
google/chromeosnavigationdemo | app/src/main/java/com/emilieroberts/chromeosnavigationdemo/MainActivity.kt | 1 | 5545 | /*
* 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
*
* 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.emilieroberts.chromeosnavigationdemo
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.google.android.material.navigation.NavigationView
class MainActivity : AppCompatActivity(),
FragmentManager.OnBackStackChangedListener,
FileBrowserFragment.FileActionsListener {
private lateinit var fileBehaviorViewModel: AdaptableDemoViewModel
private val onNavigationItemSelection: (MenuItem) -> Boolean = { item ->
//If we're in the image viewer, pop back out to the file browser
supportFragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
fileBehaviorViewModel.inPhotoViewer = false
changeFileBrowserSource(item.itemId)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fileBehaviorViewModel = ViewModelProviders.of(this).get(AdaptableDemoViewModel::class.java)
val bottomNavigationView: BottomNavigationView? = findViewById(R.id.bottomnav_main)
bottomNavigationView?.setOnNavigationItemSelectedListener(onNavigationItemSelection)
val navigationView: NavigationView? = findViewById(R.id.nav_view)
navigationView?.setNavigationItemSelectedListener(onNavigationItemSelection)
fileBehaviorViewModel.getFileSource().observe(this, Observer { updateTitle(it) })
supportFragmentManager.addOnBackStackChangedListener(this)
val fileBrowserFragment = FileBrowserFragment()
fileBrowserFragment.fileActionsListener = this
supportFragmentManager.beginTransaction().apply {
replace(R.id.file_listing_fragment, fileBrowserFragment)
commit()
}
shouldDisplayHomeUp()
}
override fun onResume() {
restoreState()
super.onResume()
}
private fun restoreState() {
if (fileBehaviorViewModel.inPhotoViewer) {
displayImage()
}
}
private fun changeFileBrowserSource(itemId: Int): Boolean {
return when (itemId) {
R.id.navigation_local -> {
fileBehaviorViewModel.setFileSource(FileStore.intToPhotoSource(R.id.navigation_local))
true
}
R.id.navigation_cloud -> {
title = getString(R.string.label_cloud)
fileBehaviorViewModel.setFileSource(FileStore.intToPhotoSource(R.id.navigation_cloud))
true
}
R.id.navigation_shared -> {
title = getString(R.string.label_shared)
fileBehaviorViewModel.setFileSource(FileStore.intToPhotoSource(R.id.navigation_shared))
true
}
else -> false
}
}
override fun onFileClick(filePosition: Int, fileId: Int) {
fileBehaviorViewModel.setCurrentPhotoId(fileId)
fileBehaviorViewModel.inPhotoViewer = true
displayImage()
}
private fun displayImage() {
supportFragmentManager.beginTransaction().apply {
replace(R.id.file_listing_fragment, ImageViewerFragment())
addToBackStack(null)
commit()
}
}
private fun updateTitle(fileSource: FileSource) {
title = when (fileSource) {
FileSource.LOCAL -> getString(R.string.label_local)
FileSource.CLOUD -> getString(R.string.label_cloud)
FileSource.SHARED -> getString(R.string.label_shared)
}
}
override fun onBackPressed() {
//If we press back, we will never be in the photo viewer
fileBehaviorViewModel.inPhotoViewer = false
super.onBackPressed()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.options_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_item_about -> {
showAboutDialog(this)
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onBackStackChanged() {
shouldDisplayHomeUp()
}
private fun shouldDisplayHomeUp() {
//Enable Up if there are entries in the back stack
supportActionBar?.setDisplayHomeAsUpEnabled(supportFragmentManager.backStackEntryCount > 0)
}
override fun onSupportNavigateUp(): Boolean {
supportFragmentManager.popBackStack()
fileBehaviorViewModel.inPhotoViewer = false
return true
}
}
| apache-2.0 |
devmil/muzei-bingimageoftheday | app/src/main/java/de/devmil/muzei/bingimageoftheday/worker/BingImageOfTheDayWorker.kt | 1 | 8060 | package de.devmil.muzei.bingimageoftheday.worker
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.util.Log
import androidx.work.*
import com.google.android.apps.muzei.api.provider.Artwork
import com.google.android.apps.muzei.api.provider.ProviderContract
import de.devmil.common.utils.LogUtil
import de.devmil.muzei.bingimageoftheday.*
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
class BingImageOfTheDayWorker(
val context: Context,
workerParams: WorkerParameters
) : Worker(context, workerParams) {
companion object {
private const val TAG = "BingImageIfTheDayWorker"
private const val SETTINGS_NAME = "BingImageOfTheDayArtSource"
internal fun enqueueLoad() {
Log.d(TAG, "Loading enqued")
val workManager = WorkManager.getInstance()
workManager.enqueue(OneTimeWorkRequestBuilder<BingImageOfTheDayWorker>()
.setConstraints(Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build())
.build())
}
private val lockObject = Object()
private var lastArtworkUpdate: Calendar? = null
}
private fun getSharedPreferences() : SharedPreferences {
return applicationContext.getSharedPreferences("muzeiartsource_$SETTINGS_NAME", 0)
}
private fun getImageTitle(imageDate: Date): String {
val df = SimpleDateFormat("MM/dd/yyyy", Locale.US)
return "Bing: " + df.format(imageDate.time)
}
override fun doWork(): Result {
LogUtil.LOGD(TAG, "Request: Loading new Bing images")
synchronized(lockObject) {
val now = Calendar.getInstance()
val settings = Settings(applicationContext, getSharedPreferences())
val isPortrait = settings.isOrientationPortrait
val isCurrentArtworkPortrait = settings.isCurrentOrientationPortrait
val market = settings.bingMarket
val currentArtworkMarket = settings.currentBingMarket
//when there are settings changes then the request for new images
//gets overwritten
val requestOverride = market != currentArtworkMarket
|| isPortrait != isCurrentArtworkPortrait
//Check if the last update is more than 2 minutes away.
//If not then return early (exception: when settings changed that lead to an update)
lastArtworkUpdate?.let {
val millisDiff = now.timeInMillis - it.timeInMillis
val minDiff = 1000 /* seconds */ * 60 /* minutes */ * 2
if(!requestOverride && millisDiff < minDiff) {
LogUtil.LOGD(TAG, "Last update was less than 2 minutes ago => ignoring")
return Result.success()
}
}
lastArtworkUpdate = now
//Default = request the image list from Bing
var requestNewImages = true
val lastArtwork = ProviderContract.getProviderClient<BingImageOfTheDayArtProvider>(applicationContext)
.lastAddedArtwork
if (lastArtwork != null) {
LogUtil.LOGD(TAG, "Found last artwork")
val timeInMillis = lastArtwork.metadata?.toLongOrNull()
if (timeInMillis != null) {
val token = getToken(Date(timeInMillis), market, isPortrait)
LogUtil.LOGD(TAG, "Metadata is correct")
if (token == lastArtwork.token && isNewestBingImage(Date(timeInMillis))) {
//when the current artwork matches the settings and is the newest, then don't load that Bing list
LogUtil.LOGD(TAG, "We have the latest image => do nothing")
requestNewImages = false
requestNextImageUpdate(Date(timeInMillis))
}
}
}
if (requestOverride) {
LogUtil.LOGD(TAG, "Settings changed! reloading anyways!")
requestNewImages = true
}
if (!requestNewImages) {
return Result.success()
}
LogUtil.LOGD(TAG, "Reloading Bing images")
val retriever = BingImageOfTheDayMetadataRetriever(
market,
BingImageDimension.UHD,
isPortrait
)
val photosMetadata = try {
retriever.bingImageOfTheDayMetadata ?: listOf()
} catch (e: IOException) {
Log.w(TAG, "Error reading Bing response", e)
return Result.retry()
}
if (photosMetadata.isEmpty()) {
Log.w(TAG, "No photos returned from Bing API.")
return Result.failure()
}
photosMetadata.asSequence().map { metadata ->
Artwork(
token = getToken(metadata.startDate, market, isPortrait),
title = metadata.startDate?.let { getImageTitle(it) } ?: "",
byline = metadata.copyright ?: "",
persistentUri = metadata.uri,
webUri = metadata.uri,
metadata = metadata.startDate?.time.toString()
)
}.sortedByDescending { aw ->
aw.metadata?.toLongOrNull() ?: 0
}.firstOrNull()
?.let { artwork ->
Log.d(TAG, "Got artworks. Selected this one: ${artwork.title} valid on: ${Date(artwork.metadata!!.toLong())}")
requestNextImageUpdate(Date(artwork.metadata!!.toLong()))
setArtwork(artwork)
settings.isCurrentOrientationPortrait = isPortrait
settings.currentBingMarket = market
}
return Result.success()
}
}
private fun getToken(startDate: Date?, market: BingMarket, isPortrait: Boolean): String {
val result = "$startDate-$market-${if(isPortrait) "portrait" else "landscape"}"
LogUtil.LOGD(TAG, "Token: $result")
return result
}
private fun isNewestBingImage(newestBingImageDate: Date) : Boolean {
val now = Calendar.getInstance().time
val nextBingImageDate = getNextBingImageDate(newestBingImageDate)
return now < nextBingImageDate
}
private fun getNextBingImageDate(newestBingImageDate: Date): Date {
val nextBingImageDate = Calendar.getInstance()
nextBingImageDate.timeInMillis = newestBingImageDate.time
nextBingImageDate.add(Calendar.DAY_OF_YEAR, 1)
return nextBingImageDate.time
}
private fun setArtwork(artwork: Artwork) {
LogUtil.LOGD(TAG, "Setting artwork: ${artwork.metadata?.toLongOrNull()?.let { Date(it) }}, ${artwork.title}")
ProviderContract.getProviderClient<BingImageOfTheDayArtProvider>(applicationContext)
.setArtwork(artwork)
}
private fun requestNextImageUpdate(currentImageDate: Date): Calendar {
val nextBingImageDate = getNextBingImageDate(currentImageDate)
val nextUpdate = Calendar.getInstance()
nextUpdate.time = nextBingImageDate
nextUpdate.add(Calendar.MINUTE, 1)
val sdf = SimpleDateFormat("dd.MM.yyyy HH:mm:ss", Locale.US)
LogUtil.LOGD(TAG, String.format("next update: %s", sdf.format(nextUpdate.time)))
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as? AlarmManager
val updateIntent = Intent(context, UpdateReceiver::class.java)
val pendingUpdateIntent = PendingIntent.getBroadcast(context, 1, updateIntent, PendingIntent.FLAG_UPDATE_CURRENT)
alarmManager?.set(AlarmManager.RTC_WAKEUP, nextUpdate.timeInMillis, pendingUpdateIntent)
return nextUpdate
}
} | apache-2.0 |
quarkusio/quarkus | devtools/project-core-extension-codestarts/src/main/resources/codestarts/quarkus/extension-codestarts/resteasy-reactive-qute-codestart/kotlin/src/main/kotlin/org/acme/SomePage.kt | 1 | 455 | package org.acme
import io.quarkus.qute.Template
import io.quarkus.qute.TemplateInstance
import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.Produces
import javax.ws.rs.QueryParam
import javax.ws.rs.core.MediaType
@Path("/some-page")
class SomePage(val page: Template) {
@GET
@Produces(MediaType.TEXT_HTML)
operator fun get(@QueryParam("name") name: String?): TemplateInstance {
return page.data("name", name)
}
}
| apache-2.0 |
camdenorrb/KPortals | src/main/kotlin/me/camdenorrb/kportals/portal/Portal.kt | 1 | 1444 | package me.camdenorrb.kportals.portal
import org.bukkit.util.Vector
import java.util.*
import kotlin.math.absoluteValue
import kotlin.math.max
/**
* Created by camdenorrb on 3/20/17.
*/
// TODO: Embed selection as a parameter so you don't need to calculate min/max ever again
data class Portal(
val name: String,
var toArgs: String,
val worldUUID: UUID,
var type: Type = Type.Unknown,
val selection: Selection,
val positions: Set<Vector>
) {
@delegate:Transient
val maxRadius by lazy {
val sel1 = selection.sel1 ?: return@lazy 0.0
val sel2 = selection.sel2 ?: return@lazy 0.0
val dist = sel1.clone().subtract(sel2)
max(max(dist.x.absoluteValue, dist.y.absoluteValue), dist.z.absoluteValue)
}
enum class Type {
ConsoleCommand, PlayerCommand, Unknown, Random, Bungee, World;
companion object {
fun byName(name: String, ignoreCase: Boolean = true): Type? {
return values().find { name.equals(it.name, ignoreCase) }
}
}
}
data class Selection(var sel1: Vector? = null, var sel2: Vector? = null) {
fun isSelected(): Boolean {
return sel1 != null && sel2 != null
}
fun center(): Vector? {
val sel1 = sel1 ?: return null
val sel2 = sel2 ?: return null
return sel1.clone().add(sel2).multiply(0.5)
}
}
} | mit |
TakuSemba/Spotlight | spotlight/src/main/java/com/takusemba/spotlight/OnSpotlightListener.kt | 1 | 255 | package com.takusemba.spotlight
/**
* Listener to notify the state of Spotlight.
*/
interface OnSpotlightListener {
/**
* Called when Spotlight is started
*/
fun onStarted()
/**
* Called when Spotlight is ended
*/
fun onEnded()
}
| apache-2.0 |
gantsign/restrulz-jvm | com.gantsign.restrulz.spring.mvc/src/main/kotlin/com/gantsign/restrulz/spring/mvc/SingleReturnValueHandler.kt | 1 | 5085 | /*-
* #%L
* Restrulz
* %%
* Copyright (C) 2017 GantSign Ltd.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.gantsign.restrulz.spring.mvc
import io.reactivex.Single
import org.springframework.core.MethodParameter
import org.springframework.core.ResolvableType
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.context.request.NativeWebRequest
import org.springframework.web.context.request.async.DeferredResult
import org.springframework.web.context.request.async.WebAsyncUtils
import org.springframework.web.method.support.AsyncHandlerMethodReturnValueHandler
import org.springframework.web.method.support.ModelAndViewContainer
/**
* A [AsyncHandlerMethodReturnValueHandler] implementation for [Single].
*/
class SingleReturnValueHandler : AsyncHandlerMethodReturnValueHandler {
private fun isSingle(returnType: MethodParameter): Boolean {
return Single::class.java.isAssignableFrom(returnType.parameterType)
}
private fun isSingleInResponseEntity(returnType: MethodParameter): Boolean {
if (ResponseEntity::class.java.isAssignableFrom(returnType.parameterType)) {
val resolvableType = ResolvableType.forMethodParameter(returnType)
val bodyType = resolvableType.getGeneric(0).resolve()
return bodyType != null && Single::class.java.isAssignableFrom(bodyType)
}
return false
}
override fun supportsReturnType(returnType: MethodParameter): Boolean {
return isSingle(returnType) || isSingleInResponseEntity(returnType)
}
override fun isAsyncReturnValue(returnValue: Any?, returnType: MethodParameter): Boolean {
return returnValue != null && supportsReturnType(returnType)
}
@Throws(Exception::class)
override fun handleReturnValue(returnValue: Any?,
returnType: MethodParameter,
mavContainer: ModelAndViewContainer,
webRequest: NativeWebRequest) {
// returnValue is either Single<ResponseEntity, Single<ResponseEntityConvertible>,
// Single<*>, ResponseEntity<Single<*>> or null
if (returnValue === null) {
mavContainer.isRequestHandled = true
return
}
val single: Single<*>
val responseEntity: ResponseEntity<Single<*>>?
if (returnValue is Single<*>) {
single = returnValue
responseEntity = null
} else {
if (returnValue !is ResponseEntity<*>) {
throw AssertionError("Expected ${Single::class.java.name} or ${ResponseEntity::class.java.name} but was ${returnValue::class.java.name}")
}
val body = returnValue.body
if (body === null) {
mavContainer.isRequestHandled = true
return
}
if (body !is Single<*>) {
throw AssertionError("Expected ${Single::class.java.name} but was ${body::class.java.name}")
}
single = body
@Suppress("UNCHECKED_CAST")
responseEntity = returnValue as ResponseEntity<Single<*>>?
}
val asyncManager = WebAsyncUtils.getAsyncManager(webRequest)
val deferredResult = convertToDeferredResult(responseEntity, single)
asyncManager.startDeferredResultProcessing(deferredResult, mavContainer)
}
private fun ResponseEntity<*>?.copy(body: Any): ResponseEntity<*> {
val statusCode: HttpStatus
val headers: HttpHeaders
if (this !== null) {
statusCode = this.statusCode
headers = this.headers
} else {
statusCode = HttpStatus.OK
headers = HttpHeaders()
}
return ResponseEntity(body, headers, statusCode)
}
private fun convertToDeferredResult(responseEntity: ResponseEntity<Single<*>>?,
single: Single<*>): DeferredResult<*> {
val singleResponse = single.map { returnValue ->
@Suppress("IfThenToElvis")
if (returnValue is ResponseEntity<*>) {
returnValue
} else if (returnValue is ResponseEntityConvertible<*>) {
returnValue.toResponseEntity()
} else {
responseEntity.copy(body = returnValue)
}
}
return SingleDeferredResult(single = singleResponse)
}
}
| apache-2.0 |
rei-m/android_hyakuninisshu | state/src/main/java/me/rei_m/hyakuninisshu/state/training/store/TrainingStarterStore.kt | 1 | 2062 | /*
* Copyright (c) 2020. Rei Matsushita
*
* 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 me.rei_m.hyakuninisshu.state.training.store
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import me.rei_m.hyakuninisshu.state.core.Dispatcher
import me.rei_m.hyakuninisshu.state.core.Event
import me.rei_m.hyakuninisshu.state.core.Store
import me.rei_m.hyakuninisshu.state.training.action.StartTrainingAction
import javax.inject.Inject
/**
* 練習の開始状態を管理する.
*/
class TrainingStarterStore @Inject constructor(dispatcher: Dispatcher) : Store() {
private val _onReadyEvent = MutableLiveData<Event<String>>()
val onReadyEvent: LiveData<Event<String>> = _onReadyEvent
private val _isEmpty = MutableLiveData(false)
val isEmpty: LiveData<Boolean> = _isEmpty
private val _isFailure = MutableLiveData(false)
val isFailure: LiveData<Boolean> = _isFailure
init {
register(dispatcher.on(StartTrainingAction::class.java).subscribe {
when (it) {
is StartTrainingAction.Success -> {
_onReadyEvent.value = Event(it.questionId)
_isEmpty.value = false
_isFailure.value = false
}
is StartTrainingAction.Empty -> {
_isEmpty.value = true
_isFailure.value = false
}
is StartTrainingAction.Failure -> {
_isFailure.value = true
}
}
})
}
}
| apache-2.0 |
jpmoreto/play-with-robots | android/lib/src/main/java/jpm/lib/graph/abs/Graph.kt | 1 | 462 | package jpm.lib.graph.abs
/**
* Created by jm on 21/03/17.
*
* see: http://btechsmartclass.com/DS/U3_T11.html
*/
interface Graph<G: Graph<G, N, A>, N: Node,A: Arc<N>> {
fun nodes(): Set<N>
fun startNodes(): Set<N>
fun endNodes(): Set<N>
infix fun add(node: N): G
infix fun add(arc: A): G
infix fun startAdd(node: N): G
infix fun endAdd(node: N): G
infix fun outArcs(node: N): Set<A>
infix fun inArcs(node: N): Set<A>
} | mit |
stoman/CompetitiveProgramming | problems/2021adventofcode16a/submissions/accepted/Stefan.kt | 2 | 2028 | import java.util.*
abstract class Packet(val version: Int, val type: Int, val bitCount: Int) {
fun versionSum(): Int = version + if(this is Operator) subPackets.sumOf { it.versionSum() } else 0
}
class Literal(version: Int, type: Int, bitCount: Int, val value: Int) : Packet(version, type, bitCount)
class Operator(version: Int, type: Int, bitCount: Int, val subPackets: List<Packet>) : Packet(version, type, bitCount)
fun Char.toBits(): List<Int> {
var v = lowercaseChar().digitToInt(16)
val r = mutableListOf<Int>()
repeat(4) {
r.add(v % 2)
v /= 2
}
return r.reversed()
}
fun List<Int>.parseBits(): Int {
var r = 0
for (bit in this) {
r *= 2
r += bit
}
return r
}
fun List<Int>.parsePacket(): Packet {
val version = slice(0..2).parseBits()
when (val type = slice(3..5).parseBits()) {
// Literal value.
4 -> {
val value = mutableListOf<Int>()
var i = 1
do {
i += 5
value.addAll(slice(i + 1..i + 4))
} while (get(i) == 1)
return Literal(version, type, i + 5, value.parseBits())
}
// Operator
else -> {
val subPackets = mutableListOf<Packet>()
var parsedBits = 0
when(get(6)) {
0 -> {
val subLength = slice(7..21).parseBits()
parsedBits = 22
while(parsedBits < 22 + subLength) {
val nextPacket = drop(parsedBits).parsePacket()
subPackets.add(nextPacket)
parsedBits += nextPacket.bitCount
}
}
1 -> {
val subLength = slice(7..17).parseBits()
parsedBits = 18
while(subPackets.size < subLength) {
val nextPacket = drop(parsedBits).parsePacket()
subPackets.add(nextPacket)
parsedBits += nextPacket.bitCount
}
}
}
return Operator(version, type, parsedBits, subPackets)
}
}
}
fun main() {
val packet = Scanner(System.`in`).next().flatMap { it.toBits() }.parsePacket()
println(packet.versionSum())
}
| mit |
http4k/http4k | http4k-testing/servirtium/src/test/kotlin/org/http4k/servirtium/InteractionStorageTest.kt | 1 | 1480 | package org.http4k.servirtium
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.File
class InteractionStorageTest {
@Test
fun `disk storage handles contract`(@TempDir root: File) {
val factory = InteractionStorage.Disk(root)
val storage = factory("foo")
val file = File(root, "foo.md")
storage.accept("hello".toByteArray())
storage.accept("goodbye".toByteArray())
assertThat(String(storage.get()), equalTo("hellogoodbye"))
assertThat(file.readText(), equalTo("hellogoodbye"))
storage.clean()
assertThat(String(storage.get()), equalTo(""))
assertThat(file.exists(), equalTo(false))
storage.accept("goodbye".toByteArray())
assertThat(String(storage.get()), equalTo("goodbye"))
assertThat(file.readText(), equalTo("goodbye"))
}
@Test
fun `memory storage handles contract`() {
val factory = InteractionStorage.InMemory()
val storage = factory("foo")
storage.accept("hello".toByteArray())
storage.accept("goodbye".toByteArray())
assertThat(String(storage.get()), equalTo("hellogoodbye"))
storage.clean()
assertThat(String(storage.get()), equalTo(""))
storage.accept("goodbye".toByteArray())
assertThat(String(storage.get()), equalTo("goodbye"))
}
}
| apache-2.0 |
kidchenko/playground | kotlin-koans/Properties/Properties/src/Task.kt | 2 | 101 | class PropertyExample() {
var counter = 0
var propertyWithCounter: Int? = null
set
}
| mit |
openMF/android-client | mifosng-android/src/main/java/com/mifos/mifosxdroid/online/savingsaccountapproval/SavingsAccountApprovalFragment.kt | 1 | 5669 | /*
* This project is licensed under the open source MPL V2.
* See https://github.com/openMF/android-client/blob/master/LICENSE.md
*/
package com.mifos.mifosxdroid.online.savingsaccountapproval
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.mifos.api.GenericResponse
import com.mifos.mifosxdroid.R
import com.mifos.mifosxdroid.core.MifosBaseActivity
import com.mifos.mifosxdroid.core.MifosBaseFragment
import com.mifos.mifosxdroid.uihelpers.MFDatePicker
import com.mifos.mifosxdroid.uihelpers.MFDatePicker.OnDatePickListener
import com.mifos.objects.accounts.loan.SavingsApproval
import com.mifos.objects.accounts.savings.DepositType
import com.mifos.utils.*
import javax.inject.Inject
/**
* @author nellyk
*/
class SavingsAccountApprovalFragment : MifosBaseFragment(), OnDatePickListener, SavingsAccountApprovalMvpView {
val LOG_TAG = javaClass.simpleName
@JvmField
@BindView(R.id.tv_approval_date)
var tvApprovalDate: TextView? = null
@JvmField
@BindView(R.id.btn_approve_savings)
var btnApproveSavings: Button? = null
@JvmField
@BindView(R.id.et_savings_approval_reason)
var etSavingsApprovalReason: EditText? = null
@JvmField
@Inject
var mSavingsAccountApprovalPresenter: SavingsAccountApprovalPresenter? = null
lateinit var rootView: View
var approvaldate: String? = null
var savingsAccountNumber = 0
var savingsAccountType: DepositType? = null
private var mfDatePicker: DialogFragment? = null
private var safeUIBlockingUtility: SafeUIBlockingUtility? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(activity as MifosBaseActivity?)!!.activityComponent.inject(this)
if (arguments != null) {
savingsAccountNumber = requireArguments().getInt(Constants.SAVINGS_ACCOUNT_NUMBER)
savingsAccountType = requireArguments().getParcelable(Constants.SAVINGS_ACCOUNT_TYPE)
}
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
activity?.actionBar?.setDisplayHomeAsUpEnabled(true)
rootView = inflater.inflate(R.layout.dialog_fragment_approve_savings, null)
ButterKnife.bind(this, rootView)
mSavingsAccountApprovalPresenter!!.attachView(this)
safeUIBlockingUtility = SafeUIBlockingUtility(activity,
getString(R.string.savings_account_approval_fragment_loading_message))
showUserInterface()
return rootView
}
override fun showUserInterface() {
mfDatePicker = MFDatePicker.newInsance(this)
tvApprovalDate!!.text = MFDatePicker.getDatePickedAsString()
approvaldate = tvApprovalDate!!.text.toString()
showApprovalDate()
}
@OnClick(R.id.btn_approve_savings)
fun onClickApproveSavings() {
if (Network.isOnline(context)) {
val savingsApproval = SavingsApproval()
savingsApproval.note = etSavingsApprovalReason!!.editableText.toString()
savingsApproval.approvedOnDate = approvaldate
initiateSavingsApproval(savingsApproval)
} else {
Toast.makeText(context,
resources.getString(R.string.error_network_not_available),
Toast.LENGTH_LONG).show()
}
}
@OnClick(R.id.tv_approval_date)
fun onClickApprovalDate() {
mfDatePicker!!.show(requireActivity().supportFragmentManager, FragmentConstants.DFRAG_DATE_PICKER)
}
override fun onDatePicked(date: String) {
tvApprovalDate!!.text = date
approvaldate = date
showApprovalDate()
}
fun showApprovalDate() {
approvaldate = DateHelper.getDateAsStringUsedForCollectionSheetPayload(approvaldate)
.replace("-", " ")
}
private fun initiateSavingsApproval(savingsApproval: SavingsApproval) {
mSavingsAccountApprovalPresenter!!.approveSavingsApplication(
savingsAccountNumber, savingsApproval)
}
override fun showSavingAccountApprovedSuccessfully(genericResponse: GenericResponse?) {
Toast.makeText(activity, "Savings Approved", Toast.LENGTH_LONG).show()
requireActivity().supportFragmentManager.popBackStack()
}
override fun showError(message: String?) {
Toast.makeText(activity, message, Toast.LENGTH_LONG).show()
}
override fun showProgressbar(b: Boolean) {
if (b) {
safeUIBlockingUtility!!.safelyBlockUI()
} else {
safeUIBlockingUtility!!.safelyUnBlockUI()
}
}
override fun onDestroyView() {
super.onDestroyView()
mSavingsAccountApprovalPresenter!!.detachView()
}
companion object {
fun newInstance(savingsAccountNumber: Int,
type: DepositType?): SavingsAccountApprovalFragment {
val savingsAccountApproval = SavingsAccountApprovalFragment()
val args = Bundle()
args.putInt(Constants.SAVINGS_ACCOUNT_NUMBER, savingsAccountNumber)
args.putParcelable(Constants.SAVINGS_ACCOUNT_TYPE, type)
savingsAccountApproval.arguments = args
return savingsAccountApproval
}
}
} | mpl-2.0 |
danfma/kodando | kodando-mithril-router-dom/src/main/kotlin/kodando/mithril/router/dom/Link.kt | 1 | 2002 | package kodando.mithril.routing
import kodando.history.History
import kodando.mithril.*
import kodando.mithril.context.contextConsumer
import kodando.mithril.elements.a
import org.w3c.dom.events.MouseEvent
external interface LinkProps : Props {
var className: String?
var onClick: EventHandler?
var target: String?
var replace: Boolean?
var to: String
}
object LinkView : View<LinkProps> {
override fun view(vnode: VNode<LinkProps>): VNode<*>? {
val props = vnode.attrs ?: return null
val className = props.className
val children = vnode.children
return root {
contextConsumer(routerContextKey) { routerContext ->
val history = routerContext.history
val location = History.createLocation(props.to, null, null, history.location)
val href: String = history.createHref(location)
a {
if (className != null) {
this.className = className
}
this.href = href
this.onClick = handleClick(props, routerContext)
addChild(*children)
}
}
}
}
private fun handleClick(props: LinkProps, routerContext: RouterContext): EventHandlerWithArgument<MouseEvent> = { event ->
props.onClick?.invoke()
if (shouldPresentDefault(event, props)) {
event.preventDefault()
val history = routerContext.history
val replace = props.replace ?: false
val to = props.to
if (replace) {
history.replace(to)
} else {
history.push(to)
}
}
}
private fun shouldPresentDefault(event: MouseEvent, props: LinkProps): Boolean {
return !event.defaultPrevented
&& event.button == 0.toShort()
&& props.target != "_blank"
&& !isModifierEvent(event)
}
private fun isModifierEvent(event: MouseEvent): Boolean {
return event.metaKey
|| event.altKey
|| event.ctrlKey
|| event.shiftKey
}
}
fun Props.routeLink(applier: Applier<LinkProps>) {
addChild(LinkView, applier)
}
| mit |
lewinskimaciej/planner | app/src/main/java/com/atc/planner/presentation/base/BaseMvpPresenter.kt | 1 | 313 | package com.atc.planner.presentation.base
import com.hannesdorfmann.mosby3.mvp.MvpBasePresenter
import com.hannesdorfmann.mosby3.mvp.MvpView
import java.io.Serializable
abstract class BaseMvpPresenter<V : MvpView> : MvpBasePresenter<V>(), BasePresenter {
abstract fun onViewCreated(data: Serializable?)
}
| mit |
square/duktape-android | zipline-gradle-plugin/src/test/projects/multipleJsTargets/lib/src/blueMain/kotlin/app/cash/zipline/tests/blue.kt | 1 | 68 | package app.cash.zipline.tests
fun main() {
println("#0000FF")
}
| apache-2.0 |
vilnius/tvarkau-vilniu | app/src/main/java/lt/vilnius/tvarkau/entity/SocialNetworkUser.kt | 1 | 339 | package lt.vilnius.tvarkau.entity
data class SocialNetworkUser internal constructor(
val token: String,
val email: String,
val provider: String
) {
companion object {
fun forGoogle(token: String, email: String): SocialNetworkUser {
return SocialNetworkUser(token, email, "google")
}
}
}
| mit |
infinum/android_dbinspector | dbinspector/src/main/kotlin/com/infinum/dbinspector/extensions/Menu.kt | 1 | 237 | package com.infinum.dbinspector.extensions
import android.view.Menu
import androidx.appcompat.widget.SearchView
import com.infinum.dbinspector.R
internal val Menu.searchView
get() = findItem(R.id.search)?.actionView as? SearchView
| apache-2.0 |
mixitconf/mixit | src/main/kotlin/mixit/MixitProperties.kt | 1 | 1298 | package mixit
import org.springframework.boot.context.properties.ConfigurationProperties
import java.math.BigDecimal
@ConfigurationProperties("mixit")
class MixitProperties {
lateinit var baseUri: String
lateinit var contact: String
lateinit var vimeoTchatUri: String
lateinit var vimeoFluxUri: String
lateinit var mixetteValue: BigDecimal
val drive = Drive()
val aes = Aes()
val googleapi = GoogleApi()
val feature = Feature()
class Drive {
val fr = DriveDocuments()
val en = DriveDocuments()
class DriveDocuments {
lateinit var sponsorform: String
lateinit var sponsor: String
lateinit var speaker: String
lateinit var press: String
}
}
class Aes {
lateinit var initvector: String
lateinit var key: String
}
class GoogleApi {
lateinit var clientid: String
lateinit var p12path: String
lateinit var user: String
lateinit var appname: String
}
class Feature {
var donation: Boolean = false
var lottery: Boolean = false
var lotteryResult: Boolean = false
var email: Boolean = false
var mixette: Boolean = false
var profilemsg: Boolean = false
}
}
| apache-2.0 |
FarbodSalamat-Zadeh/TimetableApp | app/src/main/java/co/timetableapp/ui/exams/ExamEditActivity.kt | 1 | 9290 | /*
* Copyright 2017 Farbod Salamat-Zadeh
*
* 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 co.timetableapp.ui.exams
import android.app.Activity
import android.content.Intent
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.widget.CheckBox
import android.widget.EditText
import android.widget.NumberPicker
import android.widget.TextView
import co.timetableapp.R
import co.timetableapp.TimetableApplication
import co.timetableapp.data.handler.ExamHandler
import co.timetableapp.model.Color
import co.timetableapp.model.Exam
import co.timetableapp.model.Subject
import co.timetableapp.ui.base.ItemEditActivity
import co.timetableapp.ui.components.DateSelectorHelper
import co.timetableapp.ui.components.SubjectSelectorHelper
import co.timetableapp.ui.components.TimeSelectorHelper
import co.timetableapp.ui.subjects.SubjectEditActivity
import co.timetableapp.util.UiUtils
import co.timetableapp.util.title
import org.threeten.bp.LocalDate
import org.threeten.bp.LocalTime
/**
* Allows the user to edit an [Exam].
*
* @see ExamDetailActivity
* @see ItemEditActivity
*/
class ExamEditActivity : ItemEditActivity<Exam>() {
companion object {
private const val REQUEST_CODE_SUBJECT_DETAIL = 2
private const val NO_DURATION = -1
}
private val mDataHandler = ExamHandler(this)
private lateinit var mEditTextModule: EditText
private lateinit var mEditTextSeat: EditText
private lateinit var mEditTextRoom: EditText
private var mSubject: Subject? = null
private lateinit var mSubjectHelper: SubjectSelectorHelper
private lateinit var mExamDate: LocalDate
private lateinit var mDateHelper: DateSelectorHelper
private lateinit var mExamTime: LocalTime
private lateinit var mTimeHelper: TimeSelectorHelper
private var mExamDuration = NO_DURATION
private lateinit var mDurationText: TextView
private lateinit var mDurationDialog: AlertDialog
private var mExamIsResit: Boolean = false
private lateinit var mEditTextNotes: EditText
override fun getLayoutResource() = R.layout.activity_exam_edit
override fun getTitleRes(isNewItem: Boolean) = if (isNewItem) {
R.string.title_activity_exam_new
} else {
R.string.title_activity_exam_edit
}
override fun setupLayout() {
mEditTextModule = findViewById(R.id.editText_module) as EditText
if (!mIsNew) {
mEditTextModule.setText(mItem!!.moduleName)
}
mEditTextSeat = findViewById(R.id.editText_seat) as EditText
if (!mIsNew) {
mEditTextSeat.setText(mItem!!.seat)
}
mEditTextRoom = findViewById(R.id.editText_room) as EditText
if (!mIsNew) {
mEditTextRoom.setText(mItem!!.room)
}
mEditTextNotes = findViewById(R.id.editText_notes) as EditText
if (!mIsNew) {
mEditTextNotes.setText(mItem!!.notes)
}
setupSubjectHelper()
setupDateText()
setupTimeText()
setupDurationText()
setupResitCheckbox()
}
private fun setupSubjectHelper() {
mSubjectHelper = SubjectSelectorHelper(this, R.id.textView_subject)
mSubjectHelper.onCreateNewSubject { _, _ ->
val intent = Intent(this, SubjectEditActivity::class.java)
ActivityCompat.startActivityForResult(
this,
intent,
REQUEST_CODE_SUBJECT_DETAIL,
null
)
}
mSubjectHelper.onSubjectChange {
mSubject = it!! // exams must have related subjects - it can't be null
val color = Color(it.colorId)
UiUtils.setBarColors(
color,
this,
mToolbar!!,
findViewById(R.id.appBarLayout),
findViewById(R.id.toolbar_container)
)
}
mSubjectHelper.setup(mItem?.getRelatedSubject(this))
}
private fun setupDateText() {
mExamDate = mItem?.date ?: LocalDate.now()
mDateHelper = DateSelectorHelper(this, R.id.textView_date)
mDateHelper.setup(mExamDate) { _, date ->
mExamDate = date
mDateHelper.updateDate(mExamDate)
}
}
private fun setupTimeText() {
mExamTime = mItem?.startTime ?: LocalTime.of(9 ,0)
mTimeHelper = TimeSelectorHelper(this, R.id.textView_start_time)
mTimeHelper.setup(mExamTime) { _, time ->
mExamTime = time
mTimeHelper.updateTime(mExamTime)
}
}
private fun setupDurationText() {
mDurationText = findViewById(R.id.textView_duration) as TextView
if (!mIsNew) {
mExamDuration = mItem!!.duration
updateDurationText()
}
mDurationText.setOnClickListener {
val builder = AlertDialog.Builder(this@ExamEditActivity)
val numberPicker = NumberPicker(baseContext)
numberPicker.minValue = 10
numberPicker.maxValue = 360
numberPicker.value = if (mExamDuration == NO_DURATION) 60 else mExamDuration
val titleView = layoutInflater.inflate(R.layout.dialog_title_with_padding, null)
(titleView.findViewById(R.id.title) as TextView).setText(R.string.property_duration)
builder.setView(numberPicker)
.setCustomTitle(titleView)
.setPositiveButton(R.string.action_done) { _, _ ->
mExamDuration = numberPicker.value
updateDurationText()
mDurationDialog.dismiss()
}
mDurationDialog = builder.create()
mDurationDialog.show()
}
}
private fun updateDurationText() {
mDurationText.text = "$mExamDuration mins"
mDurationText.setTextColor(ContextCompat.getColor(baseContext, R.color.mdu_text_black))
}
private fun setupResitCheckbox() {
mExamIsResit = !mIsNew && mItem!!.resit
val checkBox = findViewById(R.id.checkBox_resit) as CheckBox
checkBox.isChecked = mExamIsResit
checkBox.setOnCheckedChangeListener { _, isChecked -> mExamIsResit = isChecked }
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_SUBJECT_DETAIL) {
if (resultCode == Activity.RESULT_OK) {
mSubject = data.getParcelableExtra<Subject>(ItemEditActivity.EXTRA_ITEM)
mSubjectHelper.updateSubject(mSubject)
}
}
}
override fun handleDoneAction() {
var newModuleName = mEditTextModule.text.toString()
newModuleName = newModuleName.title()
if (mSubject == null) {
Snackbar.make(findViewById(R.id.rootView), R.string.message_subject_required,
Snackbar.LENGTH_SHORT).show()
return
}
if (mExamDuration == -1) {
Snackbar.make(findViewById(R.id.rootView), R.string.message_exam_duration_required,
Snackbar.LENGTH_SHORT).show()
return
}
val id = if (mIsNew) mDataHandler.getHighestItemId() + 1 else mItem!!.id
val timetableId = (application as TimetableApplication).currentTimetable!!.id
mItem = Exam(
id,
timetableId,
mSubject!!.id,
newModuleName,
mExamDate,
mExamTime,
mExamDuration,
mEditTextSeat.text.toString().trim(),
mEditTextRoom.text.toString().trim(),
mExamIsResit,
mEditTextNotes.text.toString().trim()
)
if (mIsNew) {
mDataHandler.addItem(mItem!!)
} else {
mDataHandler.replaceItem(mItem!!.id, mItem!!)
}
val intent = Intent()
setResult(Activity.RESULT_OK, intent)
supportFinishAfterTransition()
}
override fun handleDeleteAction() {
AlertDialog.Builder(this)
.setTitle(R.string.delete_exam)
.setMessage(R.string.delete_confirmation)
.setPositiveButton(R.string.action_delete) { _, _ ->
mDataHandler.deleteItem(mItem!!.id)
setResult(Activity.RESULT_OK)
finish()
}
.setNegativeButton(R.string.action_cancel, null)
.show()
}
}
| apache-2.0 |
ankidroid/Anki-Android | AnkiDroid/src/test/java/com/ichi2/anki/dialogs/utils/HelpDialogTest.kt | 1 | 3468 | /*
* Copyright (c) 2020 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.dialogs.utils
import android.annotation.SuppressLint
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.ichi2.anki.AnkiDroidApp
import com.ichi2.anki.RobolectricTest
import com.ichi2.anki.RunInBackground
import com.ichi2.anki.dialogs.HelpDialog.createInstance
import com.ichi2.anki.dialogs.HelpDialog.createInstanceForSupportAnkiDroid
import com.ichi2.anki.dialogs.RecursivePictureMenu
import com.ichi2.anki.dialogs.utils.RecursivePictureMenuUtil.Companion.getRecyclerViewFor
import com.ichi2.utils.IntentUtil
import io.mockk.every
import io.mockk.mockkStatic
import io.mockk.unmockkStatic
import org.hamcrest.MatcherAssert
import org.hamcrest.Matchers
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class HelpDialogTest : RobolectricTest() {
@Test
@RunInBackground
fun testMenuDoesNotCrash() {
val dialog = createInstance() as RecursivePictureMenu
openDialogFragment(dialog)
val v = getRecyclerViewFor(dialog)
MatcherAssert.assertThat(v.adapter!!.itemCount, Matchers.equalTo(4))
}
@Test
@RunInBackground
fun testMenuSupportAnkiDroidDoesNotCrash() {
val dialog = createInstanceForSupportAnkiDroid(targetContext) as RecursivePictureMenu
openDialogFragment(dialog)
val v = getRecyclerViewFor(dialog)
// to make the test more flexible, calculate the expected menu items count by actually
// checking what intents are available on the test environment
val expectedCount = if (IntentUtil.canOpenIntent(targetContext, AnkiDroidApp.getMarketIntent(targetContext))) {
6 // +1 because the "Rate" menu item should be shown as Play Store app is available on the system
} else {
5 // the default value for support dialog menu items count
}
MatcherAssert.assertThat(v.adapter!!.itemCount, Matchers.equalTo(expectedCount))
}
@Test
@RunInBackground
fun testMenuSupportAnkiDroidShowsRateWhenPossible() {
mockkStatic(IntentUtil::canOpenIntent)
every { IntentUtil.canOpenIntent(targetContext, any()) } returns true
val dialog = createInstanceForSupportAnkiDroid(targetContext) as RecursivePictureMenu
openDialogFragment(dialog)
val v = getRecyclerViewFor(dialog)
// 6 because the option to rate the app is possible on the device
MatcherAssert.assertThat(v.adapter!!.itemCount, Matchers.equalTo(6))
unmockkStatic(IntentUtil::canOpenIntent)
}
@SuppressLint("CheckResult") // openDialogFragmentUsingActivity
private fun openDialogFragment(dialog: RecursivePictureMenu) {
super.openDialogFragmentUsingActivity(dialog)
}
}
| gpl-3.0 |
tipsy/javalin | javalin/src/main/java/io/javalin/plugin/rendering/template/JavalinJte.kt | 1 | 1777 | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin.plugin.rendering.template
import gg.jte.ContentType
import gg.jte.TemplateEngine
import gg.jte.output.StringOutput
import gg.jte.resolve.DirectoryCodeResolver
import io.javalin.core.util.OptionalDependency
import io.javalin.core.util.Util
import io.javalin.http.Context
import io.javalin.http.util.ContextUtil.isLocalhost
import io.javalin.plugin.rendering.FileRenderer
import java.io.File
object JavalinJte : FileRenderer {
private var isDev: Boolean? = null // cached and easily accessible, is set on first request (can't be configured directly by end user)
@JvmField
var isDevFunction: (Context) -> Boolean = { it.isLocalhost() } // used to set isDev, will be called once
private var templateEngine: TemplateEngine? = null
private val defaultTemplateEngine: TemplateEngine by lazy { defaultJteEngine() }
@JvmStatic
fun configure(staticTemplateEngine: TemplateEngine) {
templateEngine = staticTemplateEngine
}
override fun render(filePath: String, model: Map<String, Any?>, ctx: Context): String {
Util.ensureDependencyPresent(OptionalDependency.JTE)
isDev = isDev ?: isDevFunction(ctx)
if (isDev == true && filePath.endsWith(".kte")) {
Util.ensureDependencyPresent(OptionalDependency.JTE_KOTLIN)
}
val stringOutput = StringOutput()
(templateEngine ?: defaultTemplateEngine).render(filePath, model, stringOutput)
return stringOutput.toString()
}
private fun defaultJteEngine() = TemplateEngine.create(DirectoryCodeResolver(File("src/main/jte").toPath()), ContentType.Html)
}
| apache-2.0 |
pdvrieze/ProcessManager | java-common/src/commonMain/kotlin/net/devrieze/util/security/SecurityProvider.kt | 1 | 5071 | /*
* 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 net.devrieze.util.security
import nl.adaptivity.util.security.Principal
interface SecurityProvider {
/**
* Simple marker interface to represent a permission.
*/
interface Permission// marker interface
/**
* The result of a permission request. A separate type to encourage permanent permissions.
*/
enum class PermissionResult {
/**
* Permission has been granted.
*/
GRANTED,
/**
* The user does not have permission for this operation.
*/
DENIED,
/**
* There is no authenticated user.
*/
UNAUTHENTICATED
}
/**
* Ensure that the user has the given permission.
*
* @param permission The permission to verify.
* @param subject The user to check the permission against.
* @throws PermissionDeniedException Thrown if the permission is denied.
* @throws AuthenticationNeededException Thrown if the user has no permission.
* @return The result. This should always be [PermissionResult.GRANTED].
*/
fun ensurePermission(permission: Permission, subject: Principal?): PermissionResult
/**
* Ensure that the user has the given permission in relation to another user.
*
* @param permission The permission to verify.
* @param subject The user to check the permission against.
* @param objectPrincipal The principal that represents other part of the equation.
* @throws PermissionDeniedException Thrown if the permission is denied.
* @throws AuthenticationNeededException Thrown if the user has no permission.
* @return The result. This should always be [PermissionResult.GRANTED].
*/
fun ensurePermission(permission: Permission, subject: Principal?, objectPrincipal: Principal): PermissionResult
/**
* Ensure that the user has the given permission in relation to a given
* object.
*
* @param permission The permission to verify.
* @param subject The user to verify the permission for.
* @param secureObject The object the permission applies to
* @throws PermissionDeniedException Thrown if the permission is denied.
* @throws AuthenticationNeededException Thrown if the user has no permission.
* @return The result. This should always be [PermissionResult.GRANTED].
*/
fun ensurePermission(permission: Permission, subject: Principal?, secureObject: SecureObject<*>): PermissionResult
/**
* Determine whether the user has the permission given
*
* @param permission The permission to check
* @param subject The user
* @param secureObject The object of the activity
* @return `true` if the user has the permission,
* `false` if not.
*/
fun hasPermission(permission: Permission, subject: Principal, secureObject: SecureObject<*>): Boolean
fun getPermission(permission: Permission, subject: Principal?, secureObject: SecureObject<*>): PermissionResult
/**
* Determine whether the user has the given permission.
*
* @param permission The permission to verify.
* @param subject The user to check the permission against.
* @return `true` if the user has the permission,
* `false` if not.
*/
fun hasPermission(permission: Permission, subject: Principal): Boolean
fun getPermission(permission: Permission, subject: Principal?): PermissionResult
/**
* Determine whether the user has the given permission in relation to another
* user.
*
* @param permission The permission to verify.
* @param subject The user to check the permission against.
* @param objectPrincipal The principal that represents other part of the equation.
* @return `true` if the user has the permission,
* `false` if not.
*/
fun hasPermission(permission: Permission, subject: Principal, objectPrincipal: Principal): Boolean
fun getPermission(permission: Permission, subject: Principal?, objectPrincipal: Principal): PermissionResult
companion object {
/**
* Special principal that represents the system.
*/
@Deprecated("", ReplaceWith("net.devrieze.util.security.SYSTEMPRINCIPAL", "net.devrieze.util.security.SYSTEMPRINCIPAL"))
val SYSTEMPRINCIPAL: RolePrincipal = net.devrieze.util.security.SYSTEMPRINCIPAL
}
}
| lgpl-3.0 |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/charging_station_operator/AddChargingStationOperator.kt | 1 | 1166 | package de.westnordost.streetcomplete.quests.charging_station_operator
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CAR
class AddChargingStationOperator : OsmFilterQuestType<String>() {
override val elementFilter = """
nodes, ways with
amenity = charging_station
and !operator and !name and !brand
"""
override val commitMessage = "Add charging station operator"
override val wikiLink = "Tag:amenity=charging_station"
override val icon = R.drawable.ic_quest_car_charger
override val isDeleteElementEnabled = true
override val questTypeAchievements = listOf(CAR)
override fun getTitle(tags: Map<String, String>): Int = R.string.quest_charging_station_operator_title
override fun createForm() = AddChargingStationOperatorForm()
override fun applyAnswerTo(answer: String, changes: StringMapChangesBuilder) {
changes.add("operator", answer)
}
}
| gpl-3.0 |
naosim/rtmjava | src/test/java/com/naosim/someapp/infra/datasource/TaskRepositoryOnMemoryTest.kt | 1 | 3161 | package com.naosim.someapp.infra.datasource
import com.naosim.someapp.domain.*
import junit.framework.TestCase
import org.junit.Ignore
import org.junit.Test
import java.time.LocalDate
import java.time.LocalDateTime
class タスクRepositoryOnMemoryTest(name: String?) : TestCase(name) {
lateinit var sut: タスクRepository
override fun setUp() {
super.setUp()
sut = タスクRepositoryOnMemory();
}
@Test
fun test() {
val listBefore = sut.すべてのタスク取得()
assertEquals("初期状態", 0, listBefore.size)
sut.追加(タスク名("hoge"), タスク消化予定日NotExist())
val listAfter = sut.すべてのタスク取得()
assertEquals("タスク追加", 1, listAfter.size)
assertEquals("リストはイミュータブル", 0, listBefore.size)
val タスクEntity = listAfter.get(0)
val タスクID = タスクEntity.タスクID
assertEquals("追加したタスク名", "hoge", タスクEntity.タスク名.value)
val リネームされたタスクEntity = タスクEntity.タスク更新.リネーム(タスク名("foo"))
assertEquals("変更したタスク名", "foo", リネームされたタスクEntity.タスク名.value)
assertEquals("タスクEntityはイミュータブル", "hoge", タスクEntity.タスク名.value)
assertEquals("リポジトリから再取得しても名前が変わってる", "foo", sut.すべてのタスク取得().get(0).タスク名.value)
assertEquals("タスク状態変更前", タスク状態.BACKLOG, sut.すべてのタスク取得().get(0).タスク状態(LocalDateTime.now()))
リネームされたタスクEntity.タスク更新.タスクDONE()
assertEquals("タスク状態変更後", タスク状態.DONE, sut.すべてのタスク取得().get(0).タスク状態(LocalDateTime.now()))
}
@Test
fun testentity() {
assertEquals("初期状態", 0, sut.すべてのタスク取得().size)
sut.追加(タスク名("hoge"), タスク消化予定日NotExist())
assertEquals("タスク状態変更前", タスク状態.BACKLOG, findEntity().タスク状態(LocalDateTime.now()))
findEntity().タスク更新.タスク消化予定日変更(タスク消化予定日(LocalDate.now().plusDays(1)))
assertEquals("明日開始の場合", タスク状態.TODO, findEntity().タスク状態(LocalDateTime.now()))
assertEquals("既に開始日を過ぎている", タスク状態.DOING, findEntity().タスク状態(LocalDateTime.now().plusDays(1)))
findEntity().タスク更新.タスクDONE()
assertEquals("まだDOING", タスク状態.DOING, findEntity().タスク状態(LocalDateTime.now().minusDays(1)))
assertEquals("DONE", タスク状態.DONE, findEntity().タスク状態(LocalDateTime.now().plusDays(1)))
}
@Test
fun testdate() {
assertEquals("2016-01-02", タスク消化予定日(LocalDate.of(2016, 1, 2)).format)
}
fun findEntity(): タスクEntity {
return sut.すべてのタスク取得().get(0)
}
} | mit |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/registry/type/block/BlockEntityTypeRegistry.kt | 1 | 1766 | /*
* 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.registry.type.block
import org.lanternpowered.api.key.minecraftKey
import org.lanternpowered.api.registry.catalogTypeRegistry
import org.lanternpowered.server.block.entity.BlockEntityCreationData
import org.lanternpowered.server.block.entity.LanternBlockEntityType
import org.lanternpowered.server.block.entity.vanilla.LanternBanner
import org.lanternpowered.server.block.entity.vanilla.LanternChest
import org.lanternpowered.server.block.entity.vanilla.LanternEnderChest
import org.lanternpowered.server.block.entity.vanilla.LanternFurnace
import org.lanternpowered.server.block.entity.vanilla.LanternJukebox
import org.lanternpowered.server.block.entity.vanilla.LanternShulkerBox
import org.lanternpowered.server.block.entity.vanilla.LanternSign
import org.spongepowered.api.block.entity.BlockEntity
import org.spongepowered.api.block.entity.BlockEntityType
val BlockEntityTypeRegistry = catalogTypeRegistry<BlockEntityType> {
fun <T : BlockEntity> register(id: String, supplier: (creationData: BlockEntityCreationData) -> T) =
register(LanternBlockEntityType(minecraftKey(id), supplier))
register("banner", ::LanternBanner)
register("chest", ::LanternChest)
register("ender_chest", ::LanternEnderChest)
register("furnace", ::LanternFurnace)
register("jukebox", ::LanternJukebox)
register("shulker_box", ::LanternShulkerBox)
register("sign", ::LanternSign)
}
| mit |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/api/util/option/OptionMaps.kt | 1 | 1721 | /*
* 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>.
*/
@file:Suppress("UNCHECKED_CAST")
package org.lanternpowered.api.util.option
import org.lanternpowered.api.util.collections.toImmutableMap
import org.lanternpowered.api.util.collections.toImmutableSet
/**
* Base class for all the [OptionMap]s.
*/
abstract class OptionMapBase<T : OptionMapType> internal constructor(val map: MutableMap<Option<T, Any?>, Any?>) : OptionMap<T> {
override fun options(): Collection<Option<T, *>> = this.map.keys.toImmutableSet()
override operator fun <V> get(option: Option<T, V>): V {
return (this.map[option as Option<T, Any?>] ?: option.defaultValue) as V
}
override operator fun contains(option: Option<T, *>): Boolean = (option as Option<T, Any?>) in this.map
}
/**
* A unmodifiable [OptionMap].
*/
internal class UnmodifiableOptionMap<T : OptionMapType>(map: MutableMap<Option<T, Any?>, Any?>) : OptionMapBase<T>(map)
/**
* A [HashMap] backed implementation of the [OptionMap].
*
* @param T The option map type
*/
class OptionHashMap<T : OptionMapType> : OptionMapBase<T>(HashMap()), MutableOptionMap<T> {
override fun asUnmodifiable(): OptionMap<T> = UnmodifiableOptionMap(this.map)
override fun toImmutable(): OptionMap<T> = UnmodifiableOptionMap(this.map.toImmutableMap())
override operator fun <V> set(option: Option<T, V>, value: V) {
this.map[option as Option<T, Any?>] = value as Any?
}
}
| mit |
mercadopago/px-android | px-checkout/src/main/java/com/mercadopago/android/px/tracking/internal/events/CongratsDeepLink.kt | 1 | 650 | package com.mercadopago.android.px.tracking.internal.events
import com.mercadopago.android.px.tracking.internal.TrackFactory
import com.mercadopago.android.px.tracking.internal.TrackWrapper
abstract class CongratsDeepLink : TrackWrapper() {
protected abstract val congratsType: String
protected abstract val deepLinkType: DeepLinkType
protected abstract val deepLink: String
private fun getPath() = "$BASE_PATH/result/$congratsType/deep_link"
private fun getData() = mutableMapOf("type" to deepLinkType.type, "deep_link" to deepLink)
override fun getTrack() = TrackFactory.withEvent(getPath()).addData(getData()).build()
} | mit |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/inspections/latex/redundancy/LatexRedundantParInspection.kt | 1 | 1423 | package nl.hannahsten.texifyidea.inspections.latex.redundancy
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import nl.hannahsten.texifyidea.inspections.TexifyRegexInspection
import nl.hannahsten.texifyidea.psi.LatexTypes
import nl.hannahsten.texifyidea.util.toTextRange
import java.util.regex.Matcher
import java.util.regex.Pattern
/**
* @author Hannah Schellekens
*/
open class LatexRedundantParInspection : TexifyRegexInspection(
inspectionDisplayName = "Redundant use of \\par",
inspectionId = "RedundantPar",
errorMessage = { "Use of \\par is redundant here" },
pattern = Pattern.compile("((\\s*\\n\\s*\\n\\s*(\\\\par))|(\\n\\s*(\\\\par)\\s*\\n)|((\\\\par)\\s*\\n\\s*\\n))"),
replacement = { _, _ -> "" },
replacementRange = this::parRange,
quickFixName = { "Remove \\par" },
highlightRange = { parRange(it).toTextRange() }
) {
companion object {
fun parRange(it: Matcher) = when {
it.group(3) != null -> it.groupRange(3)
it.group(5) != null -> it.groupRange(5)
else -> it.groupRange(7)
}
}
override fun checkContext(matcher: Matcher, element: PsiElement): Boolean {
val elt = element.containingFile.findElementAt(matcher.end()) as? LeafPsiElement
return super.checkContext(matcher, element) && elt?.elementType != LatexTypes.COMMAND_TOKEN ?: true
}
} | mit |
RoverPlatform/rover-android | experiences/src/main/kotlin/io/rover/sdk/experiences/ui/blocks/poll/VotingService.kt | 1 | 2760 | package io.rover.sdk.experiences.ui.blocks.poll
import android.net.Uri
import io.rover.sdk.core.data.NetworkResult
import io.rover.sdk.core.data.http.AndroidHttpsUrlConnectionNetworkClient
import io.rover.sdk.core.data.http.HttpClientResponse
import io.rover.sdk.core.data.http.HttpRequest
import io.rover.sdk.core.data.http.HttpVerb
import io.rover.sdk.core.streams.map
import io.rover.sdk.experiences.data.http.HttpResultMapper
import io.rover.sdk.experiences.logging.log
import org.json.JSONObject
import org.reactivestreams.Publisher
import java.net.URL
internal class VotingService(
private val endpoint: String,
private val httpClient: AndroidHttpsUrlConnectionNetworkClient,
private val httpResultMapper: HttpResultMapper = HttpResultMapper(),
private val urlBuilder: URLBuilder = URLBuilder()
) {
fun fetchResults(pollId: String, optionIds: List<String>): Publisher<NetworkResult<OptionResults>> {
val url = urlBuilder.build(endpoint, listOf(pollId), optionIds.map { "options" to it })
val urlRequest = HttpRequest(url, hashMapOf(), HttpVerb.GET)
return httpClient.request(urlRequest, null).map { httpClientResponse ->
httpResultMapper.mapResultWithBody(httpClientResponse) {
OptionResults.decodeJson(JSONObject(it))
}
}
}
fun castVote(pollId: String, optionId: String, jsonObject: JSONObject = JSONObject()): Publisher<VoteOutcome> {
val url = urlBuilder.build(endpoint, listOf(pollId, "vote"))
val urlRequest = HttpRequest(url, hashMapOf("Content-Type" to "application/json"), HttpVerb.POST)
val body = jsonObject.apply {
put("option", optionId)
}.toString()
return httpClient.request(urlRequest, body, false).map {
when (it) {
is HttpClientResponse.Success -> {
log.v("vote in poll $pollId with option $optionId succeeded")
VoteOutcome.VoteSuccess
}
is HttpClientResponse.ApplicationError, is HttpClientResponse.ConnectionFailure -> {
log.w("voting failed $it")
VoteOutcome.VoteFailure
}
}
}
}
}
internal sealed class VoteOutcome {
object VoteSuccess: VoteOutcome()
object VoteFailure: VoteOutcome()
}
internal class URLBuilder {
fun build(url: String, pathParams: List<String>? = null, queryParams: List<Pair<String, String>>? = null): URL {
val uri = Uri.parse(url).buildUpon().apply {
pathParams?.forEach { appendPath(it) }
queryParams?.forEach { appendQueryParameter(it.first, it.second) }
}.toString()
return URL(uri)
}
}
| apache-2.0 |
GuiyeC/Aerlink-for-Android | wear/src/main/java/com/codegy/aerlink/ui/AerlinkActivity.kt | 1 | 3329 | package com.codegy.aerlink.ui
import android.util.Log
import android.view.View
import com.codegy.aerlink.R
import com.codegy.aerlink.connection.ConnectionState
import kotlinx.android.synthetic.main.merge_connection_info.*
import kotlinx.android.synthetic.main.merge_error.*
import kotlinx.android.synthetic.main.merge_loading.*
abstract class AerlinkActivity : ServiceActivity() {
override fun updateInterfaceForState(state: ConnectionState) {
Log.d(LOG_TAG, "updateInterfaceForState :: state: $state")
val connectionInfoView = connectionInfoView ?: return
val connectionInfoTextView = connectionInfoTextView ?: return
runOnUiThread {
if (state == ConnectionState.Ready) {
connectionInfoView.visibility = View.GONE
return@runOnUiThread
}
connectionInfoView.visibility = View.VISIBLE
when (state) {
ConnectionState.Ready -> {}
ConnectionState.Connecting -> {
connectionInfoTextView.setTextColor(getColor(R.color.connection_state_connecting))
connectionInfoTextView.text = getString(R.string.connection_state_connecting)
connectionInfoHelpTextView?.text = getString(R.string.connection_state_disconnected_help)
}
ConnectionState.Bonding -> {
connectionInfoTextView.setTextColor(getColor(R.color.connection_state_bonding))
connectionInfoTextView.text = getString(R.string.connection_state_bonding)
connectionInfoHelpTextView?.text = getString(R.string.connection_state_disconnected_help)
}
ConnectionState.Disconnected -> {
connectionInfoTextView.setTextColor(getColor(R.color.connection_state_disconnected))
connectionInfoTextView.text = getString(R.string.connection_state_disconnected)
connectionInfoHelpTextView?.text = getString(R.string.connection_state_disconnected_help)
}
ConnectionState.Stopped -> {
connectionInfoTextView.setTextColor(getColor(R.color.connection_state_stopped))
connectionInfoTextView.text = getString(R.string.connection_state_stopped)
connectionInfoHelpTextView?.text = getString(R.string.connection_state_stopped_help)
}
}
}
}
fun showLoading(visible: Boolean) {
Log.d(LOG_TAG, "showLoading :: Visible: $visible")
val loadingView = loadingView ?: return
if (visible && loadingView.visibility == View.VISIBLE
|| !visible && loadingView.visibility == View.GONE) {
return
}
runOnUiThread {
loadingView.visibility = if (visible) View.VISIBLE else View.GONE
}
}
fun showError(visible: Boolean) {
Log.d(LOG_TAG, "showError :: Visible: $visible")
runOnUiThread {
errorView?.visibility = if (visible) View.VISIBLE else View.GONE
}
}
fun restartConnectionAction(view: View) {
stopService()
startService()
}
companion object {
private val LOG_TAG: String = AerlinkActivity::class.java.simpleName
}
} | mit |
googlesamples/mlkit | android/material-showcase/app/src/main/java/com/google/mlkit/md/InputInfo.kt | 1 | 1373 | /*
* 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.google.mlkit.md
import android.graphics.Bitmap
import com.google.mlkit.md.camera.FrameMetadata
import java.nio.ByteBuffer
interface InputInfo {
fun getBitmap(): Bitmap
}
class CameraInputInfo(
private val frameByteBuffer: ByteBuffer,
private val frameMetadata: FrameMetadata
) : InputInfo {
private var bitmap: Bitmap? = null
@Synchronized
override fun getBitmap(): Bitmap {
return bitmap ?: let {
bitmap = Utils.convertToBitmap(
frameByteBuffer, frameMetadata.width, frameMetadata.height, frameMetadata.rotation
)
bitmap!!
}
}
}
class BitmapInputInfo(private val bitmap: Bitmap) : InputInfo {
override fun getBitmap(): Bitmap {
return bitmap
}
}
| apache-2.0 |
AoEiuV020/PaNovel | baseJar/src/main/java/cc/aoeiuv020/base/jar/url.kt | 1 | 295 | package cc.aoeiuv020.base.jar
import java.net.MalformedURLException
import java.net.URL
/**
* Created by AoEiuV020 on 2018.09.09-02:39:00.
*/
/**
* 地址仅路径,斜杆/开头,
*/
fun path(url: String): String = try {
URL(url).path
} catch (e: MalformedURLException) {
url
}
| gpl-3.0 |
tasks/tasks | app/src/main/java/org/tasks/etebase/AddEtebaseAccountViewModel.kt | 1 | 551 | package org.tasks.etebase
import dagger.hilt.android.lifecycle.HiltViewModel
import org.tasks.ui.CompletableViewModel
import javax.inject.Inject
@HiltViewModel
class AddEtebaseAccountViewModel @Inject constructor(
private val clientProvider: EtebaseClientProvider): CompletableViewModel<String>() {
suspend fun addAccount(url: String, username: String, password: String) {
run {
clientProvider
.forUrl(url, username, password, foreground = true)
.getSession()
}
}
} | gpl-3.0 |
ken-kentan/student-portal-plus | app/src/main/java/jp/kentan/studentportalplus/StudentPortalPlus.kt | 1 | 1281 | package jp.kentan.studentportalplus
import androidx.appcompat.app.AppCompatDelegate
import dagger.android.AndroidInjector
import dagger.android.support.AndroidSupportInjectionModule
import dagger.android.support.DaggerApplication
import jp.kentan.studentportalplus.di.ActivityModule
import jp.kentan.studentportalplus.di.AppModule
import jp.kentan.studentportalplus.di.FragmentModule
import jp.kentan.studentportalplus.notification.SyncWorker
import javax.inject.Singleton
class StudentPortalPlus : DaggerApplication() {
val component: StudentPortalPlus.Component by lazy(LazyThreadSafetyMode.NONE) {
DaggerStudentPortalPlus_Component.builder()
.appModule(AppModule(this))
.build()
}
override fun onCreate() {
super.onCreate()
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
}
override fun applicationInjector(): AndroidInjector<StudentPortalPlus> {
return component
}
@Singleton
@dagger.Component(modules = [
(AndroidSupportInjectionModule::class),
(AppModule::class),
(ActivityModule::class),
(FragmentModule::class)])
interface Component : AndroidInjector<StudentPortalPlus> {
fun inject(syncWorker: SyncWorker)
}
} | gpl-3.0 |
NextFaze/dev-fun | devfun-annotations/src/main/java/com/nextfaze/devfun/function/DeveloperArguments.kt | 1 | 7031 | package com.nextfaze.devfun.function
import com.nextfaze.devfun.DeveloperAnnotation
import com.nextfaze.devfun.category.DeveloperCategory
import com.nextfaze.devfun.category.DeveloperCategoryProperties
import kotlin.annotation.AnnotationRetention.SOURCE
import kotlin.annotation.AnnotationTarget.FUNCTION
import kotlin.reflect.KClass
/**
* A function transformer that tells DevFun how to generate functions for annotation-defined arguments.
*
* @see DeveloperArguments
*/
interface ArgumentsTransformer : FunctionTransformer
/**
* An alternative to [DeveloperFunction] that allows you to provide arguments for multiple invocations.
*
* _Note: This annotation is *[SOURCE]* retained - its contents will not be kept in your binary!_
*
* For an example usage, see demo [AuthenticateFragment.signInAs](https://github.com/NextFaze/dev-fun/tree/master/demo/src/main/java/com/nextfaze/devfun/demo/AuthenticateScreen.kt#L200)
*
*
* # Args Format
* Each element in the args will be converted to the appropriate type from the string provided based on the function's parameter types.
* i.e. "1.0f" -> Float
*
* ```kotlin
* @DeveloperArguments(
* args = [Args(["A string", "1.0f"])]
* )
* fun myFunction(str: String, float: Float) = Unit
* ```
* If the second parameter was a string then it would remain a string `"1.0f"` etc.
*
*
* # Supported Types
* At present only simple types and strings are supported simply because I haven't used anything more - you're welcome to create an issue
* for other types and it'll likely be supported.
*
* If a type is not supported (or an arg is out of bounds) then DevFun will attempt to inject it as per normal DevFun behaviour.
*
*
* # Arg-index [name] & [group]
* You can use `%d` to reference your args array.
*
* i.e.
* `name = "%2"` -> `name = args[n][2]`
*
* e.g.
* ```kotlin
* @DeveloperArguments(
* name = "The string arg is: '%0'"
* args = [
* Args(["Hello", "1.0f"]), // name = "The string arg is: 'Hello'"
* Args(["World", "-1.0f"]) // name = "The string arg is: 'World'"
* ]
* )
* fun myFunction(str: String, float: Float) = Unit
* ```
*
*
* # Example Usage
* _Taken from demo [AuthenticateFragment.signInAs](https://github.com/NextFaze/dev-fun/tree/master/demo/src/main/java/com/nextfaze/devfun/demo/AuthenticateScreen.kt#L200)_
*
* ```kotlin
* @DeveloperArguments(
* args = [
* Args(["[email protected]", "hello", "Normal"]),
* Args(["[email protected]", "world", "Normal"]),
* Args(["[email protected]", "ContainDateNeck76", "Normal"]),
* Args(["[email protected]", "EveningVermontNeck29", "Normal"]),
* Args(["[email protected]", "OftenJumpCost02", "Normal"]),
* Args(["[email protected]", "TakePlayThought95", "Restricted"]),
* Args(["[email protected]", "DeviceSeedsSeason16", "Restricted"]),
* Args(["[email protected]", "ChinaMisterGeneral11", "Banned"]),
* Args(["[email protected]", "my.password", "Underage"]),
* Args(["[email protected]", "password", "Underage"]),
* Args(["[email protected]", "D3;d<HF-", "Invalid Password"]),
* Args(["[email protected]", "r2Z@fMhA", "Invalid Password"]),
* Args(["[email protected]", "RV[(x43@", "Unknown User"])
* ],
* group = "Authenticate as %2"
* )
* private fun signInAs(email: String, password: String) {
* emailEditText.setText(email)
* passwordEditText.setText(password)
* attemptLogin()
* }
* ```
* - Will result in 13 functions in the Context group when on the authenticate screen.
* - The functions will be grouped by the 3rd element "Authenticate as %2"
*
* Context Menu:
* - Authenticate as Normal
* - [email protected]
* - [email protected]
* - ...
* - Authenticate as Restricted
* - [email protected]
* - ...
*
*
* ## Sensitive Information
* A reminder that `DeveloperArguments` is _SOURCE_ retained - it will not be present in your compiled files.
*
* An alternative to having this annotation at the use-site could be to have the declaration in your Debug sources an invoke it from there.
* ```kotlin
* object MyDebugUtils {
* @DeveloperArguments(...)
* fun signInAs(...) {
* }
* }
* ```
* An alternative would be to have `signInAs` be called from the `Debug` source tree or by some other means
*
*
* # Experimental Feature
* __This annotation is experimental.__
*
* Any and all input is welcome!
*
* @param name The function's name (equivalent to [DeveloperFunction.value]). Defaults to the first element in each args item `%0`. A `null` or blank value falls back [FunctionItem.name].
* @param args A list of [Args], with each item an alternative invocation. Behaviour is as [FunctionItem.args].
* @param group A grouping for the functions - defaults to the function's name. A `null` or blank value falls back to [FunctionItem.group].
* @param requiresApi This is equivalent to [DeveloperFunction.requiresApi].
* @param transformer This is equivalent to [DeveloperFunction.transformer] - _do not change this unless you know what you're doing!_
*
* @see ArgumentsTransformer
* @see DeveloperFunction
*/
@Retention(SOURCE)
@Target(FUNCTION)
@DeveloperAnnotation(developerFunction = true)
annotation class DeveloperArguments(
val name: String = "%0",
val args: Array<Args>,
val group: String = "%FUN_SN%",
val category: DeveloperCategory = DeveloperCategory(),
val requiresApi: Int = 0,
val transformer: KClass<out FunctionTransformer> = ArgumentsTransformer::class
)
/**
* Nested annotation for declaring the arguments of a function invocation.
*
* @param value The arguments of the invocation. At present only primitive types are supported (`.toType()` will be used on the entry).
*
* @see DeveloperArguments
*/
annotation class Args(
val value: Array<String>
)
/** Properties interface for @[Args].
*
* TODO: This interface should be generated by DevFun at compile time, but as the annotations are in a separate module to the compiler
* that itself depends on the annotations module, it is non-trivial to run the DevFun processor upon it (module dependencies become cyclic).
*/
interface ArgsProperties {
val value: Array<String>
}
/**
* Properties interface for @[DeveloperArguments].
*
* TODO: This interface should be generated by DevFun at compile time, but as the annotations are in a separate module to the compiler
* that itself depends on the annotations module, it is non-trivial to run the DevFun processor upon it (module dependencies become cyclic).
*/
interface DeveloperArgumentsProperties {
val name: String get() = "%0"
val args: Array<ArgsProperties>
val group: String get() = "%FUN_SN%"
val category: DeveloperCategoryProperties get() = object : DeveloperCategoryProperties {}
val requiresApi: Int get() = 0
val transformer: KClass<out FunctionTransformer> get() = ArgumentsTransformer::class
}
| apache-2.0 |
soniccat/android-taskmanager | service/src/main/java/tools/RxTools.kt | 1 | 213 | package tools
import io.reactivex.Single
object RxTools {
fun <T> justOrError(item: T?): Single<T> {
return if (item != null) Single.just(item) else Single.error(Error("RxTools: Empty item"))
}
} | mit |
pgutkowski/KGraphQL | src/test/kotlin/com/github/pgutkowski/kgraphql/specification/introspection/DocumentationSpecificationTest.kt | 1 | 4420 | package com.github.pgutkowski.kgraphql.specification.introspection
import com.github.pgutkowski.kgraphql.defaultSchema
import com.github.pgutkowski.kgraphql.deserialize
import com.github.pgutkowski.kgraphql.extract
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
class DocumentationSpecificationTest {
@Test
fun `queries may be documented`(){
val expected = "sample query"
val schema = defaultSchema {
query("sample"){
description = expected
resolver<String> {"SAMPLE"}
}
}
val response = deserialize(schema.execute("{__schema{queryType{fields{name, description}}}}"))
assertThat(response.extract("data/__schema/queryType/fields[0]/description"), equalTo(expected))
}
@Test
fun `mutations may be documented`(){
val expected = "sample mutation"
val schema = defaultSchema {
mutation("sample"){
description = expected
resolver<String> {"SAMPLE"}
}
}
val response = deserialize(schema.execute("{__schema{mutationType{fields{name, description}}}}"))
assertThat(response.extract("data/__schema/mutationType/fields[0]/description"), equalTo(expected))
}
data class Sample(val content : String)
@Test
fun `object type may be documented`(){
val expected = "sample type"
val schema = defaultSchema {
query("sample"){
resolver<Sample>{ Sample("SAMPLE") }
}
type<Sample>{
description = expected
}
}
val response = deserialize(schema.execute("{__type(name: \"Sample\"){description}}"))
assertThat(response.extract("data/__type/description/"), equalTo(expected))
}
@Test
fun `input type may be documented`(){
val expected = "sample type"
val schema = defaultSchema {
query("sample"){
resolver<String> {"SAMPLE"}
}
inputType<Sample>{
description = expected
}
}
val response = deserialize(schema.execute("{__type(name: \"Sample\"){description}}"))
assertThat(response.extract("data/__type/description/"), equalTo(expected))
}
@Test
fun `kotlin field may be documented`(){
val expected = "sample type"
val schema = defaultSchema {
query("sample"){
resolver<String> {"SAMPLE"}
}
type<Sample>{
Sample::content.configure {
description = expected
}
}
}
val response = deserialize(schema.execute("{__type(name: \"Sample\"){fields{description}}}"))
assertThat(response.extract("data/__type/fields[0]/description/"), equalTo(expected))
}
@Test
fun `extension field may be documented`(){
val expected = "sample type"
val schema = defaultSchema {
query("sample"){
resolver<String> {"SAMPLE"}
}
type<Sample>{
property<String>("add"){
description = expected
resolver{ (content) -> content.toUpperCase() }
}
}
}
val response = deserialize(schema.execute("{__type(name: \"Sample\"){fields{name, description}}}"))
assertThat(response.extract("data/__type/fields[1]/name/"), equalTo("add"))
assertThat(response.extract("data/__type/fields[1]/description/"), equalTo(expected))
}
enum class SampleEnum { ONE, TWO, THREE }
@Test
fun `enum value may be documented`(){
val expected = "some enum value"
val schema = defaultSchema {
query("sample"){
resolver<String> {"SAMPLE"}
}
enum<SampleEnum> {
value(SampleEnum.ONE){
description = expected
}
}
}
val response = deserialize(schema.execute("{__type(name: \"SampleEnum\"){enumValues{name, description}}}"))
assertThat(response.extract("data/__type/enumValues[0]/name"), equalTo(SampleEnum.ONE.name))
assertThat(response.extract("data/__type/enumValues[0]/description"), equalTo(expected))
}
} | mit |
yinpeng/kotlin-matrix | src/main/kotlin/com/ichipsea/kotlin/matrix/NumberMatrix.kt | 1 | 1428 | package com.ichipsea.kotlin.matrix
operator fun <M: Number, N: Number> Matrix<M>.plus(other: Matrix<N>): Matrix<Double> {
if (rows !== other.rows || cols !== other.cols)
throw IllegalArgumentException("Matrices not match")
return mapIndexed { x, y, value -> value.toDouble() + other[x, y].toDouble() }
}
operator fun <N: Number> Matrix<N>.unaryMinus(): Matrix<Double> {
return map { -it.toDouble() }
}
operator fun <M: Number, N: Number> Matrix<M>.minus(other: Matrix<N>): Matrix<Double> {
return this + (-other)
}
operator fun <M: Number, N: Number> Matrix<M>.times(other: Matrix<N>): Matrix<Double> {
if (rows !== other.rows || cols !== other.cols)
throw IllegalArgumentException("Matrices not match")
return mapIndexed { x, y, value -> value.toDouble() * other[x, y].toDouble() }
}
operator fun <M: Number> Matrix<M>.times(other: Number): Matrix<Double> {
return map { it.toDouble() * other.toDouble() }
}
operator fun <M: Number> Number.times(other: Matrix<M>): Matrix<Double> {
return other * this
}
infix fun <M: Number, N: Number> Matrix<M>.x(other: Matrix<N>): Matrix<Double> {
if (rows !== other.cols)
throw IllegalArgumentException("Matrices not match")
return createMatrix(cols, other.rows) { x, y ->
var value = .0
for (i in 0..rows-1)
value += this[x, i].toDouble() * other[i, y].toDouble()
value
}
}
| apache-2.0 |
wiltonlazary/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/cgen/CBridgeGen.kt | 1 | 62687 | package org.jetbrains.kotlin.backend.konan.cgen
import org.jetbrains.kotlin.backend.common.ir.addFakeOverrides
import org.jetbrains.kotlin.backend.common.ir.createDispatchReceiverParameter
import org.jetbrains.kotlin.backend.common.ir.createParameterDeclarations
import org.jetbrains.kotlin.backend.common.ir.simpleFunctions
import org.jetbrains.kotlin.backend.common.lower.at
import org.jetbrains.kotlin.backend.common.lower.irNot
import org.jetbrains.kotlin.backend.konan.KonanFqNames
import org.jetbrains.kotlin.backend.konan.PrimitiveBinaryType
import org.jetbrains.kotlin.backend.konan.RuntimeNames
import org.jetbrains.kotlin.backend.konan.descriptors.konanLibrary
import org.jetbrains.kotlin.backend.konan.ir.*
import org.jetbrains.kotlin.backend.konan.isObjCMetaClass
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.UnsignedType
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrClassImpl
import org.jetbrains.kotlin.ir.declarations.impl.IrConstructorImpl
import org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl
import org.jetbrains.kotlin.ir.declarations.impl.IrValueParameterImpl
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.IrConstImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrFunctionReferenceImpl
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.symbols.impl.IrClassSymbolImpl
import org.jetbrains.kotlin.ir.symbols.impl.IrConstructorSymbolImpl
import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl
import org.jetbrains.kotlin.ir.symbols.impl.IrValueParameterSymbolImpl
import org.jetbrains.kotlin.ir.types.*
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.konan.target.Family
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.backend.konan.getObjCMethodInfo
import org.jetbrains.kotlin.backend.konan.lower.FunctionReferenceLowering
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.ir.descriptors.*
import org.jetbrains.kotlin.konan.ForeignExceptionMode
internal interface KotlinStubs {
val irBuiltIns: IrBuiltIns
val symbols: KonanSymbols
val target: KonanTarget
fun addKotlin(declaration: IrDeclaration)
fun addC(lines: List<String>)
fun getUniqueCName(prefix: String): String
fun getUniqueKotlinFunctionReferenceClassName(prefix: String): String
fun reportError(location: IrElement, message: String): Nothing
fun throwCompilerError(element: IrElement?, message: String): Nothing
}
private class KotlinToCCallBuilder(
val irBuilder: IrBuilderWithScope,
val stubs: KotlinStubs,
val isObjCMethod: Boolean,
foreignExceptionMode: ForeignExceptionMode.Mode
) {
val cBridgeName = stubs.getUniqueCName("knbridge")
val symbols: KonanSymbols get() = stubs.symbols
val bridgeCallBuilder = KotlinCallBuilder(irBuilder, symbols)
val bridgeBuilder = KotlinCBridgeBuilder(irBuilder.startOffset, irBuilder.endOffset, cBridgeName, stubs, isKotlinToC = true, foreignExceptionMode)
val cBridgeBodyLines = mutableListOf<String>()
val cCallBuilder = CCallBuilder()
val cFunctionBuilder = CFunctionBuilder()
}
private fun KotlinToCCallBuilder.passThroughBridge(argument: IrExpression, kotlinType: IrType, cType: CType): CVariable {
bridgeCallBuilder.arguments += argument
return bridgeBuilder.addParameter(kotlinType, cType).second
}
private fun KotlinToCCallBuilder.addArgument(
argument: IrExpression,
type: IrType,
variadic: Boolean,
parameter: IrValueParameter?
) {
val argumentPassing = mapCalleeFunctionParameter(type, variadic, parameter, argument)
addArgument(argument, argumentPassing, variadic)
}
private fun KotlinToCCallBuilder.addArgument(
argument: IrExpression,
argumentPassing: KotlinToCArgumentPassing,
variadic: Boolean
) {
val cArgument = with(argumentPassing) { passValue(argument) } ?: return
cCallBuilder.arguments += cArgument.expression
if (!variadic) cFunctionBuilder.addParameter(cArgument.type)
}
private fun KotlinToCCallBuilder.buildKotlinBridgeCall(transformCall: (IrMemberAccessExpression<*>) -> IrExpression = { it }): IrExpression =
bridgeCallBuilder.build(
bridgeBuilder.buildKotlinBridge().also {
this.stubs.addKotlin(it)
},
transformCall
)
internal fun KotlinStubs.generateCCall(expression: IrCall, builder: IrBuilderWithScope, isInvoke: Boolean,
foreignExceptionMode: ForeignExceptionMode.Mode = ForeignExceptionMode.default): IrExpression {
require(expression.dispatchReceiver == null)
val callBuilder = KotlinToCCallBuilder(builder, this, isObjCMethod = false, foreignExceptionMode)
val callee = expression.symbol.owner
// TODO: consider computing all arguments before converting.
val targetPtrParameter: String?
val targetFunctionName: String
if (isInvoke) {
targetPtrParameter = callBuilder.passThroughBridge(
expression.extensionReceiver!!,
symbols.interopCPointer.typeWithStarProjections,
CTypes.voidPtr
).name
targetFunctionName = "targetPtr"
(0 until expression.valueArgumentsCount).forEach {
callBuilder.addArgument(
expression.getValueArgument(it)!!,
type = expression.getTypeArgument(it)!!,
variadic = false,
parameter = null
)
}
} else {
require(expression.extensionReceiver == null)
targetPtrParameter = null
targetFunctionName = this.getUniqueCName("target")
val arguments = (0 until expression.valueArgumentsCount).map {
expression.getValueArgument(it)
}
callBuilder.addArguments(arguments, callee)
}
val returnValuePassing = if (isInvoke) {
val returnType = expression.getTypeArgument(expression.typeArgumentsCount - 1)!!
mapReturnType(returnType, TypeLocation.FunctionCallResult(expression), signature = null)
} else {
mapReturnType(callee.returnType, TypeLocation.FunctionCallResult(expression), signature = callee)
}
val result = callBuilder.buildCall(targetFunctionName, returnValuePassing)
val targetFunctionVariable = CVariable(CTypes.pointer(callBuilder.cFunctionBuilder.getType()), targetFunctionName)
if (isInvoke) {
callBuilder.cBridgeBodyLines.add(0, "$targetFunctionVariable = ${targetPtrParameter!!};")
} else {
val cCallSymbolName = callee.getAnnotationArgumentValue<String>(cCall, "id")!!
this.addC(listOf("extern const $targetFunctionVariable __asm(\"$cCallSymbolName\");")) // Exported from cinterop stubs.
}
callBuilder.emitCBridge()
return result
}
private fun KotlinToCCallBuilder.addArguments(arguments: List<IrExpression?>, callee: IrFunction) {
arguments.forEachIndexed { index, argument ->
val parameter = callee.valueParameters[index]
if (parameter.isVararg) {
require(index == arguments.lastIndex)
addVariadicArguments(argument)
cFunctionBuilder.variadic = true
} else {
addArgument(argument!!, parameter.type, variadic = false, parameter = parameter)
}
}
}
private fun KotlinToCCallBuilder.addVariadicArguments(
argumentForVarargParameter: IrExpression?
) = handleArgumentForVarargParameter(argumentForVarargParameter) { variable, elements ->
if (variable == null) {
unwrapVariadicArguments(elements).forEach {
addArgument(it, it.type, variadic = true, parameter = null)
}
} else {
// See comment in [handleArgumentForVarargParameter].
// Array for this vararg parameter is already computed before the call,
// so query statically known typed arguments from this array.
with(irBuilder) {
val argumentTypes = unwrapVariadicArguments(elements).map { it.type }
argumentTypes.forEachIndexed { index, type ->
val untypedArgument = irCall(symbols.arrayGet[symbols.array]!!.owner).apply {
dispatchReceiver = irGet(variable)
putValueArgument(0, irInt(index))
}
val argument = irAs(untypedArgument, type) // Note: this cast always succeeds.
addArgument(argument, type, variadic = true, parameter = null)
}
}
}
}
private fun KotlinToCCallBuilder.unwrapVariadicArguments(
elements: List<IrVarargElement>
): List<IrExpression> = elements.flatMap {
when (it) {
is IrExpression -> listOf(it)
is IrSpreadElement -> {
val expression = it.expression
if (expression is IrCall && expression.symbol == symbols.arrayOf) {
handleArgumentForVarargParameter(expression.getValueArgument(0)) { _, elements ->
unwrapVariadicArguments(elements)
}
} else {
stubs.reportError(it, "When calling variadic " +
(if (isObjCMethod) "Objective-C methods " else "C functions ") +
"spread operator is supported only for *arrayOf(...)")
}
}
else -> stubs.throwCompilerError(it, "unexpected IrVarargElement")
}
}
private fun <R> KotlinToCCallBuilder.handleArgumentForVarargParameter(
argument: IrExpression?,
block: (variable: IrVariable?, elements: List<IrVarargElement>) -> R
): R = when (argument) {
null -> block(null, emptyList())
is IrVararg -> block(null, argument.elements)
is IrGetValue -> {
/* This is possible when using named arguments with reordering, i.e.
*
* foo(second = *arrayOf(...), first = ...)
*
* psi2ir generates as
*
* val secondTmp = *arrayOf(...)
* val firstTmp = ...
* foo(firstTmp, secondTmp)
*
*
**/
val variable = argument.symbol.owner
if (variable is IrVariable && variable.origin == IrDeclarationOrigin.IR_TEMPORARY_VARIABLE && !variable.isVar) {
val initializer = variable.initializer
if (initializer is IrVararg) {
block(variable, initializer.elements)
} else {
stubs.throwCompilerError(initializer, "unexpected initializer")
}
} else if (variable is IrValueParameter && FunctionReferenceLowering.isLoweredFunctionReference(variable)) {
val location = variable.parent // Parameter itself has incorrect location.
val kind = if (this.isObjCMethod) "Objective-C methods" else "C functions"
stubs.reportError(location, "callable references to variadic $kind are not supported")
} else {
stubs.throwCompilerError(variable, "unexpected value declaration")
}
}
else -> stubs.throwCompilerError(argument, "unexpected vararg")
}
private fun KotlinToCCallBuilder.emitCBridge() {
val cLines = mutableListOf<String>()
cLines += "${bridgeBuilder.buildCSignature(cBridgeName)} {"
cLines += cBridgeBodyLines
cLines += "}"
stubs.addC(cLines)
}
private fun KotlinToCCallBuilder.buildCall(
targetFunctionName: String,
returnValuePassing: ValueReturning
): IrExpression = with(returnValuePassing) {
returnValue(cCallBuilder.build(targetFunctionName))
}
internal sealed class ObjCCallReceiver {
class Regular(val rawPtr: IrExpression) : ObjCCallReceiver()
class Retained(val rawPtr: IrExpression) : ObjCCallReceiver()
}
internal fun KotlinStubs.generateObjCCall(
builder: IrBuilderWithScope,
method: IrSimpleFunction,
isStret: Boolean,
selector: String,
call: IrFunctionAccessExpression,
superQualifier: IrClassSymbol?,
receiver: ObjCCallReceiver,
arguments: List<IrExpression?>
) = builder.irBlock {
val resolved = method.resolveFakeOverride(allowAbstract = true)?: method
val exceptionMode = ForeignExceptionMode.byValue(
resolved.module.konanLibrary?.manifestProperties
?.getProperty(ForeignExceptionMode.manifestKey)
)
val callBuilder = KotlinToCCallBuilder(builder, this@generateObjCCall, isObjCMethod = true, exceptionMode)
val superClass = irTemporaryVar(
superQualifier?.let { getObjCClass(symbols, it) } ?: irNullNativePtr(symbols)
)
val messenger = irCall(if (isStret) {
symbols.interopGetMessengerStret
} else {
symbols.interopGetMessenger
}.owner).apply {
putValueArgument(0, irGet(superClass)) // TODO: check superClass statically.
}
val targetPtrParameter = callBuilder.passThroughBridge(
messenger,
symbols.interopCPointer.typeWithStarProjections,
CTypes.voidPtr
).name
val targetFunctionName = "targetPtr"
val preparedReceiver = if (method.consumesReceiver()) {
when (receiver) {
is ObjCCallReceiver.Regular -> irCall(symbols.interopObjCRetain.owner).apply {
putValueArgument(0, receiver.rawPtr)
}
is ObjCCallReceiver.Retained -> receiver.rawPtr
}
} else {
when (receiver) {
is ObjCCallReceiver.Regular -> receiver.rawPtr
is ObjCCallReceiver.Retained -> {
// Note: shall not happen: Retained is used only for alloc result currently,
// which is used only as receiver for init methods, which are always receiver-consuming.
// Can't even add a test for the code below.
val rawPtrVar = scope.createTemporaryVariable(receiver.rawPtr)
callBuilder.bridgeCallBuilder.prepare += rawPtrVar
callBuilder.bridgeCallBuilder.cleanup += {
irCall(symbols.interopObjCRelease).apply {
putValueArgument(0, irGet(rawPtrVar)) // Balance retained pointer.
}
}
irGet(rawPtrVar)
}
}
}
val receiverOrSuper = if (superQualifier != null) {
irCall(symbols.interopCreateObjCSuperStruct.owner).apply {
putValueArgument(0, preparedReceiver)
putValueArgument(1, irGet(superClass))
}
} else {
preparedReceiver
}
callBuilder.cCallBuilder.arguments += callBuilder.passThroughBridge(
receiverOrSuper, symbols.nativePtrType, CTypes.voidPtr).name
callBuilder.cFunctionBuilder.addParameter(CTypes.voidPtr)
callBuilder.cCallBuilder.arguments += "@selector($selector)"
callBuilder.cFunctionBuilder.addParameter(CTypes.voidPtr)
callBuilder.addArguments(arguments, method)
val returnValuePassing =
mapReturnType(method.returnType, TypeLocation.FunctionCallResult(call), signature = method)
val result = callBuilder.buildCall(targetFunctionName, returnValuePassing)
val targetFunctionVariable = CVariable(CTypes.pointer(callBuilder.cFunctionBuilder.getType()), targetFunctionName)
callBuilder.cBridgeBodyLines.add(0, "$targetFunctionVariable = $targetPtrParameter;")
callBuilder.emitCBridge()
+result
}
internal fun IrBuilderWithScope.getObjCClass(symbols: KonanSymbols, symbol: IrClassSymbol): IrExpression {
val classDescriptor = symbol.descriptor
assert(!classDescriptor.isObjCMetaClass())
return irCall(symbols.interopGetObjCClass, symbols.nativePtrType, listOf(symbol.typeWithStarProjections))
}
private fun IrBuilderWithScope.irNullNativePtr(symbols: KonanSymbols) = irCall(symbols.getNativeNullPtr.owner)
private class CCallbackBuilder(
val stubs: KotlinStubs,
val location: IrElement,
val isObjCMethod: Boolean
) {
val irBuiltIns: IrBuiltIns get() = stubs.irBuiltIns
val symbols: KonanSymbols get() = stubs.symbols
private val cBridgeName = stubs.getUniqueCName("knbridge")
fun buildCBridgeCall(): String = cBridgeCallBuilder.build(cBridgeName)
fun buildCBridge(): String = bridgeBuilder.buildCSignature(cBridgeName)
val bridgeBuilder = KotlinCBridgeBuilder(location.startOffset, location.endOffset, cBridgeName, stubs, isKotlinToC = false)
val kotlinCallBuilder = KotlinCallBuilder(bridgeBuilder.kotlinIrBuilder, symbols)
val kotlinBridgeStatements = mutableListOf<IrStatement>()
val cBridgeCallBuilder = CCallBuilder()
val cBodyLines = mutableListOf<String>()
val cFunctionBuilder = CFunctionBuilder()
}
private fun CCallbackBuilder.passThroughBridge(
cBridgeArgument: String,
cBridgeParameterType: CType,
kotlinBridgeParameterType: IrType
): IrValueParameter {
cBridgeCallBuilder.arguments += cBridgeArgument
return bridgeBuilder.addParameter(kotlinBridgeParameterType, cBridgeParameterType).first
}
private fun CCallbackBuilder.addParameter(it: IrValueParameter, functionParameter: IrValueParameter) {
val typeLocation = if (isObjCMethod) {
TypeLocation.ObjCMethodParameter(it.index, functionParameter)
} else {
TypeLocation.FunctionPointerParameter(cFunctionBuilder.numberOfParameters, location)
}
if (functionParameter.isVararg) {
stubs.reportError(typeLocation.element, if (isObjCMethod) {
"overriding variadic Objective-C methods is not supported"
} else {
"variadic function pointers are not supported"
})
}
val valuePassing = stubs.mapFunctionParameterType(
it.type,
retained = it.isConsumed(),
variadic = false,
location = typeLocation
)
val kotlinArgument = with(valuePassing) { receiveValue() }
kotlinCallBuilder.arguments += kotlinArgument
}
private fun CCallbackBuilder.build(function: IrSimpleFunction, signature: IrSimpleFunction): String {
val typeLocation = if (isObjCMethod) {
TypeLocation.ObjCMethodReturnValue(function)
} else {
TypeLocation.FunctionPointerReturnValue(location)
}
val valueReturning = stubs.mapReturnType(signature.returnType, typeLocation, signature)
buildValueReturn(function, valueReturning)
return buildCFunction()
}
private fun CCallbackBuilder.buildValueReturn(function: IrSimpleFunction, valueReturning: ValueReturning) {
val kotlinCall = kotlinCallBuilder.build(function)
with(valueReturning) {
returnValue(kotlinCall)
}
val kotlinBridge = bridgeBuilder.buildKotlinBridge()
kotlinBridge.body = bridgeBuilder.kotlinIrBuilder.irBlockBody {
kotlinBridgeStatements.forEach { +it }
}
stubs.addKotlin(kotlinBridge)
stubs.addC(listOf("${buildCBridge()};"))
}
private fun CCallbackBuilder.buildCFunction(): String {
val result = stubs.getUniqueCName("kncfun")
val cLines = mutableListOf<String>()
cLines += "${cFunctionBuilder.buildSignature(result)} {"
cLines += cBodyLines
cLines += "}"
stubs.addC(cLines)
return result
}
private fun KotlinStubs.generateCFunction(
function: IrSimpleFunction,
signature: IrSimpleFunction,
isObjCMethod: Boolean,
location: IrElement
): String {
val callbackBuilder = CCallbackBuilder(this, location, isObjCMethod)
if (isObjCMethod) {
val receiver = signature.dispatchReceiverParameter!!
assert(isObjCReferenceType(receiver.type))
val valuePassing = ObjCReferenceValuePassing(symbols, receiver.type, retained = signature.consumesReceiver())
val kotlinArgument = with(valuePassing) { callbackBuilder.receiveValue() }
callbackBuilder.kotlinCallBuilder.arguments += kotlinArgument
// Selector is ignored:
with(TrivialValuePassing(symbols.nativePtrType, CTypes.voidPtr)) { callbackBuilder.receiveValue() }
} else {
require(signature.dispatchReceiverParameter == null)
}
signature.extensionReceiverParameter?.let { callbackBuilder.addParameter(it, function.extensionReceiverParameter!!) }
signature.valueParameters.forEach {
callbackBuilder.addParameter(it, function.valueParameters[it.index])
}
return callbackBuilder.build(function, signature)
}
internal fun KotlinStubs.generateCFunctionPointer(
function: IrSimpleFunction,
signature: IrSimpleFunction,
expression: IrExpression
): IrExpression {
val fakeFunction = generateCFunctionAndFakeKotlinExternalFunction(
function,
signature,
isObjCMethod = false,
location = expression
)
addKotlin(fakeFunction)
return IrFunctionReferenceImpl(
expression.startOffset,
expression.endOffset,
expression.type,
fakeFunction.symbol,
typeArgumentsCount = 0,
reflectionTarget = null
)
}
internal fun KotlinStubs.generateCFunctionAndFakeKotlinExternalFunction(
function: IrSimpleFunction,
signature: IrSimpleFunction,
isObjCMethod: Boolean,
location: IrElement
): IrSimpleFunction {
val cFunction = generateCFunction(function, signature, isObjCMethod, location)
return createFakeKotlinExternalFunction(signature, cFunction, isObjCMethod)
}
private fun KotlinStubs.createFakeKotlinExternalFunction(
signature: IrSimpleFunction,
cFunctionName: String,
isObjCMethod: Boolean
): IrSimpleFunction {
val bridgeDescriptor = WrappedSimpleFunctionDescriptor()
val bridge = IrFunctionImpl(
UNDEFINED_OFFSET,
UNDEFINED_OFFSET,
IrDeclarationOrigin.DEFINED,
IrSimpleFunctionSymbolImpl(bridgeDescriptor),
Name.identifier(cFunctionName),
DescriptorVisibilities.PRIVATE,
Modality.FINAL,
signature.returnType,
isInline = false,
isExternal = true,
isTailrec = false,
isSuspend = false,
isExpect = false,
isFakeOverride = false,
isOperator = false,
isInfix = false
)
bridgeDescriptor.bind(bridge)
bridge.annotations += buildSimpleAnnotation(irBuiltIns, UNDEFINED_OFFSET, UNDEFINED_OFFSET,
symbols.symbolName.owner, cFunctionName)
if (isObjCMethod) {
val methodInfo = signature.getObjCMethodInfo()!!
bridge.annotations += buildSimpleAnnotation(irBuiltIns, UNDEFINED_OFFSET, UNDEFINED_OFFSET,
symbols.objCMethodImp.owner, methodInfo.selector, methodInfo.encoding)
}
return bridge
}
private val cCall = RuntimeNames.cCall
private fun IrType.isUnsigned(unsignedType: UnsignedType) = this is IrSimpleType && !this.hasQuestionMark &&
(this.classifier.owner as? IrClass)?.classId == unsignedType.classId
private fun IrType.isUByte() = this.isUnsigned(UnsignedType.UBYTE)
private fun IrType.isUShort() = this.isUnsigned(UnsignedType.USHORT)
private fun IrType.isUInt() = this.isUnsigned(UnsignedType.UINT)
private fun IrType.isULong() = this.isUnsigned(UnsignedType.ULONG)
internal fun IrType.isCEnumType(): Boolean {
val simpleType = this as? IrSimpleType ?: return false
if (simpleType.hasQuestionMark) return false
val enumClass = simpleType.classifier.owner as? IrClass ?: return false
if (!enumClass.isEnumClass) return false
return enumClass.superTypes
.any { (it.classifierOrNull?.owner as? IrClass)?.fqNameForIrSerialization == FqName("kotlinx.cinterop.CEnum") }
}
// Make sure external stubs always get proper annotaions.
private fun IrDeclaration.hasCCallAnnotation(name: String): Boolean =
this.annotations.hasAnnotation(cCall.child(Name.identifier(name)))
// LazyIr doesn't pass annotations from descriptor to IrValueParameter.
|| this.descriptor.annotations.hasAnnotation(cCall.child(Name.identifier(name)))
private fun IrValueParameter.isWCStringParameter() = hasCCallAnnotation("WCString")
private fun IrValueParameter.isCStringParameter() = hasCCallAnnotation("CString")
private fun IrValueParameter.isConsumed() = hasCCallAnnotation("Consumed")
private fun IrSimpleFunction.consumesReceiver() = hasCCallAnnotation("ConsumesReceiver")
private fun IrSimpleFunction.returnsRetained() = hasCCallAnnotation("ReturnsRetained")
private fun getStructSpelling(kotlinClass: IrClass): String? =
kotlinClass.getAnnotationArgumentValue(FqName("kotlinx.cinterop.internal.CStruct"), "spelling")
private fun getCStructType(kotlinClass: IrClass): CType? =
getStructSpelling(kotlinClass)?.let { CTypes.simple(it) }
private fun KotlinStubs.getNamedCStructType(kotlinClass: IrClass): CType? {
val cStructType = getCStructType(kotlinClass) ?: return null
val name = getUniqueCName("struct")
addC(listOf("typedef ${cStructType.render(name)};"))
return CTypes.simple(name)
}
// TODO: rework Boolean support.
// TODO: What should be used on watchOS?
private fun cBoolType(target: KonanTarget): CType? = when (target.family) {
Family.IOS, Family.TVOS, Family.WATCHOS -> CTypes.C99Bool
else -> CTypes.signedChar
}
private fun KotlinToCCallBuilder.mapCalleeFunctionParameter(
type: IrType,
variadic: Boolean,
parameter: IrValueParameter?,
argument: IrExpression
): KotlinToCArgumentPassing {
val classifier = type.classifierOrNull
return when {
classifier == symbols.interopCValues || // Note: this should not be accepted, but is required for compatibility
classifier == symbols.interopCValuesRef -> CValuesRefArgumentPassing
classifier == symbols.string && (variadic || parameter?.isCStringParameter() == true) -> {
if (variadic && isObjCMethod) {
stubs.reportError(argument, "Passing String as variadic Objective-C argument is ambiguous; " +
"cast it to NSString or pass with '.cstr' as C string")
// TODO: consider reporting a warning for C functions.
}
CStringArgumentPassing()
}
classifier == symbols.string && parameter?.isWCStringParameter() == true ->
WCStringArgumentPassing()
else -> stubs.mapFunctionParameterType(
type,
retained = parameter?.isConsumed() ?: false,
variadic = variadic,
location = TypeLocation.FunctionArgument(argument)
)
}
}
private fun KotlinStubs.mapFunctionParameterType(
type: IrType,
retained: Boolean,
variadic: Boolean,
location: TypeLocation
): ArgumentPassing = when {
type.isUnit() && !variadic -> IgnoredUnitArgumentPassing
else -> mapType(type, retained = retained, variadic = variadic, location = location)
}
private sealed class TypeLocation(val element: IrElement) {
class FunctionArgument(val argument: IrExpression) : TypeLocation(argument)
class FunctionCallResult(val call: IrFunctionAccessExpression) : TypeLocation(call)
class FunctionPointerParameter(val index: Int, element: IrElement) : TypeLocation(element)
class FunctionPointerReturnValue(element: IrElement) : TypeLocation(element)
class ObjCMethodParameter(val index: Int, element: IrElement) : TypeLocation(element)
class ObjCMethodReturnValue(element: IrElement) : TypeLocation(element)
class BlockParameter(val index: Int, val blockLocation: TypeLocation) : TypeLocation(blockLocation.element)
class BlockReturnValue(val blockLocation: TypeLocation) : TypeLocation(blockLocation.element)
}
private fun KotlinStubs.mapReturnType(
type: IrType,
location: TypeLocation,
signature: IrSimpleFunction?
): ValueReturning = when {
type.isUnit() -> VoidReturning
else -> mapType(type, retained = signature?.returnsRetained() ?: false, variadic = false, location = location)
}
private fun KotlinStubs.mapBlockType(
type: IrType,
retained: Boolean,
location: TypeLocation
): ObjCBlockPointerValuePassing {
type as IrSimpleType
require(type.classifier == symbols.functionN(type.arguments.size - 1))
val returnTypeArgument = type.arguments.last()
val valueReturning = when (returnTypeArgument) {
is IrTypeProjection -> if (returnTypeArgument.variance == Variance.INVARIANT) {
mapReturnType(returnTypeArgument.type, TypeLocation.BlockReturnValue(location), null)
} else {
reportUnsupportedType("${returnTypeArgument.variance.label}-variance of return type", type, location)
}
is IrStarProjection -> reportUnsupportedType("* as return type", type, location)
else -> error(returnTypeArgument)
}
val parameterValuePassings = type.arguments.dropLast(1).mapIndexed { index, argument ->
when (argument) {
is IrTypeProjection -> if (argument.variance == Variance.INVARIANT) {
mapType(
argument.type,
retained = false,
variadic = false,
location = TypeLocation.BlockParameter(index, location)
)
} else {
reportUnsupportedType("${argument.variance.label}-variance of ${index + 1} parameter type", type, location)
}
is IrStarProjection -> reportUnsupportedType("* as ${index + 1} parameter type", type, location)
else -> error(argument)
}
}
return ObjCBlockPointerValuePassing(
this,
location.element,
type,
valueReturning,
parameterValuePassings,
retained
)
}
private fun KotlinStubs.mapType(type: IrType, retained: Boolean, variadic: Boolean, location: TypeLocation): ValuePassing =
mapType(type, retained, variadic, location, { reportUnsupportedType(it, type, location) })
private fun IrType.isTypeOfNullLiteral(): Boolean = this is IrSimpleType && hasQuestionMark
&& classifier.isClassWithFqName(StandardNames.FqNames.nothing)
internal fun IrType.isVector(): Boolean {
if (this is IrSimpleType && !this.hasQuestionMark) {
return classifier.isClassWithFqName(KonanFqNames.Vector128.toUnsafe())
}
return false
}
private fun KotlinStubs.mapType(
type: IrType,
retained: Boolean,
variadic: Boolean,
typeLocation: TypeLocation,
reportUnsupportedType: (String) -> Nothing
): ValuePassing = when {
type.isBoolean() -> BooleanValuePassing(
cBoolType(target) ?: reportUnsupportedType("unavailable on target platform"),
irBuiltIns
)
type.isByte() -> TrivialValuePassing(irBuiltIns.byteType, CTypes.signedChar)
type.isShort() -> TrivialValuePassing(irBuiltIns.shortType, CTypes.short)
type.isInt() -> TrivialValuePassing(irBuiltIns.intType, CTypes.int)
type.isLong() -> TrivialValuePassing(irBuiltIns.longType, CTypes.longLong)
type.isFloat() -> TrivialValuePassing(irBuiltIns.floatType, CTypes.float)
type.isDouble() -> TrivialValuePassing(irBuiltIns.doubleType, CTypes.double)
type.classifierOrNull == symbols.interopCPointer -> TrivialValuePassing(type, CTypes.voidPtr)
type.isTypeOfNullLiteral() && variadic -> TrivialValuePassing(symbols.interopCPointer.typeWithStarProjections.makeNullable(), CTypes.voidPtr)
type.isUByte() -> UnsignedValuePassing(type, CTypes.signedChar, CTypes.unsignedChar)
type.isUShort() -> UnsignedValuePassing(type, CTypes.short, CTypes.unsignedShort)
type.isUInt() -> UnsignedValuePassing(type, CTypes.int, CTypes.unsignedInt)
type.isULong() -> UnsignedValuePassing(type, CTypes.longLong, CTypes.unsignedLongLong)
type.isVector() -> TrivialValuePassing(type, CTypes.vector128)
type.isCEnumType() -> {
val enumClass = type.getClass()!!
val value = enumClass.declarations
.filterIsInstance<IrProperty>()
.single { it.name.asString() == "value" }
CEnumValuePassing(
enumClass,
value,
mapType(value.getter!!.returnType, retained, variadic, typeLocation) as SimpleValuePassing
)
}
type.classifierOrNull == symbols.interopCValue -> if (type.isNullable()) {
reportUnsupportedType("must not be nullable")
} else {
val kotlinClass = (type as IrSimpleType).arguments.singleOrNull()?.typeOrNull?.getClass()
?: reportUnsupportedType("must be parameterized with concrete class")
StructValuePassing(kotlinClass, getNamedCStructType(kotlinClass)
?: reportUnsupportedType("not a structure or too complex"))
}
type.classOrNull?.isSubtypeOfClass(symbols.nativePointed) == true -> {
TrivialValuePassing(type, CTypes.voidPtr)
}
type.isFunction() -> if (variadic){
reportUnsupportedType("not supported as variadic argument")
} else {
mapBlockType(type, retained = retained, location = typeLocation)
}
isObjCReferenceType(type) -> ObjCReferenceValuePassing(symbols, type, retained = retained)
else -> reportUnsupportedType("doesn't correspond to any C type")
}
private fun KotlinStubs.isObjCReferenceType(type: IrType): Boolean {
if (!target.family.isAppleFamily) return false
// Handle the same types as produced by [objCPointerMirror] in Interop/StubGenerator/.../Mappings.kt.
if (type.isObjCObjectType()) return true
val descriptor = type.classifierOrNull?.descriptor ?: return false
val builtIns = irBuiltIns.builtIns
return when (descriptor) {
builtIns.any,
builtIns.string,
builtIns.list, builtIns.mutableList,
builtIns.set,
builtIns.map -> true
else -> false
}
}
private class CExpression(val expression: String, val type: CType)
private interface KotlinToCArgumentPassing {
fun KotlinToCCallBuilder.passValue(expression: IrExpression): CExpression?
}
private interface ValueReturning {
val cType: CType
fun KotlinToCCallBuilder.returnValue(expression: String): IrExpression
fun CCallbackBuilder.returnValue(expression: IrExpression)
}
private interface ArgumentPassing : KotlinToCArgumentPassing {
fun CCallbackBuilder.receiveValue(): IrExpression
}
private interface ValuePassing : ArgumentPassing, ValueReturning
private abstract class SimpleValuePassing : ValuePassing {
abstract val kotlinBridgeType: IrType
abstract val cBridgeType: CType
override abstract val cType: CType
open val callbackParameterCType get() = cType
abstract fun IrBuilderWithScope.kotlinToBridged(expression: IrExpression): IrExpression
open fun IrBuilderWithScope.kotlinCallbackResultToBridged(expression: IrExpression): IrExpression =
kotlinToBridged(expression)
abstract fun IrBuilderWithScope.bridgedToKotlin(expression: IrExpression, symbols: KonanSymbols): IrExpression
abstract fun bridgedToC(expression: String): String
abstract fun cToBridged(expression: String): String
override fun KotlinToCCallBuilder.passValue(expression: IrExpression): CExpression {
val bridgeArgument = irBuilder.kotlinToBridged(expression)
val cBridgeValue = passThroughBridge(bridgeArgument, kotlinBridgeType, cBridgeType).name
return CExpression(bridgedToC(cBridgeValue), cType)
}
override fun KotlinToCCallBuilder.returnValue(expression: String): IrExpression {
cFunctionBuilder.setReturnType(cType)
bridgeBuilder.setReturnType(kotlinBridgeType, cBridgeType)
cBridgeBodyLines.add("return ${cToBridged(expression)};")
val kotlinBridgeCall = buildKotlinBridgeCall()
return irBuilder.bridgedToKotlin(kotlinBridgeCall, symbols)
}
override fun CCallbackBuilder.receiveValue(): IrExpression {
val cParameter = cFunctionBuilder.addParameter(callbackParameterCType)
val cBridgeArgument = cToBridged(cParameter.name)
val kotlinParameter = passThroughBridge(cBridgeArgument, cBridgeType, kotlinBridgeType)
return with(bridgeBuilder.kotlinIrBuilder) {
bridgedToKotlin(irGet(kotlinParameter), symbols)
}
}
override fun CCallbackBuilder.returnValue(expression: IrExpression) {
cFunctionBuilder.setReturnType(cType)
bridgeBuilder.setReturnType(kotlinBridgeType, cBridgeType)
kotlinBridgeStatements += with(bridgeBuilder.kotlinIrBuilder) {
irReturn(kotlinCallbackResultToBridged(expression))
}
val cBridgeCall = buildCBridgeCall()
cBodyLines += "return ${bridgedToC(cBridgeCall)};"
}
}
private class TrivialValuePassing(val kotlinType: IrType, override val cType: CType) : SimpleValuePassing() {
override val kotlinBridgeType: IrType
get() = kotlinType
override val cBridgeType: CType
get() = cType
override fun IrBuilderWithScope.kotlinToBridged(expression: IrExpression): IrExpression = expression
override fun IrBuilderWithScope.bridgedToKotlin(expression: IrExpression, symbols: KonanSymbols): IrExpression = expression
override fun bridgedToC(expression: String): String = expression
override fun cToBridged(expression: String): String = expression
}
private class UnsignedValuePassing(val kotlinType: IrType, val cSignedType: CType, override val cType: CType) : SimpleValuePassing() {
override val kotlinBridgeType: IrType
get() = kotlinType
override val cBridgeType: CType
get() = cSignedType
override fun IrBuilderWithScope.kotlinToBridged(expression: IrExpression): IrExpression = expression
override fun IrBuilderWithScope.bridgedToKotlin(expression: IrExpression, symbols: KonanSymbols): IrExpression = expression
override fun bridgedToC(expression: String): String = cType.cast(expression)
override fun cToBridged(expression: String): String = cBridgeType.cast(expression)
}
private class BooleanValuePassing(override val cType: CType, private val irBuiltIns: IrBuiltIns) : SimpleValuePassing() {
override val cBridgeType: CType get() = CTypes.signedChar
override val kotlinBridgeType: IrType get() = irBuiltIns.byteType
override fun IrBuilderWithScope.kotlinToBridged(expression: IrExpression): IrExpression = irIfThenElse(
irBuiltIns.byteType,
condition = expression,
thenPart = IrConstImpl.byte(startOffset, endOffset, irBuiltIns.byteType, 1),
elsePart = IrConstImpl.byte(startOffset, endOffset, irBuiltIns.byteType, 0)
)
override fun IrBuilderWithScope.bridgedToKotlin(
expression: IrExpression,
symbols: KonanSymbols
): IrExpression = irNot(irCall(symbols.areEqualByValue[PrimitiveBinaryType.BYTE]!!.owner).apply {
putValueArgument(0, expression)
putValueArgument(1, IrConstImpl.byte(startOffset, endOffset, irBuiltIns.byteType, 0))
})
override fun bridgedToC(expression: String): String = cType.cast(expression)
override fun cToBridged(expression: String): String = cBridgeType.cast(expression)
}
private class StructValuePassing(private val kotlinClass: IrClass, override val cType: CType) : ValuePassing {
override fun KotlinToCCallBuilder.passValue(expression: IrExpression): CExpression {
val cBridgeValue = passThroughBridge(
cValuesRefToPointer(expression),
symbols.interopCPointer.typeWithStarProjections,
CTypes.pointer(cType)
).name
return CExpression("*$cBridgeValue", cType)
}
override fun KotlinToCCallBuilder.returnValue(expression: String): IrExpression = with(irBuilder) {
cFunctionBuilder.setReturnType(cType)
bridgeBuilder.setReturnType(context.irBuiltIns.unitType, CTypes.void)
val kotlinPointed = scope.createTemporaryVariable(irCall(symbols.interopAllocType.owner).apply {
extensionReceiver = bridgeCallBuilder.getMemScope()
putValueArgument(0, getTypeObject())
})
bridgeCallBuilder.prepare += kotlinPointed
val cPointer = passThroughBridge(irGet(kotlinPointed), kotlinPointedType, CTypes.pointer(cType))
cBridgeBodyLines += "*${cPointer.name} = $expression;"
buildKotlinBridgeCall {
irBlock {
at(it)
+it
+readCValue(irGet(kotlinPointed), symbols)
}
}
}
override fun CCallbackBuilder.receiveValue(): IrExpression = with(bridgeBuilder.kotlinIrBuilder) {
val cParameter = cFunctionBuilder.addParameter(cType)
val kotlinPointed = passThroughBridge("&${cParameter.name}", CTypes.voidPtr, kotlinPointedType)
readCValue(irGet(kotlinPointed), symbols)
}
private fun IrBuilderWithScope.readCValue(kotlinPointed: IrExpression, symbols: KonanSymbols): IrExpression =
irCall(symbols.interopCValueRead.owner).apply {
extensionReceiver = kotlinPointed
putValueArgument(0, getTypeObject())
}
override fun CCallbackBuilder.returnValue(expression: IrExpression) = with(bridgeBuilder.kotlinIrBuilder) {
bridgeBuilder.setReturnType(irBuiltIns.unitType, CTypes.void)
cFunctionBuilder.setReturnType(cType)
val result = "callbackResult"
val cReturnValue = CVariable(cType, result)
cBodyLines += "$cReturnValue;"
val kotlinPtr = passThroughBridge("&$result", CTypes.voidPtr, symbols.nativePtrType)
kotlinBridgeStatements += irCall(symbols.interopCValueWrite.owner).apply {
extensionReceiver = expression
putValueArgument(0, irGet(kotlinPtr))
}
val cBridgeCall = buildCBridgeCall()
cBodyLines += "$cBridgeCall;"
cBodyLines += "return $result;"
}
private val kotlinPointedType: IrType get() = kotlinClass.defaultType
private fun IrBuilderWithScope.getTypeObject() =
irGetObject(
kotlinClass.declarations.filterIsInstance<IrClass>()
.single { it.isCompanion }.symbol
)
}
private class CEnumValuePassing(
val enumClass: IrClass,
val value: IrProperty,
val baseValuePassing: SimpleValuePassing
) : SimpleValuePassing() {
override val kotlinBridgeType: IrType
get() = baseValuePassing.kotlinBridgeType
override val cBridgeType: CType
get() = baseValuePassing.cBridgeType
override val cType: CType
get() = baseValuePassing.cType
override fun IrBuilderWithScope.kotlinToBridged(expression: IrExpression): IrExpression {
val value = irCall(value.getter!!).apply {
dispatchReceiver = expression
}
return with(baseValuePassing) { kotlinToBridged(value) }
}
override fun IrBuilderWithScope.bridgedToKotlin(expression: IrExpression, symbols: KonanSymbols): IrExpression {
val companionClass = enumClass.declarations.filterIsInstance<IrClass>().single { it.isCompanion }
val byValue = companionClass.simpleFunctions().single { it.name.asString() == "byValue" }
return irCall(byValue).apply {
dispatchReceiver = irGetObject(companionClass.symbol)
putValueArgument(0, expression)
}
}
override fun bridgedToC(expression: String): String = with(baseValuePassing) { bridgedToC(expression) }
override fun cToBridged(expression: String): String = with(baseValuePassing) { cToBridged(expression) }
}
private class ObjCReferenceValuePassing(
private val symbols: KonanSymbols,
private val type: IrType,
private val retained: Boolean
) : SimpleValuePassing() {
override val kotlinBridgeType: IrType
get() = symbols.nativePtrType
override val cBridgeType: CType
get() = CTypes.voidPtr
override val cType: CType
get() = CTypes.voidPtr
override fun IrBuilderWithScope.kotlinToBridged(expression: IrExpression): IrExpression {
val ptr = irCall(symbols.interopObjCObjectRawValueGetter.owner).apply {
extensionReceiver = expression
}
return if (retained) {
irCall(symbols.interopObjCRetain).apply {
putValueArgument(0, ptr)
}
} else {
ptr
}
}
override fun IrBuilderWithScope.kotlinCallbackResultToBridged(expression: IrExpression): IrExpression {
if (retained) return kotlinToBridged(expression) // Optimization.
// Kotlin code may loose the ownership on this pointer after returning from the bridge,
// so retain the pointer and autorelease it:
return irCall(symbols.interopObjcRetainAutoreleaseReturnValue.owner).apply {
putValueArgument(0, kotlinToBridged(expression))
}
// TODO: optimize by using specialized Kotlin-to-ObjC converter.
}
override fun IrBuilderWithScope.bridgedToKotlin(expression: IrExpression, symbols: KonanSymbols): IrExpression =
convertPossiblyRetainedObjCPointer(symbols, retained, expression) {
irCall(symbols.interopInterpretObjCPointerOrNull, listOf(type)).apply {
putValueArgument(0, it)
}
}
override fun bridgedToC(expression: String): String = expression
override fun cToBridged(expression: String): String = expression
}
private fun IrBuilderWithScope.convertPossiblyRetainedObjCPointer(
symbols: KonanSymbols,
retained: Boolean,
pointer: IrExpression,
convert: (IrExpression) -> IrExpression
): IrExpression = if (retained) {
irBlock(startOffset, endOffset) {
val ptrVar = irTemporary(pointer)
val resultVar = irTemporary(convert(irGet(ptrVar)))
+irCall(symbols.interopObjCRelease.owner).apply {
putValueArgument(0, irGet(ptrVar))
}
+irGet(resultVar)
}
} else {
convert(pointer)
}
private class ObjCBlockPointerValuePassing(
val stubs: KotlinStubs,
private val location: IrElement,
private val functionType: IrSimpleType,
private val valueReturning: ValueReturning,
private val parameterValuePassings: List<ValuePassing>,
private val retained: Boolean
) : SimpleValuePassing() {
val symbols get() = stubs.symbols
override val kotlinBridgeType: IrType
get() = symbols.nativePtrType
override val cBridgeType: CType
get() = CTypes.id
override val cType: CType
get() = CTypes.id
/**
* Callback can receive stack-allocated block. Using block type for parameter and passing it as `id` to the bridge
* makes Objective-C compiler generate proper copying to heap.
*/
override val callbackParameterCType: CType
get() = CTypes.blockPointer(
CTypes.function(
valueReturning.cType,
parameterValuePassings.map { it.cType },
variadic = false
))
override fun IrBuilderWithScope.kotlinToBridged(expression: IrExpression): IrExpression =
irCall(symbols.interopCreateKotlinObjectHolder.owner).apply {
putValueArgument(0, expression)
}
override fun IrBuilderWithScope.bridgedToKotlin(expression: IrExpression, symbols: KonanSymbols): IrExpression =
irLetS(expression) { blockPointerVarSymbol ->
val blockPointerVar = blockPointerVarSymbol.owner
irIfThenElse(
functionType.makeNullable(),
condition = irCall(symbols.areEqualByValue.getValue(PrimitiveBinaryType.POINTER).owner).apply {
putValueArgument(0, irGet(blockPointerVar))
putValueArgument(1, irNullNativePtr(symbols))
},
thenPart = irNull(),
elsePart = convertPossiblyRetainedObjCPointer(symbols, retained, irGet(blockPointerVar)) {
createKotlinFunctionObject(it)
}
)
}
private object OBJC_BLOCK_FUNCTION_IMPL : IrDeclarationOriginImpl("OBJC_BLOCK_FUNCTION_IMPL")
private fun IrBuilderWithScope.createKotlinFunctionObject(blockPointer: IrExpression): IrExpression {
val constructor = generateKotlinFunctionClass()
return irCall(constructor).apply {
putValueArgument(0, blockPointer)
}
}
private fun IrBuilderWithScope.generateKotlinFunctionClass(): IrConstructor {
val symbols = stubs.symbols
val classDescriptor = WrappedClassDescriptor()
val irClass = IrClassImpl(
startOffset, endOffset,
OBJC_BLOCK_FUNCTION_IMPL, IrClassSymbolImpl(classDescriptor),
Name.identifier(stubs.getUniqueKotlinFunctionReferenceClassName("BlockFunctionImpl")),
ClassKind.CLASS, DescriptorVisibilities.PRIVATE, Modality.FINAL,
isCompanion = false, isInner = false, isData = false, isExternal = false,
isInline = false, isExpect = false, isFun = false
)
classDescriptor.bind(irClass)
irClass.createParameterDeclarations()
irClass.superTypes += stubs.irBuiltIns.anyType
irClass.superTypes += functionType.makeNotNull()
val blockHolderField = createField(
startOffset, endOffset,
OBJC_BLOCK_FUNCTION_IMPL,
stubs.irBuiltIns.anyType,
Name.identifier("blockHolder"),
isMutable = false, owner = irClass
)
val constructorDescriptor = WrappedClassConstructorDescriptor()
val constructor = IrConstructorImpl(
startOffset, endOffset,
OBJC_BLOCK_FUNCTION_IMPL,
IrConstructorSymbolImpl(constructorDescriptor),
Name.special("<init>"),
DescriptorVisibilities.PUBLIC,
irClass.defaultType,
isInline = false, isExternal = false, isPrimary = true, isExpect = false
)
constructorDescriptor.bind(constructor)
irClass.addChild(constructor)
val constructorParameterDescriptor = WrappedValueParameterDescriptor()
val constructorParameter = IrValueParameterImpl(
startOffset, endOffset,
OBJC_BLOCK_FUNCTION_IMPL,
IrValueParameterSymbolImpl(constructorParameterDescriptor),
Name.identifier("blockPointer"),
0,
symbols.nativePtrType,
varargElementType = null, isCrossinline = false, isNoinline = false
)
constructorParameterDescriptor.bind(constructorParameter)
constructor.valueParameters += constructorParameter
constructorParameter.parent = constructor
constructor.body = irBuilder(stubs.irBuiltIns, constructor.symbol).irBlockBody(startOffset, endOffset) {
+irDelegatingConstructorCall(symbols.any.owner.constructors.single())
+irSetField(irGet(irClass.thisReceiver!!), blockHolderField,
irCall(symbols.interopCreateObjCObjectHolder.owner).apply {
putValueArgument(0, irGet(constructorParameter))
})
}
val parameterCount = parameterValuePassings.size
assert(functionType.arguments.size == parameterCount + 1)
val overriddenInvokeMethod = (functionType.classifier.owner as IrClass).simpleFunctions()
.single { it.name == OperatorNameConventions.INVOKE }
val invokeMethodDescriptor = WrappedSimpleFunctionDescriptor()
val invokeMethod = IrFunctionImpl(
startOffset, endOffset,
OBJC_BLOCK_FUNCTION_IMPL,
IrSimpleFunctionSymbolImpl(invokeMethodDescriptor),
overriddenInvokeMethod.name,
DescriptorVisibilities.PUBLIC, Modality.FINAL,
returnType = functionType.arguments.last().typeOrNull!!,
isInline = false, isExternal = false, isTailrec = false, isSuspend = false, isExpect = false,
isFakeOverride = false, isOperator = false, isInfix = false
)
invokeMethodDescriptor.bind(invokeMethod)
invokeMethod.overriddenSymbols += overriddenInvokeMethod.symbol
irClass.addChild(invokeMethod)
invokeMethod.createDispatchReceiverParameter()
invokeMethod.valueParameters += (0 until parameterCount).map { index ->
val parameterDescriptor = WrappedValueParameterDescriptor()
val parameter = IrValueParameterImpl(
startOffset, endOffset,
OBJC_BLOCK_FUNCTION_IMPL,
IrValueParameterSymbolImpl(parameterDescriptor),
Name.identifier("p$index"),
index,
functionType.arguments[index].typeOrNull!!,
varargElementType = null, isCrossinline = false, isNoinline = false
)
parameterDescriptor.bind(parameter)
parameter.parent = invokeMethod
parameter
}
invokeMethod.body = irBuilder(stubs.irBuiltIns, invokeMethod.symbol).irBlockBody(startOffset, endOffset) {
val blockPointer = irCall(symbols.interopObjCObjectRawValueGetter.owner).apply {
extensionReceiver = irGetField(irGet(invokeMethod.dispatchReceiverParameter!!), blockHolderField)
}
val arguments = (0 until parameterCount).map { index ->
irGet(invokeMethod.valueParameters[index])
}
+irReturn(callBlock(blockPointer, arguments))
}
irClass.addFakeOverrides(stubs.irBuiltIns)
stubs.addKotlin(irClass)
return constructor
}
private fun IrBuilderWithScope.callBlock(blockPtr: IrExpression, arguments: List<IrExpression>): IrExpression {
val callBuilder = KotlinToCCallBuilder(this, stubs, isObjCMethod = false, ForeignExceptionMode.default)
val rawBlockPointerParameter = callBuilder.passThroughBridge(blockPtr, blockPtr.type, CTypes.id)
val blockVariableName = "block"
arguments.forEachIndexed { index, argument ->
callBuilder.addArgument(argument, parameterValuePassings[index], variadic = false)
}
val result = callBuilder.buildCall(blockVariableName, valueReturning)
val blockVariableType = CTypes.blockPointer(callBuilder.cFunctionBuilder.getType())
val blockVariable = CVariable(blockVariableType, blockVariableName)
callBuilder.cBridgeBodyLines.add(0, "$blockVariable = ${rawBlockPointerParameter.name};")
callBuilder.emitCBridge()
return result
}
override fun bridgedToC(expression: String): String {
val callbackBuilder = CCallbackBuilder(stubs, location, isObjCMethod = false)
val kotlinFunctionHolder = "kotlinFunctionHolder"
callbackBuilder.cBridgeCallBuilder.arguments += kotlinFunctionHolder
val (kotlinFunctionHolderParameter, _) =
callbackBuilder.bridgeBuilder.addParameter(symbols.nativePtrType, CTypes.id)
callbackBuilder.kotlinCallBuilder.arguments += with(callbackBuilder.bridgeBuilder.kotlinIrBuilder) {
// TODO: consider casting to [functionType].
irCall(symbols.interopUnwrapKotlinObjectHolderImpl.owner).apply {
putValueArgument(0, irGet(kotlinFunctionHolderParameter) )
}
}
parameterValuePassings.forEach {
callbackBuilder.kotlinCallBuilder.arguments += with(it) {
callbackBuilder.receiveValue()
}
}
assert(functionType.isFunction())
val invokeFunction = (functionType.classifier.owner as IrClass)
.simpleFunctions().single { it.name == OperatorNameConventions.INVOKE }
callbackBuilder.buildValueReturn(invokeFunction, valueReturning)
val block = buildString {
append('^')
append(callbackBuilder.cFunctionBuilder.buildSignature(""))
append(" { ")
callbackBuilder.cBodyLines.forEach {
append(it)
append(' ')
}
append(" }")
}
val blockAsId = if (retained) {
"(__bridge id)(__bridge_retained void*)$block" // Retain and convert to id.
} else {
"(id)$block"
}
return "({ id $kotlinFunctionHolder = $expression; $kotlinFunctionHolder ? $blockAsId : (id)0; })"
}
override fun cToBridged(expression: String) = expression
}
private class WCStringArgumentPassing : KotlinToCArgumentPassing {
override fun KotlinToCCallBuilder.passValue(expression: IrExpression): CExpression {
val wcstr = irBuilder.irSafeTransform(expression) {
irCall(symbols.interopWcstr.owner).apply {
extensionReceiver = it
}
}
return with(CValuesRefArgumentPassing) { passValue(wcstr) }
}
}
private class CStringArgumentPassing : KotlinToCArgumentPassing {
override fun KotlinToCCallBuilder.passValue(expression: IrExpression): CExpression {
val cstr = irBuilder.irSafeTransform(expression) {
irCall(symbols.interopCstr.owner).apply {
extensionReceiver = it
}
}
return with(CValuesRefArgumentPassing) { passValue(cstr) }
}
}
private object CValuesRefArgumentPassing : KotlinToCArgumentPassing {
override fun KotlinToCCallBuilder.passValue(expression: IrExpression): CExpression {
val bridgeArgument = cValuesRefToPointer(expression)
val cBridgeValue = passThroughBridge(
bridgeArgument,
symbols.interopCPointer.typeWithStarProjections.makeNullable(),
CTypes.voidPtr
)
return CExpression(cBridgeValue.name, cBridgeValue.type)
}
}
private fun KotlinToCCallBuilder.cValuesRefToPointer(
value: IrExpression
): IrExpression = if (value.type.classifierOrNull == symbols.interopCPointer) {
value // Optimization
} else {
val getPointerFunction = symbols.interopCValuesRef.owner
.simpleFunctions()
.single { it.name.asString() == "getPointer" }
irBuilder.irSafeTransform(value) {
irCall(getPointerFunction).apply {
dispatchReceiver = it
putValueArgument(0, bridgeCallBuilder.getMemScope())
}
}
}
private fun IrBuilderWithScope.irSafeTransform(
value: IrExpression,
block: IrBuilderWithScope.(IrExpression) -> IrExpression
): IrExpression = if (!value.type.isNullable()) {
block(value) // Optimization
} else {
irLetS(value) { valueVarSymbol ->
val valueVar = valueVarSymbol.owner
val transformed = block(irGet(valueVar))
irIfThenElse(
type = transformed.type.makeNullable(),
condition = irEqeqeq(irGet(valueVar), irNull()),
thenPart = irNull(),
elsePart = transformed
)
}
}
private object VoidReturning : ValueReturning {
override val cType: CType
get() = CTypes.void
override fun KotlinToCCallBuilder.returnValue(expression: String): IrExpression {
bridgeBuilder.setReturnType(irBuilder.context.irBuiltIns.unitType, CTypes.void)
cFunctionBuilder.setReturnType(CTypes.void)
cBridgeBodyLines += "$expression;"
return buildKotlinBridgeCall()
}
override fun CCallbackBuilder.returnValue(expression: IrExpression) {
bridgeBuilder.setReturnType(irBuiltIns.unitType, CTypes.void)
cFunctionBuilder.setReturnType(CTypes.void)
kotlinBridgeStatements += bridgeBuilder.kotlinIrBuilder.irReturn(expression)
cBodyLines += "${buildCBridgeCall()};"
}
}
private object IgnoredUnitArgumentPassing : ArgumentPassing {
override fun KotlinToCCallBuilder.passValue(expression: IrExpression): CExpression? {
// Note: it is not correct to just drop the expression (due to possible side effects),
// so (in lack of other options) evaluate the expression and pass ignored value to the bridge:
val bridgeArgument = irBuilder.irBlock {
+expression
+irInt(0)
}
passThroughBridge(bridgeArgument, irBuilder.context.irBuiltIns.intType, CTypes.int).name
return null
}
override fun CCallbackBuilder.receiveValue(): IrExpression {
return bridgeBuilder.kotlinIrBuilder.irGetObject(irBuiltIns.unitClass)
}
}
internal fun CType.cast(expression: String): String = "((${this.render("")})$expression)"
private fun KotlinStubs.reportUnsupportedType(reason: String, type: IrType, location: TypeLocation): Nothing {
// TODO: report errors in frontend instead.
fun TypeLocation.render(): String = when (this) {
is TypeLocation.FunctionArgument -> ""
is TypeLocation.FunctionCallResult -> " of return value"
is TypeLocation.FunctionPointerParameter -> " of callback parameter ${index + 1}"
is TypeLocation.FunctionPointerReturnValue -> " of callback return value"
is TypeLocation.ObjCMethodParameter -> " of overridden Objective-C method parameter"
is TypeLocation.ObjCMethodReturnValue -> " of overridden Objective-C method return value"
is TypeLocation.BlockParameter -> " of ${index + 1} parameter in Objective-C block type${blockLocation.render()}"
is TypeLocation.BlockReturnValue -> " of return value of Objective-C block type${blockLocation.render()}"
}
val typeLocation: String = location.render()
reportError(location.element, "type ${type.render()} $typeLocation is not supported here" +
if (reason.isNotEmpty()) ": $reason" else "")
}
| apache-2.0 |
nemerosa/ontrack | ontrack-kdsl/src/main/java/net/nemerosa/ontrack/kdsl/connector/support/PaginatedListExtensions.kt | 1 | 144 | package net.nemerosa.ontrack.kdsl.connector.support
fun <T> emptyPaginatedList(): PaginatedList<T> = PaginatedList(
items = emptyList(),
)
| mit |
nickbutcher/plaid | designernews/src/test/java/io/plaidapp/designernews/data/comments/CommentsRepositoryTest.kt | 1 | 4607 | /*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.designernews.data.comments
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import io.plaidapp.core.data.Result
import io.plaidapp.designernews.repliesResponses
import io.plaidapp.designernews.replyResponse1
import java.io.IOException
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Tests for [CommentsRepository] mocking all dependencies
*/
class CommentsRepositoryTest {
private val body = "Plaid 2.0 is awesome"
private val dataSource: CommentsRemoteDataSource = mock()
private val repository = CommentsRepository(dataSource)
@Test
fun getComments_withSuccess() = runBlocking {
// Given a list of comment responses that are return for a specific list of ids
val ids = listOf(1L)
val result = Result.Success(repliesResponses)
whenever(dataSource.getComments(ids)).thenReturn(result)
// When requesting the comments
val data = repository.getComments(ids)
// The correct response is returned
assertEquals(result, data)
}
@Test
fun getComments_withError() = runBlocking {
// Given a list of comment responses that are return for a specific list of ids
val ids = listOf(1L)
val result = Result.Error(IOException("error"))
whenever(dataSource.getComments(ids)).thenReturn(result)
// When requesting the comments
val data = repository.getComments(ids)
// The correct response is returned
assertEquals(result, data)
}
@Test
fun postStoryComment_withSuccess() = runBlocking {
// Given that a result is return when posting a story comment
val result = Result.Success(replyResponse1)
whenever(
dataSource.comment(
commentBody = body,
parentCommentId = null,
storyId = 11L,
userId = 111L
)
).thenReturn(result)
// When posting a story comment
val data = repository.postStoryComment(body, 11L, 111L)
// The correct response is returned
assertEquals(result, data)
}
@Test
fun postStoryComment_withError() = runBlocking {
// Given that an error result is return when posting a story comment
val result = Result.Error(IOException("error"))
whenever(
dataSource.comment(
commentBody = body,
parentCommentId = null,
storyId = 11L,
userId = 111L
)
).thenReturn(result)
// When posting a story comment
val data = repository.postStoryComment(body, 11L, 111L)
// The correct response is returned
assertEquals(result, data)
}
@Test
fun postReply_withSuccess() = runBlocking {
// Given that a result is return when posting a story comment
val result = Result.Success(replyResponse1)
whenever(
dataSource.comment(
commentBody = body,
parentCommentId = 11L,
storyId = null,
userId = 111L
)
).thenReturn(result)
// When posting reply
val data = repository.postReply(body, 11L, 111L)
// The correct response is returned
assertEquals(result, data)
}
@Test
fun postReply_withError() = runBlocking {
// Given that an error result is return when posting a reply to a comment
val result = Result.Error(IOException("error"))
whenever(
dataSource.comment(
commentBody = body,
parentCommentId = 11L,
storyId = null,
userId = 111L
)
).thenReturn(result)
// When posting reply
val data = repository.postReply(body, 11L, 111L)
// The correct response is returned
assertEquals(result, data)
}
}
| apache-2.0 |
ibaton/3House | mobile/src/main/java/treehou/se/habit/ui/colorpicker/LightPresenter.kt | 1 | 1885 | package treehou.se.habit.ui.colorpicker
import android.content.Context
import android.os.Bundle
import android.util.Log
import java.util.Locale
import javax.inject.Inject
import javax.inject.Named
import io.realm.Realm
import se.treehou.ng.ohcommunicator.connector.models.OHItem
import se.treehou.ng.ohcommunicator.connector.models.OHServer
import treehou.se.habit.connector.Constants
import treehou.se.habit.core.db.model.ServerDB
import treehou.se.habit.dagger.RxPresenter
import treehou.se.habit.ui.sitemaps.page.PageContract
import treehou.se.habit.util.ConnectionFactory
class LightPresenter @Inject
constructor(private val context: Context, private val realm: Realm, @param:Named("arguments") private val args: Bundle, private val connectionFactory: ConnectionFactory) : RxPresenter(), LightContract.Presenter {
private var serverDb: ServerDB? = null
private var server: OHServer? = null
override fun load(launchData: Bundle?, savedData: Bundle?) {
super.load(launchData, savedData)
val serverId = args.getLong(PageContract.ARG_SERVER)
serverDb = ServerDB.load(realm, serverId)
server = serverDb!!.toGeneric()
}
override fun setHSV(item: OHItem, hue: Int, saturation: Int, value: Int) {
val server = server
if(server != null) {
val serverHandler = connectionFactory.createServerHandler(server, context)
Log.d(TAG, "Color changed to " + String.format("%d,%d,%d", hue, saturation, value))
if (value > 5) {
serverHandler.sendCommand(item.name, String.format(Locale.getDefault(), Constants.COMMAND_COLOR, hue, saturation, value))
} else {
serverHandler.sendCommand(item.name, Constants.COMMAND_OFF)
}
}
}
companion object {
private val TAG = LightPresenter::class.java.simpleName
}
}
| epl-1.0 |
olonho/carkot | car_srv/clients/flash/src/main/java/Main.kt | 1 | 2226 | import client.Client
import com.martiansoftware.jsap.JSAP
import io.netty.buffer.Unpooled
import io.netty.handler.codec.http.*
import java.io.FileInputStream
import java.io.IOException
val configFileName = "./config.cfg"
fun main(args: Array<String>) {
val jsap: JSAP = JSAP()
setOptions(jsap)
val clArgsConfig = jsap.parse(args)
if (!clArgsConfig.success() || clArgsConfig.getBoolean("help")) {
println(jsap.help)
return
}
val fileConfig = readFileConfig()
val host = getActualValue("host", clArgsConfig, fileConfig)
val port = getActualValue("port", clArgsConfig, fileConfig, "8888").toInt()
val flashFilePath = getActualValue("flash", clArgsConfig, fileConfig)
val actualValues = mapOf(
Pair("host", host),
Pair("port", port.toString()),
Pair("flash", flashFilePath))
if (!isCorrectArguments(actualValues)) {
return
}
var fileBytes: ByteArray = ByteArray(0)
try {
FileInputStream(flashFilePath).use { fis ->
fileBytes = ByteArray(fis.available())
fis.read(fileBytes)
}
} catch (e: IOException) {
e.printStackTrace()
println("error reading file $flashFilePath")
return
}
saveFileConfig(actualValues)
val uploadObject = Upload.BuilderUpload(fileBytes).build()
val uploadBytes = ByteArray(uploadObject.getSizeNoTag())
uploadObject.writeTo(CodedOutputStream(uploadBytes))
val request = DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/loadBin", Unpooled.copiedBuffer(uploadBytes))
request.headers().set(HttpHeaderNames.HOST, host)
request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE)
request.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes())
request.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8")
val clientInstance = Client(host, port)
clientInstance.sendRequest(request)
val requestResult = client.ClientHandler.requestResult
var printString: String = ""
synchronized(requestResult, {
printString = "result code: ${requestResult.code}"
})
println(printString)
} | mit |
jeksor/Language-Detector | app/src/main/java/com/esorokin/lantector/presentation/error/ErrorProcessor.kt | 1 | 225 | package com.esorokin.lantector.presentation.error
/**
* Using by presenters for localize domain exceptions into user friendly messages.
*/
interface ErrorProcessor {
fun processError(throwable: Throwable): UserError
}
| mit |
Orchextra/orchextra-android-sdk | core/src/main/java/com/gigigo/orchextra/core/domain/actions/ActionHandlerService.kt | 1 | 1892 | /*
* Created by Orchextra
*
* Copyright (C) 2017 Gigigo Mobile Services SL
*
* 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.gigigo.orchextra.core.domain.actions
import android.app.IntentService
import android.content.Context
import android.content.Intent
import android.util.Log
import com.gigigo.orchextra.core.domain.entities.Action
class ActionHandlerService : IntentService(TAG) {
override fun onHandleIntent(intent: Intent?) {
val actionDispatcher: ActionDispatcher = ActionDispatcher.create(this)
val action = intent?.getParcelableExtra<Action>(ACTION_EXTRA)
if (action == null) {
Log.d(TAG, "Action empty")
return
}
Log.d(TAG, "Execute action: $action")
actionDispatcher.executeAction(action)
}
companion object {
private const val TAG = "ActionHandlerService"
const val ACTION_EXTRA = "action_extra"
}
}
class ActionHandlerServiceExecutor(val context: Context) {
fun execute(action: Action) {
val intent = Intent(context, ActionHandlerService::class.java)
intent.putExtra(ActionHandlerService.ACTION_EXTRA, action)
context.startService(intent)
}
companion object Factory {
fun create(context: Context): ActionHandlerServiceExecutor = ActionHandlerServiceExecutor(
context
)
}
} | apache-2.0 |
is00hcw/anko | dsl/testData/functional/sdk23/SimpleListenerTest.kt | 2 | 7931 | public fun android.view.View.onLayoutChange(l: (v: android.view.View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) -> Unit) {
addOnLayoutChangeListener(l)
}
public fun android.gesture.GestureOverlayView.onGesturePerformed(l: (overlay: android.gesture.GestureOverlayView?, gesture: android.gesture.Gesture?) -> Unit) {
addOnGesturePerformedListener(l)
}
public fun android.media.tv.TvView.onUnhandledInputEvent(l: (event: android.view.InputEvent?) -> Boolean) {
setOnUnhandledInputEventListener(l)
}
public fun android.view.View.onApplyWindowInsets(l: (v: android.view.View?, insets: android.view.WindowInsets?) -> android.view.WindowInsets?) {
setOnApplyWindowInsetsListener(l)
}
public fun android.view.View.onClick(l: (v: android.view.View?) -> Unit) {
setOnClickListener(l)
}
public fun android.view.View.onContextClick(l: (v: android.view.View?) -> Boolean) {
setOnContextClickListener(l)
}
public fun android.view.View.onCreateContextMenu(l: (menu: android.view.ContextMenu?, v: android.view.View?, menuInfo: android.view.ContextMenu.ContextMenuInfo?) -> Unit) {
setOnCreateContextMenuListener(l)
}
public fun android.view.View.onDrag(l: (v: android.view.View, event: android.view.DragEvent) -> Boolean) {
setOnDragListener(l)
}
public fun android.view.View.onFocusChange(l: (v: android.view.View, hasFocus: Boolean) -> Unit) {
setOnFocusChangeListener(l)
}
public fun android.view.View.onGenericMotion(l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean) {
setOnGenericMotionListener(l)
}
public fun android.view.View.onHover(l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean) {
setOnHoverListener(l)
}
public fun android.view.View.onKey(l: (v: android.view.View, keyCode: Int, event: android.view.KeyEvent?) -> Boolean) {
setOnKeyListener(l)
}
public fun android.view.View.onLongClick(l: (v: android.view.View?) -> Boolean) {
setOnLongClickListener(l)
}
public fun android.view.View.onScrollChange(l: (v: android.view.View?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) -> Unit) {
setOnScrollChangeListener(l)
}
public fun android.view.View.onSystemUiVisibilityChange(l: (visibility: Int) -> Unit) {
setOnSystemUiVisibilityChangeListener(l)
}
public fun android.view.View.onTouch(l: (v: android.view.View, event: android.view.MotionEvent) -> Boolean) {
setOnTouchListener(l)
}
public fun android.view.ViewStub.onInflate(l: (stub: android.view.ViewStub?, inflated: android.view.View?) -> Unit) {
setOnInflateListener(l)
}
public fun android.widget.ActionMenuView.onMenuItemClick(l: (item: android.view.MenuItem?) -> Boolean) {
setOnMenuItemClickListener(l)
}
public fun android.widget.AdapterView<out android.widget.Adapter?>.onClick(l: (v: android.view.View?) -> Unit) {
setOnClickListener(l)
}
public fun android.widget.AdapterView<out android.widget.Adapter?>.onItemClick(l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit) {
setOnItemClickListener(l)
}
public fun android.widget.AdapterView<out android.widget.Adapter?>.onItemLongClick(l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Boolean) {
setOnItemLongClickListener(l)
}
public fun android.widget.AutoCompleteTextView.onClick(l: (v: android.view.View?) -> Unit) {
setOnClickListener(l)
}
public fun android.widget.AutoCompleteTextView.onDismiss(l: () -> Unit) {
setOnDismissListener(l)
}
public fun android.widget.AutoCompleteTextView.onItemClick(l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit) {
setOnItemClickListener(l)
}
public fun android.widget.CalendarView.onDateChange(l: (view: android.widget.CalendarView?, year: Int, month: Int, dayOfMonth: Int) -> Unit) {
setOnDateChangeListener(l)
}
public fun android.widget.Chronometer.onChronometerTick(l: (chronometer: android.widget.Chronometer?) -> Unit) {
setOnChronometerTickListener(l)
}
public fun android.widget.CompoundButton.onCheckedChange(l: (buttonView: android.widget.CompoundButton?, isChecked: Boolean) -> Unit) {
setOnCheckedChangeListener(l)
}
public fun android.widget.ExpandableListView.onChildClick(l: (parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, childPosition: Int, id: Long) -> Boolean) {
setOnChildClickListener(l)
}
public fun android.widget.ExpandableListView.onGroupClick(l: (parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, id: Long) -> Boolean) {
setOnGroupClickListener(l)
}
public fun android.widget.ExpandableListView.onGroupCollapse(l: (groupPosition: Int) -> Unit) {
setOnGroupCollapseListener(l)
}
public fun android.widget.ExpandableListView.onGroupExpand(l: (groupPosition: Int) -> Unit) {
setOnGroupExpandListener(l)
}
public fun android.widget.ExpandableListView.onItemClick(l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit) {
setOnItemClickListener(l)
}
public fun android.widget.NumberPicker.onScroll(l: (view: android.widget.NumberPicker?, scrollState: Int) -> Unit) {
setOnScrollListener(l)
}
public fun android.widget.NumberPicker.onValueChanged(l: (picker: android.widget.NumberPicker?, oldVal: Int, newVal: Int) -> Unit) {
setOnValueChangedListener(l)
}
public fun android.widget.RadioGroup.onCheckedChange(l: (group: android.widget.RadioGroup?, checkedId: Int) -> Unit) {
setOnCheckedChangeListener(l)
}
public fun android.widget.RatingBar.onRatingBarChange(l: (ratingBar: android.widget.RatingBar?, rating: Float, fromUser: Boolean) -> Unit) {
setOnRatingBarChangeListener(l)
}
public fun android.widget.SearchView.onClose(l: () -> Boolean) {
setOnCloseListener(l)
}
public fun android.widget.SearchView.onQueryTextFocusChange(l: (v: android.view.View, hasFocus: Boolean) -> Unit) {
setOnQueryTextFocusChangeListener(l)
}
public fun android.widget.SearchView.onSearchClick(l: (v: android.view.View?) -> Unit) {
setOnSearchClickListener(l)
}
public fun android.widget.SlidingDrawer.onDrawerClose(l: () -> Unit) {
setOnDrawerCloseListener(l)
}
public fun android.widget.SlidingDrawer.onDrawerOpen(l: () -> Unit) {
setOnDrawerOpenListener(l)
}
public fun android.widget.Spinner.onItemClick(l: (p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit) {
setOnItemClickListener(l)
}
public fun android.widget.TabHost.onTabChanged(l: (tabId: String?) -> Unit) {
setOnTabChangedListener(l)
}
public fun android.widget.TextView.onEditorAction(l: (v: android.widget.TextView?, actionId: Int, event: android.view.KeyEvent?) -> Boolean) {
setOnEditorActionListener(l)
}
public fun android.widget.TimePicker.onTimeChanged(l: (view: android.widget.TimePicker?, hourOfDay: Int, minute: Int) -> Unit) {
setOnTimeChangedListener(l)
}
public fun android.widget.Toolbar.onMenuItemClick(l: (item: android.view.MenuItem?) -> Boolean) {
setOnMenuItemClickListener(l)
}
public fun android.widget.VideoView.onCompletion(l: (mp: android.media.MediaPlayer?) -> Unit) {
setOnCompletionListener(l)
}
public fun android.widget.VideoView.onError(l: (mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Boolean) {
setOnErrorListener(l)
}
public fun android.widget.VideoView.onInfo(l: (mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Boolean) {
setOnInfoListener(l)
}
public fun android.widget.VideoView.onPrepared(l: (mp: android.media.MediaPlayer?) -> Unit) {
setOnPreparedListener(l)
}
public fun android.widget.ZoomControls.onZoomInClick(l: (v: android.view.View?) -> Unit) {
setOnZoomInClickListener(l)
}
public fun android.widget.ZoomControls.onZoomOutClick(l: (v: android.view.View?) -> Unit) {
setOnZoomOutClickListener(l)
} | apache-2.0 |
niranjan94/show-java | app/src/main/kotlin/com/njlabs/showjava/decompilers/BaseDecompiler.kt | 1 | 10687 | /*
* Show Java - A java/apk decompiler for android
* Copyright (c) 2018 Niranjan Rajendran
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.njlabs.showjava.decompilers
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.work.*
import com.njlabs.showjava.BuildConfig
import com.njlabs.showjava.Constants
import com.njlabs.showjava.R
import com.njlabs.showjava.data.PackageInfo
import com.njlabs.showjava.utils.ProcessNotifier
import com.njlabs.showjava.utils.UserPreferences
import com.njlabs.showjava.utils.ktx.appStorage
import com.njlabs.showjava.utils.ktx.cleanMemory
import com.njlabs.showjava.utils.streams.ProgressStream
import com.njlabs.showjava.workers.DecompilerWorker
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import org.apache.commons.io.FileUtils
import timber.log.Timber
import java.io.File
import java.io.PrintStream
import java.util.concurrent.TimeUnit
/**
* The base decompiler. This reads the input [Data] into easy to use properties of the class.
* All other components of the decompiler will extend this one.
*/
abstract class BaseDecompiler(val context: Context, val data: Data) {
var printStream: PrintStream? = null
private var id = data.getString("id")
private var processNotifier: ProcessNotifier? = null
private var runAttemptCount: Int = 0
protected var outOfMemory = false
protected val decompiler = data.getString("decompiler")
protected val type = PackageInfo.Type.values()[data.getInt("type", 0)]
private val maxAttempts = data.getInt("maxAttempts", UserPreferences.DEFAULTS.MAX_ATTEMPTS)
private val memoryThreshold = data.getInt("memoryThreshold", 80)
protected val packageName = data.getString("name").toString()
protected val packageLabel = data.getString("label").toString()
protected val keepIntermediateFiles = data.getBoolean("keepIntermediateFiles", UserPreferences.DEFAULTS.KEEP_INTERMEDIATE_FILES)
protected val workingDirectory: File = appStorage.resolve("sources/$packageName/")
protected val cacheDirectory: File = appStorage.resolve("sources/.cache/")
protected val inputPackageFile: File = File(data.getString("inputPackageFile"))
protected val outputDexFiles: File = workingDirectory.resolve("dex-files")
protected val outputJarFiles: File = workingDirectory.resolve("jar-files")
protected val outputSrcDirectory: File = workingDirectory.resolve("src")
protected val outputJavaSrcDirectory: File = outputSrcDirectory.resolve("java")
private val disposables = CompositeDisposable()
private var onLowMemory: ((Boolean) -> Unit)? = null
private var memoryThresholdCrossCount = 0
protected open val maxMemoryAdjustmentFactor = 1.25
init {
@Suppress("LeakingThis")
printStream = PrintStream(ProgressStream(this))
System.setErr(printStream)
System.setOut(printStream)
}
/**
* Prepare the required directories.
* All child classes must call this method on override.
*/
open fun doWork(): ListenableWorker.Result {
cleanMemory()
monitorMemory()
outputJavaSrcDirectory.mkdirs()
if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
data.keyValueMap.forEach { t, u ->
Timber.d("[WORKER] [INPUT] $t: $u")
}
}
return ListenableWorker.Result.success()
}
fun withAttempt(attempt: Int = 0): ListenableWorker.Result {
this.runAttemptCount = attempt
return this.doWork()
}
fun withNotifier(notifier: ProcessNotifier): BaseDecompiler {
this.processNotifier = notifier
return this
}
fun withLowMemoryCallback(onLowMemory: ((Boolean) -> Unit)): BaseDecompiler {
this.onLowMemory = onLowMemory
return this
}
private fun monitorMemory() {
disposables.add(
Observable.interval(1000, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe {
val maxAdjusted = Runtime.getRuntime().maxMemory() / maxMemoryAdjustmentFactor
val used = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()).toDouble().let { m ->
if (m > maxAdjusted) maxAdjusted else m
}
val usedPercentage = (used / maxAdjusted) * 100
Timber.d("[mem] ----")
Timber.d("[mem] Used: ${FileUtils.byteCountToDisplaySize(used.toLong())}")
Timber.d("[mem] Max: ${FileUtils.byteCountToDisplaySize(maxAdjusted.toLong())} at factor $maxMemoryAdjustmentFactor")
Timber.d("[mem] Used %: $usedPercentage")
broadcastStatus("memory", "%.2f".format(usedPercentage), "memory")
if (usedPercentage > memoryThreshold) {
if (memoryThresholdCrossCount > 2) {
onLowMemory?.invoke(true)
} else {
memoryThresholdCrossCount++
}
} else {
memoryThresholdCrossCount = 0
}
}
)
}
/**
* Update the notification and broadcast status
*/
protected fun sendStatus(title: String, message: String, forceSet: Boolean = false) {
processNotifier?.updateTitleText(title, message, forceSet)
this.broadcastStatus(title, message)
}
fun sendStatus(message: String, forceSet: Boolean = false) {
processNotifier?.updateText(message, forceSet)
this.broadcastStatus(null, message)
}
/**
* Set the current decompilation step
*/
fun setStep(title: String) {
sendStatus(title, context.getString(R.string.initializing), true)
}
/**
* Clear the notification and exit marking the work job as failed
*/
protected fun exit(exception: Exception?): ListenableWorker.Result {
Timber.e(exception)
onStopped()
disposables.clear()
return if (runAttemptCount >= (maxAttempts - 1))
ListenableWorker.Result.failure()
else
ListenableWorker.Result.retry()
}
/**
* Return a success only if the conditions is true. Else exit with an exception.
*/
protected fun successIf(condition: Boolean): ListenableWorker.Result {
disposables.clear()
return if (condition)
ListenableWorker.Result.success()
else
exit(Exception("Success condition failed"))
}
/**
* Broadcast the status to the receiver
*/
private fun broadcastStatus(title: String?, message: String, type: String = "progress") {
context.sendBroadcast(
Intent(Constants.WORKER.ACTION.BROADCAST + packageName)
.putExtra(Constants.WORKER.STATUS_TITLE, title)
.putExtra(Constants.WORKER.STATUS_MESSAGE, message)
.putExtra(Constants.WORKER.STATUS_TYPE, type)
)
}
/**
* Build a persistent notification
*/
protected fun buildNotification(title: String) {
if (processNotifier == null) {
processNotifier = ProcessNotifier(context, id)
}
processNotifier!!.buildFor(
title,
packageName,
packageLabel,
inputPackageFile,
context.resources.getStringArray(R.array.decompilersValues).indexOf(decompiler)
)
}
/**
* Clear notifications and show a success notification.
*/
fun onCompleted() {
processNotifier?.success()
broadcastStatus(
context.getString(R.string.appHasBeenDecompiled, packageLabel),
""
)
}
/**
* Cancel notification on worker stop
*/
open fun onStopped() {
Timber.d("[cancel-request] cancelled")
disposables.clear()
processNotifier?.cancel()
}
companion object {
/**
* Check if the specified decompiler is available on the device based on the android version
*/
fun isAvailable(decompiler: String): Boolean {
return when (decompiler) {
"cfr" -> true
"jadx" -> Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
"fernflower" -> Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
else -> false
}
}
/**
* For the WorkManager compatible Data object from the given map
*/
fun formData(dataMap: Map<String, Any>): Data {
val id = dataMap["name"] as String
return Data.Builder()
.putAll(dataMap)
.putString("id", id)
.build()
}
/**
* Start the jobs using the given map
*/
fun start(dataMap: Map<String, Any>): String {
val data = formData(dataMap)
val id = data.getString("id")!!
fun buildWorkRequest(type: String): OneTimeWorkRequest {
return OneTimeWorkRequestBuilder<DecompilerWorker>()
.addTag("decompile")
.addTag(type)
.addTag(id)
.setBackoffCriteria(BackoffPolicy.LINEAR, 0, TimeUnit.SECONDS)
.setInputData(data)
.build()
}
WorkManager.getInstance()
.beginUniqueWork(
id,
ExistingWorkPolicy.REPLACE,
buildWorkRequest("jar-extraction")
)
.then(buildWorkRequest("java-extraction"))
.then(buildWorkRequest("resources-extraction"))
.enqueue()
return id
}
}
class OutOfMemoryError: Exception()
} | gpl-3.0 |
oldergod/red | app/src/main/java/com/benoitquenaudon/tvfoot/red/injection/module/ServiceModule.kt | 1 | 679 | package com.benoitquenaudon.tvfoot.red.injection.module
import android.app.AlarmManager
import android.content.Context
import com.benoitquenaudon.tvfoot.red.RedApp
import com.benoitquenaudon.tvfoot.red.api.TvfootService
import dagger.Module
import dagger.Provides
import retrofit2.Retrofit
import javax.inject.Singleton
@Module
object ServiceModule {
@JvmStatic
@Provides
@Singleton
fun provideTvfootService(retrofit: Retrofit): TvfootService {
return retrofit.create(TvfootService::class.java)
}
@JvmStatic
@Provides
fun provideAlarmManager(context: RedApp): AlarmManager {
return context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
}
}
| apache-2.0 |
matejdro/WearMusicCenter | wear/src/main/java/com/matejdro/wearmusiccenter/watch/view/RecyclerClickDetector.kt | 1 | 2687 | package com.matejdro.wearmusiccenter.watch.view
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.widget.FrameLayout
import kotlin.math.abs
import kotlin.math.roundToLong
/**
* RecyclerView does not support click detection for whole view. This wrapper view provides that.
*/
class RecyclerClickDetector @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private var pressX = 0f
private var pressY = 0f
private var prePressed = false
private val maxAllowedPressMovement = ViewConfiguration.get(context).scaledTouchSlop
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
if (!isClickable) {
return false
}
when (ev.actionMasked) {
MotionEvent.ACTION_DOWN -> {
pressX = ev.x
pressY = ev.y
postDelayed(pressRunnable, ViewConfiguration.getTapTimeout().toLong())
prePressed = true
}
MotionEvent.ACTION_MOVE -> {
if (prePressed) {
drawableHotspotChanged(ev.x, ev.y)
val newY = ev.y.roundToLong()
val oldYRound = pressY.roundToLong()
val fingerMovedY = abs(newY - oldYRound)
if (fingerMovedY > maxAllowedPressMovement) {
// We are scrolling.
cancelPress()
}
}
}
MotionEvent.ACTION_UP -> {
removeCallbacks(pressRunnable)
if (prePressed) {
performClick()
isPressed = true
isPressed = false
prePressed = false
return true
}
prePressed = false
}
MotionEvent.ACTION_CANCEL -> {
cancelPress()
}
}
return isPressed
}
private fun cancelPress() {
prePressed = false
isPressed = false
removeCallbacks(pressRunnable)
}
private val pressRunnable = Runnable {
drawableHotspotChanged(pressX, pressY)
isPressed = true
}
override fun setClickable(clickable: Boolean) {
super.setClickable(clickable)
if (!clickable) {
cancelPress()
}
}
// Child buttons in RecyclerView should not get pressed when we do
override fun dispatchSetPressed(pressed: Boolean) = Unit
} | gpl-3.0 |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/views/ImagePreviewDialog.kt | 1 | 6208 | package org.wikipedia.views
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import androidx.core.os.bundleOf
import com.google.android.material.bottomsheet.BottomSheetBehavior
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.commons.ImageTagsProvider
import org.wikipedia.databinding.DialogImagePreviewBinding
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.mwapi.MwQueryPage
import org.wikipedia.descriptions.DescriptionEditActivity.Action
import org.wikipedia.page.ExtendedBottomSheetDialogFragment
import org.wikipedia.suggestededits.PageSummaryForEdit
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.L10nUtil.setConditionalLayoutDirection
import org.wikipedia.util.StringUtil
import org.wikipedia.util.log.L
class ImagePreviewDialog : ExtendedBottomSheetDialogFragment(), DialogInterface.OnDismissListener {
private var _binding: DialogImagePreviewBinding? = null
private val binding get() = _binding!!
private lateinit var pageSummaryForEdit: PageSummaryForEdit
private var action: Action? = null
private val disposables = CompositeDisposable()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = DialogImagePreviewBinding.inflate(inflater, container, false)
pageSummaryForEdit = requireArguments().getParcelable(ARG_SUMMARY)!!
action = requireArguments().getSerializable(ARG_ACTION) as Action?
setConditionalLayoutDirection(binding.root, pageSummaryForEdit.lang)
return binding.root
}
override fun onStart() {
super.onStart()
BottomSheetBehavior.from(requireView().parent as View).peekHeight = DimenUtil.roundedDpToPx(DimenUtil.getDimension(R.dimen.imagePreviewSheetPeekHeight))
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.progressBar.visibility = VISIBLE
binding.toolbarView.setOnClickListener { dismiss() }
binding.titleText.text = StringUtil.removeHTMLTags(StringUtil.removeNamespace(pageSummaryForEdit.displayTitle!!))
loadImageInfo()
}
override fun onDestroyView() {
binding.toolbarView.setOnClickListener(null)
_binding = null
disposables.clear()
super.onDestroyView()
}
private fun showError(caught: Throwable?) {
binding.dialogDetailContainer.layoutTransition = null
binding.dialogDetailContainer.minimumHeight = 0
binding.progressBar.visibility = GONE
binding.filePageView.visibility = GONE
binding.errorView.visibility = VISIBLE
binding.errorView.setError(caught, pageSummaryForEdit.pageTitle)
}
private fun loadImageInfo() {
lateinit var imageTags: Map<String, List<String>>
lateinit var page: MwQueryPage
var isFromCommons = false
var thumbnailWidth = 0
var thumbnailHeight = 0
disposables.add(ServiceFactory.get(Constants.commonsWikiSite).getImageInfo(pageSummaryForEdit.title, pageSummaryForEdit.lang)
.subscribeOn(Schedulers.io())
.flatMap {
if (it.query?.firstPage()?.imageInfo() == null) {
// If file page originally comes from *.wikipedia.org (i.e. movie posters), it will not have imageInfo and pageId.
ServiceFactory.get(pageSummaryForEdit.pageTitle.wikiSite).getImageInfo(pageSummaryForEdit.title, pageSummaryForEdit.lang)
} else {
// Fetch API from commons.wikimedia.org and check whether if it is not a "shared" image.
isFromCommons = it.query?.firstPage()?.isImageShared != true
Observable.just(it)
}
}
.flatMap { response ->
page = response.query?.firstPage()!!
page.imageInfo()?.let {
pageSummaryForEdit.timestamp = it.timestamp
pageSummaryForEdit.user = it.user
pageSummaryForEdit.metadata = it.metadata
thumbnailWidth = it.thumbWidth
thumbnailHeight = it.thumbHeight
}
ImageTagsProvider.getImageTagsObservable(page.pageId, pageSummaryForEdit.lang)
}
.observeOn(AndroidSchedulers.mainThread())
.doAfterTerminate {
binding.filePageView.visibility = VISIBLE
binding.progressBar.visibility = GONE
binding.filePageView.setup(
pageSummaryForEdit,
imageTags,
page,
binding.dialogDetailContainer.width,
thumbnailWidth, thumbnailHeight,
imageFromCommons = isFromCommons,
showFilename = false,
showEditButton = false,
action = action
)
}
.subscribe({ imageTags = it }, { caught ->
L.e(caught)
showError(caught)
}))
}
companion object {
private const val ARG_SUMMARY = "summary"
private const val ARG_ACTION = "action"
fun newInstance(pageSummaryForEdit: PageSummaryForEdit, action: Action? = null): ImagePreviewDialog {
val dialog = ImagePreviewDialog()
dialog.arguments = bundleOf(ARG_SUMMARY to pageSummaryForEdit,
ARG_ACTION to action)
return dialog
}
}
}
| apache-2.0 |
BilledTrain380/sporttag-psa | app/psa-runtime-service/psa-service-athletics/src/main/kotlin/ch/schulealtendorf/psa/service/athletics/business/DisciplineManagerImpl.kt | 1 | 2460 | /*
* Copyright (c) 2018 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA 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.
*
* Sporttag PSA 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 Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.service.athletics.business
import ch.schulealtendorf.psa.dto.participation.athletics.DisciplineDto
import ch.schulealtendorf.psa.service.standard.disciplineDtoOf
import ch.schulealtendorf.psa.service.standard.repository.DisciplineRepository
import org.springframework.stereotype.Component
import java.util.Optional
/**
* Default implementation for a {@link DisciplineManager} which uses repositories to get its data.
*
* @author nmaerchy <[email protected]>
* @since 2.0.0
*/
@Component
class DisciplineManagerImpl(
private val disciplineRepository: DisciplineRepository
) : DisciplineManager {
override fun getDisciplines(): List<DisciplineDto> {
return disciplineRepository.findAll().map { disciplineDtoOf(it) }
}
override fun getDiscipline(name: String): Optional<DisciplineDto> {
return disciplineRepository.findById(name).map { disciplineDtoOf(it) }
}
}
| gpl-3.0 |
matejdro/WearMusicCenter | wear/src/main/java/com/matejdro/wearmusiccenter/watch/communication/PreferencesReceiver.kt | 1 | 901 | package com.matejdro.wearmusiccenter.watch.communication
import android.annotation.SuppressLint
import android.content.SharedPreferences
import android.preference.PreferenceManager
import com.google.android.gms.wearable.DataEventBuffer
import com.matejdro.wearmusiccenter.common.CommPaths
import com.matejdro.wearmusiccenter.watch.config.PreferencesBus
import com.matejdro.wearutils.preferencesync.PreferenceReceiverService
class PreferencesReceiver : PreferenceReceiverService(CommPaths.PREFERENCES_PREFIX) {
@SuppressLint("CommitPrefEdits")
override fun getDestinationPreferences(): SharedPreferences.Editor =
PreferenceManager.getDefaultSharedPreferences(this).edit()
override fun onDataChanged(dataEventBuffer: DataEventBuffer?) {
super.onDataChanged(dataEventBuffer)
PreferencesBus.postValue(PreferenceManager.getDefaultSharedPreferences(this))
}
} | gpl-3.0 |
dsulimchuk/DynamicQuery | src/test/kotlin/com/github/dsulimchuk/dynamicquery/SqlTest.kt | 1 | 3756 | package com.github.dsulimchuk.dynamicquery
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.notNullValue
import org.junit.After
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
import javax.persistence.EntityManager
import javax.persistence.EntityManagerFactory
import javax.persistence.Persistence
/**
* @author Dmitrii Sulimchuk
* * created 23/10/16
*/
class SqlTest {
val sessionFactory: EntityManagerFactory = Persistence.createEntityManagerFactory("test")
val em: EntityManager = sessionFactory.createEntityManager()
@Before
fun setUp() {
em.transaction.begin()
}
@After
fun tearDown() {
em.transaction.commit()
em.close()
}
@Test
fun testQueryWithOneParameter() {
val list = Sql<Long> { +"select 1 from dual where :parameter.aa.b = 6" }
.prepare(em, 6)
.resultList as List<*>
assertThat(list, notNullValue())
assertThat(list.size, equalTo(1))
}
@Test
fun testQueryWithSeveralParameter() {
data class SearchCriteria(val a: Long, val b: Long, val c: Long)
val list = Sql<SearchCriteria> { +"select 1 from dual where :a = 1 and :b = 2 and :c = 3" }
.prepare(em, SearchCriteria(1, 2, 3))
.resultList as List<*>
assertThat(list, notNullValue())
assertThat(list.size, equalTo(1))
}
@Test
fun testQueryWithListParameter() {
val list = Sql<List<Long>> { +"select 1 from dual where 1 in :parameter" }
.prepare(em, listOf(1, 2, 3, 4, 5))
.resultList as List<*>
assertThat(list, notNullValue())
assertThat(list.size, equalTo(1))
}
@Test
fun exampleQuery() {
val sq = SearchCriteria(1, "viktor", 10.0, "branch_name, service_name")
val result = query
.prepare(em, sq)
.resultList
assertNotNull(result)
}
@Test
fun exampleQueryWithSpecificProjection() {
val sq = SearchCriteria(null, "viktor", 10.0, "branch_name, service_name")
val result = query
.prepare(em, sq, "service_name")
.resultList as List<*>
assertNotNull(result)
}
private val query = Sql<SearchCriteria> {
+"""
select t.*
from (select u.*
,s.name service_name
,b.name branch_name
from users u
left join users_services t on (u.id = t.users_id)
left join services s on (t.services_id = s.id)
left join branches b on (s.branch_id = b.id)
where 1=1
&m1
)t
order by &orderMacros
"""
projection["service_name"] = "service_name"
//now we can declare macros m1. At runtime it will be computed on given search Criteria
m("m1") {
test({ parameter.id != null }) {
+"and u.id = :id"
}
test({ !parameter.name.isNullOrEmpty() }) {
+"and upper(s.name) like upper(:name)"
}
test({ parameter.salary != null }) {
+"and u.salary < :salary"
}
}
//order by macros
m("orderMacros") {
test({ parameter.sort.isBlank() }) {
+"name" //default sort order
}
test({ parameter.sort.isNotBlank() }) {
+parameter.sort
}
}
}
data class SearchCriteria(val id: Long?,
val name: String?,
val salary: Double?,
val sort: String = "")
}
| mit |
stripe/stripe-android | payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/CardBillingSpec.kt | 1 | 1747 | package com.stripe.android.ui.core.elements
import androidx.annotation.RestrictTo
import com.stripe.android.ui.core.R
import com.stripe.android.ui.core.address.AddressRepository
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
@Serializable
data class CardBillingSpec(
@SerialName("api_path")
override val apiPath: IdentifierSpec = IdentifierSpec.Generic("card_billing"),
@SerialName("allowed_country_codes")
val allowedCountryCodes: Set<String> = supportedBillingCountries
) : FormItemSpec() {
fun transform(
initialValues: Map<IdentifierSpec, String?>,
addressRepository: AddressRepository,
shippingValues: Map<IdentifierSpec, String?>?
): SectionElement {
val sameAsShippingElement =
shippingValues?.get(IdentifierSpec.SameAsShipping)
?.toBooleanStrictOrNull()
?.let {
SameAsShippingElement(
identifier = IdentifierSpec.SameAsShipping,
controller = SameAsShippingController(it)
)
}
val addressElement = CardBillingAddressElement(
IdentifierSpec.Generic("credit_billing"),
addressRepository = addressRepository,
countryCodes = allowedCountryCodes,
rawValuesMap = initialValues,
sameAsShippingElement = sameAsShippingElement,
shippingValuesMap = shippingValues
)
return createSectionElement(
listOfNotNull(
addressElement,
sameAsShippingElement
),
R.string.billing_details
)
}
}
| mit |
kotlinz/kotlinz | src/main/kotlin/com/github/kotlinz/kotlinz/data/kleisli/KleisliCompose.kt | 1 | 553 | package com.github.kotlinz.kotlinz.data.kleisli
import com.github.kotlinz.kotlinz.K3
import com.github.kotlinz.kotlinz.type.category.Compose
import com.github.kotlinz.kotlinz.type.monad.Monad
interface KleisliCompose<F> : Compose<Kleisli.T, F> {
val monad: Monad<F>
override fun <A, B, C> compose(f: K3<Kleisli.T, F, B, C>, g: K3<Kleisli.T, F, A, B>): Kleisli<F, A, C> {
val fk = Kleisli.narrow(f)
val gk = Kleisli.narrow(g)
return Kleisli(monad) { a -> monad.bind(fk.run, monad.bind(gk.run, monad.pure(a))) }
}
} | apache-2.0 |
hannesa2/owncloud-android | owncloudDomain/src/main/java/com/owncloud/android/domain/exceptions/SpecificUnsupportedMediaTypeException.kt | 2 | 842 | /**
* ownCloud Android client application
*
* @author David González Verdugo
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.domain.exceptions
import java.lang.Exception
class SpecificUnsupportedMediaTypeException : Exception()
| gpl-2.0 |
ioc1778/incubator | incubator-events/src/main/java/com/riaektiv/events/LongEventProducer.kt | 2 | 686 | package com.riaektiv.events
import com.lmax.disruptor.RingBuffer
import java.nio.ByteBuffer
/**
* Coding With Passion Since 1991
* Created: 11/24/2016, 10:12 AM Eastern Time
* @author Sergey Chuykov
*/
class LongEventProducer : EventProducer<ByteBuffer, LongEvent> {
lateinit var ringBuffer: RingBuffer<LongEvent>
override fun set(ringBuffer: RingBuffer<LongEvent>) {
this.ringBuffer = ringBuffer
}
override fun onMessage(msg: ByteBuffer) {
val seq = ringBuffer.next()
try {
val event = ringBuffer.get(seq)
event.value = msg.getLong(0)
} finally {
ringBuffer.publish(seq)
}
}
} | bsd-3-clause |
Prokky/AsciiPanelView | asciipanelview/src/test/java/com/prokkypew/asciipanelview/CustomTestRunner.kt | 1 | 1499 | package com.prokkypew.asciipanelview
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.manifest.AndroidManifest
import org.robolectric.res.FileFsFile
/**
* Created by alexander.roman on 21.08.2017.
*/
class CustomTestRunner
constructor(klass: Class<*>) : RobolectricTestRunner(klass) {
private val BUILD_OUTPUT = "build/intermediates";
private val BUILD_OUTPUT_APP_LEVEL = "asciipanelview/build/intermediates"
override fun getAppManifest(config: Config): AndroidManifest {
var res = FileFsFile.from(BUILD_OUTPUT, "/res/merged", BuildConfig.FLAVOR, BuildConfig.BUILD_TYPE)
var assets = FileFsFile.from(BUILD_OUTPUT, "bundles", BuildConfig.FLAVOR, BuildConfig.BUILD_TYPE, "assets")
var manifest = FileFsFile.from(BUILD_OUTPUT, "manifests", "full", BuildConfig.FLAVOR, BuildConfig.BUILD_TYPE, "AndroidManifest.xml")
if (!manifest.exists()) {
manifest = FileFsFile.from(BUILD_OUTPUT_APP_LEVEL, "manifests", "full", BuildConfig.FLAVOR, BuildConfig.BUILD_TYPE, "AndroidManifest.xml")
}
if (!res.exists()) {
res = FileFsFile.from(BUILD_OUTPUT_APP_LEVEL, "/res/merged", BuildConfig.FLAVOR, BuildConfig.BUILD_TYPE)
}
if (!assets.exists()) {
assets = FileFsFile.from(BUILD_OUTPUT_APP_LEVEL, "bundles", BuildConfig.FLAVOR, BuildConfig.BUILD_TYPE, "assets")
}
return AndroidManifest(manifest, res, assets)
}
} | apache-2.0 |
TeamWizardry/LibrarianLib | testcore/src/main/kotlin/com/teamwizardry/librarianlib/testcore/content/impl/TestBlockImpl.kt | 1 | 6397 | package com.teamwizardry.librarianlib.testcore.content.impl
import com.teamwizardry.librarianlib.core.util.kotlin.threadLocal
import com.teamwizardry.librarianlib.testcore.content.TestBlock
import net.minecraft.block.Block
import net.minecraft.block.BlockState
import net.minecraft.block.FacingBlock
import net.minecraft.entity.LivingEntity
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.item.ItemPlacementContext
import net.minecraft.item.ItemStack
import net.minecraft.loot.context.LootContext
import net.minecraft.server.world.ServerWorld
import net.minecraft.state.StateManager
import net.minecraft.state.property.DirectionProperty
import net.minecraft.state.property.Properties
import net.minecraft.util.*
import net.minecraft.util.hit.BlockHitResult
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Direction
import net.minecraft.world.*
import java.util.Random
public open class TestBlockImpl(public val config: TestBlock): Block(config.also { configHolder = it }.properties) {
init {
if (config.directional) {
this.defaultState = this.stateManager.defaultState.with(FACING, Direction.UP)
}
}
public open val modelName: String
get() = "${if (config.directional) "directional" else "normal"}/${if (config.transparent) "transparent" else "solid"}"
override fun getDroppedStacks(state: BlockState, builder: LootContext.Builder): MutableList<ItemStack> {
return mutableListOf()
}
override fun rotate(state: BlockState, rotation: BlockRotation): BlockState {
if (!config.directional)
return state
return state.with(FacingBlock.FACING, rotation.rotate(state.get(FACING)))
}
override fun mirror(state: BlockState, mirror: BlockMirror): BlockState {
if (!config.directional)
return state
return state.with(FacingBlock.FACING, mirror.apply(state.get(FACING)))
}
override fun getPlacementState(ctx: ItemPlacementContext): BlockState? {
if (!config.directional)
return super.getPlacementState(ctx)
val direction = ctx.side
val blockstate = ctx.world.getBlockState(ctx.blockPos.offset(direction.opposite))
return if (blockstate.block === this && blockstate.get(FACING) == direction) this.defaultState.with(FACING, direction.opposite) else this.defaultState.with(
FACING, direction)
}
override fun appendProperties(builder: StateManager.Builder<Block, BlockState>) {
if (!configHolder!!.directional)
return
builder.add(FACING)
}
// ticks ===========================================================================================================
override fun randomDisplayTick(state: BlockState, world: World, pos: BlockPos, random: Random) {
super.randomDisplayTick(state, world, pos, random)
}
@Suppress("DEPRECATION")
override fun scheduledTick(state: BlockState, world: ServerWorld, pos: BlockPos, random: Random) {
super.scheduledTick(state, world, pos, random)
}
@Suppress("DEPRECATION")
override fun randomTick(state: BlockState, worldIn: ServerWorld, pos: BlockPos, random: Random) {
super.randomTick(state, worldIn, pos, random)
}
// placed/broken ===================================================================================================
@Suppress("DEPRECATION")
override fun onBlockAdded(state: BlockState, world: World, pos: BlockPos, oldState: BlockState, notify: Boolean) {
super.onBlockAdded(state, world, pos, oldState, notify)
}
@Suppress("DEPRECATION")
override fun getStateForNeighborUpdate(state: BlockState, direction: Direction, newState: BlockState, world: WorldAccess, pos: BlockPos, posFrom: BlockPos): BlockState {
return super.getStateForNeighborUpdate(state, direction, newState, world, pos, posFrom)
}
override fun onBreak(world: World, pos: BlockPos, state: BlockState, player: PlayerEntity) {
if (config.destroy.exists)
config.destroy.run(world.isClient, TestBlock.DestroyContext(state, world, pos, player))
else
super.onBreak(world, pos, state, player)
}
override fun onPlaced(worldIn: World, pos: BlockPos, state: BlockState, placer: LivingEntity?, stack: ItemStack) {
if (placer is PlayerEntity)
config.place.run(worldIn.isClient, TestBlock.PlaceContext(state, worldIn, pos, placer, stack))
else
super.onPlaced(worldIn, pos, state, placer, stack)
}
// interaction =====================================================================================================
override fun onUse(
state: BlockState,
world: World,
pos: BlockPos,
player: PlayerEntity,
hand: Hand,
hit: BlockHitResult
): ActionResult {
config.rightClick.run(world.isClient, TestBlock.RightClickContext(state, world, pos, player, hand, hit))
if (config.rightClick.exists)
return ActionResult.CONSUME
else
return super.onUse(state, world, pos, player, hand, hit)
}
override fun onBlockBreakStart(state: BlockState, world: World, pos: BlockPos, player: PlayerEntity) {
if (config.leftClick.exists)
config.leftClick.run(world.isClient, TestBlock.LeftClickContext(state, world, pos, player))
else
super.onBlockBreakStart(state, world, pos, player)
}
// misc ============================================================================================================
override fun neighborUpdate(
state: BlockState,
world: World,
pos: BlockPos,
block: Block,
fromPos: BlockPos,
notify: Boolean
) {
super.neighborUpdate(state, world, pos, block, fromPos, notify)
}
override fun isSideInvisible(state: BlockState, adjacentBlockState: BlockState, side: Direction): Boolean {
return if (adjacentBlockState.block === this) true else super.isSideInvisible(state, adjacentBlockState, side)
}
public companion object {
public val FACING: DirectionProperty = Properties.FACING
// needed because fillStateContainer is called before we can set the config property
private var configHolder: TestBlock? by threadLocal()
}
}
| lgpl-3.0 |
mvarnagiris/expensius | data/src/main/kotlin/com/mvcoding/expensius/data/MemoryCache.kt | 1 | 1006 | /*
* Copyright (C) 2017 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.expensius.data
import rx.Observable
import rx.lang.kotlin.BehaviorSubject
class MemoryCache<DATA>(dataSource: DataSource<DATA>) : Cache<DATA> {
private val subject = BehaviorSubject<DATA>()
private val dataSource = MemoryDataSource(FunctionDataSource { dataSource.data().mergeWith(subject) })
override fun write(data: DATA): Unit = subject.onNext(data)
override fun data(): Observable<DATA> = dataSource.data()
} | gpl-3.0 |
google/dokka | core/testdata/format/sinceKotlinWide.kt | 3 | 115 | /**
* Useful
*/
@SinceKotlin("1.1")
class `Since1.1`
/**
* Useful also
*/
@SinceKotlin("1.2")
class `Since1.2` | apache-2.0 |
deva666/anko | anko/library/robolectricTests/src/main/java/AndroidLayoutParamsTestActivity.kt | 4 | 1963 | package com.example.android_test
import android.app.Activity
import android.os.Bundle
import android.view.Gravity
import android.widget.RelativeLayout
import org.jetbrains.anko.*
open class AndroidLayoutParamsTestActivity : Activity() {
public override fun onCreate(savedInstanceState: Bundle?): Unit {
super.onCreate(savedInstanceState)
UI {
linearLayout {
editText().lparams(-2, -2) {
bottomMargin = 1
leftMargin = 2
rightMargin = 3
topMargin = 4
height = 9
gravity = Gravity.RIGHT
weight = 1.3591409142295225f
}
}
relativeLayout {
editText().lparams(-2, -2) {
bottomMargin = 1
leftMargin = 2
rightMargin = 3
topMargin = 4
height = 9
addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE)
addRule(RelativeLayout.CENTER_IN_PARENT)
}
}
absoluteLayout {
editText().lparams(-2, -2, 12, 23) {
height = 9
x = 100
y = 200
}
}
frameLayout {
editText().lparams(-2, -2) {
bottomMargin = 1
leftMargin = 2
rightMargin = 3
topMargin = 4
height = 9
gravity = Gravity.RIGHT
}
}
gridLayout {
editText().lparams {
bottomMargin = 1
leftMargin = 2
rightMargin = 3
topMargin = 4
height = 9
}
}
}
}
} | apache-2.0 |
arcuri82/testing_security_development_enterprise_systems | advanced/graphql/news-graphql/src/main/kotlin/org/tsdes/advanced/graphql/newsgraphql/type/NewsType.kt | 1 | 346 | package org.tsdes.advanced.graphql.newsgraphql.type
import java.time.ZonedDateTime
open class NewsType(
authorId: String? = null,
text: String? = null,
country: String? = null,
creationTime: ZonedDateTime? = null,
var newsId: String? = null
) : InputUpdateNewsType(authorId, text, country, creationTime) | lgpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.