content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
import java.util.* import kotlin.concurrent.fixedRateTimer /** * Created by rajeshdalsaniya on 05/08/17. */ fun main(args: Array<String>) { // Random Number Generator Object val newRandom = RandomNumber() // Timer Print Random Numbers var fixRateTimer = fixedRateTimer("randomNumber", false, 1000, 1000) { // First Random Number var random1 = newRandom.randomBetween(1,7) // Second Random Number var random2 = newRandom.randomBetween(1,7) // Print Random Numbers print("Random Numbers: $random1, $random2 \n") } // Run fix Rate Timer try { Thread.sleep(50000) } finally { fixRateTimer.cancel() } } // Random Number Generator Class class RandomNumber { // Java Random Object var random = Random() /** * Min is inclusive and max is exclusive in this case */ fun randomBetween(min: Int, max: Int): Int { return random.nextInt(max - min) + min } }
RandomNumber/src/Main.kt
777279202
package com.google.codelabs.mdc.kotlin.shrine import androidx.fragment.app.Fragment /** * A host (typically an `Activity`} that can display fragments and knows how to respond to * navigation events. */ interface NavigationHost { /** * Trigger a navigation to the specified fragment, optionally adding a transaction to the back * stack to make this navigation reversible. */ fun navigateTo(fragment: Fragment, addToBackstack: Boolean) }
kotlin/shrine/app/src/main/java/com/google/codelabs/mdc/kotlin/shrine/NavigationHost.kt
3975970373
package me.panpf.sketch.sample.ui import android.os.Bundle import android.view.View import kotlinx.android.synthetic.main.fragment_repeat_load_or_download_test.* import me.panpf.sketch.sample.base.BaseFragment import me.panpf.sketch.sample.base.BindContentView import me.panpf.sketch.sample.R import me.panpf.sketch.uri.ApkIconUriModel @BindContentView(R.layout.fragment_repeat_load_or_download_test) class RepeatLoadOrDownloadTestFragment : BaseFragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val context = context ?: return val selfApkFile = context.applicationInfo.publicSourceDir arrayOf(image_repeatLoadOrDownloadTest_1 , image_repeatLoadOrDownloadTest_2 , image_repeatLoadOrDownloadTest_3 , image_repeatLoadOrDownloadTest_4 , image_repeatLoadOrDownloadTest_5 , image_repeatLoadOrDownloadTest_6 , image_repeatLoadOrDownloadTest_7 , image_repeatLoadOrDownloadTest_8 ).forEach { it.displayImage(ApkIconUriModel.makeUri(selfApkFile)) } arrayOf(image_repeatLoadOrDownloadTest_9 , image_repeatLoadOrDownloadTest_10 , image_repeatLoadOrDownloadTest_11 , image_repeatLoadOrDownloadTest_12 , image_repeatLoadOrDownloadTest_13 , image_repeatLoadOrDownloadTest_14 , image_repeatLoadOrDownloadTest_15 , image_repeatLoadOrDownloadTest_16 ).forEach { it.displayImage("http://img3.imgtn.bdimg.com/it/u=1671737159,3601566602&fm=21&gp=0.jpg") } arrayOf(image_repeatLoadOrDownloadTest_31 , image_repeatLoadOrDownloadTest_32 , image_repeatLoadOrDownloadTest_33 , image_repeatLoadOrDownloadTest_34 , image_repeatLoadOrDownloadTest_35 , image_repeatLoadOrDownloadTest_36 , image_repeatLoadOrDownloadTest_37 , image_repeatLoadOrDownloadTest_38 ).forEach { it.displayImage("http://img3.duitang.com/uploads/item/201604/26/20160426001415_teGBZ.jpeg") } } }
sample/src/main/java/me/panpf/sketch/sample/ui/RepeatLoadOrDownloadTestFragment.kt
4219537234
/* * Copyright (c) 2010-2022 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.habdroid.background import com.google.common.reflect.ClassPath import java.util.stream.Collectors import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.newSingleThreadContext import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Assert import org.junit.Before import org.junit.Test import org.openhab.habdroid.background.tiles.AbstractTileService @ExperimentalCoroutinesApi class TileServicesTests { private val mainThreadSurrogate = newSingleThreadContext("UI thread") private lateinit var tileServices: Set<Class<*>> @Suppress("UnstableApiUsage") @Before fun setup() { tileServices = ClassPath.from(ClassLoader.getSystemClassLoader()) .allClasses .stream() .filter { it.name.startsWith("org.openhab.habdroid.background.tiles.TileService") } .map { it.load() } .collect(Collectors.toSet()) Dispatchers.setMain(mainThreadSurrogate) } @After fun tearDown() { Dispatchers.resetMain() mainThreadSurrogate.close() } @Test fun checkTileServiceNumber() { Assert.assertEquals(tileServices.size, AbstractTileService.TILE_COUNT) } @Test fun checkTileServicesImplementCorrectId() { GlobalScope.launch(Dispatchers.Main) { for (tileService in tileServices) { val id = (tileService.newInstance() as AbstractTileService).ID Assert.assertEquals( "Name of the tile service doesn't match its id", id, tileService.name.substringAfter("TileService").toInt() ) } } } @Test fun checkClassName() { GlobalScope.launch(Dispatchers.Main) { for (tileService in tileServices) { val id = (tileService.newInstance() as AbstractTileService).ID Assert.assertEquals( AbstractTileService.getClassNameForId(id), tileService.canonicalName ) Assert.assertEquals( AbstractTileService.getIdFromClassName(tileService.canonicalName!!), id ) } } } }
mobile/src/test/java/org/openhab/habdroid/background/TileServicesTests.kt
1501273259
/* * Copyright (c) 2020 Arthur Milchior <[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.libanki.template import com.ichi2.utils.KotlinCleanup object MathJax { // MathJax opening delimiters private val sMathJaxOpenings = arrayOf("\\(", "\\[") // MathJax closing delimiters private val sMathJaxClosings = arrayOf("\\)", "\\]") @KotlinCleanup("fix IDE lint issues") fun textContainsMathjax(txt: String): Boolean { // Do you have the first opening and then the first closing, // or the second opening and the second closing...? // This assumes that the openings and closings are the same length. var opening: String var closing: String for (i in sMathJaxOpenings.indices) { opening = sMathJaxOpenings[i] closing = sMathJaxClosings[i] // What if there are more than one thing? // Let's look for the first opening, and the last closing, and if they're in the right order, // we are good. val first_opening_index = txt.indexOf(opening) val last_closing_index = txt.lastIndexOf(closing) if (first_opening_index != -1 && last_closing_index != -1 && first_opening_index < last_closing_index) { return true } } return false } }
AnkiDroid/src/main/java/com/ichi2/libanki/template/MathJax.kt
4281635440
package de.tfelix.bestia.worldgen.image import de.tfelix.bestia.worldgen.io.MapGenDAO import de.tfelix.bestia.worldgen.map.Map2DDiscreteChunk import de.tfelix.bestia.worldgen.map.Map2DDiscreteCoordinate import de.tfelix.bestia.worldgen.map.MapCoordinate import de.tfelix.bestia.worldgen.map.MapDataPart import de.tfelix.bestia.worldgen.random.NoiseVector import de.tfelix.bestia.worldgen.workload.Job import java.awt.image.BufferedImage import java.nio.file.Path import javax.imageio.ImageIO fun toRGB(r: Int, g: Int, b: Int): Int { return r shl 16 or (g shl 8 and 0xFF0000) or (b and 0xFFFF00) } class ImageOutputJob( private val bitmapFile: Path, width: Int, height: Int ) : Job() { private val image = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) override fun foreachNoiseVector(dao: MapGenDAO, data: MapDataPart, vec: NoiseVector, cord: MapCoordinate) { vec.getValueDouble("noise") val part2D = data.mapChunk as Map2DDiscreteChunk val global = part2D.toGlobalCoordinates(cord) as Map2DDiscreteCoordinate image.setRGB(global.x.toInt(), global.y.toInt(), grayScale(vec.getValueDouble("chunkHeight"))) } private fun grayScale(scale: Double): Int { val rgb = Math.min(0.0, Math.max(255.0,255 * scale)).toInt() return toRGB(rgb, rgb, rgb) } override fun onFinish(dao: MapGenDAO, data: MapDataPart) { ImageIO.write(image, "png", bitmapFile.toFile()) } }
src/main/kotlin/de/tfelix/bestia/worldgen/image/ImageOutput.kt
4123507232
package io.envoyproxy.envoymobile import java.lang.IllegalArgumentException /** * Specifies how a request may be retried, containing one or more rules. * * @param maxRetryCount Maximum number of retries that a request may be performed. * @param retryOn Rules checked for retrying. * @param retryStatusCodes Additional list of status codes that should be retried. * @param perRetryTimeoutMS Timeout (in milliseconds) to apply to each retry. * Must be <= `totalUpstreamTimeoutMS` if it's a positive number. * @param totalUpstreamTimeoutMS Total timeout (in milliseconds) that includes all retries. * Spans the point at which the entire downstream request has been processed and when the * upstream response has been completely processed. Null or 0 may be specified to disable it. */ data class RetryPolicy( val maxRetryCount: Int, val retryOn: List<RetryRule>, val retryStatusCodes: List<Int> = emptyList(), val perRetryTimeoutMS: Long? = null, val totalUpstreamTimeoutMS: Long? = 15000 ) { init { if (perRetryTimeoutMS != null && totalUpstreamTimeoutMS != null && perRetryTimeoutMS > totalUpstreamTimeoutMS && totalUpstreamTimeoutMS != 0L ) { throw IllegalArgumentException("Per-retry timeout cannot be less than total timeout") } } companion object { /** * Initialize the retry policy from a set of headers. * * @param headers: The headers with which to initialize the retry policy. */ internal fun from(headers: RequestHeaders): RetryPolicy? { val maxRetries = headers.value("x-envoy-max-retries")?.first()?.toIntOrNull() ?: return null return RetryPolicy( maxRetries, // Envoy internally coalesces multiple x-envoy header values into one comma-delimited value. // These flatMap transformations split those values up to correctly map back to // Kotlin enums. headers.value("x-envoy-retry-on") ?.flatMap { it.split(",") }?.map { retryOn -> RetryRule.enumValue(retryOn) } ?.filterNotNull() ?: emptyList(), headers.value("x-envoy-retriable-status-codes") ?.flatMap { it.split(",") }?.map { statusCode -> statusCode.toIntOrNull() } ?.filterNotNull() ?: emptyList(), headers.value("x-envoy-upstream-rq-per-try-timeout-ms")?.firstOrNull()?.toLongOrNull(), headers.value("x-envoy-upstream-rq-timeout-ms")?.firstOrNull()?.toLongOrNull() ) } } } /** * Rules that may be used with `RetryPolicy`. * See the `x-envoy-retry-on` Envoy header for documentation. */ enum class RetryRule(internal val stringValue: String) { STATUS_5XX("5xx"), GATEWAY_ERROR("gateway-error"), CONNECT_FAILURE("connect-failure"), REFUSED_STREAM("refused-stream"), RETRIABLE_4XX("retriable-4xx"), RETRIABLE_HEADERS("retriable-headers"), RESET("reset"); companion object { internal fun enumValue(stringRepresentation: String): RetryRule? { return when (stringRepresentation) { "5xx" -> STATUS_5XX "gateway-error" -> GATEWAY_ERROR "connect-failure" -> CONNECT_FAILURE "refused-stream" -> REFUSED_STREAM "retriable-4xx" -> RETRIABLE_4XX "retriable-headers" -> RETRIABLE_HEADERS "reset" -> RESET // This is mapped to null because this string value is added to headers automatically // in RetryPolicy.outboundHeaders() "retriable-status-codes" -> null else -> throw IllegalArgumentException("invalid value $stringRepresentation") } } } }
mobile/library/kotlin/io/envoyproxy/envoymobile/RetryPolicy.kt
2212323890
package cn.org.cicada.jdbc.kt.api data class Page<out T>( val page: Long, val pageSize: Int, val data: List<T>, val totalSize: Long )
src/main/kotlin/cn/org/cicada/jdbc/kt/api/Page.kt
968202389
package aunmag.shooter.scenarios import aunmag.nightingale.utilities.Operative import aunmag.shooter.environment.World open class Scenario(val world: World) : Operative()
src/main/java/aunmag/shooter/scenarios/Scenario.kt
3644613539
package de.troido.bleacon.data.tuples import de.troido.bleacon.data.BleDeserializer import de.troido.bleacon.data.then import de.troido.ekstend.functional.tuples.Tuple9 import de.troido.ekstend.functional.tuples.flat class Tuple9Deserializer<out A : Any, out B : Any, out C : Any, out D : Any, out E : Any, out F : Any, out G : Any, out H : Any, out I : Any>( private val deserializerA: BleDeserializer<A>, private val deserializerB: BleDeserializer<B>, private val deserializerC: BleDeserializer<C>, private val deserializerD: BleDeserializer<D>, private val deserializerE: BleDeserializer<E>, private val deserializerF: BleDeserializer<F>, private val deserializerG: BleDeserializer<G>, private val deserializerH: BleDeserializer<H>, private val deserializerI: BleDeserializer<I> ) : BleDeserializer<Tuple9<A, B, C, D, E, F, G, H, I>> { override val length: Int = deserializerA.length + deserializerB.length + deserializerC.length + deserializerD.length + deserializerE.length + deserializerF.length + deserializerG.length + deserializerH.length + deserializerI.length override fun deserialize(data: ByteArray): Tuple9<A, B, C, D, E, F, G, H, I>? = deserializerA.then(deserializerB).then(deserializerC).then(deserializerD) .then(deserializerE).then(deserializerF).then(deserializerG) .then(deserializerH).then(deserializerI) .deserialize(data)?.flat() }
library/src/main/java/de/troido/bleacon/data/tuples/Tuple9Deserializer.kt
2489558789
/* * Copyright 2021 Alex Almeida Tavella * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package br.com.bookmark.movie.testdoubles import br.com.bookmark.movie.data.local.dao.MovieBookmarksDao import br.com.bookmark.movie.data.local.entity.MovieBookmark import java.io.IOException class TestMovieBookmarksDao( initialMovies: List<MovieBookmark> = emptyList() ) : MovieBookmarksDao { private val movies = initialMovies.toMutableList() override suspend fun getAll(): List<MovieBookmark> { return movies.toList() } override suspend fun get(movieId: Int): MovieBookmark? { return movies.find { it.id == movieId } } override suspend fun loadAllByIds(movieIds: IntArray): List<MovieBookmark> { return movies.filter { movieIds.contains(it.id) } } override suspend fun insert(movie: MovieBookmark): Long { if (movies.contains(movie)) throw IOException("Movie already on database") movies.add(movie) return movies.size.toLong() } override suspend fun delete(movieId: Int): Int { if (movies.none { it.id == movieId }) throw IOException("Movie not on database") movies.removeIf { it.id == movieId } return movies.size } }
feature/bookmark-movie/impl/src/test/java/br/com/bookmark/movie/testdoubles/TestMovieBookmarksDao.kt
3248703863
package de.westnordost.streetcomplete.quests.bridge_structure import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.BUILDING class AddBridgeStructure : OsmFilterQuestType<BridgeStructure>() { override val elementFilter = "ways with man_made = bridge and !bridge:structure and !bridge:movable" override val commitMessage = "Add bridge structures" override val wikiLink = "Key:bridge:structure" override val icon = R.drawable.ic_quest_bridge override val questTypeAchievements = listOf(BUILDING) override fun getTitle(tags: Map<String, String>) = R.string.quest_bridge_structure_title override fun createForm() = AddBridgeStructureForm() override fun applyAnswerTo(answer: BridgeStructure, changes: StringMapChangesBuilder) { changes.add("bridge:structure", answer.osmValue) } }
app/src/main/java/de/westnordost/streetcomplete/quests/bridge_structure/AddBridgeStructure.kt
2755170982
package de.westnordost.streetcomplete.quests.lanes sealed class LanesAnswer data class MarkedLanes(val count: Int) : LanesAnswer() object UnmarkedLanes : LanesAnswer() data class UnmarkedLanesKnowLaneCount(val count: Int) : LanesAnswer() data class MarkedLanesSides(val forward: Int, val backward: Int, val centerLeftTurnLane: Boolean) : LanesAnswer() val LanesAnswer.total: Int? get() = when(this) { is MarkedLanes -> count is UnmarkedLanesKnowLaneCount -> count is UnmarkedLanes -> null is MarkedLanesSides -> forward + backward + (if (centerLeftTurnLane) 1 else 0) }
app/src/main/java/de/westnordost/streetcomplete/quests/lanes/LanesAnswer.kt
2377744337
package de.westnordost.streetcomplete.quests.diet_type import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.meta.updateWithCheckDate 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.CITIZEN class AddHalal : OsmFilterQuestType<DietAvailability>() { override val elementFilter = """ nodes, ways with ( amenity ~ restaurant|cafe|fast_food|ice_cream or shop ~ butcher|supermarket|ice_cream ) and name and ( !diet:halal or diet:halal != only and diet:halal older today -4 years ) """ override val commitMessage = "Add Halal status" override val wikiLink = "Key:diet:halal" override val icon = R.drawable.ic_quest_halal override val isReplaceShopEnabled = true override val defaultDisabledMessage = R.string.default_disabled_msg_go_inside_regional_warning override val questTypeAchievements = listOf(CITIZEN) override fun getTitle(tags: Map<String, String>) = R.string.quest_dietType_halal_name_title override fun createForm() = AddDietTypeForm.create(R.string.quest_dietType_explanation_halal) override fun applyAnswerTo(answer: DietAvailability, changes: StringMapChangesBuilder) { changes.updateWithCheckDate("diet:halal", answer.osmValue) } }
app/src/main/java/de/westnordost/streetcomplete/quests/diet_type/AddHalal.kt
1265680797
package org.wordpress.android.fluxc.store.stats.time import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.eq import com.nhaarman.mockitokotlin2.isNull import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.never import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.stats.LimitMode import org.wordpress.android.fluxc.model.stats.time.TimeStatsMapper import org.wordpress.android.fluxc.model.stats.time.VisitsAndViewsModel import org.wordpress.android.fluxc.network.rest.wpcom.stats.time.StatsUtils import org.wordpress.android.fluxc.network.rest.wpcom.stats.time.VisitAndViewsRestClient import org.wordpress.android.fluxc.network.rest.wpcom.stats.time.VisitAndViewsRestClient.VisitsAndViewsResponse import org.wordpress.android.fluxc.network.utils.StatsGranularity.DAYS import org.wordpress.android.fluxc.persistence.TimeStatsSqlUtils.VisitsAndViewsSqlUtils import org.wordpress.android.fluxc.store.StatsStore.FetchStatsPayload import org.wordpress.android.fluxc.store.StatsStore.StatsError import org.wordpress.android.fluxc.store.StatsStore.StatsErrorType.API_ERROR import org.wordpress.android.fluxc.test import org.wordpress.android.fluxc.tools.initCoroutineEngine import org.wordpress.android.fluxc.utils.AppLogWrapper import org.wordpress.android.fluxc.utils.CurrentTimeProvider import java.util.Date import kotlin.test.assertEquals import kotlin.test.assertNotNull private const val ITEMS_TO_LOAD = 8 private val LIMIT_MODE = LimitMode.Top(ITEMS_TO_LOAD) private const val FORMATTED_DATE = "2019-10-10" @RunWith(MockitoJUnitRunner::class) class VisitsAndViewsStoreTest { @Mock lateinit var site: SiteModel @Mock lateinit var restClient: VisitAndViewsRestClient @Mock lateinit var sqlUtils: VisitsAndViewsSqlUtils @Mock lateinit var statsUtils: StatsUtils @Mock lateinit var currentTimeProvider: CurrentTimeProvider @Mock lateinit var mapper: TimeStatsMapper @Mock lateinit var appLogWrapper: AppLogWrapper private lateinit var store: VisitsAndViewsStore @Before fun setUp() { store = VisitsAndViewsStore( restClient, sqlUtils, mapper, statsUtils, currentTimeProvider, initCoroutineEngine(), appLogWrapper ) val currentDate = Date(0) whenever(currentTimeProvider.currentDate()).thenReturn(currentDate) val timeZone = "GMT" whenever(site.timezone).thenReturn(timeZone) whenever( statsUtils.getFormattedDate( eq(currentDate), any() ) ).thenReturn(FORMATTED_DATE) } @Test fun `returns data per site`() = test { val fetchInsightsPayload = FetchStatsPayload( VISITS_AND_VIEWS_RESPONSE ) val forced = true whenever(restClient.fetchVisits(site, DAYS, FORMATTED_DATE, ITEMS_TO_LOAD, forced)).thenReturn( fetchInsightsPayload ) whenever(mapper.map(VISITS_AND_VIEWS_RESPONSE, LIMIT_MODE)).thenReturn(VISITS_AND_VIEWS_MODEL) val responseModel = store.fetchVisits(site, DAYS, LIMIT_MODE, forced) assertThat(responseModel.model).isEqualTo(VISITS_AND_VIEWS_MODEL) verify(sqlUtils).insert(site, VISITS_AND_VIEWS_RESPONSE, DAYS, FORMATTED_DATE, ITEMS_TO_LOAD) } @Test fun `returns cached data per site`() = test { whenever(sqlUtils.hasFreshRequest(site, DAYS, FORMATTED_DATE, ITEMS_TO_LOAD)).thenReturn(true) whenever(sqlUtils.select(site, DAYS, FORMATTED_DATE)).thenReturn(VISITS_AND_VIEWS_RESPONSE) val model = mock<VisitsAndViewsModel>() whenever(mapper.map(VISITS_AND_VIEWS_RESPONSE, LIMIT_MODE)).thenReturn(model) val forced = false val responseModel = store.fetchVisits(site, DAYS, LIMIT_MODE, forced) assertThat(responseModel.model).isEqualTo(model) assertThat(responseModel.cached).isTrue() verify(sqlUtils, never()).insert(any(), any(), any(), any<String>(), isNull()) } @Test fun `returns error when invalid data`() = test { val forced = true val fetchInsightsPayload = FetchStatsPayload( VISITS_AND_VIEWS_RESPONSE ) whenever(restClient.fetchVisits(site, DAYS, FORMATTED_DATE, ITEMS_TO_LOAD, forced)).thenReturn( fetchInsightsPayload ) val emptyModel = VisitsAndViewsModel("", emptyList()) whenever(mapper.map(VISITS_AND_VIEWS_RESPONSE, LIMIT_MODE)).thenReturn(emptyModel) val responseModel = store.fetchVisits(site, DAYS, LIMIT_MODE, forced) assertThat(responseModel.error.type).isEqualTo(INVALID_DATA_ERROR.type) assertThat(responseModel.error.message).isEqualTo(INVALID_DATA_ERROR.message) } @Test fun `returns error when data call fail`() = test { val type = API_ERROR val message = "message" val errorPayload = FetchStatsPayload<VisitsAndViewsResponse>(StatsError(type, message)) val forced = true whenever(restClient.fetchVisits(site, DAYS, FORMATTED_DATE, ITEMS_TO_LOAD, forced)).thenReturn(errorPayload) val responseModel = store.fetchVisits(site, DAYS, LIMIT_MODE, forced) assertNotNull(responseModel.error) val error = responseModel.error!! assertEquals(type, error.type) assertEquals(message, error.message) } @Test fun `returns data from db`() { whenever(sqlUtils.select(site, DAYS, FORMATTED_DATE)).thenReturn(VISITS_AND_VIEWS_RESPONSE) val model = mock<VisitsAndViewsModel>() whenever(mapper.map(VISITS_AND_VIEWS_RESPONSE, LIMIT_MODE)).thenReturn(model) val result = store.getVisits(site, DAYS, LIMIT_MODE) assertThat(result).isEqualTo(model) } }
example/src/test/java/org/wordpress/android/fluxc/store/stats/time/VisitsAndViewsStoreTest.kt
1347051418
// Copyright 2021 [email protected] // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cfig.helper import org.apache.commons.exec.CommandLine import org.apache.commons.exec.DefaultExecutor import org.apache.commons.exec.ExecuteException import org.apache.commons.exec.PumpStreamHandler import org.slf4j.LoggerFactory import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.security.MessageDigest import javax.crypto.Cipher class KeyHelper2 { companion object { private val log = LoggerFactory.getLogger(KeyHelper2::class.java) /* inspired by https://stackoverflow.com/questions/40242391/how-can-i-sign-a-raw-message-without-first-hashing-it-in-bouncy-castle "specifying Cipher.ENCRYPT mode or Cipher.DECRYPT mode doesn't make a difference; both simply perform modular exponentiation" python counterpart: import Crypto.PublicKey.RSA key = Crypto.PublicKey.RSA.construct((modulus, exponent)) vRet = key.verify(decode_long(padding_and_digest), (decode_long(sig_blob), None)) print("verify padded digest: %s" % binascii.hexlify(padding_and_digest)) print("verify sig: %s" % binascii.hexlify(sig_blob)) print("X: Verify: %s" % vRet) */ fun rawRsa(key: java.security.Key, data: ByteArray): ByteArray { return Cipher.getInstance("RSA/ECB/NoPadding").let { cipher -> cipher.init(Cipher.ENCRYPT_MODE, key) cipher.update(data) cipher.doFinal() } } fun rawSignOpenSsl(keyPath: String, data: ByteArray): ByteArray { log.debug("raw input: " + Helper.toHexString(data)) log.debug("Raw sign data size = ${data.size}, key = $keyPath") var ret = byteArrayOf() val exe = DefaultExecutor() val stdin = ByteArrayInputStream(data) val stdout = ByteArrayOutputStream() val stderr = ByteArrayOutputStream() exe.streamHandler = PumpStreamHandler(stdout, stderr, stdin) try { exe.execute(CommandLine.parse("openssl rsautl -sign -inkey $keyPath -raw")) ret = stdout.toByteArray() log.debug("Raw signature size = " + ret.size) } catch (e: ExecuteException) { log.error("Execute error") } finally { log.debug("OUT: " + Helper.toHexString(stdout.toByteArray())) log.debug("ERR: " + String(stderr.toByteArray())) } if (ret.isEmpty()) throw RuntimeException("raw sign failed") return ret } fun pyAlg2java(alg: String): String { return when (alg) { "sha1" -> "sha-1" "sha224" -> "sha-224" "sha256" -> "sha-256" "sha384" -> "sha-384" "sha512" -> "sha-512" else -> throw IllegalArgumentException("unknown algorithm: [$alg]") } } /* openssl dgst -sha256 <file> */ fun sha256(inData: ByteArray): ByteArray { return MessageDigest.getInstance("SHA-256").digest(inData) } fun rsa(inData: ByteArray, inKey: java.security.PrivateKey): ByteArray { return Cipher.getInstance("RSA").let { it.init(Cipher.ENCRYPT_MODE, inKey) it.doFinal(inData) } } fun sha256rsa(inData: ByteArray, inKey: java.security.PrivateKey): ByteArray { return rsa(sha256(inData), inKey) } } }
helper/src/main/kotlin/cfig/helper/KeyHelper2.kt
80187254
package org.wordpress.android.fluxc.store import javax.inject.Inject import org.wordpress.android.fluxc.utils.PreferenceUtils class GetDeviceRegistrationStatus @Inject constructor( private val prefsWrapper: PreferenceUtils.PreferenceUtilsWrapper ) { operator fun invoke(): Status { val deviceId = prefsWrapper.getFluxCPreferences().getString(NotificationStore.WPCOM_PUSH_DEVICE_SERVER_ID, null) return if (deviceId.isNullOrEmpty()) { Status.UNREGISTERED } else { Status.REGISTERED } } enum class Status { REGISTERED, UNREGISTERED } }
fluxc/src/main/java/org/wordpress/android/fluxc/store/GetDeviceRegistrationStatus.kt
917752047
// Copyright 2021 [email protected] // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cfig.bootimg.v3 import avb.AVBInfo import avb.alg.Algorithms import avb.blob.AuxBlob import cfig.Avb import cfig.EnvironmentVerifier import cfig.bootimg.Common.Companion.deleleIfExists import cfig.bootimg.Common.Companion.getPaddingSize import cfig.bootimg.Signer import cfig.helper.Helper import cfig.packable.VBMetaParser import com.fasterxml.jackson.databind.ObjectMapper import de.vandermeer.asciitable.AsciiTable import org.apache.commons.exec.CommandLine import org.apache.commons.exec.DefaultExecutor import org.slf4j.LoggerFactory import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.nio.ByteBuffer import java.nio.ByteOrder import cfig.bootimg.Common as C data class BootV3( var info: MiscInfo = MiscInfo(), var kernel: CommArgs = CommArgs(), val ramdisk: CommArgs = CommArgs(), var bootSignature: CommArgs = CommArgs(), ) { companion object { private val log = LoggerFactory.getLogger(BootV3::class.java) private val mapper = ObjectMapper() private val workDir = Helper.prop("workDir") fun parse(fileName: String): BootV3 { val ret = BootV3() FileInputStream(fileName).use { fis -> val header = BootHeaderV3(fis) //info ret.info.output = File(fileName).name ret.info.json = File(fileName).name.removeSuffix(".img") + ".json" ret.info.cmdline = header.cmdline ret.info.headerSize = header.headerSize ret.info.headerVersion = header.headerVersion ret.info.osVersion = header.osVersion ret.info.osPatchLevel = header.osPatchLevel ret.info.pageSize = BootHeaderV3.pageSize ret.info.signatureSize = header.signatureSize //kernel ret.kernel.file = workDir + "kernel" ret.kernel.size = header.kernelSize ret.kernel.position = BootHeaderV3.pageSize //ramdisk ret.ramdisk.file = workDir + "ramdisk.img" ret.ramdisk.size = header.ramdiskSize ret.ramdisk.position = ret.kernel.position + header.kernelSize + getPaddingSize(header.kernelSize, BootHeaderV3.pageSize) //boot signature if (header.signatureSize > 0) { ret.bootSignature.file = workDir + "bootsig" ret.bootSignature.size = header.signatureSize ret.bootSignature.position = ret.ramdisk.position + ret.ramdisk.size + getPaddingSize(header.ramdiskSize, BootHeaderV3.pageSize) } } ret.info.imageSize = File(fileName).length() return ret } } data class MiscInfo( var output: String = "", var json: String = "", var headerVersion: Int = 0, var headerSize: Int = 0, var pageSize: Int = 0, var cmdline: String = "", var osVersion: String = "", var osPatchLevel: String = "", var imageSize: Long = 0, var signatureSize: Int = 0, ) data class CommArgs( var file: String = "", var position: Int = 0, var size: Int = 0, ) fun pack(): BootV3 { if (File(this.ramdisk.file).exists() && !File(workDir + "root").exists()) { //do nothing if we have ramdisk.img.gz but no /root log.warn("Use prebuilt ramdisk file: ${this.ramdisk.file}") } else { File(this.ramdisk.file).deleleIfExists() File(this.ramdisk.file.replaceFirst("[.][^.]+$", "")).deleleIfExists() //TODO: remove cpio in C/C++ //C.packRootfs("$workDir/root", this.ramdisk.file, C.parseOsMajor(info.osVersion)) // enable advance JAVA cpio C.packRootfs("$workDir/root", this.ramdisk.file) } this.kernel.size = File(this.kernel.file).length().toInt() this.ramdisk.size = File(this.ramdisk.file).length().toInt() //header FileOutputStream(this.info.output + ".clear", false).use { fos -> val encodedHeader = this.toHeader().encode() fos.write(encodedHeader) fos.write( ByteArray(Helper.round_to_multiple(encodedHeader.size, this.info.pageSize) - encodedHeader.size) ) } //data log.info("Writing data ...") //BootV3 should have correct image size val bf = ByteBuffer.allocate(maxOf(info.imageSize.toInt(), 64 * 1024 * 1024)) bf.order(ByteOrder.LITTLE_ENDIAN) C.writePaddedFile(bf, this.kernel.file, this.info.pageSize) C.writePaddedFile(bf, this.ramdisk.file, this.info.pageSize) //write V3 data FileOutputStream("${this.info.output}.clear", true).use { fos -> fos.write(bf.array(), 0, bf.position()) } //write V4 boot sig if (this.info.headerVersion > 3) { val bootSigJson = File(Avb.getJsonFileName(this.bootSignature.file)) var bootSigBytes = ByteArray(this.bootSignature.size) if (bootSigJson.exists()) { log.warn("V4 BootImage has GKI boot signature") val readBackBootSig = mapper.readValue(bootSigJson, AVBInfo::class.java) val alg = Algorithms.get(readBackBootSig.header!!.algorithm_type)!! //replace new pub key readBackBootSig.auxBlob!!.pubkey!!.pubkey = AuxBlob.encodePubKey(alg) //update hash and sig readBackBootSig.auxBlob!!.hashDescriptors.get(0).update(this.info.output + ".clear") bootSigBytes = readBackBootSig.encodePadded() } //write V4 data FileOutputStream("${this.info.output}.clear", true).use { fos -> fos.write(bootSigBytes) } } //google way this.toCommandLine().addArgument(this.info.output + ".google").let { log.info(it.toString()) DefaultExecutor().execute(it) } C.assertFileEquals(this.info.output + ".clear", this.info.output + ".google") return this } fun sign(fileName: String): BootV3 { if (File(Avb.getJsonFileName(info.output)).exists()) { Signer.signAVB(fileName, this.info.imageSize, String.format(Helper.prop("avbtool"), "v1.2")) } else { log.warn("no AVB info found, assume it's clear image") } return this } private fun toHeader(): BootHeaderV3 { return BootHeaderV3( kernelSize = kernel.size, ramdiskSize = ramdisk.size, headerVersion = info.headerVersion, osVersion = info.osVersion, osPatchLevel = info.osPatchLevel, headerSize = info.headerSize, cmdline = info.cmdline, signatureSize = info.signatureSize ) } fun extractImages(): BootV3 { val workDir = Helper.prop("workDir") //info mapper.writerWithDefaultPrettyPrinter().writeValue(File(workDir + this.info.json), this) //kernel C.dumpKernel(Helper.Slice(info.output, kernel.position, kernel.size, kernel.file)) //ramdisk val fmt = C.dumpRamdisk( Helper.Slice(info.output, ramdisk.position, ramdisk.size, ramdisk.file), "${workDir}root" ) this.ramdisk.file = this.ramdisk.file + ".$fmt" //bootsig if (info.signatureSize > 0) { Helper.extractFile( info.output, this.bootSignature.file, this.bootSignature.position.toLong(), this.bootSignature.size ) try { AVBInfo.parseFrom(this.bootSignature.file).dumpDefault(this.bootSignature.file) } catch (e: IllegalArgumentException) { log.warn("boot signature is invalid") } } //dump info again mapper.writerWithDefaultPrettyPrinter().writeValue(File(workDir + this.info.json), this) return this } fun extractVBMeta(): BootV3 { try { AVBInfo.parseFrom(info.output).dumpDefault(info.output) if (File("vbmeta.img").exists()) { log.warn("Found vbmeta.img, parsing ...") VBMetaParser().unpack("vbmeta.img") } } catch (e: IllegalArgumentException) { log.warn(e.message) log.warn("failed to parse vbmeta info") } return this } fun printSummary(): BootV3 { val workDir = Helper.prop("workDir") val tableHeader = AsciiTable().apply { addRule() addRow("What", "Where") addRule() } val tab = AsciiTable().let { it.addRule() it.addRow("image info", workDir + info.output.removeSuffix(".img") + ".json") it.addRule() it.addRow("kernel", this.kernel.file) File(Helper.prop("kernelVersionFile")).let { kernelVersionFile -> if (kernelVersionFile.exists()) { it.addRow("\\-- version " + kernelVersionFile.readLines().toString(), kernelVersionFile.path) } } File(Helper.prop("kernelConfigFile")).let { kernelConfigFile -> if (kernelConfigFile.exists()) { it.addRow("\\-- config", kernelConfigFile.path) } } it.addRule() it.addRow("ramdisk", this.ramdisk.file) it.addRow("\\-- extracted ramdisk rootfs", "${workDir}root") it.addRule() if (this.info.signatureSize > 0) { it.addRow("boot signature", this.bootSignature.file) Avb.getJsonFileName(this.bootSignature.file).let { jsFile -> it.addRow("\\-- decoded boot signature", if (File(jsFile).exists()) jsFile else "N/A") } it.addRule() } Avb.getJsonFileName(info.output).let { jsonFile -> it.addRow("AVB info", if (File(jsonFile).exists()) jsonFile else "NONE") } it.addRule() it } val tabVBMeta = AsciiTable().let { if (File("vbmeta.img").exists()) { it.addRule() it.addRow("vbmeta.img", Avb.getJsonFileName("vbmeta.img")) it.addRule() "\n" + it.render() } else { "" } } log.info( "\n\t\t\tUnpack Summary of ${info.output}\n{}\n{}{}", tableHeader.render(), tab.render(), tabVBMeta ) return this } private fun toCommandLine(): CommandLine { val cmdPrefix = if (EnvironmentVerifier().isWindows) "python " else "" return CommandLine.parse(cmdPrefix + Helper.prop("mkbootimg")).let { ret -> ret.addArgument("--header_version") ret.addArgument(info.headerVersion.toString()) if (kernel.size > 0) { ret.addArgument("--kernel") ret.addArgument(this.kernel.file) } if (ramdisk.size > 0) { ret.addArgument("--ramdisk") ret.addArgument(this.ramdisk.file) } if (info.cmdline.isNotBlank()) { ret.addArgument(" --cmdline ") ret.addArgument(info.cmdline, false) } if (info.osVersion.isNotBlank()) { ret.addArgument(" --os_version") ret.addArgument(info.osVersion) } if (info.osPatchLevel.isNotBlank()) { ret.addArgument(" --os_patch_level") ret.addArgument(info.osPatchLevel) } if (this.bootSignature.size > 0 && File(Avb.getJsonFileName(this.bootSignature.file)).exists()) { val origSig = mapper.readValue(File(Avb.getJsonFileName(this.bootSignature.file)), AVBInfo::class.java) val alg = Algorithms.get(origSig.header!!.algorithm_type)!! ret.addArgument("--gki_signing_algorithm").addArgument(alg.name) ret.addArgument("--gki_signing_key").addArgument(alg.defaultKey) ret.addArgument("--gki_signing_avbtool_path").addArgument(String.format(Helper.prop("avbtool"), "v1.2")) } ret.addArgument(" --id ") ret.addArgument(" --output ") //ret.addArgument("boot.img" + ".google") log.debug("To Commandline: $ret") ret } } }
bbootimg/src/main/kotlin/bootimg/v3/BootV3.kt
2763507365
package com.vocalabs.egtest.example.kotlin import com.vocalabs.egtest.annotation.EgMatch import com.vocalabs.egtest.annotation.EgNoMatch class KotlinClassExample(vararg val s: String) { // Note: to have a non-empty "construct", the first annotation must be non-empty. Kapt bug KT-23427 @EgMatch(value = "[email protected]", construct = ["\"Hello\"", "\"World\""]) @EgMatch(value = "[email protected]", construct = []) @EgNoMatch(value = "dleppik@[email protected]", construct = ["\"A\""]) @EgNoMatch(value = "David Leppik <[email protected]>", construct = ["\"Hello\""]) @EgNoMatch(value = "dleppik", construct = []) val simpleEmailRe = """^[\w+.\-=&|/?!#$*]+@[\w.\-]+\.[\w]+$""".toRegex() @EgMatch(value = "[email protected]", construct = ["\"Hello\"", "\"World\""]) @EgMatch(value = "[email protected]", construct = []) @EgNoMatch(value = "dleppik@[email protected]", construct = ["\"A\""]) @EgNoMatch(value = "David Leppik <[email protected]>", construct = ["\"Hello\""]) @EgNoMatch(value = "dleppik", construct = []) fun isEmail(s: String): Boolean = simpleEmailRe.matches(s) }
kotlin-example/src/main/java/com/vocalabs/egtest/example/kotlin/KotlinClassExample.kt
462292405
package io.foliage.api.config import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Configuration import org.springframework.web.servlet.config.annotation.EnableWebMvc import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry import org.springframework.web.servlet.config.annotation.ViewControllerRegistry import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration @ComponentScan("io.foliage.api.controller") @EnableWebMvc open class WebConfig : WebMvcConfigurerAdapter() { override fun addResourceHandlers(registry: ResourceHandlerRegistry) { registry.addResourceHandler("/favicon.ico", "/static/**", "/**") .addResourceLocations("classpath:/static/") } override fun addViewControllers(registry: ViewControllerRegistry) { registry.addViewController("/").setViewName("index") } }
foliage-api/src/main/kotlin/io/foliage/api/config/WebConfig.kt
1770771028
package org.fossasia.openevent.general import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import org.fossasia.openevent.general.auth.AuthHolder import org.fossasia.openevent.general.auth.AuthService import org.fossasia.openevent.general.auth.RequestPasswordReset import org.fossasia.openevent.general.auth.forgot.PasswordReset import org.fossasia.openevent.general.common.SingleLiveEvent import org.fossasia.openevent.general.data.Preference import org.fossasia.openevent.general.data.Resource import org.fossasia.openevent.general.event.NEW_NOTIFICATIONS import org.fossasia.openevent.general.notification.NotificationService import org.fossasia.openevent.general.settings.SettingsService import org.fossasia.openevent.general.utils.HttpErrors import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers import retrofit2.HttpException import timber.log.Timber class StartupViewModel( private val preference: Preference, private val resource: Resource, private val authHolder: AuthHolder, private val authService: AuthService, private val notificationService: NotificationService, private val settingsService: SettingsService ) : ViewModel() { private val compositeDisposable = CompositeDisposable() val mutableNewNotifications = MutableLiveData<Boolean>() val newNotifications: LiveData<Boolean> = mutableNewNotifications private val mutableDialogProgress = MutableLiveData<Boolean>() val dialogProgress: LiveData<Boolean> = mutableDialogProgress private val mutableIsRefresh = MutableLiveData<Boolean>() val isRefresh: LiveData<Boolean> = mutableIsRefresh private val mutableResetPasswordEmail = MutableLiveData<String>() val resetPasswordEmail: LiveData<String> = mutableResetPasswordEmail private val mutableMessage = SingleLiveEvent<String>() val message: SingleLiveEvent<String> = mutableMessage fun isLoggedIn() = authHolder.isLoggedIn() fun getId() = authHolder.getId() fun syncNotifications() { if (!isLoggedIn()) return compositeDisposable += notificationService.syncNotifications(getId()) .withDefaultSchedulers() .subscribe({ list -> list?.forEach { if (!it.isRead) { preference.putBoolean(NEW_NOTIFICATIONS, true) mutableNewNotifications.value = true } } }, { if (it is HttpException) { if (authHolder.isLoggedIn() && it.code() == HttpErrors.UNAUTHORIZED) { logoutAndRefresh() } } Timber.e(it, "Error fetching notifications") }) } private fun logoutAndRefresh() { compositeDisposable += authService.logout() .withDefaultSchedulers() .subscribe({ mutableIsRefresh.value = true }, { Timber.e(it, "Error while logout") mutableMessage.value = resource.getString(R.string.error) }) } fun checkAndReset(token: String, newPassword: String) { val resetRequest = RequestPasswordReset(PasswordReset(token, newPassword)) if (authHolder.isLoggedIn()) { compositeDisposable += authService.logout() .withDefaultSchedulers() .doOnSubscribe { mutableDialogProgress.value = true }.subscribe { resetPassword(resetRequest) } } else resetPassword(resetRequest) } private fun resetPassword(resetRequest: RequestPasswordReset) { compositeDisposable += authService.resetPassword(resetRequest) .withDefaultSchedulers() .doOnSubscribe { mutableDialogProgress.value = true }.doFinally { mutableDialogProgress.value = false }.subscribe({ Timber.e(it.toString()) mutableMessage.value = resource.getString(R.string.reset_password_message) mutableResetPasswordEmail.value = it.email }, { Timber.e(it, "Failed to reset password") }) } fun fetchSettings() { compositeDisposable += settingsService.fetchSettings() .withDefaultSchedulers() .subscribe({ Timber.d("Settings fetched successfully") }, { Timber.e(it, "Error in fetching settings form API") }) } }
app/src/main/java/org/fossasia/openevent/general/StartupViewModel.kt
1966149288
package org.mifos.mobile.models.accounts.loan import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize import java.util.ArrayList /** * Created by Rajan Maurya on 04/03/17. */ @Parcelize data class RepaymentSchedule( @SerializedName("currency") var currency: Currency, @SerializedName("loanTermInDays") var loanTermInDays: Int? = null, @SerializedName("totalPrincipalDisbursed") var totalPrincipalDisbursed: Double? = null, @SerializedName("totalPrincipalExpected") var totalPrincipalExpected: Double? = null, @SerializedName("totalPrincipalPaid") var totalPrincipalPaid: Double? = null, @SerializedName("totalInterestCharged") var totalInterestCharged: Double? = null, @SerializedName("totalFeeChargesCharged") var totalFeeChargesCharged: Double? = null, @SerializedName("totalPenaltyChargesCharged") var totalPenaltyChargesCharged: Double? = null, @SerializedName("totalWaived") var totalWaived: Double? = null, @SerializedName("totalWrittenOff") var totalWrittenOff: Double? = null, @SerializedName("totalRepaymentExpected") var totalRepaymentExpected: Double? = null, @SerializedName("totalRepayment") var totalRepayment: Double? = null, @SerializedName("totalPaidInAdvance") var totalPaidInAdvance: Double? = null, @SerializedName("totalPaidLate") var totalPaidLate: Double? = null, @SerializedName("totalOutstanding") var totalOutstanding: Double? = null, @SerializedName("periods") var periods: List<Periods> = ArrayList() ) : Parcelable
app/src/main/java/org/mifos/mobile/models/accounts/loan/RepaymentSchedule.kt
4235803521
/* * Copyright 2017-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("unused") package kotlinx.serialization.json import kotlinx.serialization.* import kotlinx.serialization.json.internal.* /** * Class representing single JSON element. * Can be [JsonPrimitive], [JsonArray] or [JsonObject]. * * [JsonElement.toString] properly prints JSON tree as valid JSON, taking into account quoted values and primitives. * Whole hierarchy is serializable, but only when used with [Json] as [JsonElement] is purely JSON-specific structure * which has a meaningful schemaless semantics only for JSON. * * The whole hierarchy is [serializable][Serializable] only by [Json] format. */ @Serializable(JsonElementSerializer::class) public sealed class JsonElement /** * Class representing JSON primitive value. * JSON primitives include numbers, strings, booleans and special null value [JsonNull]. */ @Serializable(JsonPrimitiveSerializer::class) public sealed class JsonPrimitive : JsonElement() { /** * Indicates whether the primitive was explicitly constructed from [String] and * whether it should be serialized as one. E.g. `JsonPrimitive("42")` is represented * by a string, while `JsonPrimitive(42)` is not. * These primitives will be serialized as `42` and `"42"` respectively. */ public abstract val isString: Boolean /** * Content of given element without quotes. For [JsonNull] this methods returns `null` */ public abstract val content: String public override fun toString(): String = content } /** * Creates [JsonPrimitive] from the given boolean. */ public fun JsonPrimitive(value: Boolean?): JsonPrimitive { if (value == null) return JsonNull return JsonLiteral(value, isString = false) } /** * Creates [JsonPrimitive] from the given number. */ public fun JsonPrimitive(value: Number?): JsonPrimitive { if (value == null) return JsonNull return JsonLiteral(value, isString = false) } /** * Creates [JsonPrimitive] from the given string. */ public fun JsonPrimitive(value: String?): JsonPrimitive { if (value == null) return JsonNull return JsonLiteral(value, isString = true) } /** * Creates [JsonNull]. */ @ExperimentalSerializationApi @Suppress("FunctionName", "UNUSED_PARAMETER") // allows to call `JsonPrimitive(null)` public fun JsonPrimitive(value: Nothing?): JsonNull = JsonNull // JsonLiteral is deprecated for public use and no longer available. Please use JsonPrimitive instead internal class JsonLiteral internal constructor( body: Any, public override val isString: Boolean ) : JsonPrimitive() { public override val content: String = body.toString() public override fun toString(): String = if (isString) buildString { printQuoted(content) } else content // Compare by `content` and `isString`, because body can be kotlin.Long=42 or kotlin.String="42" public override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false other as JsonLiteral if (isString != other.isString) return false if (content != other.content) return false return true } @SuppressAnimalSniffer // Boolean.hashCode(boolean) public override fun hashCode(): Int { var result = isString.hashCode() result = 31 * result + content.hashCode() return result } } /** * Class representing JSON `null` value */ @Serializable(JsonNullSerializer::class) public object JsonNull : JsonPrimitive() { override val isString: Boolean get() = false override val content: String = "null" } /** * Class representing JSON object, consisting of name-value pairs, where value is arbitrary [JsonElement] * * Since this class also implements [Map] interface, you can use * traditional methods like [Map.get] or [Map.getValue] to obtain Json elements. */ @Serializable(JsonObjectSerializer::class) public class JsonObject(private val content: Map<String, JsonElement>) : JsonElement(), Map<String, JsonElement> by content { public override fun equals(other: Any?): Boolean = content == other public override fun hashCode(): Int = content.hashCode() public override fun toString(): String { return content.entries.joinToString( separator = ",", prefix = "{", postfix = "}", transform = { (k, v) -> buildString { printQuoted(k) append(':') append(v) } } ) } } /** * Class representing JSON array, consisting of indexed values, where value is arbitrary [JsonElement] * * Since this class also implements [List] interface, you can use * traditional methods like [List.get] or [List.getOrNull] to obtain Json elements. */ @Serializable(JsonArraySerializer::class) public class JsonArray(private val content: List<JsonElement>) : JsonElement(), List<JsonElement> by content { public override fun equals(other: Any?): Boolean = content == other public override fun hashCode(): Int = content.hashCode() public override fun toString(): String = content.joinToString(prefix = "[", postfix = "]", separator = ",") } /** * Convenience method to get current element as [JsonPrimitive] * @throws IllegalArgumentException if current element is not a [JsonPrimitive] */ public val JsonElement.jsonPrimitive: JsonPrimitive get() = this as? JsonPrimitive ?: error("JsonPrimitive") /** * Convenience method to get current element as [JsonObject] * @throws IllegalArgumentException if current element is not a [JsonObject] */ public val JsonElement.jsonObject: JsonObject get() = this as? JsonObject ?: error("JsonObject") /** * Convenience method to get current element as [JsonArray] * @throws IllegalArgumentException if current element is not a [JsonArray] */ public val JsonElement.jsonArray: JsonArray get() = this as? JsonArray ?: error("JsonArray") /** * Convenience method to get current element as [JsonNull] * @throws IllegalArgumentException if current element is not a [JsonNull] */ public val JsonElement.jsonNull: JsonNull get() = this as? JsonNull ?: error("JsonNull") /** * Returns content of the current element as int * @throws NumberFormatException if current element is not a valid representation of number */ public val JsonPrimitive.int: Int get() = content.toInt() /** * Returns content of the current element as int or `null` if current element is not a valid representation of number */ public val JsonPrimitive.intOrNull: Int? get() = content.toIntOrNull() /** * Returns content of current element as long * @throws NumberFormatException if current element is not a valid representation of number */ public val JsonPrimitive.long: Long get() = content.toLong() /** * Returns content of current element as long or `null` if current element is not a valid representation of number */ public val JsonPrimitive.longOrNull: Long? get() = content.toLongOrNull() /** * Returns content of current element as double * @throws NumberFormatException if current element is not a valid representation of number */ public val JsonPrimitive.double: Double get() = content.toDouble() /** * Returns content of current element as double or `null` if current element is not a valid representation of number */ public val JsonPrimitive.doubleOrNull: Double? get() = content.toDoubleOrNull() /** * Returns content of current element as float * @throws NumberFormatException if current element is not a valid representation of number */ public val JsonPrimitive.float: Float get() = content.toFloat() /** * Returns content of current element as float or `null` if current element is not a valid representation of number */ public val JsonPrimitive.floatOrNull: Float? get() = content.toFloatOrNull() /** * Returns content of current element as boolean * @throws IllegalStateException if current element doesn't represent boolean */ public val JsonPrimitive.boolean: Boolean get() = content.toBooleanStrictOrNull() ?: throw IllegalStateException("$this does not represent a Boolean") /** * Returns content of current element as boolean or `null` if current element is not a valid representation of boolean */ public val JsonPrimitive.booleanOrNull: Boolean? get() = content.toBooleanStrictOrNull() /** * Content of the given element without quotes or `null` if current element is [JsonNull] */ public val JsonPrimitive.contentOrNull: String? get() = if (this is JsonNull) null else content private fun JsonElement.error(element: String): Nothing = throw IllegalArgumentException("Element ${this::class} is not a $element") @PublishedApi internal fun unexpectedJson(key: String, expected: String): Nothing = throw IllegalArgumentException("Element $key is not a $expected")
formats/json/commonMain/src/kotlinx/serialization/json/JsonElement.kt
169893457
package antimattermod.core.Energy.Item.Wrench import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.world.World /** * Created by kojin15. */ interface IEnergyWrenchAction { /** * ブロック側の送受信設定 * なんてなかった、いいね? by C6H2Cl2 */ //fun settingTransceiver(itemStack: ItemStack, player: EntityPlayer, world: World, blockPos: BlockPos, side: Int, isSneaking: Boolean) }
src/main/java/antimattermod/core/Energy/Item/Wrench/IEnergyWrenchAction.kt
2424903205
@file:Suppress("unused") package tech.shadowfox.shadow.android.view.widgets import android.content.Context import android.util.AttributeSet import android.widget.RelativeLayout /** * Copyright 2017 Camaron Crowe * * 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. **/ class SquareRelativeLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : RelativeLayout(context, attrs, defStyleAttr) { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, widthMeasureSpec) } }
shadow-android/src/main/java/tech/shadowfox/shadow/android/view/widgets/SquareRelativeLayout.kt
17961647
package com.belatrix.authentication.ui import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import com.belatrix.authentication.R import com.belatrix.authentication.utils.ValidationUtils import kotlinx.android.synthetic.main.activity_registration.* @Suppress("UNUSED_PARAMETER") class RegistrationActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_registration) } /** * Validates the registration, and return all the errors * to the views */ fun attemptRegister(view: View) { var message: String? = null var editText: View? = null if (etFirstName.text.isEmpty()) { tilFirstName.error = getString(R.string.error_required) editText = etFirstName } if (etLastName.text.isEmpty()) { tilLastName.error = getString(R.string.error_required) editText = etLastName } if (etEmail.text.isEmpty()) { message = getString(R.string.error_required) } else if (!ValidationUtils.isEmailValid(etEmail.text)) { message = getString(R.string.error_email) } tilEmail.error = message if (message != null) { editText = etEmail message = null } if (etPassword.text.isEmpty()) { message = getString(R.string.error_required) } else if (!ValidationUtils.isPasswordValid(etPassword.text)) { message = getString(R.string.error_password) } tilPassword.error = message if (message != null) { editText = tilPassword } if (editText != null) { editText.requestFocus() } else { finish() } } /** * Returns to the login activity */ fun login(view: View) { finish() } }
app/src/main/java/com/belatrix/authentication/ui/RegistrationActivity.kt
3636166018
package com.github.feed.sample.ui.main import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.annotation.ColorRes import android.support.annotation.IdRes import android.support.v4.view.GravityCompat import android.view.Gravity import android.view.Menu import android.view.MenuItem import android.widget.CheckBox import com.github.feed.sample.R import com.github.feed.sample.data.* import com.github.feed.sample.data.model.Event import com.github.feed.sample.di.viewmodel.ViewModelFactory import com.github.feed.sample.ext.* import com.github.feed.sample.ui.common.mvp.MvpActivity import com.github.feed.sample.ui.details.DetailsActivity import com.github.feed.sample.ui.eventlist.EventListFragment import com.google.android.gms.oss.licenses.OssLicensesMenuActivity import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.toolbar.* import org.jetbrains.anko.intentFor class MainActivity : MvpActivity<MainContract.View, MainPresenter, MainViewModel>(), MainContract.View { companion object { private const val FRAGMENT_TAG_EVENTS = "fragment_tag_events" } private var eventsFragment: EventListFragment? = null private var checkBoxList = mutableListOf<CheckBox>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) eventsFragment = findFragment(FRAGMENT_TAG_EVENTS) as EventListFragment? if (eventsFragment == null){ eventsFragment = EventListFragment().apply { addFragment(this, R.id.container, FRAGMENT_TAG_EVENTS) } } requireNotNull(eventsFragment).eventClick = onEventClicked setupFilters() } override fun getViewModel(viewModelFactory: ViewModelFactory): MainViewModel { return ViewModelProviders.of(this, viewModelFactory).get() } override fun onStart() { super.onStart() presenter.loadFilterSelections() setTaskColor(getColorCompat(R.color.colorPrimary)) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_main, menu) menu.findItem(R.id.menu_item_filter).isVisible = hasInternetConnection() return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_item_filter -> drawerLayout.openDrawer(Gravity.END) R.id.menu_item_licenses -> startActivity(intentFor<OssLicensesMenuActivity>()) } return true } private val onEventClicked: (Event) -> Unit = { event -> startActivityTransition(DetailsActivity.createIntent(this, event)) } override fun onBackPressed() { if (drawerLayout.isDrawerOpen(GravityCompat.END)) { drawerLayout.closeDrawer(Gravity.END) } else { super.onBackPressed() } } override fun selectFilter(tag: String, selected: Boolean) { checkBoxList.find { it.tag as String == tag }?.isChecked = selected } private fun setupFilters() { setupCheckBox(R.id.action_filter_create, R.color.orange_A400, EVENT_CREATE) setupCheckBox(R.id.action_filter_delete, R.color.purple_A200, EVENT_DELETE) setupCheckBox(R.id.action_filter_fork, R.color.green_A400, EVENT_FORK) setupCheckBox(R.id.action_filter_pull_request, R.color.deep_purple_A200, EVENT_PULL_REQUEST) setupCheckBox(R.id.action_filter_push, R.color.red_A200, EVENT_PUSH) setupCheckBox(R.id.action_filter_watch, R.color.indigo_A400, EVENT_WATCH) navigationView.setNavigationItemSelectedListener { item -> (item.actionView as CheckBox).apply { post { isChecked = !isChecked } } true } } private fun setupCheckBox(@IdRes checkboxId: Int, @ColorRes colorId: Int, eventType: String) { navigationView.findCheckbox(checkboxId).apply { checkBoxList.add(this) tag = eventType isChecked = true setButtonTintColor(colorId) setOnCheckedChangeListener { _, isChecked -> presenter.saveFilterSelection(tag as String, isChecked) if (isChecked) { requireNotNull(eventsFragment).unfilterEventType(eventType) } else { requireNotNull(eventsFragment).filterEventType(eventType) } } } } }
app/src/main/kotlin/com/github/feed/sample/ui/main/MainActivity.kt
2692985238
package ch.difty.scipamato.core.entity.code import ch.difty.scipamato.core.entity.CodeClass import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeFalse import org.amshove.kluent.shouldBeNull import org.amshove.kluent.shouldBeTrue import org.amshove.kluent.shouldContainSame import org.amshove.kluent.shouldHaveSize import org.amshove.kluent.shouldNotBeNull import org.junit.jupiter.api.Test @Suppress("PrivatePropertyName", "SpellCheckingInspection", "SameParameterValue", "VariableNaming") internal class CodeDefinitionTest { private val c_de = CodeTranslation(10, "de", "codede2", "kommentar", 1) private val c_de2 = CodeTranslation(10, "de", "codede2foo", null, 1) private val c_en = CodeTranslation(11, "en", "codeen2", "comment", 1) private val c_fr = CodeTranslation(12, "fr", "codefr2", "remarc", 1) private val codeClass = CodeClass(1, "cc1", "foo") @Test fun withNoTranslations_unableToEstablishMainName() { val code = CodeDefinition("1A", "de", codeClass, 2, false, 1) code.code shouldBeEqualTo "1A" code.name shouldBeEqualTo "n.a." code.codeClass shouldBeEqualTo codeClass code.sort shouldBeEqualTo 2 code.isInternal.shouldBeFalse() code.displayValue shouldBeEqualTo "n.a." } @Test fun withTranslations_onePerLanguage() { val code = CodeDefinition("1A", "de", codeClass, 1, true, 1, c_de, c_en, c_fr) code.code shouldBeEqualTo "1A" code.name shouldBeEqualTo "codede2" code.isInternal.shouldBeTrue() code.mainLanguageCode shouldBeEqualTo "de" code.displayValue shouldBeEqualTo "codede2" code.getTranslations() shouldHaveSize 3 val trs = code.getTranslations() trs.map { it.name } shouldContainSame listOf("codede2", "codeen2", "codefr2") for (tr in trs) tr.lastModified.shouldBeNull() } @Test fun canGetTranslationsAsString_withTranslationsIncludingMainTranslation() { val code = CodeDefinition("1A", "de", codeClass, 1, false, 1, c_de, c_en, c_fr) code.translationsAsString shouldBeEqualTo "DE: 'codede2'; EN: 'codeen2'; FR: 'codefr2'" } @Test fun canGetTranslationsAsString_withTranslationsIncludingMainTranslation_withPartialTranslation() { val code = CodeDefinition( "1A", "de", codeClass, 1, false, 1, c_de, c_en, CodeTranslation(12, "fr", null, "remarc", 1) ) code.translationsAsString shouldBeEqualTo "DE: 'codede2'; EN: 'codeen2'; FR: n.a." } @Test fun modifyTranslation_withMainLanguTranslationModified_changesMainName_translationName_andSetsModifiedTimestamp() { val code = CodeDefinition( "1A", "de", codeClass, 1, false, 1, c_de, c_en, c_fr ) code.setNameInLanguage("de", "CODE 2") code.name shouldBeEqualTo "CODE 2" assertTranslatedName(code, "de", 0, "CODE 2") assertLastModifiedIsNotNull(code, "de", 0) assertLastModifiedIsNull(code, "en", 0) assertLastModifiedIsNull(code, "fr", 0) } private fun assertTranslatedName(code: CodeDefinition, lc: String, index: Int, value: String) { code.getTranslations(lc)[index]?.name shouldBeEqualTo value } private fun assertLastModifiedIsNotNull(code: CodeDefinition, lc: String, index: Int) { code.getTranslations(lc)[index]?.lastModified.shouldNotBeNull() } private fun assertLastModifiedIsNull(code: CodeDefinition, lc: String, index: Int) { code.getTranslations(lc)[index]?.lastModified.shouldBeNull() } @Test fun modifyTranslation_withNonMainLangTranslModified_keepsMainName_changesTranslName_andSetsModifiedTimestamp() { val code = CodeDefinition( "1A", "de", codeClass, 1, false, 1, c_de, c_en, c_fr ) code.setNameInLanguage("fr", "bar") code.name shouldBeEqualTo "codede2" assertTranslatedName(code, "fr", 0, "bar") code.getTranslations("de")[0]?.lastModified.shouldBeNull() code.getTranslations("en")[0].lastModified.shouldBeNull() assertLastModifiedIsNotNull(code, "fr", 0) } @Test fun gettingNameInLanguage_withValidLanguages_returnsNames() { val code = CodeDefinition( "1A", "de", codeClass, 1, false, 1, c_de, c_en, c_fr ) code.getNameInLanguage("de") shouldBeEqualTo "codede2" code.getNameInLanguage("en") shouldBeEqualTo "codeen2" code.getNameInLanguage("fr") shouldBeEqualTo "codefr2" } @Test fun gettingNameInLanguage_withInvalidLanguage_returnsNames() { val code = CodeDefinition("1A", "de", codeClass, 1, false, 1, c_de, c_en, c_fr) code.getNameInLanguage("deX").shouldBeNull() } @Test fun withTranslations_moreThanOnePerLanguage() { val code = CodeDefinition("1B", "de", codeClass, 1, false, 1, c_de, c_de2, c_en, c_fr) code.code shouldBeEqualTo "1B" code.name shouldBeEqualTo "codede2" code.displayValue shouldBeEqualTo "codede2" val trs = code.getTranslations() trs.map { it.name } shouldContainSame listOf("codede2", "codede2foo", "codeen2", "codefr2") for (tr in trs) tr.lastModified.shouldBeNull() } @Test fun canGetTranslationsAsString_withTranslationsIncludingMainTranslation_withMultipleTranslations() { val code = CodeDefinition("1A", "de", codeClass, 1, false, 1, c_de, c_de2, c_en, c_fr) code.translationsAsString shouldBeEqualTo "DE: 'codede2','codede2foo'; EN: 'codeen2'; FR: 'codefr2'" } @Test fun modifyTransl_withMainLangTranslMod_changesMainName_translName_andSetsModTimestamp_multipleTranslsPerLanguage() { val code = CodeDefinition( "1A", "de", codeClass, 1, false, 1, c_de, c_de2, c_en, c_fr ) code.setNameInLanguage("de", "Code 2") code.name shouldBeEqualTo "Code 2" assertTranslatedName(code, "de", 0, "Code 2") assertTranslatedName(code, "de", 1, "codede2foo") assertLastModifiedIsNotNull(code, "de", 0) assertLastModifiedIsNull(code, "de", 1) assertLastModifiedIsNull(code, "en", 0) assertLastModifiedIsNull(code, "fr", 0) } @Test fun assertCodeFields() { CodeDefinition.CodeDefinitionFields.values().map { it.fieldName } shouldContainSame listOf("code", "mainLanguageCode", "codeClass", "sort", "internal", "name") } @Test fun gettingNulSafeId() { val code = CodeDefinition("1A", "de", codeClass, 1, false, 1, c_de, c_de2, c_en, c_fr) code.nullSafeId shouldBeEqualTo "1A" } }
core/core-entity/src/test/kotlin/ch/difty/scipamato/core/entity/code/CodeDefinitionTest.kt
756278224
package org.kwicket.wicket.core.markup.html.panel import org.apache.wicket.behavior.Behavior import org.apache.wicket.markup.html.panel.Panel import org.apache.wicket.model.IModel import org.kwicket.component.init /** * [Panel] with named and default constructor arguments. * * @param id id of the [Component] * @param model optional [IModel] of the [Component] * @param outputMarkupId optional flag indicating whether an id attribute will be created on the HTML element * @param outputMarkupPlaceholderTag optional flag indicating whether an id attribtue will be created on the HTML * element, creating a placeholder id if the component is initially not visible * @param visible optional flag indicating whether the [Component] is visible * @param enabled optional flag indicating whether the [Component] is enabled * @param renderBodyOnly optional flag indicating whether only the [Component]'s HTML will be rendered or whether the * tag the [Component] is attached to will also be rendered * @param escapeModelStrings optional flag indicating whether the [Component]'s model String values will be escaped * @param behaviors [List] of [Behavior]s to add to the [Component] */ abstract class KPanel( id: String, model: IModel<*>? = null, outputMarkupId: Boolean? = null, outputMarkupPlaceholderTag: Boolean? = null, visible: Boolean? = null, enabled: Boolean? = null, renderBodyOnly: Boolean? = null, escapeModelStrings: Boolean? = null, behaviors: List<Behavior>? = null ) : Panel(id, model) { constructor( id: String, model: IModel<*>? = null, outputMarkupId: Boolean? = null, outputMarkupPlaceholderTag: Boolean? = null, visible: Boolean? = null, enabled: Boolean? = null, renderBodyOnly: Boolean? = null, escapeModelStrings: Boolean? = null, behavior: Behavior ) : this( id = id, model = model, outputMarkupId = outputMarkupId, outputMarkupPlaceholderTag = outputMarkupPlaceholderTag, visible = visible, enabled = enabled, escapeModelStrings = escapeModelStrings, renderBodyOnly = renderBodyOnly, behaviors = listOf(behavior) ) init { init( outputMarkupId = outputMarkupId, outputMarkupPlaceholderTag = outputMarkupPlaceholderTag, visible = visible, enabled = enabled, escapeModelStrings = escapeModelStrings, renderBodyOnly = renderBodyOnly, behaviors = behaviors ) } }
kwicket-wicket-core/src/main/kotlin/org/kwicket/wicket/core/markup/html/panel/KPanel.kt
650115108
package io.rover.sdk.core.platform import android.content.Context import android.content.Context.MODE_PRIVATE import android.content.SharedPreferences /** * Very simple hash-like storage of keys and values. */ interface KeyValueStorage { /** * Get the current value of the given key, or null if unset. */ operator fun get(key: String): String? /** * Set the value of the given key. If [value] is null, unsets the key. */ operator fun set(key: String, value: String?) /** * Clear and remove a given key. */ fun unset(key: String) val keys: Set<String> } /** * Obtain a persistent key-value named persistent storage area. */ interface LocalStorage { fun getKeyValueStorageFor(namedContext: String): KeyValueStorage } /** * Implementation of [LocalStorage] using Android's [SharedPreferences]. */ class SharedPreferencesLocalStorage( val context: Context, private val baseContextName: String = "io.rover.local-storage" ) : LocalStorage { override fun getKeyValueStorageFor(namedContext: String): KeyValueStorage { val prefs = context.getSharedPreferences("$baseContextName.$namedContext", MODE_PRIVATE) // TODO: implement singleton guarding to avoid multiple consumer instances requesting the // same namedContext and possibly conflicting. return object : KeyValueStorage { override fun get(key: String): String? = prefs.getString(key, null) override fun set(key: String, value: String?) { prefs.edit().putString(key, value).apply() } override fun unset(key: String) { prefs.edit().remove(key).apply() } override val keys: Set<String> get() = prefs.all.keys .toSet() } } }
core/src/main/kotlin/io/rover/sdk/core/platform/LocalStorage.kt
1046522360
package me.hyemdooly.sangs.dimigo.app.project.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import me.hyemdooly.sangs.dimigo.app.project.database.DataController import java.util.* class ScreenOnOffReceiver : BroadcastReceiver() { var dataController: DataController? = null var firstTime: Long = System.currentTimeMillis() var lastTime: Long = 0 var countTime: Long = 0 override fun onReceive(p0: Context?, p1: Intent?) { dataController = DataController(p0!!) when(p1?.action){ Intent.ACTION_SCREEN_OFF -> { lastTime = System.currentTimeMillis() if(!firstTime.equals(0)){ countTime = lastTime-firstTime dataController!!.addTimeData("used", countTime, Date()) firstTime = lastTime } } Intent.ACTION_SCREEN_ON -> { lastTime = System.currentTimeMillis() if(!firstTime.equals(0)){ countTime = lastTime-firstTime dataController!!.addTimeData("unused", countTime, Date()) firstTime = lastTime } } } } }
app/src/main/kotlin/me/hyemdooly/sangs/dimigo/app/project/receiver/ScreenOnOffReceiver.kt
2690728354
package lindar.acolyte.vo import java.util.function.Function data class PaginatedCollection<out T>(val contents: List<T>, val pagination: PaginationVO, val sort: SortVO) data class CursorPaginatedCollection<T>(val contents: List<T>, val pagination: CursorPaginationVO, val sort: SortVO) { fun <U> map(converter: Function<T, U>): CursorPaginatedCollection<U> { return CursorPaginatedCollection(contents.map(converter::apply), pagination, sort) } fun filter(predicate: Function<T, Boolean>): CursorPaginatedCollection<T> { return CursorPaginatedCollection(contents.filter(predicate::apply), pagination, sort) } } data class PaginationVO(val page: Int, val size: Int, val totalPages: Int, var totalElements: Long) { companion object Builder { private var builderPage = 0 private var builderSize = 20 private var builderTotalPages = 0 private var builderTotalElements = 0L fun page(page: Int): PaginationVO.Builder { this.builderPage = page return this } fun size(size: Int): PaginationVO.Builder { this.builderSize = size return this } fun totalPages(totalPages: Int): PaginationVO.Builder { this.builderTotalPages = totalPages return this } fun totalElements(totalElements: Long): PaginationVO.Builder { this.builderTotalElements = totalElements return this } fun build() = PaginationVO(builderPage, builderSize, builderTotalPages, builderTotalElements) } } data class CursorPaginationVO(val cursor: String?, val size: Int) { val hasNext: Boolean get() = this.cursor != null companion object Builder { private var builderCursor: String? = null private var builderSize = 20 fun cursor(cursor: String?): CursorPaginationVO.Builder { this.builderCursor = cursor return this } fun size(size: Int): CursorPaginationVO.Builder { this.builderSize = size return this } fun build() = CursorPaginationVO(builderCursor, builderSize) } } data class PageableVO(val page: Int, val size: Int, val sort: List<SortVO>? = null) { companion object Builder { private var builderPage = 0 private var builderSize = 20 private var builderSort: List<SortVO>? = null fun page(page: Int): PageableVO.Builder { this.builderPage = page return this } fun size(size: Int): PageableVO.Builder { this.builderSize = size return this } fun sort(sort: List<SortVO>): PageableVO.Builder { this.builderSort = sort return this } fun build() = PageableVO(builderPage, builderSize, builderSort) } } data class SortVO(val field: String, val dir: SortDirection = SortDirection.ASC) { companion object Builder { private var builderField = "" private var builderDir = SortDirection.ASC fun field(field: String): SortVO.Builder { this.builderField = field return this } fun dir(dir: SortDirection): SortVO.Builder { this.builderDir = dir return this } fun build() = SortVO(builderField, builderDir) } } enum class SortDirection { DESC, ASC }
src/main/kotlin/lindar/acolyte/vo/pagination.kt
1700573940
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInspection.javaDoc import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.SuppressQuickFix import com.intellij.codeInspection.ex.ExternalAnnotatorBatchInspection import com.intellij.psi.PsiElement class JavadocHtmlLintInspection : LocalInspectionTool(), ExternalAnnotatorBatchInspection { companion object { val SHORT_NAME = "JavadocHtmlLint" } override fun getBatchSuppressActions(element: PsiElement?): Array<out SuppressQuickFix> = SuppressQuickFix.EMPTY_ARRAY }
java/java-impl/src/com/intellij/codeInspection/javaDoc/JavadocHtmlLintInspection.kt
1823611671
package za.org.grassroot2.util import android.content.Context import java.util.Calendar import java.util.concurrent.TimeUnit import za.org.grassroot2.R object LastModifiedFormatter { fun lastSeen(c: Context, datetimeInMillis: Long): String { var out = "" try { val calendar = Calendar.getInstance() val diff = calendar.timeInMillis - datetimeInMillis val difSeconds = TimeUnit.MILLISECONDS.toSeconds(diff).toInt() val difMinutes = TimeUnit.MILLISECONDS.toMinutes(diff).toInt() val difHours = TimeUnit.MILLISECONDS.toHours(diff).toInt() val difDay = TimeUnit.MILLISECONDS.toDays(diff).toInt() val difMonth = difDay / 30 val difYear = difMonth / 12 if (difSeconds <= 0) { out = "Now" } else if (difSeconds < 60) { out = c.resources.getQuantityString(R.plurals.last_modified, difSeconds, difSeconds, "second") } else if (difMinutes < 60) { out = c.resources.getQuantityString(R.plurals.last_modified, difMinutes, difMinutes, "minute") } else if (difHours < 24) { out = c.resources.getQuantityString(R.plurals.last_modified, difHours, difHours, "hour") } else if (difDay < 30) { out = c.resources.getQuantityString(R.plurals.last_modified, difDay, difDay, "day") } else if (difMonth < 12) { out = c.resources.getQuantityString(R.plurals.last_modified, difMonth, difMonth, "month") } else { out = c.resources.getQuantityString(R.plurals.last_modified, difYear, difYear, "year") } } catch (e: Exception) { e.printStackTrace() } return out } }
app/src/main/java/za/org/grassroot2/util/LastModifiedFormatter.kt
3085294011
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.tests import com.intellij.testGuiFramework.impl.GuiTestCase import org.junit.After import org.junit.Before /** * @author Sergey Karashevich */ open class GitGuiTestCase: GuiTestCase(){ @Before override fun setUp() { super.setUp() if (IS_UNDER_TEAMCITY) GitSettings.setup() } @After override fun tearDown() { GitSettings.restore() super.tearDown() } }
plugins/git4idea/tests/com/intellij/testGuiFramework/tests/GitGuiTestCase.kt
354188777
/***************************************************************************** * CoverMediaSwitcher.java * * Copyright © 2011-2014 VLC authors and VideoLAN * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. */ package org.videolan.vlc.gui.view import android.content.Context import android.graphics.Bitmap import android.util.AttributeSet import android.view.LayoutInflater import android.widget.ImageView import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import org.videolan.vlc.R @ExperimentalCoroutinesApi @ObsoleteCoroutinesApi class CoverMediaSwitcher(context: Context, attrs: AttributeSet) : AudioMediaSwitcher(context, attrs) { override fun addMediaView(inflater: LayoutInflater, title: String?, artist: String?, cover: Bitmap?) { val imageView = ImageView(context) imageView.scaleType = ImageView.ScaleType.FIT_CENTER if (cover == null) imageView.setImageResource(R.drawable.icon) else imageView.setImageBitmap(cover) addView(imageView) } }
application/vlc-android/src/org/videolan/vlc/gui/view/CoverMediaSwitcher.kt
4224290899
package org.jetbrains.builtInWebServer import com.intellij.execution.ExecutionException import com.intellij.execution.filters.TextConsoleBuilder import com.intellij.execution.process.OSProcessHandler import com.intellij.execution.process.ProcessAdapter import com.intellij.execution.process.ProcessEvent import com.intellij.execution.ui.ConsoleViewContentType import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.util.Consumer import com.intellij.util.net.NetUtils import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.AsyncValueLoader import org.jetbrains.concurrency.Promise import org.jetbrains.util.concurrency import org.jetbrains.util.concurrency.toPromise import javax.swing.Icon public abstract class NetService @jvmOverloads protected constructor(protected val project: Project, private val consoleManager: ConsoleManager = ConsoleManager()) : Disposable { companion object { protected val LOG: Logger = Logger.getInstance(javaClass<NetService>()) } protected val processHandler: AsyncValueLoader<OSProcessHandler> = object : AsyncValueLoader<OSProcessHandler>() { override fun isCancelOnReject() = true private fun doGetProcessHandler(port: Int): OSProcessHandler? { try { return createProcessHandler(project, port) } catch (e: ExecutionException) { LOG.error(e) return null } } override fun load(promise: AsyncPromise<OSProcessHandler>): Promise<OSProcessHandler> { val port = NetUtils.findAvailableSocketPort() val processHandler = doGetProcessHandler(port) if (processHandler == null) { promise.setError("rejected") return promise } promise.rejected(object : Consumer<Throwable> { override fun consume(error: Throwable) { processHandler.destroyProcess() Promise.logError(LOG, error) } }) val processListener = MyProcessAdapter() processHandler.addProcessListener(processListener) processHandler.startNotify() if (promise.getState() === Promise.State.REJECTED) { return promise } ApplicationManager.getApplication().executeOnPooledThread(object : Runnable { override fun run() { if (promise.getState() !== Promise.State.REJECTED) { try { connectToProcess(promise.toPromise(), port, processHandler, processListener) } catch (e: Throwable) { if (!promise.setError(e)) { LOG.error(e) } } } } }) return promise } override fun disposeResult(processHandler: OSProcessHandler) { try { closeProcessConnections() } finally { processHandler.destroyProcess() } } } throws(ExecutionException::class) protected abstract fun createProcessHandler(project: Project, port: Int): OSProcessHandler? protected open fun connectToProcess(promise: concurrency.AsyncPromise<OSProcessHandler>, port: Int, processHandler: OSProcessHandler, errorOutputConsumer: Consumer<String>) { promise.setResult(processHandler) } protected abstract fun closeProcessConnections() override fun dispose() { processHandler.reset() } protected open fun configureConsole(consoleBuilder: TextConsoleBuilder) { } protected abstract fun getConsoleToolWindowId(): String protected abstract fun getConsoleToolWindowIcon(): Icon public open fun getConsoleToolWindowActions(): ActionGroup = DefaultActionGroup() private inner class MyProcessAdapter : ProcessAdapter(), Consumer<String> { override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) { print(event.getText(), ConsoleViewContentType.getConsoleViewType(outputType)) } private fun print(text: String, contentType: ConsoleViewContentType) { consoleManager.getConsole(this@NetService).print(text, contentType) } override fun processTerminated(event: ProcessEvent) { processHandler.reset() print("${getConsoleToolWindowId()} terminated\n", ConsoleViewContentType.SYSTEM_OUTPUT) } override fun consume(message: String) { print(message, ConsoleViewContentType.ERROR_OUTPUT) } } }
platform/built-in-server/src/org/jetbrains/builtInWebServer/NetService.kt
1267908012
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.material.composethemeadapter.test import android.content.Context import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate /** * An [AppCompatActivity] which forces the night mode to 'dark theme'. */ class DarkMdcActivity : AppCompatActivity() { override fun attachBaseContext(newBase: Context) { delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_YES super.attachBaseContext(newBase) } }
materialLib/src/androidTest/java/com/google/android/material/composethemeadapter/test/DarkMdcActivity.kt
3290549392
package com.didichuxing.doraemonkit.kit.dokitforweb import android.app.Activity import android.content.Context import com.didichuxing.doraemonkit.R import com.didichuxing.doraemonkit.aop.DokitPluginConfig import com.didichuxing.doraemonkit.kit.AbstractKit import com.didichuxing.doraemonkit.kit.weaknetwork.WeakNetworkFragment import com.didichuxing.doraemonkit.util.DoKitCommUtil import com.didichuxing.doraemonkit.util.ToastUtils import com.google.auto.service.AutoService /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2019-09-24-17:05 * 描 述:数据库远程访问入口 去掉 * 修订历史: * ================================================ */ @AutoService(AbstractKit::class) class DokitForWebKit : AbstractKit() { override val name: Int get() = R.string.dk_kit_dokit_for_web override val icon: Int get() = R.mipmap.dk_dokit_for_web override fun onClickWithReturn(activity: Activity): Boolean { if (!DokitPluginConfig.SWITCH_DOKIT_PLUGIN) { ToastUtils.showShort(DoKitCommUtil.getString(R.string.dk_plugin_close_tip)) return false } startUniversalActivity(DoKitForWebJsInjectFragment::class.java, activity, null, true) return true } override fun onAppInit(context: Context?) { DokitForWeb.loadConfig() } override val isInnerKit: Boolean get() = true override fun innerKitId(): String { return "dokit_sdk_platform_ck_dokit_for_web" } }
Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/dokitforweb/DokitForWebKit.kt
2919155801
/* * Copyright (C) 2020-2021 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.apps.adrcotfas.goodtime.ui.upgrade_dialog import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.apps.adrcotfas.goodtime.R import com.apps.adrcotfas.goodtime.util.ThemeHelper class ExtraFeaturesAdapter( private val context: Context, private val data : List<Pair<String, Int>>) : RecyclerView.Adapter<ExtraFeaturesAdapter.ViewHolder>() { override fun getItemCount(): Int = data.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(context, data[position]) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder.from(parent) } class ViewHolder private constructor(itemView: View) : RecyclerView.ViewHolder(itemView) { private val text: TextView = itemView.findViewById(R.id.text) private val icon: ImageView = itemView.findViewById(R.id.icon) fun bind(context : Context, item: Pair<String, Int>) { text.text = item.first icon.setImageDrawable(context.resources.getDrawable(item.second)) icon.setColorFilter(ThemeHelper.getColor(context, ThemeHelper.COLOR_INDEX_UNLABELED)) } companion object { fun from(parent: ViewGroup) : ViewHolder { val inflater = LayoutInflater.from(parent.context) val view = inflater.inflate(R.layout.dialog_upgrade_row, parent, false) return ViewHolder(view) } } } }
app/src/google/java/com/apps/adrcotfas/goodtime/ui/upgrade_dialog/ExtraFeaturesAdapter.kt
1332441423
package io.gitlab.arturbosch.detekt.generator.collection import io.gitlab.arturbosch.detekt.generator.collection.exception.InvalidDocumentationException sealed class DefaultActivationStatus { abstract val active: Boolean } object Inactive : DefaultActivationStatus() { override val active = false } data class Active(val since: String) : DefaultActivationStatus() { override val active = true init { if (!since.matches(SEMANTIC_VERSION_PATTERN)) { throw InvalidDocumentationException( "'$since' must match the semantic version pattern <major>.<minor>.<patch>" ) } } companion object { private val SEMANTIC_VERSION_PATTERN = """^\d+\.\d+.\d+$""".toRegex() } }
detekt-generator/src/main/kotlin/io/gitlab/arturbosch/detekt/generator/collection/DefaultActivationStatus.kt
2859787503
package com.klask.session import com.klask.Klask import com.klask.request import com.klask.router.Route import org.junit.Assert import org.junit.Test object app : Klask() { Route("/set") fun set() { request.session["name"] = request.values["name"]?.get(0) } Route("/get") fun get(): String? { return request.session["name"] as String? } } class TestSession { Test fun testGet() { val client = app.client client.get("/set?name=steve") Assert.assertEquals("steve", client.get("/get").data) } }
src/test/kotlin/com/klask/session.kt
2670720588
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.project.esb import com.google.common.eventbus.AllowConcurrentEvents import com.google.common.eventbus.Subscribe import com.mycollab.common.dao.CommentMapper import com.mycollab.common.domain.CommentExample import com.mycollab.common.domain.TagExample import com.mycollab.common.service.TagService import com.mycollab.module.ecm.service.ResourceService import com.mycollab.module.esb.GenericCommand import com.mycollab.module.file.AttachmentUtils import com.mycollab.module.project.ProjectTypeConstants import com.mycollab.module.project.dao.TicketKeyMapper import com.mycollab.module.project.dao.TicketRelationMapper import com.mycollab.module.project.domain.TicketKeyExample import com.mycollab.module.project.domain.TicketRelationExample import org.springframework.stereotype.Component /** * @author MyCollab Ltd * @since 6.0.0 */ @Component class DeleteProjectTaskCommand(private val resourceService: ResourceService, private val commentMapper: CommentMapper, private val tagService: TagService, private val ticketKeyMapper: TicketKeyMapper, private val ticketRelationMapper: TicketRelationMapper) : GenericCommand() { @AllowConcurrentEvents @Subscribe fun removedTask(event: DeleteProjectTaskEvent) { val taskIds = event.tasks.map { it.id }.toCollection(mutableListOf()) event.tasks.forEach { removeRelatedFiles(event.accountId, it.projectid, it.id) removeRelatedTags(it.id) } removeRelatedComments(taskIds) removeTicketKeys(taskIds) removeTicketRelations(taskIds) } private fun removeRelatedFiles(accountId: Int, projectId: Int, taskId: Int) { val attachmentPath = AttachmentUtils.getProjectEntityAttachmentPath(accountId, projectId, ProjectTypeConstants.TASK, "$taskId") resourceService.removeResource(attachmentPath, "", true, accountId) } private fun removeRelatedComments(taskIds: MutableList<Int>) { val ex = CommentExample() ex.createCriteria().andTypeEqualTo(ProjectTypeConstants.TASK).andExtratypeidIn(taskIds) commentMapper.deleteByExample(ex) } private fun removeTicketKeys(taskIds: MutableList<Int>) { val ex = TicketKeyExample() ex.createCriteria().andTicketidIn(taskIds).andTickettypeEqualTo(ProjectTypeConstants.TASK) ticketKeyMapper.deleteByExample(ex) } private fun removeTicketRelations(taskIds: MutableList<Int>) { val ex = TicketRelationExample() ex.createCriteria().andTicketidIn(taskIds).andTickettypeEqualTo(ProjectTypeConstants.TASK) ticketRelationMapper.deleteByExample(ex) } private fun removeRelatedTags(taskId: Int) { val ex = TagExample() ex.createCriteria().andTypeEqualTo(ProjectTypeConstants.TASK).andTypeidEqualTo("$taskId") tagService.deleteByExample(ex) } }
mycollab-esb/src/main/java/com/mycollab/module/project/esb/DeleteProjectTaskCommand.kt
1898564835
/* * Copyright (c) 2019 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.upnp.internal.server import net.mm2d.upnp.Http import net.mm2d.upnp.HttpRequest import net.mm2d.upnp.internal.parser.parseEventXml import net.mm2d.upnp.internal.parser.parseUsn import net.mm2d.upnp.internal.thread.TaskExecutors import net.mm2d.upnp.internal.thread.ThreadCondition import net.mm2d.upnp.internal.util.closeQuietly import net.mm2d.upnp.util.findInet4Address import net.mm2d.upnp.util.findInet6Address import net.mm2d.upnp.util.toSimpleString import java.io.ByteArrayInputStream import java.io.IOException import java.net.DatagramPacket import java.net.InterfaceAddress import java.net.MulticastSocket import java.net.NetworkInterface import java.net.SocketTimeoutException internal class MulticastEventReceiver( taskExecutors: TaskExecutors, val address: Address, private val networkInterface: NetworkInterface, private val listener: (uuid: String, svcid: String, lvl: String, seq: Long, properties: List<Pair<String, String>>) -> Unit ) : Runnable { private val interfaceAddress: InterfaceAddress = if (address == Address.IP_V4) networkInterface.findInet4Address() else networkInterface.findInet6Address() private var socket: MulticastSocket? = null private val threadCondition = ThreadCondition(taskExecutors.server) // VisibleForTesting @Throws(IOException::class) internal fun createMulticastSocket(port: Int): MulticastSocket { return MulticastSocket(port).also { it.networkInterface = networkInterface } } fun start() { threadCondition.start(this) } fun stop() { threadCondition.stop() socket.closeQuietly() } override fun run() { val suffix = "-multicast-event-" + networkInterface.name + "-" + interfaceAddress.address.toSimpleString() Thread.currentThread().let { it.name = it.name + suffix } if (threadCondition.isCanceled()) return try { val socket = createMulticastSocket(ServerConst.EVENT_PORT) this.socket = socket socket.joinGroup(address.eventInetAddress) threadCondition.notifyReady() receiveLoop(socket) } catch (ignored: IOException) { } finally { socket?.leaveGroup(address.eventInetAddress) socket.closeQuietly() socket = null } } // VisibleForTesting @Throws(IOException::class) internal fun receiveLoop(socket: MulticastSocket) { val buf = ByteArray(1500) while (!threadCondition.isCanceled()) { try { val dp = DatagramPacket(buf, buf.size) socket.receive(dp) if (threadCondition.isCanceled()) break onReceive(dp.data, dp.length) } catch (ignored: SocketTimeoutException) { } } } // VisibleForTesting internal fun onReceive(data: ByteArray, length: Int) { val request = HttpRequest.create().apply { readData(ByteArrayInputStream(data, 0, length)) } if (request.getHeader(Http.NT) != Http.UPNP_EVENT) return if (request.getHeader(Http.NTS) != Http.UPNP_PROPCHANGE) return val lvl = request.getHeader(Http.LVL) if (lvl.isNullOrEmpty()) return val seq = request.getHeader(Http.SEQ)?.toLongOrNull() ?: return val svcid = request.getHeader(Http.SVCID) if (svcid.isNullOrEmpty()) return val (uuid, _) = request.parseUsn() if (uuid.isEmpty()) return val properties = request.getBody().parseEventXml() if (properties.isEmpty()) return listener.invoke(uuid, svcid, lvl, seq, properties) } }
mmupnp/src/main/java/net/mm2d/upnp/internal/server/MulticastEventReceiver.kt
1558409721
package com.andrewgrosner.kbinding.sample.widget import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import com.andrewgrosner.kbinding.BindingHolder import com.andrewgrosner.kbinding.BindingRegister import com.andrewgrosner.kbinding.anko.BindingComponent import org.jetbrains.anko.AnkoContext /** * Description: ViewHolder that holds a required binding. */ abstract class BaseViewHolder<Data> : RecyclerView.ViewHolder { val component: BindingRegister<Data> constructor(view: View) : super(view) { component = BindingHolder<Data>() component.bindAll() } constructor(parent: ViewGroup, component: BindingComponent<ViewGroup, Data>) : super(component.createView(AnkoContext.create(parent.context, parent))) { this.component = component component.bindAll() } val context get() = itemView.context fun bind(data: Data) { applyBindings(data, component) if (!component.isBound) { component.bindAll() } } abstract fun applyBindings(data: Data, holder: BindingRegister<Data>) } class AnkoViewHolder<Data>(parent: ViewGroup, component: BindingComponent<ViewGroup, Data>) : BaseViewHolder<Data>(parent, component) { override fun applyBindings(data: Data, holder: BindingRegister<Data>) { holder.viewModel = data } } class NoBindingViewHolder<Any>(view: View) : BaseViewHolder<Any>(view) { override fun applyBindings(data: Any, holder: BindingRegister<Any>) = Unit }
app/src/main/java/com/andrewgrosner/kbinding/sample/widget/BaseViewHolder.kt
2569146780
package com.emogoth.android.phone.mimi.span import android.text.TextPaint import android.text.style.ClickableSpan import android.util.Log import android.view.View import com.emogoth.android.phone.mimi.activity.MimiActivity import com.emogoth.android.phone.mimi.interfaces.ReplyClickListener import com.emogoth.android.phone.mimi.util.MimiUtil class ReplySpan(private val boardName: String, private val threadId: Long, private val replies: List<String>, private val textColor: Int) : ClickableSpan() { override fun updateDrawState(ds: TextPaint) { super.updateDrawState(ds) ds.isUnderlineText = true ds.color = textColor } override fun onClick(widget: View) { Log.i(LOG_TAG, "Caught click on reply: view=" + widget.javaClass.simpleName) val activity = MimiUtil.scanForActivity(widget.context) if (activity is ReplyClickListener) { activity.onReplyClicked(boardName, threadId, -1, replies) } } companion object { private val LOG_TAG = ReplySpan::class.java.simpleName } }
mimi-app/src/main/java/com/emogoth/android/phone/mimi/span/ReplySpan.kt
597336396
package com.u1f4f1.sample import android.app.Application import com.facebook.stetho.Stetho import com.mooveit.library.Fakeit import java.util.* class SampleApp : Application() { override fun onCreate() { super.onCreate() Stetho.initializeWithDefaults(this) Fakeit.initWithLocale(Locale.ENGLISH) } }
sample/src/main/java/com/u1f4f1/sample/SampleApp.kt
2432314050
fun main(args: Array<String>) { println("Hello, World.") }
src/main/kotlin/HelloWorld.kt
371228406
package com.tamsiree.rxui.model /** * 图片实体类 * @author Tamsiree * @date : 2017/6/12 ${time} */ class ModelPicture { var id: String? = null var longitude: String? = null var latitude: String? = null var date: String? = null var pictureName: String? = null var picturePath: String? = null var parentId: String? = null constructor() constructor(id: String?, longitude: String?, latitude: String?, date: String?, pictureName: String?, picturePath: String?, parentId: String?) { this.id = id this.longitude = longitude this.latitude = latitude this.date = date this.pictureName = pictureName this.picturePath = picturePath this.parentId = parentId } }
RxUI/src/main/java/com/tamsiree/rxui/model/ModelPicture.kt
3399365632
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.healthconnectsample.presentation.screen.inputreadings import android.os.RemoteException import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.health.connect.client.permission.HealthPermission import androidx.health.connect.client.records.WeightRecord import androidx.health.connect.client.units.Mass import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.example.healthconnectsample.data.HealthConnectManager import com.example.healthconnectsample.data.WeightData import com.example.healthconnectsample.data.dateTimeWithOffsetOrDefault import kotlinx.coroutines.launch import java.io.IOException import java.time.Instant import java.time.ZonedDateTime import java.time.temporal.ChronoUnit import java.util.UUID class InputReadingsViewModel(private val healthConnectManager: HealthConnectManager) : ViewModel() { private val healthConnectCompatibleApps = healthConnectManager.healthConnectCompatibleApps val permissions = setOf( HealthPermission.createReadPermission(WeightRecord::class), HealthPermission.createWritePermission(WeightRecord::class), ) var weeklyAvg: MutableState<Mass?> = mutableStateOf(Mass.kilograms(0.0)) private set var permissionsGranted = mutableStateOf(false) private set var readingsList: MutableState<List<WeightData>> = mutableStateOf(listOf()) private set var uiState: UiState by mutableStateOf(UiState.Uninitialized) private set val permissionsLauncher = healthConnectManager.requestPermissionsActivityContract() fun initialLoad() { viewModelScope.launch { tryWithPermissionsCheck { readWeightInputs() } } } fun inputReadings(inputValue: Double) { viewModelScope.launch { tryWithPermissionsCheck { val time = ZonedDateTime.now().withNano(0) val weight = WeightRecord( weight = Mass.kilograms(inputValue), time = time.toInstant(), zoneOffset = time.offset ) healthConnectManager.writeWeightInput(weight) readWeightInputs() } } } fun deleteWeightInput(uid: String) { viewModelScope.launch { tryWithPermissionsCheck { healthConnectManager.deleteWeightInput(uid) readWeightInputs() } } } private suspend fun readWeightInputs() { val startOfDay = ZonedDateTime.now().truncatedTo(ChronoUnit.DAYS) val now = Instant.now() val endofWeek = startOfDay.toInstant().plus(7, ChronoUnit.DAYS) readingsList.value = healthConnectManager .readWeightInputs(startOfDay.toInstant(), now) .map { record -> val packageName = record.metadata.dataOrigin.packageName WeightData( weight = record.weight, id = record.metadata.id, time = dateTimeWithOffsetOrDefault(record.time, record.zoneOffset), sourceAppInfo = healthConnectCompatibleApps[packageName] ) } weeklyAvg.value = healthConnectManager.computeWeeklyAverage(startOfDay.toInstant(), endofWeek) } /** * Provides permission check and error handling for Health Connect suspend function calls. * * Permissions are checked prior to execution of [block], and if all permissions aren't granted * the [block] won't be executed, and [permissionsGranted] will be set to false, which will * result in the UI showing the permissions button. * * Where an error is caught, of the type Health Connect is known to throw, [uiState] is set to * [UiState.Error], which results in the snackbar being used to show the error message. */ private suspend fun tryWithPermissionsCheck(block: suspend () -> Unit) { permissionsGranted.value = healthConnectManager.hasAllPermissions(permissions) uiState = try { if (permissionsGranted.value) { block() } UiState.Done } catch (remoteException: RemoteException) { UiState.Error(remoteException) } catch (securityException: SecurityException) { UiState.Error(securityException) } catch (ioException: IOException) { UiState.Error(ioException) } catch (illegalStateException: IllegalStateException) { UiState.Error(illegalStateException) } } sealed class UiState { object Uninitialized : UiState() object Done : UiState() // A random UUID is used in each Error object to allow errors to be uniquely identified, // and recomposition won't result in multiple snackbars. data class Error(val exception: Throwable, val uuid: UUID = UUID.randomUUID()) : UiState() } } class InputReadingsViewModelFactory( private val healthConnectManager: HealthConnectManager ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(InputReadingsViewModel::class.java)) { @Suppress("UNCHECKED_CAST") return InputReadingsViewModel( healthConnectManager = healthConnectManager ) as T } throw IllegalArgumentException("Unknown ViewModel class") } }
health-connect/HealthConnectSample/app/src/main/java/com/example/healthconnectsample/presentation/screen/inputreadings/InputReadingsViewModel.kt
3642063123
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.preference import android.content.Context import android.util.AttributeSet import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_ACCOUNT import de.vanita5.twittnuker.constant.SharedPreferenceConstants.KEY_DEFAULT_AUTO_REFRESH import de.vanita5.twittnuker.fragment.AccountRefreshSettingsFragment import de.vanita5.twittnuker.model.AccountDetails class AutoRefreshAccountsListPreference(context: Context, attrs: AttributeSet? = null) : AccountsListPreference(context, attrs) { override fun setupPreference(preference: AccountsListPreference.AccountItemPreference, account: AccountDetails) { preference.fragment = AccountRefreshSettingsFragment::class.java.name val args = preference.extras args.putParcelable(EXTRA_ACCOUNT, account) } override fun getSwitchDefault(): Boolean { return preferenceManager.sharedPreferences.getBoolean(KEY_DEFAULT_AUTO_REFRESH, false) } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/preference/AutoRefreshAccountsListPreference.kt
2872645101
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.loader.statuses import android.content.Context import android.support.annotation.WorkerThread import de.vanita5.microblog.library.MicroBlog import de.vanita5.microblog.library.MicroBlogException import de.vanita5.microblog.library.mastodon.Mastodon import de.vanita5.microblog.library.twitter.model.Paging import de.vanita5.twittnuker.annotation.AccountType import de.vanita5.twittnuker.annotation.FilterScope import de.vanita5.twittnuker.extension.model.api.mastodon.mapToPaginated import de.vanita5.twittnuker.extension.model.api.mastodon.toParcelable import de.vanita5.twittnuker.extension.model.api.toParcelable import de.vanita5.twittnuker.extension.model.newMicroBlogInstance import de.vanita5.twittnuker.model.AccountDetails import de.vanita5.twittnuker.model.ParcelableStatus import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.model.pagination.PaginatedList import de.vanita5.twittnuker.util.database.ContentFiltersUtils class PublicTimelineLoader( context: Context, accountKey: UserKey?, adapterData: List<ParcelableStatus>?, savedStatusesArgs: Array<String>?, tabPosition: Int, fromUser: Boolean, loadingMore: Boolean ) : AbsRequestStatusesLoader(context, accountKey, adapterData, savedStatusesArgs, tabPosition, fromUser, loadingMore) { @Throws(MicroBlogException::class) override fun getStatuses(account: AccountDetails, paging: Paging): PaginatedList<ParcelableStatus> { when (account.type) { AccountType.MASTODON -> { val mastodon = account.newMicroBlogInstance(context, Mastodon::class.java) return mastodon.getPublicTimeline(paging, true).mapToPaginated { it.toParcelable(account) } } else -> { val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java) return microBlog.getPublicTimeline(paging).mapMicroBlogToPaginated { it.toParcelable(account, profileImageSize = profileImageSize) } } } } @WorkerThread override fun shouldFilterStatus(status: ParcelableStatus): Boolean { return ContentFiltersUtils.isFiltered(context.contentResolver, status, true, FilterScope.SEARCH_RESULTS) } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/statuses/PublicTimelineLoader.kt
2174837984
/* * Copyright 2017 RedRoma, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tech.aroma.data.sql.serializers import org.slf4j.LoggerFactory import org.springframework.jdbc.core.JdbcOperations import tech.aroma.data.assertions.RequestAssertions.validReaction import tech.aroma.data.sql.DatabaseSerializer import tech.aroma.data.sql.serializers.Columns.Reactions import tech.aroma.thrift.reactions.Reaction import tech.sirwellington.alchemy.arguments.Arguments.checkThat import tech.sirwellington.alchemy.arguments.assertions.* import tech.sirwellington.alchemy.thrift.ThriftObjects import java.sql.ResultSet /** * * @author SirWellington */ internal class ReactionsSerializer : DatabaseSerializer<MutableList<Reaction>> { private companion object { @JvmStatic val LOG = LoggerFactory.getLogger(this::class.java)!! } override fun save(reactions: MutableList<Reaction>, statement: String, database: JdbcOperations) { reactions.forEach { checkThat(it).isA(validReaction()) } checkThat(statement).isA(nonEmptyString()) } override fun deserialize(row: ResultSet): MutableList<Reaction> { val array = row.getArray(Reactions.SERIALIZED_REACTIONS)?.array as? Array<*> ?: return mutableListOf() return array.filterNotNull() .map { it.toString() } .map(this::reactionFromString) .filterNotNull() .toMutableList() } private fun reactionFromString(string: String): Reaction? { val prototype = Reaction() return try { ThriftObjects.fromJson(prototype, string) } catch (ex: Exception) { LOG.warn("Failed to deserialize reaction from $string", ex) return null } } }
src/main/java/tech/aroma/data/sql/serializers/ReactionsSerializer.kt
3381170999
package eu.widgetlabs.fleet.units enum class SpeedUnit : Unit { KILOMETERS_PER_HOUR, MILES_PER_HOUR, KNOTS; companion object { @JvmStatic fun forSystem(isMetric: Boolean): SpeedUnit { return if (isMetric) KILOMETERS_PER_HOUR else MILES_PER_HOUR } } }
fleet/units/src/main/kotlin/eu/widgetlabs/fleet/units/SpeedUnit.kt
3590795512
package ru.molkov.collapsarserver.service import ru.molkov.collapsarserver.entity.Apod import java.util.* interface NasaWebService { fun get(date: Date): Apod }
src/main/kotlin/ru/molkov/collapsarserver/service/NasaWebService.kt
1936294396
package it.czerwinski.android.delegates.sharedpreferences import android.app.Activity import android.os.Bundle import android.widget.RelativeLayout class StringSetPreferenceDelegateActivity : Activity() { val readOnlyPreference by stringSetSharedPreference("TEST_DELEGATE_KEY") val readOnlyPreferenceWithDefaultValue by stringSetSharedPreference("TEST_DELEGATE_KEY", setOf("abc", "def")) var writablePreference by stringSetSharedPreference("TEST_DELEGATE_KEY") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(RelativeLayout(this)) } }
delegates-shared-preferences/src/androidTest/kotlin/it/czerwinski/android/delegates/sharedpreferences/StringSetPreferenceDelegateActivity.kt
3454352336
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material import androidx.compose.foundation.text.BasicText import androidx.compose.foundation.text.InlineTextContent import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.structuralEqualityPolicy import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.takeOrElse import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.Paragraph import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.TextUnit /** * High level element that displays text and provides semantics / accessibility information. * * The default [style] uses the [LocalTextStyle] provided by the [MaterialTheme] / components. If * you are setting your own style, you may want to consider first retrieving [LocalTextStyle], * and using [TextStyle.copy] to keep any theme defined attributes, only modifying the specific * attributes you want to override. * * For ease of use, commonly used parameters from [TextStyle] are also present here. The order of * precedence is as follows: * - If a parameter is explicitly set here (i.e, it is _not_ `null` or [TextUnit.Unspecified]), * then this parameter will always be used. * - If a parameter is _not_ set, (`null` or [TextUnit.Unspecified]), then the corresponding value * from [style] will be used instead. * * Additionally, for [color], if [color] is not set, and [style] does not have a color, then * [LocalContentColor] will be used with an alpha of [LocalContentAlpha]- this allows this * [Text] or element containing this [Text] to adapt to different background colors and still * maintain contrast and accessibility. * * @param text The text to be displayed. * @param modifier [Modifier] to apply to this layout node. * @param color [Color] to apply to the text. If [Color.Unspecified], and [style] has no color set, * this will be [LocalContentColor]. * @param fontSize The size of glyphs to use when painting the text. See [TextStyle.fontSize]. * @param fontStyle The typeface variant to use when drawing the letters (e.g., italic). * See [TextStyle.fontStyle]. * @param fontWeight The typeface thickness to use when painting the text (e.g., [FontWeight.Bold]). * @param fontFamily The font family to be used when rendering the text. See [TextStyle.fontFamily]. * @param letterSpacing The amount of space to add between each letter. * See [TextStyle.letterSpacing]. * @param textDecoration The decorations to paint on the text (e.g., an underline). * See [TextStyle.textDecoration]. * @param textAlign The alignment of the text within the lines of the paragraph. * See [TextStyle.textAlign]. * @param lineHeight Line height for the [Paragraph] in [TextUnit] unit, e.g. SP or EM. * See [TextStyle.lineHeight]. * @param overflow How visual overflow should be handled. * @param softWrap Whether the text should break at soft line breaks. If false, the glyphs in the * text will be positioned as if there was unlimited horizontal space. If [softWrap] is false, * [overflow] and TextAlign may have unexpected effects. * @param maxLines An optional maximum number of lines for the text to span, wrapping if * necessary. If the text exceeds the given number of lines, it will be truncated according to * [overflow] and [softWrap]. It is required that 1 <= [minLines] <= [maxLines]. * @param minLines The minimum height in terms of minimum number of visible lines. It is required * that 1 <= [minLines] <= [maxLines]. * @param onTextLayout Callback that is executed when a new text layout is calculated. A * [TextLayoutResult] object that callback provides contains paragraph information, size of the * text, baselines and other details. The callback can be used to add additional decoration or * functionality to the text. For example, to draw selection around the text. * @param style Style configuration for the text such as color, font, line height etc. */ @Composable fun Text( text: String, modifier: Modifier = Modifier, color: Color = Color.Unspecified, fontSize: TextUnit = TextUnit.Unspecified, fontStyle: FontStyle? = null, fontWeight: FontWeight? = null, fontFamily: FontFamily? = null, letterSpacing: TextUnit = TextUnit.Unspecified, textDecoration: TextDecoration? = null, textAlign: TextAlign? = null, lineHeight: TextUnit = TextUnit.Unspecified, overflow: TextOverflow = TextOverflow.Clip, softWrap: Boolean = true, maxLines: Int = Int.MAX_VALUE, minLines: Int = 1, onTextLayout: (TextLayoutResult) -> Unit = {}, style: TextStyle = LocalTextStyle.current ) { val textColor = color.takeOrElse { style.color.takeOrElse { LocalContentColor.current.copy(alpha = LocalContentAlpha.current) } } // NOTE(text-perf-review): It might be worthwhile writing a bespoke merge implementation that // will avoid reallocating if all of the options here are the defaults val mergedStyle = style.merge( TextStyle( color = textColor, fontSize = fontSize, fontWeight = fontWeight, textAlign = textAlign, lineHeight = lineHeight, fontFamily = fontFamily, textDecoration = textDecoration, fontStyle = fontStyle, letterSpacing = letterSpacing ) ) BasicText( text = text, modifier = modifier, style = mergedStyle, onTextLayout = onTextLayout, overflow = overflow, softWrap = softWrap, maxLines = maxLines, minLines = minLines ) } @Deprecated( "Maintained for binary compatibility. Use version with minLines instead", level = DeprecationLevel.HIDDEN ) @Composable fun Text( text: String, modifier: Modifier = Modifier, color: Color = Color.Unspecified, fontSize: TextUnit = TextUnit.Unspecified, fontStyle: FontStyle? = null, fontWeight: FontWeight? = null, fontFamily: FontFamily? = null, letterSpacing: TextUnit = TextUnit.Unspecified, textDecoration: TextDecoration? = null, textAlign: TextAlign? = null, lineHeight: TextUnit = TextUnit.Unspecified, overflow: TextOverflow = TextOverflow.Clip, softWrap: Boolean = true, maxLines: Int = Int.MAX_VALUE, onTextLayout: (TextLayoutResult) -> Unit = {}, style: TextStyle = LocalTextStyle.current ) { Text( text, modifier, color, fontSize, fontStyle, fontWeight, fontFamily, letterSpacing, textDecoration, textAlign, lineHeight, overflow, softWrap, maxLines, 1, onTextLayout, style ) } /** * High level element that displays text and provides semantics / accessibility information. * * The default [style] uses the [LocalTextStyle] provided by the [MaterialTheme] / components. If * you are setting your own style, you may want to consider first retrieving [LocalTextStyle], * and using [TextStyle.copy] to keep any theme defined attributes, only modifying the specific * attributes you want to override. * * For ease of use, commonly used parameters from [TextStyle] are also present here. The order of * precedence is as follows: * - If a parameter is explicitly set here (i.e, it is _not_ `null` or [TextUnit.Unspecified]), * then this parameter will always be used. * - If a parameter is _not_ set, (`null` or [TextUnit.Unspecified]), then the corresponding value * from [style] will be used instead. * * Additionally, for [color], if [color] is not set, and [style] does not have a color, then * [LocalContentColor] will be used with an alpha of [LocalContentAlpha]- this allows this * [Text] or element containing this [Text] to adapt to different background colors and still * maintain contrast and accessibility. * * @param text The text to be displayed. * @param modifier [Modifier] to apply to this layout node. * @param color [Color] to apply to the text. If [Color.Unspecified], and [style] has no color set, * this will be [LocalContentColor]. * @param fontSize The size of glyphs to use when painting the text. See [TextStyle.fontSize]. * @param fontStyle The typeface variant to use when drawing the letters (e.g., italic). * See [TextStyle.fontStyle]. * @param fontWeight The typeface thickness to use when painting the text (e.g., [FontWeight.Bold]). * @param fontFamily The font family to be used when rendering the text. See [TextStyle.fontFamily]. * @param letterSpacing The amount of space to add between each letter. * See [TextStyle.letterSpacing]. * @param textDecoration The decorations to paint on the text (e.g., an underline). * See [TextStyle.textDecoration]. * @param textAlign The alignment of the text within the lines of the paragraph. * See [TextStyle.textAlign]. * @param lineHeight Line height for the [Paragraph] in [TextUnit] unit, e.g. SP or EM. * See [TextStyle.lineHeight]. * @param overflow How visual overflow should be handled. * @param softWrap Whether the text should break at soft line breaks. If false, the glyphs in the * text will be positioned as if there was unlimited horizontal space. If [softWrap] is false, * [overflow] and TextAlign may have unexpected effects. * @param maxLines An optional maximum number of lines for the text to span, wrapping if * necessary. If the text exceeds the given number of lines, it will be truncated according to * [overflow] and [softWrap]. It is required that 1 <= [minLines] <= [maxLines]. * @param minLines The minimum height in terms of minimum number of visible lines. It is required * that 1 <= [minLines] <= [maxLines]. * @param inlineContent A map store composables that replaces certain ranges of the text. It's * used to insert composables into text layout. Check [InlineTextContent] for more information. * @param onTextLayout Callback that is executed when a new text layout is calculated. A * [TextLayoutResult] object that callback provides contains paragraph information, size of the * text, baselines and other details. The callback can be used to add additional decoration or * functionality to the text. For example, to draw selection around the text. * @param style Style configuration for the text such as color, font, line height etc. */ @Composable fun Text( text: AnnotatedString, modifier: Modifier = Modifier, color: Color = Color.Unspecified, fontSize: TextUnit = TextUnit.Unspecified, fontStyle: FontStyle? = null, fontWeight: FontWeight? = null, fontFamily: FontFamily? = null, letterSpacing: TextUnit = TextUnit.Unspecified, textDecoration: TextDecoration? = null, textAlign: TextAlign? = null, lineHeight: TextUnit = TextUnit.Unspecified, overflow: TextOverflow = TextOverflow.Clip, softWrap: Boolean = true, maxLines: Int = Int.MAX_VALUE, minLines: Int = 1, inlineContent: Map<String, InlineTextContent> = mapOf(), onTextLayout: (TextLayoutResult) -> Unit = {}, style: TextStyle = LocalTextStyle.current ) { val textColor = color.takeOrElse { style.color.takeOrElse { LocalContentColor.current.copy(alpha = LocalContentAlpha.current) } } // NOTE(text-perf-review): It might be worthwhile writing a bespoke merge implementation that // will avoid reallocating if all of the options here are the defaults val mergedStyle = style.merge( TextStyle( color = textColor, fontSize = fontSize, fontWeight = fontWeight, textAlign = textAlign, lineHeight = lineHeight, fontFamily = fontFamily, textDecoration = textDecoration, fontStyle = fontStyle, letterSpacing = letterSpacing ) ) BasicText( text = text, modifier = modifier, style = mergedStyle, onTextLayout = onTextLayout, overflow = overflow, softWrap = softWrap, maxLines = maxLines, minLines = minLines, inlineContent = inlineContent ) } @Deprecated( "Maintained for binary compatibility. Use version with minLines instead", level = DeprecationLevel.HIDDEN ) @Composable fun Text( text: AnnotatedString, modifier: Modifier = Modifier, color: Color = Color.Unspecified, fontSize: TextUnit = TextUnit.Unspecified, fontStyle: FontStyle? = null, fontWeight: FontWeight? = null, fontFamily: FontFamily? = null, letterSpacing: TextUnit = TextUnit.Unspecified, textDecoration: TextDecoration? = null, textAlign: TextAlign? = null, lineHeight: TextUnit = TextUnit.Unspecified, overflow: TextOverflow = TextOverflow.Clip, softWrap: Boolean = true, maxLines: Int = Int.MAX_VALUE, inlineContent: Map<String, InlineTextContent> = mapOf(), onTextLayout: (TextLayoutResult) -> Unit = {}, style: TextStyle = LocalTextStyle.current ) { Text( text, modifier, color, fontSize, fontStyle, fontWeight, fontFamily, letterSpacing, textDecoration, textAlign, lineHeight, overflow, softWrap, maxLines, 1, inlineContent, onTextLayout, style ) } /** * CompositionLocal containing the preferred [TextStyle] that will be used by [Text] components by * default. To set the value for this CompositionLocal, see [ProvideTextStyle] which will merge any * missing [TextStyle] properties with the existing [TextStyle] set in this CompositionLocal. * * @see ProvideTextStyle */ val LocalTextStyle = compositionLocalOf(structuralEqualityPolicy()) { TextStyle.Default } // TODO: b/156598010 remove this and replace with fold definition on the backing CompositionLocal /** * This function is used to set the current value of [LocalTextStyle], merging the given style * with the current style values for any missing attributes. Any [Text] components included in * this component's [content] will be styled with this style unless styled explicitly. * * @see LocalTextStyle */ @Composable fun ProvideTextStyle(value: TextStyle, content: @Composable () -> Unit) { val mergedStyle = LocalTextStyle.current.merge(value) CompositionLocalProvider(LocalTextStyle provides mergedStyle, content = content) }
compose/material/material/src/commonMain/kotlin/androidx/compose/material/Text.kt
4177603378
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing.ksp import androidx.room.compiler.processing.XExecutableElement import androidx.room.compiler.processing.XMethodElement import androidx.room.compiler.processing.ksp.synthetic.KspSyntheticPropertyMethodElement import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.symbol.KSDeclaration import com.google.devtools.ksp.symbol.KSFunctionDeclaration import com.google.devtools.ksp.symbol.KSTypeParameter import com.google.devtools.ksp.symbol.Nullability internal fun Resolver.findClass(qName: String) = getClassDeclarationByName( getKSNameFromString(qName) ) internal fun Resolver.requireClass(qName: String) = checkNotNull(findClass(qName)) { "cannot find class $qName" } internal fun Resolver.requireType(qName: String) = requireClass(qName).asType(emptyList()) internal fun Resolver.requireContinuationClass() = requireClass("kotlin.coroutines.Continuation") private fun XExecutableElement.getDeclarationForOverride(): KSDeclaration = when (this) { is KspExecutableElement -> this.declaration is KspSyntheticPropertyMethodElement -> this.field.declaration else -> throw IllegalStateException("unexpected XExecutableElement type. $this") } internal fun Resolver.overrides( overriderElement: XMethodElement, overrideeElement: XMethodElement ): Boolean { // in addition to functions declared in kotlin, we also synthesize getter/setter functions for // properties which means we cannot simply send the declaration to KSP for override check // (otherwise, it won't give us a definitive answer when java methods override property // getters /setters or even we won't be able to distinguish between our own Getter/Setter // synthetics). // By cheaply checking parameter counts, we avoid all those cases and if KSP returns true, it // won't include false positives. if (overriderElement.parameters.size != overrideeElement.parameters.size) { return false } val ksOverrider = overriderElement.getDeclarationForOverride() val ksOverridee = overrideeElement.getDeclarationForOverride() if (overrides(ksOverrider, ksOverridee)) { // Make sure it also overrides in JVM descriptors as well. // This happens in cases where parent class has `<T>` type argument and child class // declares it has `Int` (a type that might map to a primitive). In those cases, // KAPT generates two methods, 1 w/ primitive and 1 boxed so we replicate that behavior // here. This code would change when we generate kotlin code. if (ksOverridee is KSFunctionDeclaration && ksOverrider is KSFunctionDeclaration) { return ksOverrider.overridesInJvm(ksOverridee) } return true } return false } /** * If the overrider specifies a primitive value for a type argument, ignore the override as * kotlin will generate two class methods for them. * * see: b/160258066 for details */ private fun KSFunctionDeclaration.overridesInJvm( other: KSFunctionDeclaration ): Boolean { parameters.forEachIndexed { index, myParam -> val myParamType = myParam.type.resolve() if (myParamType.nullability == Nullability.NOT_NULL) { val myParamDecl = myParamType.declaration val paramQName = myParamDecl.qualifiedName?.asString() if (paramQName != null && KspTypeMapper.getPrimitiveJavaTypeName(paramQName) != null ) { // parameter is a primitive. Check if the parent declared it as a type argument, // in which case, we should ignore the override. val otherParamDeclaration = other.parameters .getOrNull(index)?.type?.resolve()?.declaration if (otherParamDeclaration is KSTypeParameter) { return false } } } } return true }
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/ResolverExt.kt
843805813
/* * Copyright 2019 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.pyamsoft.padlock.list.info import android.app.Dialog import android.os.Bundle import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import androidx.annotation.CheckResult import androidx.fragment.app.DialogFragment import com.pyamsoft.padlock.Injector import com.pyamsoft.padlock.PadLockComponent import com.pyamsoft.padlock.R import com.pyamsoft.padlock.loader.AppIconLoader import com.pyamsoft.padlock.model.list.ActivityEntry import com.pyamsoft.padlock.model.list.AppEntry import com.pyamsoft.padlock.model.list.ListDiffProvider import com.pyamsoft.pydroid.core.singleDisposable import com.pyamsoft.pydroid.core.tryDispose import com.pyamsoft.pydroid.ui.app.noTitle import com.pyamsoft.pydroid.ui.app.requireArguments import com.pyamsoft.pydroid.ui.util.show import javax.inject.Inject class LockInfoDialog : DialogFragment() { @field:Inject internal lateinit var appIconLoader: AppIconLoader @field:Inject internal lateinit var viewModel: LockInfoViewModel @field:Inject internal lateinit var lockView: LockInfoView private var databaseChangeDisposable by singleDisposable() private var lockEventDisposable by singleDisposable() private var populateDisposable by singleDisposable() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val appPackageName = requireArguments().getString( ARG_APP_PACKAGE_NAME, "") val appName = requireArguments().getString( ARG_APP_NAME, "") val appIcon = requireArguments().getInt( ARG_APP_ICON, 0) val appIsSystem = requireArguments().getBoolean( ARG_APP_SYSTEM, false) require(appPackageName.isNotBlank()) require(appName.isNotBlank()) val listStateTag = TAG + appPackageName Injector.obtain<PadLockComponent>(requireContext().applicationContext) .plusLockInfoComponent() .activity(requireActivity()) .owner(viewLifecycleOwner) .appName(appName) .packageName(appPackageName) .appIcon(appIcon) .appSystem(appIsSystem) .listStateTag(listStateTag) .inflater(inflater) .container(container) .savedInstanceState(savedInstanceState) .diffProvider(object : ListDiffProvider<ActivityEntry> { override fun data(): List<ActivityEntry> = lockView.getListData() }) .build() .inject(this) lockView.create() return lockView.root() } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return super.onCreateDialog(savedInstanceState) .noTitle() } override fun onViewCreated( view: View, savedInstanceState: Bundle? ) { super.onViewCreated(view, savedInstanceState) lockView.onSwipeRefresh { populateList(true) } lockView.onToolbarNavigationClicked { dismiss() } lockView.onToolbarMenuItemClicked { if (it == R.id.menu_explain_lock_type) { LockInfoExplanationDialog() .show(requireActivity(), "lock_info_explain") } } databaseChangeDisposable = viewModel.onDatabaseChangeEvent( onChange = { lockView.onDatabaseChangeReceived(it.index, it.entry) }, onError = { lockView.onDatabaseChangeError { populateList(true) } } ) lockEventDisposable = viewModel.onLockEvent( onWhitelist = { populateList(true) }, onError = { lockView.onModifyEntryError { populateList(true) } } ) } private fun populateList(forced: Boolean) { populateDisposable = viewModel.populateList(forced, onPopulateBegin = { lockView.onListPopulateBegin() }, onPopulateSuccess = { lockView.onListLoaded(it) }, onPopulateError = { lockView.onListPopulateError { populateList(true) } }, onPopulateComplete = { lockView.onListPopulated() } ) } override fun onDestroyView() { super.onDestroyView() databaseChangeDisposable.tryDispose() lockEventDisposable.tryDispose() populateDisposable.tryDispose() } override fun onStart() { super.onStart() populateList(false) } override fun onPause() { super.onPause() lockView.commitListState(null) } override fun onSaveInstanceState(outState: Bundle) { lockView.commitListState(outState) super.onSaveInstanceState(outState) } override fun onResume() { super.onResume() // The dialog is super small for some reason. We have to set the size manually, in onResume dialog.window?.apply { setLayout( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT ) setGravity(Gravity.CENTER) } } companion object { internal const val TAG = "LockInfoDialog" private const val ARG_APP_PACKAGE_NAME = "app_packagename" private const val ARG_APP_ICON = "app_icon" private const val ARG_APP_NAME = "app_name" private const val ARG_APP_SYSTEM = "app_system" @CheckResult @JvmStatic fun newInstance(appEntry: AppEntry): LockInfoDialog { return LockInfoDialog() .apply { arguments = Bundle().apply { putString(ARG_APP_PACKAGE_NAME, appEntry.packageName) putString(ARG_APP_NAME, appEntry.name) putInt(ARG_APP_ICON, appEntry.icon) putBoolean(ARG_APP_SYSTEM, appEntry.system) } } } } }
padlock/src/main/java/com/pyamsoft/padlock/list/info/LockInfoDialog.kt
4050559035
/* * Copyright (c) 2017-2019 Yui * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package moe.kyubey.akatsuki.annotations @Repeatable annotation class Argument(val name: String, val type: String, val optional: Boolean = false) annotation class Arguments(vararg val args: Argument)
src/main/kotlin/moe/kyubey/akatsuki/annotations/Argument.kt
3089037485
package com.twitter.meil_mitu.twitter4hk.api.help import com.twitter.meil_mitu.twitter4hk.AbsGet import com.twitter.meil_mitu.twitter4hk.AbsOauth import com.twitter.meil_mitu.twitter4hk.OauthType import com.twitter.meil_mitu.twitter4hk.ResponseData import com.twitter.meil_mitu.twitter4hk.converter.ITosResultConverter import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException class Tos<TTosResult>( oauth: AbsOauth, protected val json: ITosResultConverter<TTosResult>) : AbsGet<ResponseData<TTosResult>>(oauth) { override val url = "https://api.twitter.com/1.1/help/tos.json" override val allowOauthType = OauthType.oauth1 or OauthType.oauth2 override val isAuthorization = true @Throws(Twitter4HKException::class) override fun call(): ResponseData<TTosResult> { return json.toTosResultResponseData(oauth.get(this)) } }
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/api/help/Tos.kt
2922987081
/* Copyright 2017-2020 Charles Korn. 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 batect.ui import batect.cli.CommandLineOptionsParser import batect.config.Container import batect.docker.DockerContainer import batect.execution.CleanupOption import batect.execution.RunOptions import batect.execution.model.events.ContainerCreatedEvent import batect.execution.model.events.ContainerCreationFailedEvent import batect.execution.model.events.ContainerDidNotBecomeHealthyEvent import batect.execution.model.events.ContainerRemovalFailedEvent import batect.execution.model.events.ContainerRunFailedEvent import batect.execution.model.events.ContainerStartedEvent import batect.execution.model.events.ContainerStopFailedEvent import batect.execution.model.events.ExecutionFailedEvent import batect.execution.model.events.ImageBuildFailedEvent import batect.execution.model.events.ImagePullFailedEvent import batect.execution.model.events.RunningContainerExitedEvent import batect.execution.model.events.SetupCommandExecutionErrorEvent import batect.execution.model.events.SetupCommandFailedEvent import batect.execution.model.events.TaskEvent import batect.execution.model.events.TaskFailedEvent import batect.execution.model.events.TaskNetworkCreationFailedEvent import batect.execution.model.events.TaskNetworkDeletionFailedEvent import batect.execution.model.events.TemporaryDirectoryDeletionFailedEvent import batect.execution.model.events.TemporaryFileDeletionFailedEvent import batect.execution.model.events.UserInterruptedExecutionEvent import batect.os.SystemInfo import batect.ui.text.Text import batect.ui.text.TextRun import batect.ui.text.join class FailureErrorMessageFormatter(systemInfo: SystemInfo) { private val newLine = systemInfo.lineSeparator fun formatErrorMessage(event: TaskFailedEvent, runOptions: RunOptions): TextRun = when (event) { is TaskNetworkCreationFailedEvent -> formatErrorMessage("Could not create network for task", event.message) is ImageBuildFailedEvent -> formatErrorMessage("Could not build image from directory '${event.source.buildDirectory}'", event.message) is ImagePullFailedEvent -> formatErrorMessage(Text("Could not pull image ") + Text.bold(event.source.imageName), event.message) is ContainerCreationFailedEvent -> formatErrorMessage(Text("Could not create container ") + Text.bold(event.container.name), event.message) is ContainerDidNotBecomeHealthyEvent -> formatErrorMessage(Text("Container ") + Text.bold(event.container.name) + Text(" did not become healthy"), event.message) + hintToReRunWithCleanupDisabled(runOptions) is ContainerRunFailedEvent -> formatErrorMessage(Text("Could not run container ") + Text.bold(event.container.name), event.message) is ContainerStopFailedEvent -> formatErrorMessage(Text("Could not stop container ") + Text.bold(event.container.name), event.message) is ContainerRemovalFailedEvent -> formatErrorMessage(Text("Could not remove container ") + Text.bold(event.container.name), event.message) is TaskNetworkDeletionFailedEvent -> formatErrorMessage("Could not delete the task network", event.message) is TemporaryFileDeletionFailedEvent -> formatErrorMessage("Could not delete temporary file '${event.filePath}'", event.message) is TemporaryDirectoryDeletionFailedEvent -> formatErrorMessage("Could not delete temporary directory '${event.directoryPath}'", event.message) is SetupCommandExecutionErrorEvent -> formatErrorMessage(Text("Could not run setup command ") + Text.bold(event.command.command.originalCommand) + Text(" in container ") + Text.bold(event.container.name), event.message) + hintToReRunWithCleanupDisabled(runOptions) is SetupCommandFailedEvent -> formatErrorMessage(Text("Setup command ") + Text.bold(event.command.command.originalCommand) + Text(" in container ") + Text.bold(event.container.name) + Text(" failed"), setupCommandFailedBodyText(event.exitCode, event.output)) + hintToReRunWithCleanupDisabled(runOptions) is ExecutionFailedEvent -> formatErrorMessage("An unexpected exception occurred during execution", event.message) is UserInterruptedExecutionEvent -> formatMessage("Task cancelled", TextRun("Interrupt received during execution"), "Waiting for outstanding operations to stop or finish before cleaning up...") } private fun formatErrorMessage(headline: String, body: String) = formatErrorMessage(TextRun(headline), body) private fun formatErrorMessage(headline: TextRun, body: String) = formatMessage("Error", headline, body) private fun formatMessage(type: String, headline: TextRun, body: String) = Text.red(Text.bold("$type: ") + headline + Text(".$newLine")) + Text(body) private fun hintToReRunWithCleanupDisabled(runOptions: RunOptions): TextRun = when (runOptions.behaviourAfterFailure) { CleanupOption.Cleanup -> Text("$newLine${newLine}You can re-run the task with ") + Text.bold("--${CommandLineOptionsParser.disableCleanupAfterFailureFlagName}") + Text(" to leave the created containers running to diagnose the issue.") CleanupOption.DontCleanup -> TextRun("") } private fun setupCommandFailedBodyText(exitCode: Int, output: String): String = if (output.isEmpty()) { "The command exited with code $exitCode and did not produce any output." } else { "The command exited with code $exitCode and output:$newLine$output" } fun formatManualCleanupMessageAfterTaskFailureWithCleanupDisabled(events: Set<TaskEvent>, cleanupCommands: List<String>): TextRun { return formatManualCleanupMessageWhenCleanupDisabled(events, cleanupCommands, CommandLineOptionsParser.disableCleanupAfterFailureFlagName, "Once you have finished investigating the issue") } fun formatManualCleanupMessageAfterTaskSuccessWithCleanupDisabled(events: Set<TaskEvent>, cleanupCommands: List<String>): TextRun { return formatManualCleanupMessageWhenCleanupDisabled(events, cleanupCommands, CommandLineOptionsParser.disableCleanupAfterSuccessFlagName, "Once you have finished using the containers") } private fun formatManualCleanupMessageWhenCleanupDisabled(events: Set<TaskEvent>, cleanupCommands: List<String>, argumentName: String, cleanupPhrase: String): TextRun { val containerCreationEvents = events.filterIsInstance<ContainerCreatedEvent>() if (containerCreationEvents.isEmpty()) { throw IllegalArgumentException("No containers were created and so this method should not be called.") } if (cleanupCommands.isEmpty()) { throw IllegalArgumentException("No cleanup commands were provided.") } val containerMessages = containerCreationEvents .sortedBy { it.container.name } .map { event -> containerOutputAndExecInstructions(event.container, event.dockerContainer, events) } .join() val formattedCommands = cleanupCommands.joinToString(newLine) return Text.red(Text("As the task was run with ") + Text.bold("--$argumentName") + Text(" or ") + Text.bold("--${CommandLineOptionsParser.disableCleanupFlagName}") + Text(", the created containers will not be cleaned up.$newLine")) + containerMessages + Text(newLine) + Text("$cleanupPhrase, clean up all temporary resources created by batect by running:$newLine") + Text.bold(formattedCommands) } private fun containerOutputAndExecInstructions(container: Container, dockerContainer: DockerContainer, events: Set<TaskEvent>): TextRun { val neverStarted = events.none { it is ContainerStartedEvent && it.container == container } val alreadyExited = events.any { it is RunningContainerExitedEvent && it.container == container } val execCommand = if (neverStarted || alreadyExited) { "docker start ${dockerContainer.id}; docker exec -it ${dockerContainer.id} <command>" } else { "docker exec -it ${dockerContainer.id} <command>" } return Text("For container ") + Text.bold(container.name) + Text(", view its output by running '") + Text.bold("docker logs ${dockerContainer.id}") + Text("', or run a command in the container with '") + Text.bold(execCommand) + Text("'.$newLine") } fun formatManualCleanupMessageAfterCleanupFailure(cleanupCommands: List<String>): TextRun { if (cleanupCommands.isEmpty()) { return TextRun() } val instruction = if (cleanupCommands.size == 1) { "You may need to run the following command to clean up any remaining resources:" } else { "You may need to run some or all of the following commands to clean up any remaining resources:" } val formattedCommands = cleanupCommands.joinToString(newLine) return Text.red("Clean up has failed, and batect cannot guarantee that all temporary resources created have been completely cleaned up.$newLine") + Text(instruction) + Text(newLine) + Text.bold(formattedCommands) } }
app/src/main/kotlin/batect/ui/FailureErrorMessageFormatter.kt
1761429271
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.graphics.vector import androidx.compose.runtime.Immutable import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.unit.Dp /** * Vector graphics object that is generated as a result of [ImageVector.Builder] * It can be composed and rendered by passing it as an argument to [rememberVectorPainter] */ @Immutable class ImageVector internal constructor( /** * Name of the Vector asset */ val name: String, /** * Intrinsic width of the vector asset in [Dp] */ val defaultWidth: Dp, /** * Intrinsic height of the vector asset in [Dp] */ val defaultHeight: Dp, /** * Used to define the width of the viewport space. Viewport is basically the virtual canvas * where the paths are drawn on. */ val viewportWidth: Float, /** * Used to define the height of the viewport space. Viewport is basically the virtual canvas * where the paths are drawn on. */ val viewportHeight: Float, /** * Root group of the vector asset that contains all the child groups and paths */ val root: VectorGroup, /** * Optional tint color to be applied to the vector graphic */ val tintColor: Color, /** * Blend mode used to apply [tintColor] */ val tintBlendMode: BlendMode, /** * Determines if the vector asset should automatically be mirrored for right to left locales */ val autoMirror: Boolean ) { /** * Builder used to construct a Vector graphic tree. * This is useful for caching the result of expensive operations used to construct * a vector graphic for compose. * For example, the vector graphic could be serialized and downloaded from a server and represented * internally in a ImageVector before it is composed through [rememberVectorPainter] * The generated ImageVector is recommended to be memoized across composition calls to avoid * doing redundant work */ @Suppress("MissingGetterMatchingBuilder") class Builder( /** * Name of the vector asset */ private val name: String = DefaultGroupName, /** * Intrinsic width of the Vector in [Dp] */ private val defaultWidth: Dp, /** * Intrinsic height of the Vector in [Dp] */ private val defaultHeight: Dp, /** * Used to define the width of the viewport space. Viewport is basically the virtual canvas * where the paths are drawn on. */ private val viewportWidth: Float, /** * Used to define the height of the viewport space. Viewport is basically the virtual canvas * where the paths are drawn on. */ private val viewportHeight: Float, /** * Optional color used to tint the entire vector image */ private val tintColor: Color = Color.Unspecified, /** * Blend mode used to apply the tint color */ private val tintBlendMode: BlendMode = BlendMode.SrcIn, /** * Determines if the vector asset should automatically be mirrored for right to left locales */ private val autoMirror: Boolean = false ) { // Secondary constructor to maintain API compatibility that defaults autoMirror to false @Deprecated( "Replace with ImageVector.Builder that consumes an optional auto " + "mirror parameter", replaceWith = ReplaceWith( "Builder(name, defaultWidth, defaultHeight, viewportWidth, " + "viewportHeight, tintColor, tintBlendMode, false)", "androidx.compose.ui.graphics.vector" ), DeprecationLevel.HIDDEN ) constructor( /** * Name of the vector asset */ name: String = DefaultGroupName, /** * Intrinsic width of the Vector in [Dp] */ defaultWidth: Dp, /** * Intrinsic height of the Vector in [Dp] */ defaultHeight: Dp, /** * Used to define the width of the viewport space. Viewport is basically the virtual * canvas where the paths are drawn on. */ viewportWidth: Float, /** * Used to define the height of the viewport space. Viewport is basically the virtual canvas * where the paths are drawn on. */ viewportHeight: Float, /** * Optional color used to tint the entire vector image */ tintColor: Color = Color.Unspecified, /** * Blend mode used to apply the tint color */ tintBlendMode: BlendMode = BlendMode.SrcIn ) : this( name, defaultWidth, defaultHeight, viewportWidth, viewportHeight, tintColor, tintBlendMode, false ) private val nodes = ArrayList<GroupParams>() private var root = GroupParams() private var isConsumed = false private val currentGroup: GroupParams get() = nodes.peek() init { nodes.push(root) } /** * Create a new group and push it to the front of the stack of ImageVector nodes * * @param name the name of the group * @param rotate the rotation of the group in degrees * @param pivotX the x coordinate of the pivot point to rotate or scale the group * @param pivotY the y coordinate of the pivot point to rotate or scale the group * @param scaleX the scale factor in the X-axis to apply to the group * @param scaleY the scale factor in the Y-axis to apply to the group * @param translationX the translation in virtual pixels to apply along the x-axis * @param translationY the translation in virtual pixels to apply along the y-axis * @param clipPathData the path information used to clip the content within the group * * @return This ImageVector.Builder instance as a convenience for chaining calls */ @Suppress("MissingGetterMatchingBuilder") fun addGroup( name: String = DefaultGroupName, rotate: Float = DefaultRotation, pivotX: Float = DefaultPivotX, pivotY: Float = DefaultPivotY, scaleX: Float = DefaultScaleX, scaleY: Float = DefaultScaleY, translationX: Float = DefaultTranslationX, translationY: Float = DefaultTranslationY, clipPathData: List<PathNode> = EmptyPath ): Builder { ensureNotConsumed() val group = GroupParams( name, rotate, pivotX, pivotY, scaleX, scaleY, translationX, translationY, clipPathData ) nodes.push(group) return this } /** * Pops the topmost VectorGroup from this ImageVector.Builder. This is used to indicate * that no additional ImageVector nodes will be added to the current VectorGroup * @return This ImageVector.Builder instance as a convenience for chaining calls */ fun clearGroup(): Builder { ensureNotConsumed() val popped = nodes.pop() currentGroup.children.add(popped.asVectorGroup()) return this } /** * Add a path to the ImageVector graphic. This represents a leaf node in the ImageVector graphics * tree structure * * @param pathData path information to render the shape of the path * @param pathFillType rule to determine how the interior of the path is to be calculated * @param name the name of the path * @param fill specifies the [Brush] used to fill the path * @param fillAlpha the alpha to fill the path * @param stroke specifies the [Brush] used to fill the stroke * @param strokeAlpha the alpha to stroke the path * @param strokeLineWidth the width of the line to stroke the path * @param strokeLineCap specifies the linecap for a stroked path * @param strokeLineJoin specifies the linejoin for a stroked path * @param strokeLineMiter specifies the miter limit for a stroked path * @param trimPathStart specifies the fraction of the path to trim from the start in the * range from 0 to 1. Values outside the range will wrap around the length of the path. * Default is 0. * @param trimPathStart specifies the fraction of the path to trim from the end in the * range from 0 to 1. Values outside the range will wrap around the length of the path. * Default is 1. * @param trimPathOffset specifies the fraction to shift the path trim region in the range * from 0 to 1. Values outside the range will wrap around the length of the path. Default is 0. * * @return This ImageVector.Builder instance as a convenience for chaining calls */ @Suppress("MissingGetterMatchingBuilder") fun addPath( pathData: List<PathNode>, pathFillType: PathFillType = DefaultFillType, name: String = DefaultPathName, fill: Brush? = null, fillAlpha: Float = 1.0f, stroke: Brush? = null, strokeAlpha: Float = 1.0f, strokeLineWidth: Float = DefaultStrokeLineWidth, strokeLineCap: StrokeCap = DefaultStrokeLineCap, strokeLineJoin: StrokeJoin = DefaultStrokeLineJoin, strokeLineMiter: Float = DefaultStrokeLineMiter, trimPathStart: Float = DefaultTrimPathStart, trimPathEnd: Float = DefaultTrimPathEnd, trimPathOffset: Float = DefaultTrimPathOffset ): Builder { ensureNotConsumed() currentGroup.children.add( VectorPath( name, pathData, pathFillType, fill, fillAlpha, stroke, strokeAlpha, strokeLineWidth, strokeLineCap, strokeLineJoin, strokeLineMiter, trimPathStart, trimPathEnd, trimPathOffset ) ) return this } /** * Construct a ImageVector. This concludes the creation process of a ImageVector graphic * This builder cannot be re-used to create additional ImageVector instances * @return The newly created ImageVector instance */ fun build(): ImageVector { ensureNotConsumed() // pop all groups except for the root while (nodes.size > 1) { clearGroup() } val vectorImage = ImageVector( name, defaultWidth, defaultHeight, viewportWidth, viewportHeight, root.asVectorGroup(), tintColor, tintBlendMode, autoMirror ) isConsumed = true return vectorImage } /** * Throws IllegalStateException if the ImageVector.Builder has already been consumed */ private fun ensureNotConsumed() { check(!isConsumed) { "ImageVector.Builder is single use, create a new instance " + "to create a new ImageVector" } } /** * Helper method to create an immutable VectorGroup object * from an set of GroupParams which represent a group * that is in the middle of being constructed */ private fun GroupParams.asVectorGroup(): VectorGroup = VectorGroup( name, rotate, pivotX, pivotY, scaleX, scaleY, translationX, translationY, clipPathData, children ) /** * Internal helper class to help assist with in progress creation of * a vector group before creating the immutable result */ private class GroupParams( var name: String = DefaultGroupName, var rotate: Float = DefaultRotation, var pivotX: Float = DefaultPivotX, var pivotY: Float = DefaultPivotY, var scaleX: Float = DefaultScaleX, var scaleY: Float = DefaultScaleY, var translationX: Float = DefaultTranslationX, var translationY: Float = DefaultTranslationY, var clipPathData: List<PathNode> = EmptyPath, var children: MutableList<VectorNode> = mutableListOf() ) } /** * Provide an empty companion object to hang platform-specific companion extensions onto. */ companion object { } // ktlint-disable no-empty-class-body override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ImageVector) return false if (name != other.name) return false if (defaultWidth != other.defaultWidth) return false if (defaultHeight != other.defaultHeight) return false if (viewportWidth != other.viewportWidth) return false if (viewportHeight != other.viewportHeight) return false if (root != other.root) return false if (tintColor != other.tintColor) return false if (tintBlendMode != other.tintBlendMode) return false if (autoMirror != other.autoMirror) return false return true } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + defaultWidth.hashCode() result = 31 * result + defaultHeight.hashCode() result = 31 * result + viewportWidth.hashCode() result = 31 * result + viewportHeight.hashCode() result = 31 * result + root.hashCode() result = 31 * result + tintColor.hashCode() result = 31 * result + tintBlendMode.hashCode() result = 31 * result + autoMirror.hashCode() return result } } sealed class VectorNode /** * Defines a group of paths or subgroups, plus transformation information. * The transformations are defined in the same coordinates as the viewport. * The transformations are applied in the order of scale, rotate then translate. * * This is constructed as part of the result of [ImageVector.Builder] construction */ @Immutable class VectorGroup internal constructor( /** * Name of the corresponding group */ val name: String = DefaultGroupName, /** * Rotation of the group in degrees */ val rotation: Float = DefaultRotation, /** * X coordinate of the pivot point to rotate or scale the group */ val pivotX: Float = DefaultPivotX, /** * Y coordinate of the pivot point to rotate or scale the group */ val pivotY: Float = DefaultPivotY, /** * Scale factor in the X-axis to apply to the group */ val scaleX: Float = DefaultScaleX, /** * Scale factor in the Y-axis to apply to the group */ val scaleY: Float = DefaultScaleY, /** * Translation in virtual pixels to apply along the x-axis */ val translationX: Float = DefaultTranslationX, /** * Translation in virtual pixels to apply along the y-axis */ val translationY: Float = DefaultTranslationY, /** * Path information used to clip the content within the group */ val clipPathData: List<PathNode> = EmptyPath, /** * Child Vector nodes that are part of this group, this can contain * paths or other groups */ private val children: List<VectorNode> = emptyList() ) : VectorNode(), Iterable<VectorNode> { val size: Int get() = children.size operator fun get(index: Int): VectorNode { return children[index] } override fun iterator(): Iterator<VectorNode> { return object : Iterator<VectorNode> { val it = children.iterator() override fun hasNext(): Boolean = it.hasNext() override fun next(): VectorNode = it.next() } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other !is VectorGroup) return false if (name != other.name) return false if (rotation != other.rotation) return false if (pivotX != other.pivotX) return false if (pivotY != other.pivotY) return false if (scaleX != other.scaleX) return false if (scaleY != other.scaleY) return false if (translationX != other.translationX) return false if (translationY != other.translationY) return false if (clipPathData != other.clipPathData) return false if (children != other.children) return false return true } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + rotation.hashCode() result = 31 * result + pivotX.hashCode() result = 31 * result + pivotY.hashCode() result = 31 * result + scaleX.hashCode() result = 31 * result + scaleY.hashCode() result = 31 * result + translationX.hashCode() result = 31 * result + translationY.hashCode() result = 31 * result + clipPathData.hashCode() result = 31 * result + children.hashCode() return result } } /** * Leaf node of a Vector graphics tree. This specifies a path shape and parameters * to color and style the shape itself * * This is constructed as part of the result of [ImageVector.Builder] construction */ @Immutable class VectorPath internal constructor( /** * Name of the corresponding path */ val name: String = DefaultPathName, /** * Path information to render the shape of the path */ val pathData: List<PathNode>, /** * Rule to determine how the interior of the path is to be calculated */ val pathFillType: PathFillType, /** * Specifies the color or gradient used to fill the path */ val fill: Brush? = null, /** * Opacity to fill the path */ val fillAlpha: Float = 1.0f, /** * Specifies the color or gradient used to fill the stroke */ val stroke: Brush? = null, /** * Opacity to stroke the path */ val strokeAlpha: Float = 1.0f, /** * Width of the line to stroke the path */ val strokeLineWidth: Float = DefaultStrokeLineWidth, /** * Specifies the linecap for a stroked path, either butt, round, or square. The default is butt. */ val strokeLineCap: StrokeCap = DefaultStrokeLineCap, /** * Specifies the linejoin for a stroked path, either miter, round or bevel. The default is miter */ val strokeLineJoin: StrokeJoin = DefaultStrokeLineJoin, /** * Specifies the miter limit for a stroked path, the default is 4 */ val strokeLineMiter: Float = DefaultStrokeLineMiter, /** * Specifies the fraction of the path to trim from the start, in the range from 0 to 1. * The default is 0. */ val trimPathStart: Float = DefaultTrimPathStart, /** * Specifies the fraction of the path to trim from the end, in the range from 0 to 1. * The default is 1. */ val trimPathEnd: Float = DefaultTrimPathEnd, /** * Specifies the offset of the trim region (allows showed region to include the start and end), * in the range from 0 to 1. The default is 0. */ val trimPathOffset: Float = DefaultTrimPathOffset ) : VectorNode() { override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false other as VectorPath if (name != other.name) return false if (fill != other.fill) return false if (fillAlpha != other.fillAlpha) return false if (stroke != other.stroke) return false if (strokeAlpha != other.strokeAlpha) return false if (strokeLineWidth != other.strokeLineWidth) return false if (strokeLineCap != other.strokeLineCap) return false if (strokeLineJoin != other.strokeLineJoin) return false if (strokeLineMiter != other.strokeLineMiter) return false if (trimPathStart != other.trimPathStart) return false if (trimPathEnd != other.trimPathEnd) return false if (trimPathOffset != other.trimPathOffset) return false if (pathFillType != other.pathFillType) return false if (pathData != other.pathData) return false return true } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + pathData.hashCode() result = 31 * result + (fill?.hashCode() ?: 0) result = 31 * result + fillAlpha.hashCode() result = 31 * result + (stroke?.hashCode() ?: 0) result = 31 * result + strokeAlpha.hashCode() result = 31 * result + strokeLineWidth.hashCode() result = 31 * result + strokeLineCap.hashCode() result = 31 * result + strokeLineJoin.hashCode() result = 31 * result + strokeLineMiter.hashCode() result = 31 * result + trimPathStart.hashCode() result = 31 * result + trimPathEnd.hashCode() result = 31 * result + trimPathOffset.hashCode() result = 31 * result + pathFillType.hashCode() return result } } /** * DSL extension for adding a [VectorPath] to [this]. * * See [ImageVector.Builder.addPath] for the corresponding builder function. * * @param name the name for this path * @param fill specifies the [Brush] used to fill the path * @param fillAlpha the alpha to fill the path * @param stroke specifies the [Brush] used to fill the stroke * @param strokeAlpha the alpha to stroke the path * @param strokeLineWidth the width of the line to stroke the path * @param strokeLineCap specifies the linecap for a stroked path * @param strokeLineJoin specifies the linejoin for a stroked path * @param strokeLineMiter specifies the miter limit for a stroked path * @param pathBuilder [PathBuilder] lambda for adding [PathNode]s to this path. */ inline fun ImageVector.Builder.path( name: String = DefaultPathName, fill: Brush? = null, fillAlpha: Float = 1.0f, stroke: Brush? = null, strokeAlpha: Float = 1.0f, strokeLineWidth: Float = DefaultStrokeLineWidth, strokeLineCap: StrokeCap = DefaultStrokeLineCap, strokeLineJoin: StrokeJoin = DefaultStrokeLineJoin, strokeLineMiter: Float = DefaultStrokeLineMiter, pathFillType: PathFillType = DefaultFillType, pathBuilder: PathBuilder.() -> Unit ) = addPath( PathData(pathBuilder), pathFillType, name, fill, fillAlpha, stroke, strokeAlpha, strokeLineWidth, strokeLineCap, strokeLineJoin, strokeLineMiter ) /** * DSL extension for adding a [VectorGroup] to [this]. * * See [ImageVector.Builder.pushGroup] for the corresponding builder function. * * @param name the name of the group * @param rotate the rotation of the group in degrees * @param pivotX the x coordinate of the pivot point to rotate or scale the group * @param pivotY the y coordinate of the pivot point to rotate or scale the group * @param scaleX the scale factor in the X-axis to apply to the group * @param scaleY the scale factor in the Y-axis to apply to the group * @param translationX the translation in virtual pixels to apply along the x-axis * @param translationY the translation in virtual pixels to apply along the y-axis * @param clipPathData the path information used to clip the content within the group * @param block builder lambda to add children to this group */ inline fun ImageVector.Builder.group( name: String = DefaultGroupName, rotate: Float = DefaultRotation, pivotX: Float = DefaultPivotX, pivotY: Float = DefaultPivotY, scaleX: Float = DefaultScaleX, scaleY: Float = DefaultScaleY, translationX: Float = DefaultTranslationX, translationY: Float = DefaultTranslationY, clipPathData: List<PathNode> = EmptyPath, block: ImageVector.Builder.() -> Unit ) = apply { addGroup( name, rotate, pivotX, pivotY, scaleX, scaleY, translationX, translationY, clipPathData ) block() clearGroup() } private fun <T> ArrayList<T>.push(value: T): Boolean = add(value) private fun <T> ArrayList<T>.pop(): T = this.removeAt(size - 1) private fun <T> ArrayList<T>.peek(): T = this[size - 1]
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/graphics/vector/ImageVector.kt
3316070737
package com.sedsoftware.yaptalker.presentation.feature.search import android.content.Context import android.os.Bundle import android.view.View import android.view.inputmethod.InputMethodManager import com.arellomobile.mvp.presenter.InjectPresenter import com.arellomobile.mvp.presenter.ProvidePresenter import com.jakewharton.rxbinding2.view.RxView import com.jakewharton.rxbinding2.widget.RxAdapterView import com.jakewharton.rxbinding2.widget.RxRadioGroup import com.sedsoftware.yaptalker.R import com.sedsoftware.yaptalker.common.annotation.LayoutResource import com.sedsoftware.yaptalker.presentation.base.BaseFragment import com.sedsoftware.yaptalker.presentation.base.enums.lifecycle.FragmentLifecycle import com.sedsoftware.yaptalker.presentation.base.enums.navigation.NavigationSection import com.sedsoftware.yaptalker.presentation.extensions.string import com.sedsoftware.yaptalker.presentation.feature.search.options.SearchConditions import com.sedsoftware.yaptalker.presentation.feature.search.options.SortingMode import com.sedsoftware.yaptalker.presentation.feature.search.options.TargetPeriod import com.uber.autodispose.kotlin.autoDisposable import kotlinx.android.synthetic.main.fragment_site_search.search_box_chaos import kotlinx.android.synthetic.main.fragment_site_search.search_box_communication import kotlinx.android.synthetic.main.fragment_site_search.search_box_feed import kotlinx.android.synthetic.main.fragment_site_search.search_button import kotlinx.android.synthetic.main.fragment_site_search.search_group_conditions import kotlinx.android.synthetic.main.fragment_site_search.search_group_sorting import kotlinx.android.synthetic.main.fragment_site_search.search_period_spinner import kotlinx.android.synthetic.main.fragment_site_search.search_target_text import java.util.ArrayList import javax.inject.Inject @LayoutResource(value = R.layout.fragment_site_search) class SearchFormFragment : BaseFragment(), SearchFormView { companion object { fun getNewInstance() = SearchFormFragment() private const val SEARCH_IN = "titles" private const val CATEGORY_ALL = "all" private const val ALL_CATEGORIES_SIZE = 3 private const val CATEGORY_FEED = "c_2" private const val CATEGORY_COMMUNICATION = "c_5" private const val CATEGORY_CHAOS = "c_3" } private var currentSearchPeriod = TargetPeriod.ALL_TIME private var currentSearchConditions = SearchConditions.ANY_WORD private var currentSortingMode = SortingMode.DATE @Inject @InjectPresenter lateinit var presenter: SearchFormPresenter @ProvidePresenter fun provideSearchFormPresenter() = presenter @Suppress("MagicNumber") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) RxAdapterView .itemSelections(search_period_spinner) .autoDisposable(event(FragmentLifecycle.DESTROY)) .subscribe { itemId: Int? -> currentSearchPeriod = when (itemId) { 1 -> TargetPeriod.TODAY 2 -> TargetPeriod.DAYS_7 3 -> TargetPeriod.DAYS_30 4 -> TargetPeriod.DAYS_60 5 -> TargetPeriod.DAYS_90 6 -> TargetPeriod.DAYS_180 7 -> TargetPeriod.DAYS_365 else -> TargetPeriod.ALL_TIME } } RxRadioGroup .checkedChanges(search_group_conditions) .autoDisposable(event(FragmentLifecycle.DESTROY)) .subscribe { itemId: Int? -> currentSearchConditions = when (itemId) { R.id.search_rb_words_all -> SearchConditions.ALL_WORDS R.id.search_rb_words_phrase -> SearchConditions.EXACT_PHRASE else -> SearchConditions.ANY_WORD } } RxRadioGroup .checkedChanges(search_group_sorting) .autoDisposable(event(FragmentLifecycle.DESTROY)) .subscribe { itemId: Int? -> currentSortingMode = when (itemId) { R.id.search_rb_relevant -> SortingMode.DATE else -> SortingMode.RELEVANT } } RxView .clicks(search_button) .autoDisposable(event(FragmentLifecycle.DESTROY)) .subscribe { prepareSearchRequest() } } override fun updateCurrentUiState() { setCurrentAppbarTitle(string(R.string.nav_drawer_search)) setCurrentNavDrawerItem(NavigationSection.SITE_SEARCH) } override fun hideKeyboard() { val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view?.windowToken, 0) } private fun getCheckedCategories(): List<String> { val categories: MutableList<String> = ArrayList() if (search_box_feed.isChecked) { categories.add(CATEGORY_FEED) } if (search_box_communication.isChecked) { categories.add(CATEGORY_COMMUNICATION) } if (search_box_chaos.isChecked) { categories.add(CATEGORY_CHAOS) } if (categories.isEmpty() || categories.size == ALL_CATEGORIES_SIZE) { return listOf(CATEGORY_ALL) } return categories } private fun prepareSearchRequest() { val searchText = search_target_text.text.toString() if (searchText.isEmpty()) { return } val request = SearchRequest( searchFor = searchText, targetForums = getCheckedCategories(), searchIn = SEARCH_IN, searchHow = currentSearchConditions, searchInTags = false, sortBy = currentSortingMode, periodInDays = currentSearchPeriod ) presenter.performSearchRequest(request) } }
app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/search/SearchFormFragment.kt
2089678690
val v = "<selection>a<caret>aa ${x + y} bbb</selection>"
kotlin-eclipse-ui-test/testData/wordSelection/selectNext/TemplateStringLiteral/3.kt
3382863646
package net.yested interface Dimension { fun toHtml():String } class Percent(val value:Double) : Dimension { override fun toHtml(): String { return "${value}%" } } fun Int.pct():Percent = Percent(this.toDouble()) fun Double.pct():Percent = Percent(this) class Pixels(val value:Int) : Dimension { override fun toHtml(): String { return "${value}px" } } fun Int.px():Pixels = Pixels(this)
src/main/kotlin/net/yested/dimensions.kt
2021878836
/* * Copyright (C) 2019 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.timeline import org.andstatus.app.origin.Origin import org.andstatus.app.util.TriState import java.util.* /** Parameters that don't require reloading of the list */ class LoadableListViewParameters(val collapseDuplicates: TriState, val collapsedItemId: Long, val preferredOrigin: Optional<Origin>) { fun isViewChanging(): Boolean { return collapseDuplicates.known || preferredOrigin.isPresent() } companion object { val EMPTY: LoadableListViewParameters = LoadableListViewParameters(TriState.UNKNOWN, 0, Optional.empty()) fun collapseDuplicates(collapseDuplicates: Boolean): LoadableListViewParameters { return collapseOneDuplicate(collapseDuplicates, 0) } fun collapseOneDuplicate(collapseDuplicates: Boolean, collapsedItemId: Long): LoadableListViewParameters { return LoadableListViewParameters(TriState.Companion.fromBoolean(collapseDuplicates), collapsedItemId, Optional.empty()) } fun fromOrigin(preferredOrigin: Origin?): LoadableListViewParameters { return LoadableListViewParameters(TriState.UNKNOWN, 0, Optional.ofNullable(preferredOrigin)) } } }
app/src/main/kotlin/org/andstatus/app/timeline/LoadableListViewParameters.kt
2104577962
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.config.reference import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Classes.MIXIN_PLUGIN import com.demonwav.mcdev.util.reference.ClassNameReferenceProvider import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.searches.ClassInheritorsSearch import com.intellij.psi.util.PsiUtil object MixinPlugin : ClassNameReferenceProvider() { fun findInterface(context: PsiElement): PsiClass? { return JavaPsiFacade.getInstance(context.project).findClass(MIXIN_PLUGIN, context.resolveScope) } override fun findClasses(element: PsiElement, scope: GlobalSearchScope): List<PsiClass> { val configInterface = findInterface(element) ?: return emptyList() return ClassInheritorsSearch.search(configInterface, scope, true, true, false).filter { PsiUtil.isInstantiatable(it) } } }
src/main/kotlin/platform/mixin/config/reference/MixinPlugin.kt
3449860668
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.car.trustagent.blemessagestream import android.bluetooth.BluetoothDevice import androidx.annotation.IntRange import com.google.android.companionprotos.OperationProto.OperationType import com.google.android.encryptionrunner.Key import com.google.android.libraries.car.trustagent.blemessagestream.version2.BluetoothMessageStreamV2 import com.google.android.libraries.car.trustagent.util.loge import com.google.android.libraries.car.trustagent.util.logi import com.google.android.libraries.car.trustagent.util.logwtf import java.util.Objects import java.util.UUID import java.util.zip.DataFormatException import java.util.zip.Deflater import java.util.zip.Inflater /** * Handles the streaming of messages to a specific [BluetoothDevice]. * * This stream will handle if messages to a particular remote device need to be split into multiple * messages or if the messages can be sent all at once. Internally, it will have its own protocol * for how the split messages are structured. */ interface MessageStream { /** Encryption key used to encrypt/decrypt data over this stream. */ var encryptionKey: Key? /** * Sends the given [streamMessage] to remote device and returns a message id generated for * [streamMessage]. * * The given message will adhere to the size limit of delivery channel. If the wrapped message is * greater than the limit, then this stream should take the appropriate actions necessary to chunk * the message to the device so that no parts of the message is dropped. The message id that will * be return is an [Int] internally assigned to [streamMessage]. When [streamMessage] is sent out, * callback [Callback.onMessageSent] will be invoked with this message id. If the sending fails, * remote device will be disconnected. Message id will never be negative. */ @IntRange(from = 0) fun sendMessage(streamMessage: StreamMessage): Int fun registerMessageEventCallback(callback: Callback) fun unregisterMessageEventCallback(callback: Callback) /** Encrypts the payload; throws exception if encrypted is not requested. */ fun StreamMessage.toEncrypted(): StreamMessage { check(isPayloadEncrypted) { "StreamMessage should not be encrypted: $this" } val key = checkNotNull(encryptionKey) { "Could not encrypt $this; encryption key is null." } val encrypted = key.encryptData(payload) return copy(payload = encrypted) } /** Decrypts the payload; throws exception if it is not marked as encrypted. */ fun StreamMessage.toDecrypted(): StreamMessage { check(isPayloadEncrypted) { "StreamMessage is not encrypted: $this" } val key = checkNotNull(encryptionKey) { "Could not decrypt $this; encryption key is null." } val decrypted = key.decryptData(payload) return copy(payload = decrypted, isPayloadEncrypted = false) } /** * Compresses the payload. * * Data should be compressed before it's encrypted. */ fun StreamMessage.toCompressed(): StreamMessage { if (isCompressed) { loge(TAG, "StreamMessage compression: message is already compressed. Returning as is.") return this } val compressed = compressData(payload) if (compressed == null) { logi(TAG, "Compression did not result in positive net savings. Returning as is.") return this } var originalSize = payload.size val saving = Math.round(100L * (originalSize - compressed.size) / originalSize.toDouble()) logi(TAG, "Compressed from $originalSize to ${compressed.size} bytes saved $saving%.") return copy(payload = compressed, originalMessageSize = originalSize) } /** * Decompresses the payload. * * Data should be decrypted before they are decompressed. */ fun StreamMessage.toDecompressed(): StreamMessage { if (!isCompressed) { return this } val decompressed = decompressData(payload, originalMessageSize) if (decompressed == null) { logwtf(TAG, "Could not decompress $this. Returning as is.") return this } return copy(payload = decompressed, originalMessageSize = 0) } /** Callbacks that will be invoked for message events. */ interface Callback { /** Invoked when the specified [streamMessage] has been received. */ fun onMessageReceived(streamMessage: StreamMessage) /** Invoked when the specified [streamMessage] has been sent successfully. */ fun onMessageSent(messageId: Int) } companion object { private const val TAG = "MessageStream" private val inflater = Inflater() private val deflater = Deflater(Deflater.BEST_COMPRESSION) /** * Compresses input and return the resulting [ByteArray]. * * Returns `null` if compressed result is larger than the original input. */ internal fun compressData(byteArray: ByteArray): ByteArray? { val buffer = ByteArray(byteArray.size) val compressedSize = deflater.run { reset() setInput(byteArray) finish() deflate(buffer) } // Unfinished deflater means compression generated data larger than the original input. // Return null to indicate it should not be compressed. if (!deflater.finished()) { return null } return buffer.take(compressedSize).toByteArray() } /** * Decompresses input and returns the resulting [ByteArray]. * * @param originalSize The size of [byteArray] before compression. * * Returns `null` if [byteArray] could not be decompressed. */ internal fun decompressData( byteArray: ByteArray, @IntRange(from = 0) originalSize: Int ): ByteArray? { if (originalSize == 0) { logi(TAG, "Decompression: input is not compressed because original size is 0.") return byteArray } val decompressedData = ByteArray(originalSize) try { inflater.run { reset() setInput(byteArray) inflate(decompressedData) } } catch (exception: DataFormatException) { loge(TAG, "An error occurred while decompressing the message.", exception) return null } if (!inflater.finished()) { loge(TAG, "Inflater is not finished after decompression.") return null } logi(TAG, "Decompressed message from ${byteArray.size} to $originalSize bytes.") return decompressedData } /** * Creates an implementation of [MessageStream] with [bluetoothManager], based on * [messageVersion]. * * [messageVersion] must be no less than ConnectionResolver.MIN_MESSAGING_VERSION. */ fun create( @IntRange(from = 2) messageVersion: Int, bluetoothManager: BluetoothConnectionManager ): MessageStream? { return when (messageVersion) { 2 -> { logi(TAG, "Creating MessageStreamV2 without compression support") BluetoothMessageStreamV2(bluetoothManager, isCompressionEnabled = false) } 3 -> { logi(TAG, "Creating MessageStreamV2 with compression support") BluetoothMessageStreamV2(bluetoothManager, isCompressionEnabled = true) } else -> { loge(TAG, "Unrecognized message version $messageVersion. No stream created.") return null } } } } } /** * The [payload] to be sent and its metadata. * * @property payload Bytes to be sent. * @property operation The [OperationType] of this message. * @property isPayloadEncrypted For a outgoing message, `true` if the payload should be encrypted; * For an incoming message, `true` is the payload is encrypted. * @property originalMessageSize If payload is compressed, its original size. * 0 if payload is not compressed. * @property recipient Identifies the intended receiver of payload. */ data class StreamMessage( val payload: ByteArray, val operation: OperationType, val isPayloadEncrypted: Boolean, val originalMessageSize: Int, val recipient: UUID? ) { val isCompressed: Boolean = originalMessageSize > 0 // Kotlin cannot properly generate these common functions for array property [payload]. override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is StreamMessage) return false return payload.contentEquals(other.payload) && operation == other.operation && isPayloadEncrypted == other.isPayloadEncrypted && recipient == other.recipient && originalMessageSize == other.originalMessageSize } override fun hashCode() = Objects.hash( payload.contentHashCode(), recipient, operation, isPayloadEncrypted, originalMessageSize ) }
trustagent/src/com/google/android/libraries/car/trustagent/blemessagestream/MessageStream.kt
3411270617
/* * Copyright (c) 2017 Zhang Hai <[email protected]> * All Rights Reserved. */ package me.zhanghai.android.materialprogressbar import android.graphics.Canvas import android.graphics.Paint /** * Adjusted drawable to make stroke thinner. * * @author Ruben Gees */ internal class ThinSingleCircularProgressDrawable(style: Int) : SingleCircularProgressDrawable(style) { override fun onDrawRing(canvas: Canvas, paint: Paint) { super.onDrawRing(canvas, paint.apply { strokeWidth = 2f }) } }
src/main/kotlin/me/zhanghai/android/materialprogressbar/ThinSingleCircularProgressDrawable.kt
3018893052
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations.reference import com.demonwav.mcdev.translations.TranslationFiles import com.demonwav.mcdev.translations.lang.gen.psi.LangEntry import com.intellij.json.psi.JsonProperty import com.intellij.psi.ElementDescriptionLocation import com.intellij.psi.ElementDescriptionProvider import com.intellij.psi.PsiElement import com.intellij.usageView.UsageViewTypeLocation class TranslationDescriptionProvider : ElementDescriptionProvider { override fun getElementDescription(element: PsiElement, location: ElementDescriptionLocation): String? { val file = element.containingFile?.virtualFile if (!TranslationFiles.isTranslationFile(file)) { return null } return when (element) { is LangEntry -> if (location is UsageViewTypeLocation) "translation" else element.key is JsonProperty -> if (location is UsageViewTypeLocation) "translation" else element.name else -> null } } }
src/main/kotlin/translations/reference/TranslationDescriptionProvider.kt
1270313881
/* * Copyright 2017 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.powermanager.base.shell import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class ShellModule { @Singleton @Provides fun provideRootChecker(): RootChecker { return RootCheckerImpl() } @Provides fun provideShellHelper(): ShellHelper { return ShellHelperImpl() } }
powermanager-base/src/main/java/com/pyamsoft/powermanager/base/shell/ShellModule.kt
354568168
package fr.jaydeer.chat.discord import fr.jaydeer.chat.Room sealed class DiscordRoom(val id: Long): Room
src/main/kotlin/fr/jaydeer/chat/discord/DiscordRooms.kt
122335185
package org.mapdb.store import io.kotlintest.shouldBe import org.eclipse.collections.impl.list.mutable.primitive.LongArrayList import org.eclipse.collections.impl.map.mutable.primitive.LongObjectHashMap import org.junit.Assert.* import org.junit.Test import org.mapdb.DBException import org.mapdb.TT import org.mapdb.io.DataIO import org.mapdb.io.DataInput2 import org.mapdb.io.DataOutput2 import org.mapdb.ser.Serializer import org.mapdb.ser.Serializers import org.mapdb.ser.Serializers.LONG import org.mapdb.store.li.LiStore import java.util.* import java.util.concurrent.atomic.AtomicLong class HeapBufStoreTest : StoreTest() { override fun openStore() = HeapBufStore() } class HeapBufStoreRWLockTest : StoreTest() { override fun openStore() = HeapBufStoreRWLock() } class ConcMapStoreTest : StoreTest() { override fun openStore() = ConcMapStore() override fun recid_getAll_sorted(){ //TODO support multiform store } } class LiStoreTest : StoreTest() { override fun openStore() = LiStore() } /** * Tests contract on `Store` interface */ abstract class StoreTest { abstract fun openStore(): Store @Test fun put_get() { val e = openStore() val l = 11231203099090L val recid = e.put(l, LONG) assertEquals(l, e.get(recid, LONG)) e.verify() e.close() } @Test fun put_get_large() { val e = openStore() if(e.maxRecordSize()<1e6) return val b = TT.randomByteArray(1000000) Random().nextBytes(b) val recid = e.put(b, Serializers.BYTE_ARRAY_NOSIZE) assertTrue(Arrays.equals(b, e.get(recid, Serializers.BYTE_ARRAY_NOSIZE))) e.verify() e.close() } @Test fun testSetGet() { val e = openStore() val recid = e.put(10000.toLong(), LONG) val s2 = e.get(recid, LONG) assertEquals(s2, java.lang.Long.valueOf(10000)) e.verify() e.close() } @Test fun reserved_recids(){ val e = openStore() for(expectedRecid in 1 .. Recids.RECID_MAX_RESERVED){ val allocRecid = e.preallocate() assertEquals(expectedRecid, allocRecid) } e.verify() e.close() } @Test fun large_record() { val e = openStore() if(e.maxRecordSize()<1e6) return val b = TT.randomByteArray(100000) val recid = e.put(b, Serializers.BYTE_ARRAY_NOSIZE) val b2 = e.get(recid, Serializers.BYTE_ARRAY_NOSIZE) assertTrue(Arrays.equals(b, b2)) e.verify() e.close() } @Test fun large_record_delete() { val e = openStore() if(e.maxRecordSize()<1e6) return val b = TT.randomByteArray(100000) val recid = e.put(b, Serializers.BYTE_ARRAY_NOSIZE) e.verify() e.delete(recid, Serializers.BYTE_ARRAY_NOSIZE) e.verify() e.close() } @Test fun large_record_delete2(){ val s = openStore() if(s.maxRecordSize()<1e6) return val b = TT.randomByteArray(200000) val recid1 = s.put(b, Serializers.BYTE_ARRAY_NOSIZE) s.verify() val b2 = TT.randomByteArray(220000) val recid2 = s.put(b2, Serializers.BYTE_ARRAY_NOSIZE) s.verify() assertTrue(Arrays.equals(b, s.get(recid1, Serializers.BYTE_ARRAY_NOSIZE))) assertTrue(Arrays.equals(b2, s.get(recid2, Serializers.BYTE_ARRAY_NOSIZE))) s.delete(recid1, Serializers.BYTE_ARRAY_NOSIZE) assertTrue(Arrays.equals(b2, s.get(recid2, Serializers.BYTE_ARRAY_NOSIZE))) s.verify() s.delete(recid2, Serializers.BYTE_ARRAY_NOSIZE) s.verify() s.verify() s.close() } @Test fun large_record_update(){ val s = openStore() if(s.maxRecordSize()<1e6) return var b = TT.randomByteArray(200000) val recid1 = s.put(b, Serializers.BYTE_ARRAY_NOSIZE) s.verify() val b2 = TT.randomByteArray(220000) val recid2 = s.put(b2, Serializers.BYTE_ARRAY_NOSIZE) s.verify() assertTrue(Arrays.equals(b, s.get(recid1, Serializers.BYTE_ARRAY_NOSIZE))) assertTrue(Arrays.equals(b2, s.get(recid2, Serializers.BYTE_ARRAY_NOSIZE))) b = TT.randomByteArray(210000) s.update(recid1, Serializers.BYTE_ARRAY_NOSIZE, b); assertTrue(Arrays.equals(b, s.get(recid1, Serializers.BYTE_ARRAY_NOSIZE))) assertTrue(Arrays.equals(b2, s.get(recid2, Serializers.BYTE_ARRAY_NOSIZE))) s.verify() b = TT.randomByteArray(28001) s.update(recid1, Serializers.BYTE_ARRAY_NOSIZE, b); assertTrue(Arrays.equals(b, s.get(recid1, Serializers.BYTE_ARRAY_NOSIZE))) assertTrue(Arrays.equals(b2, s.get(recid2, Serializers.BYTE_ARRAY_NOSIZE))) s.verify() s.close() } @Test fun get_non_existent() { val e = openStore() TT.assertFailsWith(DBException.RecordNotFound::class) { e.get(1, TT.Serializer_ILLEGAL_ACCESS) } e.verify() e.close() } @Test fun preallocate_cas() { val e = openStore() val recid = e.preallocate() e.verify() TT.assertFailsWith(DBException.PreallocRecordAccess::class) { e.compareAndUpdate(recid, LONG, 1L, 2L) } TT.assertFailsWith(DBException.PreallocRecordAccess::class) { e.compareAndUpdate(recid, LONG, 2L, 2L) } TT.assertFailsWith(DBException.PreallocRecordAccess::class) { e.get(recid, LONG) } e.preallocatePut(recid, LONG, 2L) assertFalse(e.compareAndUpdate(recid, LONG, 1L, 3L)) assertTrue(e.compareAndUpdate(recid, LONG, 2L, 2L)) assertTrue(e.compareAndUpdate(recid, LONG, 2L, 3L)) assertEquals(3L, e.get(recid, LONG)) e.verify() e.close() } @Test fun preallocate_get_update_delete_update_get() { val e = openStore() val recid = e.preallocate() e.verify() TT.assertFailsWith(DBException.PreallocRecordAccess::class) { e.get(recid, TT.Serializer_ILLEGAL_ACCESS) } TT.assertFailsWith(DBException.PreallocRecordAccess::class) { e.update(recid, LONG, 1L) } TT.assertFailsWith(DBException.PreallocRecordAccess::class) { assertEquals(1L.toLong(), e.get(recid, LONG)) } e.preallocatePut(recid, LONG, 1L) assertEquals(1L.toLong(), e.get(recid, LONG)) e.delete(recid, LONG) TT.assertFailsWith(DBException.RecordNotFound::class) { assertNull(e.get(recid, TT.Serializer_ILLEGAL_ACCESS)) } e.verify() TT.assertFailsWith(DBException.RecordNotFound::class) { e.update(recid, LONG, 1L) } e.verify() e.close() } @Test fun cas_delete() { val e = openStore() val recid = e.put(1L, LONG) e.verify() assertTrue(e.compareAndDelete(recid, LONG, 1L)) TT.assertFailsWith(DBException.RecordNotFound::class) { assertNull(e.get(recid, TT.Serializer_ILLEGAL_ACCESS)) } e.verify() TT.assertFailsWith(DBException.RecordNotFound::class) { e.update(recid, LONG, 1L) } e.verify() e.close() } @Test fun cas_prealloc() { val e = openStore() val recid = e.preallocate() TT.assertFailsWith(DBException.PreallocRecordAccess::class) { e.compareAndUpdate(recid, LONG, 2L, 1L) } e.preallocatePut(recid, LONG, 2L) assertTrue(e.compareAndUpdate(recid, LONG, 2L, 1L)) e.verify() assertEquals(1L, e.get(recid, LONG)) assertTrue(e.compareAndUpdate(recid, LONG, 1L, 3L)) e.verify() assertEquals(3L, e.get(recid, LONG)) e.verify() e.close() } @Test fun cas_prealloc_delete() { val e = openStore() val recid = e.preallocate() TT.assertFailsWith(DBException.PreallocRecordAccess::class) { e.delete(recid, LONG) } TT.assertFailsWith(DBException.PreallocRecordAccess::class) { e.get(recid, LONG) } e.preallocatePut(recid, LONG, 1L) e.delete(recid, LONG) TT.assertFailsWith(DBException.RecordNotFound::class) { assertTrue(e.compareAndUpdate(recid, LONG, 3L, 1L)) } e.verify() e.close() } @Test fun putGetUpdateDelete() { val e = openStore() var s = "aaaad9009" val recid = e.put(s, Serializers.STRING) assertEquals(s, e.get(recid, Serializers.STRING)) s = "da8898fe89w98fw98f9" e.update(recid, Serializers.STRING, s) assertEquals(s, e.get(recid, Serializers.STRING)) e.verify() e.delete(recid, Serializers.STRING) TT.assertFailsWith(DBException.RecordNotFound::class) { e.get(recid, Serializers.STRING) } e.verify() e.close() } @Test fun not_preallocated() { val e = openStore() TT.assertFailsWith(DBException.RecordNotPreallocated::class) { e.preallocatePut(222, LONG, 1L) } val recid = e.put(1L, LONG) TT.assertFailsWith(DBException.RecordNotPreallocated::class) { e.preallocatePut(recid, LONG, 1L) } } @Test fun nosize_array() { val e = openStore() var b = ByteArray(0) val recid = e.put(b, Serializers.BYTE_ARRAY_NOSIZE) assertTrue(Arrays.equals(b, e.get(recid, Serializers.BYTE_ARRAY_NOSIZE))) b = byteArrayOf(1, 2, 3) e.update(recid, Serializers.BYTE_ARRAY_NOSIZE, b) assertTrue(Arrays.equals(b, e.get(recid, Serializers.BYTE_ARRAY_NOSIZE))) e.verify() b = byteArrayOf() e.update(recid, Serializers.BYTE_ARRAY_NOSIZE, b) assertTrue(Arrays.equals(b, e.get(recid, Serializers.BYTE_ARRAY_NOSIZE))) e.verify() e.delete(recid, Serializers.BYTE_ARRAY_NOSIZE) TT.assertFailsWith(DBException.RecordNotFound::class) { e.get(recid, Serializers.BYTE_ARRAY_NOSIZE) } e.verify() e.close() } @Test fun nosize_array_prealloc() { val e = openStore() var b = ByteArray(0) val recid = e.preallocate(); e.preallocatePut(recid, Serializers.BYTE_ARRAY_NOSIZE, b) assertTrue(Arrays.equals(b, e.get(recid, Serializers.BYTE_ARRAY_NOSIZE))) b = byteArrayOf(1, 2, 3) e.update(recid, Serializers.BYTE_ARRAY_NOSIZE, b) assertTrue(Arrays.equals(b, e.get(recid, Serializers.BYTE_ARRAY_NOSIZE))) e.verify() b = byteArrayOf() e.update(recid, Serializers.BYTE_ARRAY_NOSIZE, b) assertTrue(Arrays.equals(b, e.get(recid, Serializers.BYTE_ARRAY_NOSIZE))) e.verify() e.delete(recid, Serializers.BYTE_ARRAY_NOSIZE) TT.assertFailsWith(DBException.RecordNotFound::class) { e.get(recid, Serializers.BYTE_ARRAY_NOSIZE) } e.verify() e.close() } @Test fun get_deleted() { val e = openStore() val recid = e.put(1L, LONG) e.verify() e.delete(recid, LONG) TT.assertFailsWith(DBException.RecordNotFound::class) { e.get(recid, LONG) } e.verify() e.close() } @Test fun update_deleted() { val e = openStore() val recid = e.put(1L, LONG) e.delete(recid, LONG) TT.assertFailsWith(DBException.RecordNotFound::class) { e.update(recid, LONG, 2L) } e.verify() e.close() } @Test fun double_delete() { val e = openStore() val recid = e.put(1L, LONG) e.delete(recid, LONG) TT.assertFailsWith(DBException.RecordNotFound::class) { e.delete(recid, LONG) } e.verify() e.close() } @Test fun empty_update_commit() { if (TT.shortTest()) return var e = openStore() val recid = e.put("", Serializers.STRING) assertEquals("", e.get(recid, Serializers.STRING)) for (i in 0..9999) { val s = TT.randomString(80000) e.update(recid, Serializers.STRING, s) assertEquals(s, e.get(recid, Serializers.STRING)) e.commit() assertEquals(s, e.get(recid, Serializers.STRING)) } e.verify() e.close() } @Test fun delete_reuse() { for(size in 1 .. 20){ val e = openStore() val recid = e.put(TT.randomString(size), Serializers.STRING) e.delete(recid, Serializers.STRING) TT.assertFailsWith(DBException.RecordNotFound::class) { e.get(recid, TT.Serializer_ILLEGAL_ACCESS) } val recid2 = e.put(TT.randomString(size), Serializers.STRING) assertEquals(recid, recid2) e.verify() e.close() } } //TODO test // @Test fun empty_rollback(){ // val e = openStore() // if(e is StoreTx) // e.rollback() // e.verify() // e.close() // } @Test fun empty_commit(){ val e = openStore() e.commit() e.verify() e.close() } @Test fun randomUpdates() { if(TT.shortTest()) return; val s = openStore() val random = Random(1); val endTime = TT.nowPlusMinutes(10.0) val ref = LongObjectHashMap<ByteArray>() //TODO params could cause OOEM if too big. Make another case of tests with extremely large memory, or disk space val maxRecSize = 1000 val maxSize = 66000 * 3 //fill up for (i in 0 until maxSize){ val size = random.nextInt(maxRecSize) val b = TT.randomByteArray(size, random.nextInt()) val recid = s.put(b, Serializers.BYTE_ARRAY_NOSIZE) ref.put(recid, b) } s.verify() while(endTime>System.currentTimeMillis()){ ref.forEachKeyValue { recid, record -> val old = s.get(recid, Serializers.BYTE_ARRAY_NOSIZE) assertTrue(Arrays.equals(record, old)) val size = random.nextInt(maxRecSize) val b = TT.randomByteArray(size, random.nextInt()) ref.put(recid,b.clone()) s.update(recid, Serializers.BYTE_ARRAY_NOSIZE, b) assertTrue(Arrays.equals(b, s.get(recid, Serializers.BYTE_ARRAY_NOSIZE))); } s.verify() //TODO TX test // if(s is StoreWAL) { // s.commit() // s.verify() // } } } @Test fun concurrent_CAS(){ if(TT.shortTest()) return; val s = openStore(); if(s.isThreadSafe().not()) return; val ntime = TT.nowPlusMinutes(1.0) var counter = AtomicLong(0); val recid = s.put(0L, LONG) TT.fork(10){ val random = Random(); while(ntime>System.currentTimeMillis()){ val plus = random.nextInt(1000).toLong() val v:Long = s.get(recid, LONG)!! if(s.compareAndUpdate(recid, LONG, v, v+plus)){ counter.addAndGet(plus); } } } assertTrue(counter.get()>0) assertEquals(counter.get(), s.get(recid, LONG)) } @Test fun varRecordSizeCompact(){ if(TT.shortTest()) return val maxStoreSize = 10*1024*1024 var size = 1 while(size<maxStoreSize) { val store = openStore() val maxCount = 1 + maxStoreSize / size; //insert recids val recids = LongArrayList() for (i in 0..maxCount) { val r = TT.randomByteArray(size, seed = i) val recid = store.put(r, Serializers.BYTE_ARRAY_NOSIZE) recids.add(recid) } fun verify() { //verify recids recids.forEachWithIndex { recid, i -> val r = store.get(recid, Serializers.BYTE_ARRAY_NOSIZE) assertTrue(Arrays.equals(r, TT.randomByteArray(size, seed=i))) } } verify() store.compact() verify() size += 1 + size/113 } } // @Test //TODO reentry test with preprocessor in paranoid mode fun reentry(){ val store = openStore() val recid = store.put("aa", Serializers.STRING) val reentrySer1 = object: Serializer<String> { override fun serializedType() = String::class.java override fun serialize(out: DataOutput2, k: String) { out.writeUTF(k) // that should fail store.update(recid, Serializers.STRING, k) } override fun deserialize(input: DataInput2): String { return input.readUTF() } } val reentrySer2 = object: Serializer<String> { override fun serializedType() = String::class.java override fun serialize(out: DataOutput2, k: String) { out.writeUTF(k) } override fun deserialize(input: DataInput2): String { val s = input.readUTF() // that should fail store.update(recid, Serializers.STRING, s) return s } } TT.assertFailsWith(DBException.StoreReentry::class){ store.put("aa", reentrySer1) store.commit() } val recid2 = store.put("aa", Serializers.STRING) TT.assertFailsWith(DBException.StoreReentry::class){ store.get(recid2, reentrySer2) } TT.assertFailsWith(DBException.StoreReentry::class){ store.update(recid2, reentrySer1, "bb") store.commit() } TT.assertFailsWith(DBException.StoreReentry::class){ store.compareAndUpdate(recid2, reentrySer1, "aa", "bb") store.commit() } TT.assertFailsWith(DBException.StoreReentry::class){ store.compareAndUpdate(recid2, reentrySer2, "aa", "bb") store.commit() } TT.assertFailsWith(DBException.StoreReentry::class){ store.compareAndDelete(recid2, reentrySer2, "aa") store.commit() } } open @Test fun recid_getAll_sorted(){ val store = openStore() val max = 1000 val records = (0 until max).map{ n-> val recid = store.put(n, Serializers.INTEGER) Pair(recid, n) } val records2 = ArrayList<Pair<Long, Int>>() store.getAll{recid, data:ByteArray? -> data!!.size shouldBe 4 val n = DataIO.getInt(data!!, 0) records2+=Pair(recid, n) } //TODO check preallocated records are excluded //TODO check deleted records are excluded records2.size shouldBe max for(i in 0 until max){ val (recid, n) = records2[i] n shouldBe i store.get(recid, Serializers.INTEGER) shouldBe i records[i].first shouldBe recid records[i].second shouldBe n } } // // @Test fun export_to_archive(){ // val store = openStore() // // val max = 1000 // // val records = (0 until max).map{ n-> // val recid = store.put(n*1000, Serializers.INTEGER) // Pair(recid, n*1000) // } // // val out = ByteArrayOutputStream() // StoreArchive.importFromStore(store, out) // // val archive = StoreArchive(ByteBuffer.wrap(out.toByteArray())) // // for((recid,n) in records){ // archive.get(recid, Serializers.INTEGER) shouldBe n // } // } @Test fun empty(){ val store = openStore() store.isEmpty() shouldBe true val recid = store.put(1, Serializers.INTEGER) store.isEmpty() shouldBe false store.delete(recid, Serializers.INTEGER) //TODO restore empty state when no data in store? perhaps not possible, so replace is 'isFresh()` (no data inserted yet) // store.isEmpty() shouldBe true } @Test fun null_prealloc_update_delete(){ val store = openStore() val recid = store.preallocate() TT.assertFailsWith(DBException.PreallocRecordAccess::class) { store.update(recid, LONG, 1L) } TT.assertFailsWith(DBException.PreallocRecordAccess::class) { store.get(recid, TT.Serializer_ILLEGAL_ACCESS) } TT.assertFailsWith(DBException.PreallocRecordAccess::class) { store.delete(recid, TT.Serializer_ILLEGAL_ACCESS) } store.preallocatePut(recid, LONG, 1L) store.delete(recid, LONG); TT.assertFailsWith(DBException.RecordNotFound::class) { store.get(recid, TT.Serializer_ILLEGAL_ACCESS) } } //TODO nullability tests outside of kotlin }
src/test/java/org/mapdb/store/StoreTest.kt
160463846
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.module.project.domain.criteria import com.mycollab.db.arguments.NumberSearchField import com.mycollab.db.arguments.SearchCriteria import com.mycollab.db.arguments.StringSearchField /** * @author MyCollab Ltd. * @since 1.0.0 */ class VersionSearchCriteria : SearchCriteria() { var projectId: NumberSearchField? = null var id: NumberSearchField? = null var versionname: StringSearchField? = null var status: StringSearchField? = null }
mycollab-services/src/main/java/com/mycollab/module/project/domain/criteria/VersionSearchCriteria.kt
685280780
package io.bazel.kotlin.plugin.jdeps import com.intellij.mock.MockProject import org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar import org.jetbrains.kotlin.config.CompilerConfiguration import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor import org.jetbrains.kotlin.resolve.jvm.extensions.AnalysisHandlerExtension class JdepsGenComponentRegistrar : ComponentRegistrar { override fun registerProjectComponents( project: MockProject, configuration: CompilerConfiguration, ) { // Capture all types referenced by the compiler for this module and look up the jar from which // they were loaded from val extension = JdepsGenExtension(project, configuration) AnalysisHandlerExtension.registerExtension(project, extension) StorageComponentContainerContributor.registerExtension(project, extension) } }
src/main/kotlin/io/bazel/kotlin/plugin/jdeps/JdepsGenComponentRegistrar.kt
1697624868
package com.google.firebase.dynamicinvites.kotlin.presenter import android.content.Context import android.widget.Toast import com.google.firebase.dynamicinvites.R import com.google.firebase.dynamicinvites.kotlin.model.InviteContent class MessagePresenter(isAvailable: Boolean, content: InviteContent) : InvitePresenter("Message", R.drawable.ic_sms, isAvailable, content) { override fun sendInvite(context: Context) { super.sendInvite(context) Toast.makeText(context, "TODO: Implement SMS", Toast.LENGTH_SHORT).show() } }
dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/MessagePresenter.kt
1770833521
/* 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 org.mozilla.focus.session.ui import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.support.v4.content.ContextCompat import android.support.v4.graphics.drawable.DrawableCompat import android.support.v7.content.res.AppCompatResources import android.support.v7.widget.RecyclerView import android.view.View import android.widget.TextView import org.mozilla.focus.R import org.mozilla.focus.session.Session import org.mozilla.focus.session.SessionManager import org.mozilla.focus.telemetry.TelemetryWrapper import org.mozilla.focus.ext.beautifyUrl import java.lang.ref.WeakReference class SessionViewHolder internal constructor(private val fragment: SessionsSheetFragment, private val textView: TextView) : RecyclerView.ViewHolder(textView), View.OnClickListener { companion object { @JvmField internal val LAYOUT_ID = R.layout.item_session } private var sessionReference: WeakReference<Session> = WeakReference<Session>(null) init { textView.setOnClickListener(this) } fun bind(session: Session) { this.sessionReference = WeakReference(session) updateUrl(session) val isCurrentSession = SessionManager.getInstance().isCurrentSession(session) val actionColor = ContextCompat.getColor(textView.context, R.color.colorAction) val darkColor = ContextCompat.getColor(textView.context, R.color.colorSession) updateTextColor(isCurrentSession, actionColor, darkColor) updateDrawable(isCurrentSession, actionColor, darkColor) } private fun updateTextColor(isCurrentSession: Boolean, actionColor: Int, darkColor: Int) { textView.setTextColor(if (isCurrentSession) actionColor else darkColor) } private fun updateDrawable(isCurrentSession: Boolean, actionColor: Int, darkColor: Int) { val drawable = AppCompatResources.getDrawable(itemView.context, R.drawable.ic_link) ?: return val wrapDrawable = DrawableCompat.wrap(drawable.mutate()) DrawableCompat.setTint(wrapDrawable, if (isCurrentSession) actionColor else darkColor) textView.setCompoundDrawablesWithIntrinsicBounds(wrapDrawable, null, null, null) } private fun updateUrl(session: Session) { textView.text = session.url.value.beautifyUrl() } override fun onClick(view: View) { val session = sessionReference.get() ?: return selectSession(session) } private fun selectSession(session: Session) { fragment.animateAndDismiss().addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { SessionManager.getInstance().selectSession(session) TelemetryWrapper.switchTabInTabsTrayEvent() } }) } }
app/src/main/java/org/mozilla/focus/session/ui/SessionViewHolder.kt
3723030657
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plugins.plsqlopen.api.sql import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.sonar.plugins.plsqlopen.api.DmlGrammar import org.sonar.plugins.plsqlopen.api.RuleTest import com.felipebz.flr.tests.Assertions.assertThat class StartWithClauseTest : RuleTest() { @BeforeEach fun init() { setRootRule(DmlGrammar.START_WITH_CLAUSE) } @Test fun matchesSimpleConnectBy() { assertThat(p).matches("start with foo = bar") } }
zpa-core/src/test/kotlin/org/sonar/plugins/plsqlopen/api/sql/StartWithClauseTest.kt
3446321537
package com.habitrpg.android.habitica.helpers import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.models.inventory.Equipment import com.habitrpg.android.habitica.models.user.Stats import com.habitrpg.shared.habitica.models.Avatar class UserStatComputer { interface StatsRow inner class AttributeRow : StatsRow { var labelId: Int = 0 var strVal: Float = 0.toFloat() var intVal: Float = 0.toFloat() var conVal: Float = 0.toFloat() var perVal: Float = 0.toFloat() var roundDown: Boolean = false var summary: Boolean = false } inner class EquipmentRow : StatsRow { var gearKey: String? = null var text: String? = null var stats: String? = null } fun computeClassBonus(equipmentList: List<Equipment>, user: Avatar): List<StatsRow> { val skillRows = ArrayList<StatsRow>() var strAttributes = 0f var intAttributes = 0f var conAttributes = 0f var perAttributes = 0f var strClassBonus = 0f var intClassBonus = 0f var conClassBonus = 0f var perClassBonus = 0f // Summarize stats and fill equipment table for (i in equipmentList) { val strength = i.str val intelligence = i._int val constitution = i.con val perception = i.per strAttributes += strength.toFloat() intAttributes += intelligence.toFloat() conAttributes += constitution.toFloat() perAttributes += perception.toFloat() val sb = StringBuilder() if (strength != 0) { sb.append("STR ").append(strength).append(", ") } if (intelligence != 0) { sb.append("INT ").append(intelligence).append(", ") } if (constitution != 0) { sb.append("CON ").append(constitution).append(", ") } if (perception != 0) { sb.append("PER ").append(perception).append(", ") } // remove the last comma if (sb.length > 2) { sb.delete(sb.length - 2, sb.length) } val equipmentRow = EquipmentRow() equipmentRow.gearKey = i.key equipmentRow.text = i.text equipmentRow.stats = sb.toString() skillRows.add(equipmentRow) // Calculate class bonus var itemClass: String? = i.klass val itemSpecialClass = i.specialClass val classDoesNotExist = itemClass == null || itemClass.isEmpty() val specialClassDoesNotExist = itemSpecialClass.isEmpty() if (classDoesNotExist && specialClassDoesNotExist) { continue } var classBonus = 0.5f val userClassMatchesGearClass = !classDoesNotExist && itemClass == user.stats?.habitClass val userClassMatchesGearSpecialClass = !specialClassDoesNotExist && itemSpecialClass == user.stats?.habitClass if (!userClassMatchesGearClass && !userClassMatchesGearSpecialClass) classBonus = 0f if (itemClass == null || itemClass.isEmpty() || itemClass == "special") { itemClass = itemSpecialClass } when (itemClass) { Stats.ROGUE -> { strClassBonus += strength * classBonus perClassBonus += perception * classBonus } Stats.HEALER -> { conClassBonus += constitution * classBonus intClassBonus += intelligence * classBonus } Stats.WARRIOR -> { strClassBonus += strength * classBonus conClassBonus += constitution * classBonus } Stats.MAGE -> { intClassBonus += intelligence * classBonus perClassBonus += perception * classBonus } } } val attributeRow = AttributeRow() attributeRow.labelId = R.string.battle_gear attributeRow.strVal = strAttributes attributeRow.intVal = intAttributes attributeRow.conVal = conAttributes attributeRow.perVal = perAttributes attributeRow.roundDown = true attributeRow.summary = false skillRows.add(attributeRow) val attributeRow2 = AttributeRow() attributeRow2.labelId = R.string.profile_class_bonus attributeRow2.strVal = strClassBonus attributeRow2.intVal = intClassBonus attributeRow2.conVal = conClassBonus attributeRow2.perVal = perClassBonus attributeRow2.roundDown = false attributeRow2.summary = false skillRows.add(attributeRow2) return skillRows } }
Habitica/src/main/java/com/habitrpg/android/habitica/helpers/UserStatComputer.kt
26420738
/* * Copyright (C) 2016-2017, 2019-2020 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery import com.intellij.openapi.util.TextRange import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.tree.IElementType import uk.co.reecedunn.intellij.plugin.core.lang.injection.PsiElementTextDecoder import uk.co.reecedunn.intellij.plugin.core.lexer.entityReferenceCodePoint import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryCharRef import xqt.platform.xml.model.XmlChar class XQueryCharRefImpl(type: IElementType, text: CharSequence) : LeafPsiElement(type, text), XQueryCharRef, PsiElementTextDecoder { override val codepoint: XmlChar get() = XmlChar(node.chars.entityReferenceCodePoint()) override fun decode(decoded: StringBuilder) { decoded.append(codepoint.toString()) } override fun decode(offset: Int, rangeInsideHost: TextRange, decoded: StringBuilder, offsets: ArrayList<Int>) { if (offset >= rangeInsideHost.startOffset && offset + textLength <= rangeInsideHost.endOffset) { val text = codepoint.toString() decoded.append(text) repeat(text.length) { offsets.add(offset) } } } }
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/xquery/XQueryCharRefImpl.kt
3938505456
/* * Copyright (C) 2019-2020 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.type.Type open class XdmValue(val saxonObject: Any, private val `class`: Class<*>) { fun iterator(): XdmSequenceIterator { val xdmSequenceIteratorClass = `class`.classLoader.loadClass("net.sf.saxon.s9api.XdmSequenceIterator") return XdmSequenceIterator(`class`.getMethod("iterator").invoke(saxonObject), xdmSequenceIteratorClass) } private fun getUnderlyingValue(): Any = `class`.getMethod("getUnderlyingValue").invoke(saxonObject) fun getItemType(typeHierarchy: Any?): Any { val value = getUnderlyingValue() return Type.getItemType(value, typeHierarchy, `class`.classLoader) } override fun toString(): String = saxonObject.toString() override fun hashCode(): Int = saxonObject.hashCode() override fun equals(other: Any?): Boolean { if (other !is XdmItem) return false return saxonObject == other.saxonObject } companion object { fun newInstance(value: Any?, type: String, processor: Processor): XdmValue = when { type == "empty-sequence()" || value == null -> XdmEmptySequence.getInstance(processor.classLoader) else -> XdmItem.newInstance(value, type, processor) } } }
src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/query/s9api/binding/XdmValue.kt
1997386671
/* * Copyright (C) 2016-2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xdm.tests.functions.op import com.intellij.lang.LanguageASTFactory import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.roots.ProjectRootManager import uk.co.reecedunn.intellij.plugin.core.extensions.registerServiceInstance import uk.co.reecedunn.intellij.plugin.core.tests.module.MockModuleManager import uk.co.reecedunn.intellij.plugin.core.tests.parser.ParsingTestCase import uk.co.reecedunn.intellij.plugin.core.tests.roots.MockProjectRootsManager import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathASTFactory import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathParserDefinition import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XpmNamespaceProvider import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryModule import uk.co.reecedunn.intellij.plugin.xquery.lang.XQuery import uk.co.reecedunn.intellij.plugin.xquery.optree.XQueryNamespaceProvider import uk.co.reecedunn.intellij.plugin.xquery.parser.XQueryASTFactory import uk.co.reecedunn.intellij.plugin.xquery.parser.XQueryParserDefinition import uk.co.reecedunn.intellij.plugin.xquery.project.settings.XQueryProjectSettings import xqt.platform.intellij.xpath.XPath abstract class ParserTestCase : ParsingTestCase<XQueryModule>("xqy", XQueryParserDefinition(), XPathParserDefinition()) { open fun registerModules(manager: MockModuleManager) {} override fun registerServicesAndExtensions() { super.registerServicesAndExtensions() project.registerServiceInstance(XQueryProjectSettings::class.java, XQueryProjectSettings()) addExplicitExtension(LanguageASTFactory.INSTANCE, XPath, XPathASTFactory()) addExplicitExtension(LanguageASTFactory.INSTANCE, XQuery, XQueryASTFactory()) project.registerServiceInstance(ProjectRootManager::class.java, MockProjectRootsManager()) val manager = MockModuleManager(project) registerModules(manager) project.registerServiceInstance(ModuleManager::class.java, manager) XpmNamespaceProvider.register(this, XQueryNamespaceProvider) } }
src/lang-xdm/test/uk/co/reecedunn/intellij/plugin/xdm/tests/functions/op/ParserTestCase.kt
212649615
package org.stepik.android.view.achievement.ui.adapter.delegate import android.view.View import android.view.ViewGroup import android.widget.TextView import kotlinx.android.synthetic.main.view_achievement_item.view.* import org.stepic.droid.R import org.stepik.android.view.achievement.ui.resolver.AchievementResourceResolver import org.stepik.android.domain.achievement.model.AchievementItem import org.stepik.android.view.achievement.ui.delegate.AchievementTileDelegate import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder class AchievementAdapterDelegate( private val achievementResourceResolver: AchievementResourceResolver, private val onItemClicked: (AchievementItem) -> Unit ) : AdapterDelegate<AchievementItem, DelegateViewHolder<AchievementItem>>() { override fun isForViewType(position: Int, data: AchievementItem): Boolean = true override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<AchievementItem> = ViewHolder(createView(parent, R.layout.view_achievement_item)) private inner class ViewHolder(root: View) : DelegateViewHolder<AchievementItem>(root) { private val achievementTitle: TextView = root.achievementTitle private val achievementDescription: TextView = root.achievementDescription private val achievementTileDelegate = AchievementTileDelegate(root.achievementTile, achievementResourceResolver) init { root.setOnClickListener { itemData?.let(onItemClicked) } } override fun onBind(data: AchievementItem) { achievementTileDelegate.setAchievement(data) achievementTitle.text = achievementResourceResolver.resolveTitleForKind(data.kind) achievementDescription.text = achievementResourceResolver.resolveDescription(data) } } }
app/src/main/java/org/stepik/android/view/achievement/ui/adapter/delegate/AchievementAdapterDelegate.kt
2373914879
fun box(): String { val a: A = B(1) a.copy(1) a.component1() return "OK" } interface A { fun copy(x: Int): A fun component1(): Any } data class B(val x: Int) : A
backend.native/tests/external/codegen/box/dataClasses/copy/kt12708.kt
3850047450
package jp.keita.kagurazaka.rxproperty.sample.todo import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.subjects.PublishSubject import jp.keita.kagurazaka.rxproperty.NoParameter object TodoRepository { val onChanged: Observable<NoParameter> get() = changeEmitter.observeOn(AndroidSchedulers.mainThread()) val all: List<TodoItem> get() = list val active: List<TodoItem> get() = list.filter { !it.isDone } val done: List<TodoItem> get() = list.filter { it.isDone } private val list = arrayListOf<TodoItem>() private val changeEmitter = PublishSubject.create<NoParameter>().toSerialized() fun store(item: TodoItem) { list.add(item) changeEmitter.onNext(NoParameter.INSTANCE) } fun update(item: TodoItem) { val index = list.indexOf(item) if (index >= 0) { list[index] = item changeEmitter.onNext(NoParameter.INSTANCE) } } fun deleteDone() { list.removeAll { it.isDone } changeEmitter.onNext(NoParameter.INSTANCE) } fun clear() { list.clear() changeEmitter.onNext(NoParameter.INSTANCE) } }
sample/src/main/kotlin/jp/keita/kagurazaka/rxproperty/sample/todo/TodoRepository.kt
1456123045
package com.commit451.gitlab.event /** * Signifies that the fragments should reload their data */ class ReloadDataEvent
app/src/main/java/com/commit451/gitlab/event/ReloadDataEvent.kt
3538927891
package com.example fun main() { // Can reference the main source set println(com.example.MainQuery::class.java.name) // Can reference the debug source set println(com.example.DebugQuery::class.java.name) // Can reference the demoDebug source set println(com.example.DemoDebugQuery::class.java.name) }
apollo-gradle-plugin/testProjects/androidVariants/src/demoDebug/java/com/example/DemoDebug.kt
785309977
package io.github.feelfreelinux.wykopmobilny.ui.widgets.buttons.vote.entry.comment import io.github.feelfreelinux.wykopmobilny.ui.widgets.buttons.vote.base.BaseVoteButtonView interface EntryCommentVoteButtonView : BaseVoteButtonView
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/buttons/vote/entry/comment/EntryCommentVoteButtonView.kt
3525657223
package venus.riscv.insts.dsl import venus.assembler.AssemblerError import venus.riscv.userStringToInt /** * Gets the immediate from a string, checking if it is in range. * * @param str the immediate as a string * @param min the minimum allowable value of the immediate * @param max the maximum allowable value of the immediate * @return the immediate, as an integer * * @throws IllegalArgumentException if the wrong number of arguments is given */ internal fun getImmediate(str: String, min: Int, max: Int): Int { val imm = try { userStringToInt(str) } catch (e: NumberFormatException) { val hint = when { str.length > 4 -> " (might be too large)" else -> "" } throw AssemblerError("invalid number, got $str$hint") } if (imm !in min..max) throw AssemblerError("immediate $str (= $imm) out of range (should be between $min and $max)") return imm } internal fun compareUnsigned(v1: Int, v2: Int): Int { return (v1 xor Int.MIN_VALUE).compareTo(v2 xor Int.MIN_VALUE) } internal fun compareUnsignedLong(v1: Long, v2: Long): Int { return (v1 xor Long.MIN_VALUE).compareTo(v2 xor Long.MIN_VALUE) }
src/main/kotlin/venus/riscv/insts/dsl/utils.kt
169014797
package expo.modules.adapters.react.apploader import android.content.Context import com.facebook.react.ReactApplication import com.facebook.react.ReactInstanceManager import com.facebook.react.common.LifecycleState import expo.modules.apploader.HeadlessAppLoader import expo.modules.core.interfaces.Consumer import expo.modules.core.interfaces.DoNotStrip private val appRecords: MutableMap<String, ReactInstanceManager> = mutableMapOf() class RNHeadlessAppLoader @DoNotStrip constructor(private val context: Context) : HeadlessAppLoader { //region HeadlessAppLoader override fun loadApp(context: Context, params: HeadlessAppLoader.Params?, alreadyRunning: Runnable?, callback: Consumer<Boolean>?) { if (params == null || params.appScopeKey == null) { throw IllegalArgumentException("Params must be set with appScopeKey!") } if (context.applicationContext is ReactApplication) { val reactInstanceManager = (context.applicationContext as ReactApplication).reactNativeHost.reactInstanceManager if (!appRecords.containsKey(params.appScopeKey)) { reactInstanceManager.addReactInstanceEventListener { HeadlessAppLoaderNotifier.notifyAppLoaded(params.appScopeKey) callback?.apply(true) } appRecords[params.appScopeKey] = reactInstanceManager if (reactInstanceManager.hasStartedCreatingInitialContext()) { reactInstanceManager.recreateReactContextInBackground() } else { reactInstanceManager.createReactContextInBackground() } } else { alreadyRunning?.run() } } else { throw IllegalStateException("Your application must implement ReactApplication") } } override fun invalidateApp(appScopeKey: String?): Boolean { return if (appRecords.containsKey(appScopeKey) && appRecords[appScopeKey] != null) { val appRecord: ReactInstanceManager = appRecords[appScopeKey]!! android.os.Handler(context.mainLooper).post { // Only destroy the `ReactInstanceManager` if it does not bind with an Activity. // And The Activity would take over the ownership of `ReactInstanceManager`. // This case happens when a user clicks a background task triggered notification immediately. if (appRecord.lifecycleState == LifecycleState.BEFORE_CREATE) { appRecord.destroy() } HeadlessAppLoaderNotifier.notifyAppDestroyed(appScopeKey) appRecords.remove(appScopeKey) } true } else { false } } override fun isRunning(appScopeKey: String?): Boolean = appRecords.contains(appScopeKey) && appRecords[appScopeKey]!!.hasStartedCreatingInitialContext() //endregion HeadlessAppLoader }
packages/expo-modules-core/android/src/main/java/expo/modules/adapters/react/apploader/RNHeadlessAppLoader.kt
2468119072
package io.github.feelfreelinux.wykopmobilny.models.dataclass import retrofit2.http.Body data class PMMessage( val author: Author, val date : String, val body: String, val embed: Embed?, val isNew : Boolean, val isSentFromUser : Boolean )
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/dataclass/PMMessage.kt
2883744784
package host.exp.exponent.kernel import android.os.Bundle interface DevMenuModuleInterface { fun getManifestUrl(): String fun getInitialProps(): Bundle fun getMenuItems(): Bundle fun selectItemWithKey(itemKey: String) fun reloadApp() fun isDevSupportEnabled(): Boolean }
android/expoview/src/main/java/host/exp/exponent/kernel/DevMenuModuleInterface.kt
358656756
package net.paslavsky.msm import org.slf4j.Logger import org.slf4j.LoggerFactory import kotlin.util.measureTimeMillis /** * Functions that helps to write logs * @author Andrey Paslavsky * @version 1.0 */ private val Any.logger: Logger get() = LoggerFactory.getLogger(this.javaClass)!! private fun Any.logError(t: Throwable, message: String = t.getMessage() ?: "System error") = logger.error(message, t) private fun Any.logError(message: String, t: Throwable) = logger.error(message, t) //private fun Any.logError(format: String, vararg params: Any?) = logger.error(format, params) private fun Any.logWarning(message: String, t: Throwable? = null) = logger.warn(message, t) //private fun Any.logWarning(format: String, vararg params: Any?) = logger.warn(format, params) private fun Any.logInfo(message: String, t: Throwable? = null) = logger.info(message, t) //private fun Any.logInfo(format: String, vararg params: Any?) = logger.info(format, params) private fun Any.logDebug(message: String, t: Throwable? = null) = logger.debug(message, t) //private fun Any.logDebug(format: String, vararg params: Any?) = logger.debug(format, params) //private fun Any.logTrace(message: String, t: Throwable? = null) = logger.trace(message, t) //private fun Any.logTrace(format: String, vararg params: Any?) = logger.trace(format, params) private fun Any.isErrorEnabled() = logger.isErrorEnabled() private fun Any.isWarnEnabled() = logger.isWarnEnabled() private fun Any.isInfoEnabled() = logger.isInfoEnabled() private fun Any.isDebugEnabled() = logger.isDebugEnabled() private fun Any.isTraceEnabled() = logger.isTraceEnabled() interface IndexGetter {fun index(): String} val static = object: IndexGetter { private var index = 0L public override fun index(): String = java.lang.Long.toString(++index, 16) } private fun <T> Any.logProcess(name: String, block: () -> T): T { var result: T = null val index = static.index() logInfo("Starting the process (#$index) \"$name\"...") try { val millis = measureTimeMillis({ result = block() }) logInfo("...\"$name\" process (#$index) is completed (took $millis ms${getCount(result)})") return result } catch (t: Throwable) { logError("...\"$name\" process (#$index) is completed with an error!", t) throw t } } private fun getCount(value: Any) = when (value) { is Array<*> -> ", processed ${value.size()} element(s)" is Collection<*> -> ", processed ${value.size()} element(s)" is Map<*, *> -> ", processed ${value.size()} element(s)" is Iterator<*> -> ", processed ${value.size()} element(s)" is Iterable<*> -> ", processed ${value.iterator().size()} element(s)" else -> "" }
msm-server/src/main/kotlin/net/paslavsky/msm/Logging.kt
2076444085
package com.rolandvitezhu.todocloud.ui.activity.main.dialogfragment import android.content.DialogInterface import android.os.Bundle import android.os.Parcelable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatDialogFragment import androidx.fragment.app.DialogFragment import androidx.lifecycle.ViewModelProvider import com.rolandvitezhu.todocloud.R import com.rolandvitezhu.todocloud.data.Todo import com.rolandvitezhu.todocloud.databinding.DialogConfirmdeleteBinding import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.CategoriesViewModel import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.ListsViewModel import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.TodosViewModel import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.viewmodelfactory.ListsViewModelFactory import kotlinx.android.synthetic.main.dialog_confirmdelete.view.* import java.util.* class ConfirmDeleteDialogFragment : AppCompatDialogFragment() { private var itemType: String? = null private var itemsToDelete: ArrayList<*>? = null private var isMultipleItems = false private val todosViewModel by lazy { ViewModelProvider(requireActivity()).get(TodosViewModel::class.java) } private val categoriesViewModel by lazy { ViewModelProvider(requireActivity()).get(CategoriesViewModel::class.java) } private val listsViewModel by lazy { ViewModelProvider(requireActivity(), ListsViewModelFactory(categoriesViewModel)). get(ListsViewModel::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(DialogFragment.STYLE_NORMAL, R.style.MyDialogTheme) prepareItemVariables() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val dialogConfirmdeleteBinding: DialogConfirmdeleteBinding = DialogConfirmdeleteBinding.inflate(inflater, container, false) val view: View = dialogConfirmdeleteBinding.root dialogConfirmdeleteBinding.confirmDeleteDialogFragment = this dialogConfirmdeleteBinding.executePendingBindings() prepareDialogTexts(view) return view } private fun prepareItemVariables() { itemType = requireArguments().getString("itemType") itemsToDelete = requireArguments().getParcelableArrayList<Parcelable>("itemsToDelete") prepareIsMultipleItems() } private fun prepareIsMultipleItems() { isMultipleItems = !itemsToDelete.isNullOrEmpty() } /** * Prepare and set the dialog title and the action text by the item type. */ private fun prepareDialogTexts(view: View) { val itemTitle = requireArguments().getString("itemTitle") when (itemType) { "todo" -> if (isMultipleItems) { prepareConfirmDeleteTodosDialogTexts(view) } else { prepareConfirmDeleteTodoDialogTexts(view) } "list" -> if (isMultipleItems) { prepareConfirmDeleteListsDialogTexts(view) } else { prepareConfirmDeleteListDialogTexts(itemTitle, view) } "listInCategory" -> if (isMultipleItems) { prepareConfirmDeleteListsDialogTexts(view) } else { prepareConfirmDeleteListDialogTexts(itemTitle, view) } "category" -> if (isMultipleItems) { prepareConfirmDeleteCategoriesDialogTexts(view) } else { prepareConfirmDeleteCategoryDialogTexts(itemTitle, view) } } } private fun prepareConfirmDeleteCategoryDialogTexts(itemTitle: String?, view: View) { val dialogTitle = getString(R.string.confirmdelete_deletecategorytitle) val actionTextPrefix = getString(R.string.confirmdelete_deletecategoryactiontext) val actionText = prepareActionText(actionTextPrefix, itemTitle) setDialogTitle(dialogTitle) setActionText(actionText, view) } private fun prepareConfirmDeleteCategoriesDialogTexts(view: View) { val dialogTitle = getString(R.string.confirmdelete_categoriestitle) val actionText = getString(R.string.confirmdelete_categoriesactiontext) setDialogTitle(dialogTitle) setActionText(actionText, view) } private fun prepareConfirmDeleteListDialogTexts(itemTitle: String?, view: View) { val dialogTitle = getString(R.string.confirmdelete_deletelisttitle) val actionTextPrefix = getString(R.string.confirmdelete_deletelistactiontext) val actionText = prepareActionText(actionTextPrefix, itemTitle) setDialogTitle(dialogTitle) setActionText(actionText, view) } private fun prepareConfirmDeleteListsDialogTexts(view: View) { val dialogTitle = getString(R.string.confirmdelete_liststitle) val actionText = getString(R.string.confirmdelete_listsactiontext) setDialogTitle(dialogTitle) setActionText(actionText, view) } private fun prepareConfirmDeleteTodoDialogTexts(view: View) { val dialogTitle = getString(R.string.confirmdelete_deletetodotitle) val itemTitle = prepareTodoItemTitle() val actionTextPrefix = getString(R.string.confirmdelete_deletetodoactiontext) val actionText = prepareActionText(actionTextPrefix, itemTitle) setDialogTitle(dialogTitle) setActionText(actionText, view) } private fun prepareConfirmDeleteTodosDialogTexts(view: View) { val dialogTitle = getString(R.string.confirmdelete_todostitle) val actionText = getString(R.string.confirmdelete_todosactiontext) setDialogTitle(dialogTitle) setActionText(actionText, view) } private fun prepareTodoItemTitle(): String? { val todos: ArrayList<Todo>? = itemsToDelete as ArrayList<Todo>? return todos!![0].title } private fun prepareActionText(actionTextPrefix: String, itemTitle: String?): String { return "$actionTextPrefix\"$itemTitle\"?" } private fun setDialogTitle(dialogTitle: String) { requireDialog().setTitle(dialogTitle) } private fun setActionText(actionText: String, view: View) { view.textview_confirmdelete_actiontext.text = actionText } /** * Mark categories as deleted, update them in the local database and update the categories. */ private fun softDeleteCategories(onlineId: String?) { if (isMultipleItems) categoriesViewModel.onSoftDelete(itemsToDelete, targetFragment) else categoriesViewModel.onSoftDelete(onlineId, targetFragment) } /** * Mark lists as deleted, update them in the local database and update the lists. */ private fun softDeleteLists(onlineId: String?) { if (isMultipleItems) listsViewModel.onSoftDelete(itemsToDelete, targetFragment) else listsViewModel.onSoftDelete(onlineId, targetFragment) } /** * Mark todos as deleted, update them in the local database and update the todos. */ private fun softDeleteTodos(onlineId: String?) { if (isMultipleItems) todosViewModel.onSoftDelete(itemsToDelete, targetFragment) else todosViewModel.onSoftDelete(onlineId, targetFragment) } fun onButtonOkClick(view: View) { val onlineId = requireArguments().getString("onlineId") when (itemType) { "todo" -> { softDeleteTodos(onlineId) } "list" -> { softDeleteLists(onlineId) } "listInCategory" -> { softDeleteLists(onlineId) } "category" -> { softDeleteCategories(onlineId) } } dismiss() } fun onButtonCancelClick(view: View) { dismiss() } override fun onDismiss(dialog: DialogInterface) { super.onDismiss(dialog) if (targetFragment is DialogInterface.OnDismissListener?) { (targetFragment as DialogInterface.OnDismissListener?)?.onDismiss(dialog) } } }
app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/dialogfragment/ConfirmDeleteDialogFragment.kt
2630504147
/* * Copyright 2020 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.realm.examples.coroutinesexample.ui.main import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import io.realm.examples.coroutinesexample.R import io.realm.examples.coroutinesexample.data.newsreader.local.RealmNYTimesArticle class MainAdapter( private val onClick: (String) -> Unit ) : ListAdapter<RealmNYTimesArticle, MainAdapter.ArticleViewHolder>(DIFF_CALLBACK) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder = LayoutInflater.from(parent.context) .inflate(R.layout.item_article, parent, false) .let { view -> ArticleViewHolder(view) } override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) { with(holder.title) { val article = getItem(position) text = article.title isEnabled = !article.read } } inner class ArticleViewHolder(view: View) : RecyclerView.ViewHolder(view) { val title: TextView = view.findViewById(R.id.title) init { view.setOnClickListener { onClick.invoke(getItem(adapterPosition).url) } } } companion object { val DIFF_CALLBACK = object : DiffUtil.ItemCallback<RealmNYTimesArticle>() { override fun areItemsTheSame(oldItem: RealmNYTimesArticle, newItem: RealmNYTimesArticle): Boolean = oldItem == newItem override fun areContentsTheSame(oldItem: RealmNYTimesArticle, newItem: RealmNYTimesArticle): Boolean = oldItem.read == newItem.read && oldItem.title == newItem.title && oldItem.abstractText == newItem.abstractText } } }
examples/coroutinesExample/src/main/java/io/realm/examples/coroutinesexample/ui/main/MainAdapter.kt
3327136448
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInsight.FileModificationService import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isStableSimpleExpression import org.jetbrains.kotlin.lexer.KtToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.types.TypeUtils class NullChecksToSafeCallInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) = binaryExpressionVisitor { expression -> if (isNullChecksToSafeCallFixAvailable(expression)) { holder.registerProblem( expression, KotlinBundle.message("null.checks.replaceable.with.safe.calls"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, NullChecksToSafeCallCheckFix() ) } } private class NullChecksToSafeCallCheckFix : LocalQuickFix { override fun getName() = KotlinBundle.message("null.checks.to.safe.call.check.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { applyFix(descriptor.psiElement as? KtBinaryExpression ?: return) } private fun applyFix(expression: KtBinaryExpression) { if (!FileModificationService.getInstance().preparePsiElementForWrite(expression)) return val (lte, rte, isAnd) = collectNullCheckExpressions(expression) ?: return val parent = expression.parent expression.replaced(KtPsiFactory(lte).buildExpression { appendExpression(lte) appendFixedText("?.") appendExpression(rte.selectorExpression) appendFixedText(if (isAnd) "!= null" else "== null") }) if (isNullChecksToSafeCallFixAvailable(parent as? KtBinaryExpression ?: return)) { applyFix(parent) } } } companion object { private fun isNullChecksToSafeCallFixAvailable(expression: KtBinaryExpression): Boolean { fun String.afterIgnoreCalls() = replace("?.", ".") val (lte, rte) = collectNullCheckExpressions(expression) ?: return false val context = expression.analyze() if (!lte.isChainStable(context)) return false val resolvedCall = rte.getResolvedCall(context) ?: return false val extensionReceiver = resolvedCall.extensionReceiver if (extensionReceiver != null && TypeUtils.isNullableType(extensionReceiver.type)) return false return rte.receiverExpression.text.afterIgnoreCalls() == lte.text.afterIgnoreCalls() } private fun collectNullCheckExpressions(expression: KtBinaryExpression): Triple<KtExpression, KtQualifiedExpression, Boolean>? { val isAnd = when (expression.operationToken) { KtTokens.ANDAND -> true KtTokens.OROR -> false else -> return null } val lhs = expression.left as? KtBinaryExpression ?: return null val rhs = expression.right as? KtBinaryExpression ?: return null val expectedOperation = if (isAnd) KtTokens.EXCLEQ else KtTokens.EQEQ val lte = lhs.getNullTestableExpression(expectedOperation) ?: return null val rte = rhs.getNullTestableExpression(expectedOperation) as? KtQualifiedExpression ?: return null return Triple(lte, rte, isAnd) } private fun KtBinaryExpression.getNullTestableExpression(expectedOperation: KtToken): KtExpression? { if (operationToken != expectedOperation) return null val lhs = left ?: return null val rhs = right ?: return null if (KtPsiUtil.isNullConstant(lhs)) return rhs if (KtPsiUtil.isNullConstant(rhs)) return lhs return null } private fun KtExpression.isChainStable(context: BindingContext): Boolean = when (this) { is KtReferenceExpression -> isStableSimpleExpression(context) is KtQualifiedExpression -> selectorExpression?.isStableSimpleExpression(context) == true && receiverExpression.isChainStable( context ) else -> false } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/NullChecksToSafeCallInspection.kt
1403355529
package me.elsiff.morefish.announcement import org.bukkit.entity.Player /** * Created by elsiff on 2019-01-15. */ interface PlayerAnnouncement { fun receiversOf(catcher: Player): Collection<Player> companion object { fun ofEmpty(): PlayerAnnouncement = NoAnnouncement() fun ofRanged(radius: Double): PlayerAnnouncement { require(radius >= 0) { "Radius must not be negative" } return RangedAnnouncement(radius) } fun ofBaseOnly(): PlayerAnnouncement = BaseOnlyAnnouncement() fun ofServerBroadcast(): PlayerAnnouncement = ServerAnnouncement() } }
src/main/kotlin/me/elsiff/morefish/announcement/PlayerAnnouncement.kt
3159394419
package com.fsck.k9.notification import android.app.PendingIntent import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat.WearableExtender import androidx.core.app.NotificationManagerCompat import com.fsck.k9.Account import com.fsck.k9.notification.NotificationChannelManager.ChannelType import com.fsck.k9.notification.NotificationIds.getNewMailSummaryNotificationId import timber.log.Timber import androidx.core.app.NotificationCompat.Builder as NotificationBuilder internal class SummaryNotificationCreator( private val notificationHelper: NotificationHelper, private val actionCreator: NotificationActionCreator, private val lockScreenNotificationCreator: LockScreenNotificationCreator, private val singleMessageNotificationCreator: SingleMessageNotificationCreator, private val resourceProvider: NotificationResourceProvider, private val notificationManager: NotificationManagerCompat ) { fun createSummaryNotification( baseNotificationData: BaseNotificationData, summaryNotificationData: SummaryNotificationData ) { when (summaryNotificationData) { is SummarySingleNotificationData -> { createSingleMessageNotification(baseNotificationData, summaryNotificationData.singleNotificationData) } is SummaryInboxNotificationData -> { createInboxStyleSummaryNotification(baseNotificationData, summaryNotificationData) } } } private fun createSingleMessageNotification( baseNotificationData: BaseNotificationData, singleNotificationData: SingleNotificationData ) { singleMessageNotificationCreator.createSingleNotification( baseNotificationData, singleNotificationData, isGroupSummary = true ) } private fun createInboxStyleSummaryNotification( baseNotificationData: BaseNotificationData, notificationData: SummaryInboxNotificationData ) { val account = baseNotificationData.account val accountName = baseNotificationData.accountName val newMessagesCount = baseNotificationData.newMessagesCount val title = resourceProvider.newMessagesTitle(newMessagesCount) val summary = buildInboxSummaryText(accountName, notificationData) val notification = notificationHelper.createNotificationBuilder(account, ChannelType.MESSAGES) .setCategory(NotificationCompat.CATEGORY_EMAIL) .setAutoCancel(true) .setGroup(baseNotificationData.groupKey) .setGroupSummary(true) .setSmallIcon(resourceProvider.iconNewMail) .setColor(baseNotificationData.color) .setWhen(notificationData.timestamp) .setNumber(notificationData.additionalMessagesCount) .setTicker(notificationData.content.firstOrNull()) .setContentTitle(title) .setSubText(accountName) .setInboxStyle(title, summary, notificationData.content) .setContentIntent(createViewIntent(account, notificationData)) .setDeleteIntent(createDismissIntent(account, notificationData.notificationId)) .setDeviceActions(account, notificationData) .setWearActions(account, notificationData) .setAppearance(notificationData.isSilent, baseNotificationData.appearance) .setLockScreenNotification(baseNotificationData) .build() Timber.v("Creating inbox-style summary notification (silent=%b): %s", notificationData.isSilent, notification) notificationManager.notify(notificationData.notificationId, notification) } private fun buildInboxSummaryText(accountName: String, notificationData: SummaryInboxNotificationData): String { return if (notificationData.additionalMessagesCount > 0) { resourceProvider.additionalMessages(notificationData.additionalMessagesCount, accountName) } else { accountName } } private fun NotificationBuilder.setInboxStyle( title: String, summary: String, contentLines: List<CharSequence> ) = apply { val style = NotificationCompat.InboxStyle() .setBigContentTitle(title) .setSummaryText(summary) for (line in contentLines) { style.addLine(line) } setStyle(style) } private fun createViewIntent(account: Account, notificationData: SummaryInboxNotificationData): PendingIntent { return actionCreator.createViewMessagesPendingIntent( account = account, messageReferences = notificationData.messageReferences, notificationId = notificationData.notificationId ) } private fun createDismissIntent(account: Account, notificationId: Int): PendingIntent { return actionCreator.createDismissAllMessagesPendingIntent(account, notificationId) } private fun NotificationBuilder.setDeviceActions( account: Account, notificationData: SummaryInboxNotificationData ) = apply { for (action in notificationData.actions) { when (action) { SummaryNotificationAction.MarkAsRead -> addMarkAllAsReadAction(account, notificationData) SummaryNotificationAction.Delete -> addDeleteAllAction(account, notificationData) } } } private fun NotificationBuilder.addMarkAllAsReadAction( account: Account, notificationData: SummaryInboxNotificationData ) { val icon = resourceProvider.iconMarkAsRead val title = resourceProvider.actionMarkAsRead() val messageReferences = notificationData.messageReferences val notificationId = notificationData.notificationId val markAllAsReadPendingIntent = actionCreator.createMarkAllAsReadPendingIntent(account, messageReferences, notificationId) addAction(icon, title, markAllAsReadPendingIntent) } private fun NotificationBuilder.addDeleteAllAction( account: Account, notificationData: SummaryInboxNotificationData ) { val icon = resourceProvider.iconDelete val title = resourceProvider.actionDelete() val notificationId = getNewMailSummaryNotificationId(account) val messageReferences = notificationData.messageReferences val action = actionCreator.createDeleteAllPendingIntent(account, messageReferences, notificationId) addAction(icon, title, action) } private fun NotificationBuilder.setWearActions( account: Account, notificationData: SummaryInboxNotificationData ) = apply { val wearableExtender = WearableExtender().apply { for (action in notificationData.wearActions) { when (action) { SummaryWearNotificationAction.MarkAsRead -> addMarkAllAsReadAction(account, notificationData) SummaryWearNotificationAction.Delete -> addDeleteAllAction(account, notificationData) SummaryWearNotificationAction.Archive -> addArchiveAllAction(account, notificationData) } } } extend(wearableExtender) } private fun WearableExtender.addMarkAllAsReadAction( account: Account, notificationData: SummaryInboxNotificationData ) { val icon = resourceProvider.wearIconMarkAsRead val title = resourceProvider.actionMarkAllAsRead() val messageReferences = notificationData.messageReferences val notificationId = getNewMailSummaryNotificationId(account) val action = actionCreator.createMarkAllAsReadPendingIntent(account, messageReferences, notificationId) val markAsReadAction = NotificationCompat.Action.Builder(icon, title, action).build() addAction(markAsReadAction) } private fun WearableExtender.addDeleteAllAction(account: Account, notificationData: SummaryInboxNotificationData) { val icon = resourceProvider.wearIconDelete val title = resourceProvider.actionDeleteAll() val messageReferences = notificationData.messageReferences val notificationId = getNewMailSummaryNotificationId(account) val action = actionCreator.createDeleteAllPendingIntent(account, messageReferences, notificationId) val deleteAction = NotificationCompat.Action.Builder(icon, title, action).build() addAction(deleteAction) } private fun WearableExtender.addArchiveAllAction(account: Account, notificationData: SummaryInboxNotificationData) { val icon = resourceProvider.wearIconArchive val title = resourceProvider.actionArchiveAll() val messageReferences = notificationData.messageReferences val notificationId = getNewMailSummaryNotificationId(account) val action = actionCreator.createArchiveAllPendingIntent(account, messageReferences, notificationId) val archiveAction = NotificationCompat.Action.Builder(icon, title, action).build() addAction(archiveAction) } private fun NotificationBuilder.setLockScreenNotification(notificationData: BaseNotificationData) = apply { lockScreenNotificationCreator.configureLockScreenNotification(this, notificationData) } }
app/core/src/main/java/com/fsck/k9/notification/SummaryNotificationCreator.kt
2680247374
package org.intellij.plugins.markdown.model import com.intellij.model.psi.PsiSymbolReferenceService import com.intellij.openapi.components.service import com.intellij.psi.PsiFile import com.intellij.psi.util.parents import com.intellij.testFramework.fixtures.BasePlatformTestCase import org.assertj.core.api.Assertions.assertThat import org.intellij.plugins.markdown.MarkdownTestingUtil import org.intellij.plugins.markdown.lang.psi.impl.MarkdownLinkDestination import org.intellij.plugins.markdown.model.psi.headers.HeaderAnchorLinkDestinationReference import org.intellij.plugins.markdown.model.psi.headers.HeaderSymbol import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class HeaderAnchorSymbolResolveTest: BasePlatformTestCase() { override fun setUp() { super.setUp() myFixture.copyDirectoryToProject("", "") } private fun findLinkDestination(file: PsiFile, offset: Int): MarkdownLinkDestination? { val elementUnderCaret = file.findElementAt(offset) checkNotNull(elementUnderCaret) return elementUnderCaret.parents(withSelf = true).filterIsInstance<MarkdownLinkDestination>().firstOrNull() } @Test fun `reference to own header is resolved`() = doTest("own-header") @Test fun `reference to header in other file is resolved`() = doTest("header-near-main") @Test fun `reference to header in subdirectory is resolved`() = doTest("header-in-subdirectory") @Test fun `reference to header in deep subdirectory is resolved`() = doTest("some-deep-header") @Test fun `reference to header in list is resolved`() = doTest("header-inside-list-item") @Test fun `reference to header in other file without extension is resolved`() = doTest("header-near-main") @Test fun `special gfm case`() = doTest("get-method") @Test fun `weird date case`() = doTest("100-april-8-2018") private fun doTest(expectedAnchor: String) { val testName = getTestName(true) val file = myFixture.configureFromTempProjectFile("$testName.md") val caretModel = myFixture.editor.caretModel val caret = caretModel.primaryCaret val offset = caret.offset val linkDestination = findLinkDestination(file, offset) checkNotNull(linkDestination) val references = service<PsiSymbolReferenceService>().getReferences(linkDestination) val targetReferences = references.filterIsInstance<HeaderAnchorLinkDestinationReference>() assertThat(targetReferences) .withFailMessage { "Failed to collect symbol references for ${linkDestination.text}" } .isNotEmpty val resolved = targetReferences.flatMap { it.resolveReference().filterIsInstance<HeaderSymbol>() } assertThat(resolved) .withFailMessage { "Failed to resolve symbol reference for ${linkDestination.text}" } .isNotEmpty val header = resolved.find { it.anchorText == expectedAnchor } assertThat(header) .withFailMessage { "Anchor reference resolved to something else: ${resolved.map { "${it.anchorText} - ${it.text}" }}\n" + "Expected resolution result: $expectedAnchor" }.isNotNull } override fun getTestName(lowercaseFirstLetter: Boolean): String { val name = super.getTestName(lowercaseFirstLetter) return name.trimStart().replace(' ', '_') } override fun getTestDataPath(): String { return "${MarkdownTestingUtil.TEST_DATA_PATH}/model/headers/resolve" } }
plugins/markdown/test/src/org/intellij/plugins/markdown/model/HeaderAnchorSymbolResolveTest.kt
1968163002