content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package org.evomaster.core.database.extract.postgres import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType import org.evomaster.client.java.controller.db.SqlScriptRunner import org.evomaster.client.java.controller.internal.db.SchemaExtractor import org.evomaster.core.database.DbActionTransformer import org.evomaster.core.database.SqlInsertBuilder import org.evomaster.core.search.gene.collection.ArrayGene import org.evomaster.core.search.gene.BooleanGene import org.evomaster.core.search.gene.sql.SqlBitStringGene import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test /** * Created by jgaleotti on 18-Apr-22. */ class BitStringTypesTest : ExtractTestBasePostgres() { override fun getSchemaLocation() = "/sql_schema/postgres_bitstring_types.sql" @Test fun testBitStringTypes() { val schema = SchemaExtractor.extract(connection) assertNotNull(schema) assertEquals("public", schema.name.lowercase()) assertEquals(DatabaseType.POSTGRES, schema.databaseType) val builder = SqlInsertBuilder(schema) val actions = builder.createSqlInsertionAction( "BitStringTypes", setOf( "bitColumn", "bitvaryingColumn" ) ) val genes = actions[0].seeTopGenes() assertEquals(2, genes.size) assertTrue(genes[0] is SqlBitStringGene) //character varying val bitColumnGene = genes[0] as SqlBitStringGene assertEquals(5, bitColumnGene.minSize) assertEquals(5, bitColumnGene.maxSize) val arrayGene = bitColumnGene.getViewOfChildren()[0] as ArrayGene<BooleanGene> repeat(bitColumnGene.minSize) { arrayGene.addElement(BooleanGene("booleanGene")) } assertTrue(genes[1] is SqlBitStringGene) //character varying val bitVaryingColumnGene = genes[1] as SqlBitStringGene assertEquals(0, bitVaryingColumnGene.minSize) assertEquals(10, bitVaryingColumnGene.maxSize) val dbCommandDto = DbActionTransformer.transform(actions) SqlScriptRunner.execInsert(connection, dbCommandDto.insertions) } }
core/src/test/kotlin/org/evomaster/core/database/extract/postgres/BitStringTypesTest.kt
106818440
package com.leaguechampions.libraries.core.utils import android.content.Context import android.content.Intent object Router { fun getSettingsIntent(context: Context) = internalIntent(context, "com.leaguechampions.features.settings.open") // .putExtra() private fun internalIntent(context: Context, action: String) = Intent(action).setPackage(context.packageName) }
libraries/core/src/main/java/com/leaguechampions/libraries/core/utils/Router.kt
827965460
package com.buildServer.rest.agent import org.springframework.boot.SpringBootConfiguration import org.springframework.boot.autoconfigure.EnableAutoConfiguration import org.springframework.boot.test.context.SpringBootTest import org.springframework.context.annotation.ComponentScan /** * @author Dmitry Zhuravlev * Date: 19.10.2016 */ @SpringBootConfiguration @EnableAutoConfiguration @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) @ComponentScan("com.buildServer.rest.agent") annotation class RestAgentTest
rest-runner-agent/src/test/kotlin/com/buildServer/rest/agent/RestAgentTest.kt
610751396
package com.petrulak.cleankotlin.di.component import com.petrulak.cleankotlin.di.module.ApplicationMockModule import com.petrulak.cleankotlin.di.module.InteractorMockModule import dagger.Component import javax.inject.Singleton @Singleton @Component( modules = arrayOf( ApplicationMockModule::class, InteractorMockModule::class ) ) interface ApplicationMockComponent : ApplicationComponent { }
app/src/androidTest/java/com/petrulak/cleankotlin/di/component/ApplicationMockComponent.kt
664109078
/* Copyright 2018 Esri * * 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.esri.arcgisruntime.sample.geodesicoperations import android.graphics.Color import android.os.Bundle import android.view.MotionEvent import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.esri.arcgisruntime.ArcGISRuntimeEnvironment import com.esri.arcgisruntime.geometry.GeodeticCurveType import com.esri.arcgisruntime.geometry.GeometryEngine import com.esri.arcgisruntime.geometry.LinearUnit import com.esri.arcgisruntime.geometry.LinearUnitId import com.esri.arcgisruntime.geometry.Point import com.esri.arcgisruntime.geometry.PointCollection import com.esri.arcgisruntime.geometry.Polyline import com.esri.arcgisruntime.geometry.SpatialReferences import com.esri.arcgisruntime.mapping.ArcGISMap import com.esri.arcgisruntime.mapping.BasemapStyle import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener import com.esri.arcgisruntime.mapping.view.Graphic import com.esri.arcgisruntime.mapping.view.GraphicsOverlay import com.esri.arcgisruntime.mapping.view.MapView import com.esri.arcgisruntime.symbology.SimpleLineSymbol import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol import com.esri.arcgisruntime.sample.geodesicoperations.databinding.ActivityMainBinding import kotlin.math.roundToInt class MainActivity : AppCompatActivity() { private val srWgs84 = SpatialReferences.getWgs84() private val unitOfMeasurement = LinearUnit(LinearUnitId.KILOMETERS) private val units = "Kilometers" private val activityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) } private val mapView: MapView by lazy { activityMainBinding.mapView } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(activityMainBinding.root) // authentication with an API key or named user is required to access basemaps and other // location services ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY) // create a map val map = ArcGISMap(BasemapStyle.ARCGIS_IMAGERY) // set a map to a map view mapView.map = map // create a graphic overlay val graphicOverlay = GraphicsOverlay() mapView.graphicsOverlays.add(graphicOverlay) // add a graphic at JFK to represent the flight start location val start = Point(-73.7781, 40.6413, srWgs84) val locationMarker = SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, 0xFF0000FF.toInt(), 10f) val startLocation = Graphic(start, locationMarker) // create a graphic for the destination val endLocation = Graphic() endLocation.symbol = locationMarker // create a graphic representing the geodesic path between the two locations val path = Graphic() path.symbol = SimpleLineSymbol(SimpleLineSymbol.Style.DASH, 0xFF0000FF.toInt(), 5f) // add graphics to graphics overlay graphicOverlay.graphics.apply { add(startLocation) add(endLocation) add(path) } // create listener to get the location of the tap in the screen mapView.onTouchListener = object : DefaultMapViewOnTouchListener(this, mapView) { override fun onSingleTapConfirmed(e: MotionEvent): Boolean { // get the point that was clicked and convert it to a point in the map val clickLocation = android.graphics.Point(e.x.roundToInt(), e.y.roundToInt()) val mapPoint = mapView.screenToLocation(clickLocation) val destination = GeometryEngine.project(mapPoint, SpatialReferences.getWgs84()) endLocation.geometry = destination // create a straight line path between the start and end locations val points = PointCollection(listOf(start, destination as Point), srWgs84) val polyLine = Polyline(points) // densify the path as a geodesic curve with the path graphic val pathGeometry = GeometryEngine.densifyGeodetic( polyLine, 1.0, unitOfMeasurement, GeodeticCurveType.GEODESIC ) path.geometry = pathGeometry // calculate path distance val distance = GeometryEngine.lengthGeodetic( pathGeometry, unitOfMeasurement, GeodeticCurveType.GEODESIC ) // create a textView for the callout val calloutContent = TextView(applicationContext) calloutContent.setTextColor(Color.BLACK) calloutContent.setSingleLine() // format coordinates to 2 decimal places val distanceString = String.format("%.2f", distance) // display distance as a callout calloutContent.text = "Distance: $distanceString $units" val callout = mapView.callout callout.location = mapPoint callout.content = calloutContent callout.show() return true } } } override fun onPause() { super.onPause() mapView.pause() } override fun onResume() { super.onResume() mapView.resume() } override fun onDestroy() { super.onDestroy() mapView.dispose() } }
kotlin/geodesic-operations/src/main/java/com/esri/arcgisruntime/sample/geodesicoperations/MainActivity.kt
3591462893
package configurations import common.functionalTestExtraParameters import jetbrains.buildServer.configs.kotlin.v2019_2.BuildSteps import model.CIBuildModel import model.Stage import model.StageName import model.TestCoverage const val functionalTestTag = "FunctionalTest" class FunctionalTest( model: CIBuildModel, id: String, name: String, description: String, val testCoverage: TestCoverage, stage: Stage, enableTestDistribution: Boolean, subprojects: List<String> = listOf(), extraParameters: String = "", extraBuildSteps: BuildSteps.() -> Unit = {}, preBuildSteps: BuildSteps.() -> Unit = {} ) : BaseGradleBuildType(stage = stage, init = { this.name = name this.description = description this.id(id) val testTasks = getTestTaskName(testCoverage, subprojects) applyTestDefaults( model, this, testTasks, dependsOnQuickFeedbackLinux = !testCoverage.withoutDependencies && stage.stageName > StageName.PULL_REQUEST_FEEDBACK, os = testCoverage.os, buildJvm = testCoverage.buildJvm, arch = testCoverage.arch, extraParameters = ( listOf(functionalTestExtraParameters(functionalTestTag, testCoverage.os, testCoverage.arch, testCoverage.testJvmVersion.major.toString(), testCoverage.vendor.name)) + (if (enableTestDistribution) "-DenableTestDistribution=%enableTestDistribution% -DtestDistributionPartitionSizeInSeconds=%testDistributionPartitionSizeInSeconds%" else "") + "-PflakyTests=${determineFlakyTestStrategy(stage)}" + extraParameters ).filter { it.isNotBlank() }.joinToString(separator = " "), timeout = testCoverage.testType.timeout, extraSteps = extraBuildSteps, preSteps = preBuildSteps ) failureConditions { // JavaExecDebugIntegrationTest.debug session fails without debugger might cause JVM crash // Some soak tests produce OOM exceptions // There are also random worker crashes for some tests. // We have test-retry to handle the crash in tests javaCrash = false } }) private fun determineFlakyTestStrategy(stage: Stage): String { val stageName = StageName.values().first { it.stageName == stage.stageName.stageName } // See gradlebuild.basics.FlakyTestStrategy return if (stageName < StageName.READY_FOR_RELEASE) "exclude" else "include" } fun getTestTaskName(testCoverage: TestCoverage, subprojects: List<String>): String { val testTaskName = "${testCoverage.testType.name}Test" return when { subprojects.isEmpty() -> { testTaskName } else -> { subprojects.joinToString(" ") { "$it:$testTaskName" } } } }
.teamcity/src/main/kotlin/configurations/FunctionalTest.kt
1826434299
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * 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. */ @file:Suppress("UNUSED", "PublicApiImplicitType", "KDocMissingDocumentation") package jp.nephy.penicillin.models import jp.nephy.jsonkt.JsonObject import jp.nephy.jsonkt.delegation.* import jp.nephy.penicillin.core.session.ApiClient import jp.nephy.penicillin.extensions.nullablePenicillinModel data class TrendType(override val json: JsonObject, override val client: ApiClient): PenicillinModel { val trend by nullablePenicillinModel<Trend>() val promotedTrend by nullablePenicillinModel<PromotedTrend>() data class Trend(override val json: JsonObject, override val client: ApiClient): PenicillinModel { val name by string val description by nullableString("meta_description") val rank by int val token by string val context by nullablePenicillinModel<Context>() val target by nullablePenicillinModel<Target>() data class Context(override val json: JsonObject, override val client: ApiClient): PenicillinModel { val relatedQuery by stringList("query") } data class Target(override val json: JsonObject, override val client: ApiClient): PenicillinModel { val query by string val pinnedTweets by longList("pinned_tweets") val pinnedTweetsStr by stringList("pinned_tweets_string") } } data class PromotedTrend(override val json: JsonObject, override val client: ApiClient): PenicillinModel }
src/main/kotlin/jp/nephy/penicillin/models/TrendType.kt
3272208671
package com.halangode.devicescanner import android.util.Log /** * Created by Harikumar Alangode on 24-Jun-17. */ internal object LogUtil { fun d(label: String, description: String) { if (Constants.isLogEnabled) { Log.d(label, description) } } fun e(label: String, description: String) { if (Constants.isLogEnabled) { Log.e(label, description) } } }
devicescanner/src/main/java/com/halangode/devicescanner/LogUtil.kt
1287368745
package kondorcet /** * Represent a an algorithm used to compute the winners and losers from a set of ballots. */ interface VoteMethod { /** * Compute the resultOf of a poll * * @param poll Poll of ballots * @return A ballot that represent the better the poll */ fun <T : Any> resultOf(poll: Poll<T>): Ballot<T> }
src/main/kotlin/kondorcet/VoteMethod.kt
3525436744
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.entity import com.almasb.fxgl.entity.component.Component /** * @return component of given type or throws exception if entity has no such component */ inline fun <reified T : Component> Entity.getComponent(): T { return this.getComponent(T::class.java) }
fxgl-entity/src/main/kotlin/com/almasb/fxgl/entity/EntityExt.kt
2859058635
/* * Copyright 2017 Alexey Shtanko * * 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.shtanko.picasagallery.data.api import com.github.kittinunf.fuel.core.FuelManager import com.github.kittinunf.fuel.httpGet import com.github.kittinunf.fuel.rx.rx_object import com.github.kittinunf.result.Result import com.google.gson.Gson import io.reactivex.BackpressureStrategy.DROP import io.reactivex.Flowable import io.reactivex.Maybe import io.reactivex.Observable import io.shtanko.picasagallery.Config import io.shtanko.picasagallery.Config.PICASA_BASE_API_URL import io.shtanko.picasagallery.Config.PICASA_BASE_USER_API_URL import io.shtanko.picasagallery.core.prefs.PreferenceHelper import io.shtanko.picasagallery.data.model.AlbumEntity import io.shtanko.picasagallery.data.model.AlbumsResponseEntity import io.shtanko.picasagallery.data.model.UserFeedResponseEntity import io.shtanko.picasagallery.data.user.UserException import io.shtanko.picasagallery.extensions.authenticate import io.shtanko.picasagallery.util.Logger import javax.inject.Inject import javax.inject.Singleton import kotlin.text.Charsets.UTF_8 import io.shtanko.picasagallery.Config.JSON_PARAMS as PARAMS @Singleton class ApiManagerImpl @Inject constructor( private val preferencesHelper: PreferenceHelper ) : ApiManager { override fun getUserAlbums(userId: String): Flowable<List<AlbumEntity>> = getUser(userId).map { return@map it.feed.entry }.toFlowable(DROP) init { FuelManager.instance.basePath = PICASA_BASE_API_URL } override fun getUser(userId: String): Observable<UserFeedResponseEntity> { Logger.vTemp(PICASA_BASE_USER_API_URL.httpGet(PARAMS).path) Logger.vTemp("TOKEN: ${preferencesHelper.getToken()}") return PICASA_BASE_USER_API_URL.httpGet(PARAMS) .authenticate( preferencesHelper.getToken() ) .rx_object( UserFeedResponseEntity.Deserializer ) .flatMapMaybe { when (it) { is Result.Success -> { if (!it.value.feed.id.body.isEmpty()) { Maybe.just(it.value) } else { Maybe.empty<UserFeedResponseEntity>() } } is Result.Failure -> { try { Maybe.error<UserFeedResponseEntity>( Gson().fromJson( it.error.response.data.toString(UTF_8), UserException::class.java ) ) } catch (e: Throwable) { Maybe.error<UserFeedResponseEntity>( UserException( it.error.message ?: it.error.exception.message ?: it.error.response.responseMessage ) ) } } } } .toObservable() } override fun getAlbums( userId: String, albumId: String ): Observable<AlbumsResponseEntity> { Logger.verbose(Config.configureAlbumsPath(userId, albumId).httpGet(PARAMS).path) return Config.configureAlbumsPath(userId, albumId) .httpGet(PARAMS) .rx_object( AlbumsResponseEntity.Deserializer ) .flatMapMaybe { when (it) { is Result.Success -> { if (!it.value.version.isEmpty()) { Maybe.just(it.value) } else { Maybe.empty<AlbumsResponseEntity>() } } is Result.Failure -> { try { Maybe.error<AlbumsResponseEntity>( Gson().fromJson( it.error.response.data.toString(UTF_8), UserException::class.java ) ) } catch (e: Throwable) { Maybe.error<AlbumsResponseEntity>( UserException( it.error.message ?: it.error.exception.message ?: it.error.response.responseMessage ) ) } } } } .toObservable() } }
app/src/main/kotlin/io/shtanko/picasagallery/data/api/ApiManagerImpl.kt
3952880312
@file:Suppress("NOTHING_TO_INLINE") package me.eugeniomarletti.extras.bundle.base import android.os.Parcelable import me.eugeniomarletti.extras.bundle.BundleExtra inline fun BundleExtra.ParcelableArray(name: String? = null, customPrefix: String? = null) = ParcelableArray({ it }, { it }, name, customPrefix) inline fun BundleExtra.ParcelableArray(defaultValue: Array<Parcelable?>, name: String? = null, customPrefix: String? = null) = ParcelableArray({ it ?: defaultValue }, { it }, name, customPrefix) inline fun BundleExtra.CharSequenceArray(name: String? = null, customPrefix: String? = null) = CharSequenceArray({ it }, { it }, name, customPrefix) inline fun BundleExtra.CharSequenceArray(defaultValue: Array<CharSequence?>, name: String? = null, customPrefix: String? = null) = CharSequenceArray({ it ?: defaultValue }, { it }, name, customPrefix) inline fun BundleExtra.StringArray(name: String? = null, customPrefix: String? = null) = StringArray({ it }, { it }, name, customPrefix) inline fun BundleExtra.StringArray(defaultValue: Array<String?>, name: String? = null, customPrefix: String? = null) = StringArray({ it ?: defaultValue }, { it }, name, customPrefix) inline fun BundleExtra.ByteArray(name: String? = null, customPrefix: String? = null) = ByteArray({ it }, { it }, name, customPrefix) inline fun BundleExtra.ByteArray(defaultValue: ByteArray, name: String? = null, customPrefix: String? = null) = ByteArray({ it ?: defaultValue }, { it }, name, customPrefix) inline fun BundleExtra.CharArray(name: String? = null, customPrefix: String? = null) = CharArray({ it }, { it }, name, customPrefix) inline fun BundleExtra.CharArray(defaultValue: CharArray, name: String? = null, customPrefix: String? = null) = CharArray({ it ?: defaultValue }, { it }, name, customPrefix) inline fun BundleExtra.IntArray(name: String? = null, customPrefix: String? = null) = IntArray({ it }, { it }, name, customPrefix) inline fun BundleExtra.IntArray(defaultValue: IntArray, name: String? = null, customPrefix: String? = null) = IntArray({ it ?: defaultValue }, { it }, name, customPrefix) inline fun BundleExtra.ShortArray(name: String? = null, customPrefix: String? = null) = ShortArray({ it }, { it }, name, customPrefix) inline fun BundleExtra.ShortArray(defaultValue: ShortArray, name: String? = null, customPrefix: String? = null) = ShortArray({ it ?: defaultValue }, { it }, name, customPrefix) inline fun BundleExtra.LongArray(name: String? = null, customPrefix: String? = null) = LongArray({ it }, { it }, name, customPrefix) inline fun BundleExtra.LongArray(defaultValue: LongArray, name: String? = null, customPrefix: String? = null) = LongArray({ it ?: defaultValue }, { it }, name, customPrefix) inline fun BundleExtra.DoubleArray(name: String? = null, customPrefix: String? = null) = DoubleArray({ it }, { it }, name, customPrefix) inline fun BundleExtra.DoubleArray(defaultValue: DoubleArray, name: String? = null, customPrefix: String? = null) = DoubleArray({ it ?: defaultValue }, { it }, name, customPrefix) inline fun BundleExtra.FloatArray(name: String? = null, customPrefix: String? = null) = FloatArray({ it }, { it }, name, customPrefix) inline fun BundleExtra.FloatArray(defaultValue: FloatArray, name: String? = null, customPrefix: String? = null) = FloatArray({ it ?: defaultValue }, { it }, name, customPrefix) inline fun BundleExtra.BooleanArray(name: String? = null, customPrefix: String? = null) = BooleanArray({ it }, { it }, name, customPrefix) inline fun BundleExtra.BooleanArray(defaultValue: BooleanArray, name: String? = null, customPrefix: String? = null) = BooleanArray({ it ?: defaultValue }, { it }, name, customPrefix)
library/src/main/java/me/eugeniomarletti/extras/bundle/base/Array.kt
832418854
/* * Copyright 2022 Ren Binden * * 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.rpkit.chat.bukkit.database.table import com.rpkit.chat.bukkit.RPKChatBukkit import com.rpkit.chat.bukkit.chatchannel.RPKChatChannel import com.rpkit.chat.bukkit.database.create import com.rpkit.chat.bukkit.database.jooq.Tables.RPKIT_CHAT_CHANNEL_MUTE import com.rpkit.chat.bukkit.mute.RPKChatChannelMute import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileId import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletableFuture.runAsync import java.util.logging.Level.SEVERE /** * Represents the chat channel mute table */ class RPKChatChannelMuteTable(private val database: Database, private val plugin: RPKChatBukkit) : Table { private data class MinecraftProfileChatChannelCacheKey( val minecraftProfileId: Int, val chatChannelName: String ) private val cache = if (plugin.config.getBoolean("caching.rpkit_chat_channel_mute.minecraft_profile_id.enabled")) { database.cacheManager.createCache( "rpk-chat-bukkit.rpkit_chat_channel_mute.minecraft_profile_id", MinecraftProfileChatChannelCacheKey::class.java, RPKChatChannelMute::class.java, plugin.config.getLong("caching.rpkit_chat_channel_mute.minecraft_profile_id.size") ) } else { null } fun insert(entity: RPKChatChannelMute): CompletableFuture<Void> { val minecraftProfileId = entity.minecraftProfile.id ?: return CompletableFuture.completedFuture(null) val chatChannelName = entity.chatChannel.name return runAsync { database.create .insertInto( RPKIT_CHAT_CHANNEL_MUTE, RPKIT_CHAT_CHANNEL_MUTE.MINECRAFT_PROFILE_ID, RPKIT_CHAT_CHANNEL_MUTE.CHAT_CHANNEL_NAME ) .values( minecraftProfileId.value, chatChannelName.value ) .execute() cache?.set(MinecraftProfileChatChannelCacheKey(minecraftProfileId.value, chatChannelName.value), entity) }.exceptionally { exception -> plugin.logger.log(SEVERE, "Failed to insert chat channel mute", exception) throw exception } } fun get(minecraftProfile: RPKMinecraftProfile, chatChannel: RPKChatChannel): CompletableFuture<RPKChatChannelMute?> { val minecraftProfileId = minecraftProfile.id ?: return CompletableFuture.completedFuture(null) val chatChannelName = chatChannel.name val cacheKey = MinecraftProfileChatChannelCacheKey(minecraftProfileId.value, chatChannelName.value) if (cache?.containsKey(cacheKey) == true) { return CompletableFuture.completedFuture(cache[cacheKey]) } return CompletableFuture.supplyAsync { database.create .select( RPKIT_CHAT_CHANNEL_MUTE.MINECRAFT_PROFILE_ID, RPKIT_CHAT_CHANNEL_MUTE.CHAT_CHANNEL_NAME ) .from(RPKIT_CHAT_CHANNEL_MUTE) .where(RPKIT_CHAT_CHANNEL_MUTE.MINECRAFT_PROFILE_ID.eq(minecraftProfileId.value)) .and(RPKIT_CHAT_CHANNEL_MUTE.CHAT_CHANNEL_NAME.eq(chatChannelName.value)) .fetchOne() ?: return@supplyAsync null val chatChannelMute = RPKChatChannelMute( minecraftProfile, chatChannel ) cache?.set(cacheKey, chatChannelMute) return@supplyAsync chatChannelMute }.exceptionally { exception -> plugin.logger.log(SEVERE, "Failed to get chat channel mute", exception) throw exception } } fun delete(entity: RPKChatChannelMute): CompletableFuture<Void> { val minecraftProfileId = entity.minecraftProfile.id ?: return CompletableFuture.completedFuture(null) val chatChannelName = entity.chatChannel.name val cacheKey = MinecraftProfileChatChannelCacheKey(minecraftProfileId.value, chatChannelName.value) return runAsync { database.create .deleteFrom(RPKIT_CHAT_CHANNEL_MUTE) .where(RPKIT_CHAT_CHANNEL_MUTE.MINECRAFT_PROFILE_ID.eq(minecraftProfileId.value)) .and(RPKIT_CHAT_CHANNEL_MUTE.CHAT_CHANNEL_NAME.eq(chatChannelName.value)) .execute() cache?.remove(cacheKey) }.exceptionally { exception -> plugin.logger.log(SEVERE, "Failed to delete chat channel mute", exception) throw exception } } fun delete(minecraftProfileId: RPKMinecraftProfileId): CompletableFuture<Void> = runAsync { database.create .deleteFrom(RPKIT_CHAT_CHANNEL_MUTE) .where(RPKIT_CHAT_CHANNEL_MUTE.MINECRAFT_PROFILE_ID.eq(minecraftProfileId.value)) .execute() cache?.removeMatching { it.minecraftProfile.id?.value == minecraftProfileId.value } }.exceptionally { exception -> plugin.logger.log(SEVERE, "Failed to delete chat channel mutes for Minecraft profile id", exception) throw exception } }
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/database/table/RPKChatChannelMuteTable.kt
2694031594
package com.lapptelier.smartrecyclerview /** * com.lapptelier.smartrecyclerview.smart_recycler_view.PlaceHolderCell * * * Generic model of a generic placeholder cell * * @author L'Apptelier SARL * @date 14/09/2017 */ class PlaceHolderCell
smartrecyclerview/src/main/java/com/lapptelier/smartrecyclerview/PlaceHolderCell.kt
2990770016
package com.guideapp.ui.views.map import android.content.Context import android.support.v4.app.LoaderManager import android.widget.ImageView import com.guideapp.model.Local internal interface MapContract { interface View { fun showLocals(locals: List<Local>) fun showLocalSummary(local: Local) fun showLocalDetailUi(local: Local, view: ImageView) fun getContext() : Context } interface Presenter { fun loadLocals(loaderManager: LoaderManager) fun openLocalSummary(local: Local?) fun openLocalDetails(local: Local, view: ImageView) } }
app/src/main/java/com/guideapp/ui/views/map/MapContract.kt
1075440158
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.clouddriver.saga.flow.seekers import com.netflix.spinnaker.clouddriver.saga.SagaCommandCompleted import com.netflix.spinnaker.clouddriver.saga.flow.SagaFlow import com.netflix.spinnaker.clouddriver.saga.flow.Seeker import com.netflix.spinnaker.clouddriver.saga.flow.convertActionStepToCommandName import com.netflix.spinnaker.clouddriver.saga.models.Saga import org.slf4j.LoggerFactory /** * Seeks the [SagaFlowIterator] index to the next command following a [SagaCommandCompleted] event. */ internal class SagaCommandCompletedEventSeeker : Seeker { private val log by lazy { LoggerFactory.getLogger(javaClass) } override fun invoke(currentIndex: Int, steps: List<SagaFlow.Step>, saga: Saga): Int? { val completionEvents = saga.getEvents().filterIsInstance<SagaCommandCompleted>() if (completionEvents.isEmpty()) { // If there are no completion events, we don't need to seek at all. return null } val lastCompletedCommand = completionEvents.last().command val step = steps .filterIsInstance<SagaFlow.ActionStep>() .find { convertActionStepToCommandName(it) == lastCompletedCommand } if (step == null) { // Not the end of the world if this seeker doesn't find a correlated step, but it's definitely an error case log.error("Could not find step associated with last completed command ($lastCompletedCommand)") return null } return (steps.indexOf(step) + 1).also { log.debug("Suggesting to seek index to $it") } } }
clouddriver-saga/src/main/kotlin/com/netflix/spinnaker/clouddriver/saga/flow/seekers/SagaCommandCompletedEventSeeker.kt
2284929148
package org.luxons.sevenwonders.ui.components.gameBrowser import kotlinx.css.* import react.RBuilder import react.dom.* import styled.css import styled.styledDiv fun RBuilder.gameBrowser() = styledDiv { css { margin(all = 1.rem) } h1 { +"Games" } createGameForm {} gameList() }
sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/gameBrowser/GameBrowser.kt
2842320037
package siosio.jsr352.jsl.integration.flow import org.jboss.logging.* import javax.batch.api.* import javax.enterprise.context.Dependent import javax.inject.Named @Named @Dependent class FlowJobBatchlet2 : AbstractBatchlet() { val log : Logger = Logger.getLogger(FlowJobBatchlet2::class.java) override fun process(): String { log.info("FlowJobBatchlet2!!!!!!") return "ok" } }
src/test/kotlin/siosio/jsr352/jsl/integration/flow/FlowJobBatchlet2.kt
3162812496
package com.wiseassblog.domain.api import com.wiseassblog.common.ResultWrapper import com.wiseassblog.domain.domainmodel.Reminder /** * This interface describes the responsibilities and interactions between * Presenters and The ReminderRepository class. * Created by Ryan on 09/03/2017. */ interface IReminderAPI { suspend fun setReminder(reminder: Reminder): ResultWrapper<Exception, Unit> suspend fun cancelReminder(reminder: Reminder): ResultWrapper<Exception, Unit> }
domain/src/main/java/com/wiseassblog/domain/api/IReminderAPI.kt
98453764
package injection import dagger.Binds import dagger.Module import data.ChangeVersion import data.ChangeVersionImp /** * Created on 29/08/2017. * * All Dagger interface to implementation Bindings are declared here */ @Module abstract class BindingModule { @Binds abstract fun bindChangeVersion(changeVersionImp: ChangeVersionImp): ChangeVersion }
src/main/kotlin/injection/BindingModule.kt
657012943
package net.perfectdreams.loritta.morenitta.commands.vanilla.images import net.perfectdreams.loritta.common.utils.image.JVMImage import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.api.commands.CommandException import net.perfectdreams.loritta.morenitta.api.entities.User import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase import net.perfectdreams.loritta.morenitta.platform.discord.legacy.entities.DiscordUser import net.perfectdreams.loritta.morenitta.platform.discord.legacy.entities.jda.JDAUser import net.perfectdreams.loritta.morenitta.utils.* import net.perfectdreams.loritta.morenitta.utils.locale.Gender import net.perfectdreams.loritta.morenitta.utils.locale.PersonalPronoun import java.awt.* import java.awt.image.BufferedImage class TristeRealidadeCommand(loritta: LorittaBot) : DiscordAbstractCommandBase(loritta, listOf("sadreality", "tristerealidade"), net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) { companion object { private const val LOCALE_PREFIX = "commands.command" } override fun command() = create { needsToUploadFiles = true localizedDescription("$LOCALE_PREFIX.tristerealidade.description") executesDiscord { OutdatedCommandUtils.sendOutdatedCommandMessage(this, this.locale, "sadreality") val context = this var x = 0 var y = 0 val base = BufferedImage(384, 256, BufferedImage.TYPE_INT_ARGB) // Iremos criar uma imagem 384x256 (tamanho do template) val baseGraph = base.graphics.enableFontAntiAliasing() val users = mutableListOf<User>() val user1 = context.user(0) val user2 = context.user(1) val user3 = context.user(2) val user4 = context.user(3) val user5 = context.user(4) val user6 = context.user(5) if (user1 != null) users.add(user1) if (user2 != null) users.add(user2) if (user3 != null) users.add(user3) if (user4 != null) users.add(user4) if (user5 != null) users.add(user5) if (user6 != null) users.add(user6) val members = context.guild.members.filter { !it.user.isBot}.toMutableList() while (6 > users.size) { val member = if (members.isNotEmpty()) { members[LorittaBot.RANDOM.nextInt(members.size)] } else { throw CommandException("Não existem membros suficientes para fazer uma triste realidade, sorry ;w;", Constants.ERROR) } users.add(JDAUser(member.user)) members.remove(member) } var lovedGender = Gender.UNKNOWN val firstUser = users[0] if (firstUser is DiscordUser) { lovedGender = loritta.pudding.transaction { val profile = loritta.getLorittaProfile(firstUser.id) profile?.settings?.gender ?: Gender.UNKNOWN } } if (lovedGender == Gender.UNKNOWN) lovedGender = Gender.FEMALE var aux = 0 while (6 > aux) { val member = users[0] if (member is JDAUser) { val avatarImg = ( LorittaUtils.downloadImage( loritta, member.getEffectiveAvatarUrl(ImageFormat.PNG, 128) ) ?: LorittaUtils.downloadImage(loritta, member.handle.defaultAvatarUrl))!! .getScaledInstance(128, 128, Image.SCALE_SMOOTH) baseGraph.drawImage(avatarImg, x, y, null) baseGraph.font = Constants.MINECRAFTIA.deriveFont(Font.PLAIN, 8f) baseGraph.color = Color.BLACK baseGraph.drawString(member.name + "#" + member.handle.discriminator, x + 1, y + 12) baseGraph.drawString(member.name + "#" + member.handle.discriminator, x + 1, y + 14) baseGraph.drawString(member.name + "#" + member.handle.discriminator, x, y + 13) baseGraph.drawString(member.name + "#" + member.handle.discriminator, x + 2, y + 13) baseGraph.color = Color.WHITE baseGraph.drawString(member.name + "#" + member.handle.discriminator, x + 1, y + 13) baseGraph.font = ArtsyJoyLoriConstants.BEBAS_NEUE.deriveFont(22f) var gender = Gender.UNKNOWN gender = loritta.pudding.transaction { val profile = loritta.getLorittaProfile(firstUser.id) profile?.settings?.gender ?: Gender.UNKNOWN } if (gender == Gender.UNKNOWN) gender = Gender.MALE if (aux == 0) gender = lovedGender // If we use '0', '1', '2' in the YAML, Crowdin may think that's an array, and that's no good val slot = when (aux) { 0 -> "theGuyYouLike" 1 -> "theFather" 2 -> "theBrother" 3 -> "theFirstLover" 4 -> "theBestFriend" 5 -> "you" else -> throw RuntimeException("Invalid slot $aux") } drawCentralizedTextOutlined( baseGraph, locale["$LOCALE_PREFIX.tristerealidade.slot.$slot.${gender.name}", lovedGender.getPossessivePronoun(locale, PersonalPronoun.THIRD_PERSON, member.name)], Rectangle(x, y + 80, 128, 42), Color.WHITE, Color.BLACK, 2 ) x += 128 if (x > 256) { x = 0 y = 128 } } aux++ users.removeAt(0) } context.sendImage(JVMImage(base), "sad_reality.png", context.getUserMention(true)) } } private fun drawCentralizedTextOutlined(graphics: Graphics, text: String, rectangle: Rectangle, fontColor: Color, strokeColor: Color, strokeSize: Int) { val font = graphics.font graphics.font = font val fontMetrics = graphics.fontMetrics val lines = mutableListOf<String>() val split = text.split(" ") var x = 0 var currentLine = StringBuilder() for (string in split) { val stringWidth = fontMetrics.stringWidth("$string ") val newX = x + stringWidth if (newX >= rectangle.width) { var endResult = currentLine.toString().trim() if (endResult.isEmpty()) { // okay wtf // Se o texto é grande demais e o conteúdo atual está vazio... bem... substitua o endResult pela string atual endResult = string lines.add(endResult) x = 0 continue } lines.add(endResult) currentLine = StringBuilder() currentLine.append(' ') currentLine.append(string) x = fontMetrics.stringWidth("$string ") } else { currentLine.append(' ') currentLine.append(string) x = newX } } lines.add(currentLine.toString().trim()) val skipHeight = fontMetrics.ascent var y = (rectangle.height / 2) - ((skipHeight - 4) * (lines.size - 1)) for (line in lines) { graphics.color = strokeColor for (strokeX in rectangle.x - strokeSize .. rectangle.x + strokeSize) { for (strokeY in rectangle.y + y - strokeSize .. rectangle.y + y + strokeSize) { ImageUtils.drawCenteredStringEmoji(loritta, graphics, line, Rectangle(strokeX, strokeY, rectangle.width, 24), font) } } graphics.color = fontColor ImageUtils.drawCenteredStringEmoji(loritta, graphics, line, Rectangle(rectangle.x, rectangle.y + y, rectangle.width, 24), font) y += skipHeight } } }
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/TristeRealidadeCommand.kt
284634577
package com.directdev.portal.di import dagger.Module import dagger.Provides import io.realm.Realm /**------------------------------------------------------------------------------------------------- * Created by chris on 8/25/17. *------------------------------------------------------------------------------------------------*/ @Module class RealmModule { @Provides fun provideRealm(): Realm = Realm.getDefaultInstance() }
app/src/main/java/com/directdev/portal/di/RealmModule.kt
2009619876
package io.sniffy.test.kotest.usage import io.kotest.core.extensions.TestCaseExtension import io.kotest.core.test.TestCase import io.kotest.core.test.TestResult import io.sniffy.Sniffy import io.sniffy.SniffyAssertionError import io.sniffy.Spy import io.sniffy.Threads import io.sniffy.configuration.SniffyConfiguration import io.sniffy.socket.TcpConnections import io.sniffy.sql.SqlQueries /** * @since 3.1.7 */ open class SniffyExtension(expectation: Spy.Expectation? = null) : TestCaseExtension { private val spy: Spy<*> = Sniffy.spy<Spy<*>>() init { expectation.let { spy.expect(it) } SniffyConfiguration.INSTANCE.isMonitorJdbc = true SniffyConfiguration.INSTANCE.isMonitorSocket = true SniffyConfiguration.INSTANCE.isMonitorNio = true Sniffy.initialize() } fun expect(expectation: Spy.Expectation): SniffyExtension { spy.expect(expectation) return this } override suspend fun intercept(testCase: TestCase, execute: suspend (TestCase) -> TestResult): TestResult { val testResult = execute.invoke(testCase) try { spy.verify() } catch (e: SniffyAssertionError) { return TestResult.failure(duration = testResult.duration, e = e) } return testResult } } class NoSocketsAllowedExtension(threads: Threads = Threads.ANY) : SniffyExtension(TcpConnections.none().threads(threads)) class NoSqlExtension(threads: Threads = Threads.ANY) : SniffyExtension(SqlQueries.noneQueries().threads(threads))
sniffy-test/sniffy-kotest/src/main/kotlin/io/sniffy/test/kotest/usage/SniffyExtension.kt
1576125911
package library.integration.slack.services.error.handling import mu.KotlinLogging import org.springframework.stereotype.Component @Component class ErrorHandler { private val log = KotlinLogging.logger {} /** * Handles all errors related to Slack Service integration by logging detailed reason and status for the error. */ fun handleSlackServiceErrors(e: Exception, slackMessage: String) { when (e) { is SlackInvalidPayloadException -> log.error(e) { setLogMessage(e.status, e.reason, slackMessage) } is SlackChannelProhibitedException -> log.error(e) { setLogMessage(e.status, e.reason, slackMessage) } is SlackChannelNotFoundException -> log.error(e) { setLogMessage(e.status, e.reason, slackMessage) } is SlackChannelArchivedException -> log.error(e) { setLogMessage(e.status, e.reason, slackMessage) } is SlackServerException -> log.error(e) { setLogMessage(e.status, e.reason, slackMessage) } else -> log.error(e) { "Unexpected error occurred when trying to post message with body [$slackMessage]." } } } private fun setLogMessage(status: Int, reason: String, slackMessage: String): String { return "Error with statusCode [${status}] and reason [${reason}] " + "when trying to post message with body [$slackMessage]." } }
library-integration-slack/src/main/kotlin/library/integration/slack/services/error/handling/ErrorHandler.kt
1330003953
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vanniktech.emoji.facebook import com.vanniktech.emoji.Emoji import com.vanniktech.emoji.IgnoredOnParcel import com.vanniktech.emoji.Parcelable import com.vanniktech.emoji.Parcelize @Parcelize internal class FacebookEmoji internal constructor( override val unicode: String, override val shortcodes: List<String>, internal val x: Int, internal val y: Int, override val isDuplicate: Boolean, override val variants: List<FacebookEmoji> = emptyList(), private var parent: FacebookEmoji? = null, ) : Emoji, Parcelable { @IgnoredOnParcel override val base by lazy(LazyThreadSafetyMode.NONE) { var result = this while (result.parent != null) { result = result.parent!! } result } init { @Suppress("LeakingThis") for (variant in variants) { variant.parent = this } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as FacebookEmoji if (unicode != other.unicode) return false if (shortcodes != other.shortcodes) return false if (x != other.x) return false if (y != other.y) return false if (isDuplicate != other.isDuplicate) return false if (variants != other.variants) return false return true } override fun hashCode(): Int { var result = unicode.hashCode() result = 31 * result + shortcodes.hashCode() result = 31 * result + x result = 31 * result + y result = 31 * result + isDuplicate.hashCode() result = 31 * result + variants.hashCode() return result } override fun toString(): String { return "FacebookEmoji(unicode='$unicode', shortcodes=$shortcodes, x=$x, y=$y, isDuplicate=$isDuplicate, variants=$variants)" } }
emoji-facebook/src/commonMain/kotlin/com/vanniktech/emoji/facebook/FacebookEmoji.kt
1343577253
@file:Suppress("MemberVisibilityCanBePrivate") package io.kotest.core.config import io.kotest.core.Tags import io.kotest.core.extensions.* import io.kotest.core.filters.Filter import io.kotest.core.filters.TestCaseFilter import io.kotest.core.listeners.Listener import io.kotest.core.listeners.ProjectListener import io.kotest.core.listeners.TestListener import io.kotest.core.spec.IsolationMode import io.kotest.core.spec.LexicographicSpecExecutionOrder import io.kotest.core.spec.SpecExecutionOrder import io.kotest.core.test.* import kotlin.reflect.KClass import kotlin.time.Duration import kotlin.time.ExperimentalTime import kotlin.time.seconds /** * A central store of project wide configuration. This configuration contains defaults for kotest, and is * supplemented by user configuration (if present) as loaded by [detectConfig]. * * Additionally config can be programatically added to this class by using the mutator methods such * as [registerExtension] or [setFailOnIgnoredTests]. */ @UseExperimental(ExperimentalTime::class) object Project { private val userconf = detectConfig() private val defaultTimeout = 600.seconds private var extensions = userconf.extensions + listOf(SystemPropertyTagExtension, RuntimeTagExtension) private var listeners = userconf.listeners private var filters = userconf.filters private var timeout = userconf.timeout ?: defaultTimeout private var failOnIgnoredTests = userconf.failOnIgnoredTests ?: false private var specExecutionOrder = userconf.specExecutionOrder ?: LexicographicSpecExecutionOrder private var writeSpecFailureFile = userconf.writeSpecFailureFile ?: false private var specFailureFilePath = userconf.specFailureFilePath ?: "./.kotest/spec_failures" private var globalAssertSoftly = userconf.globalAssertSoftly ?: false private var parallelism = userconf.parallelism ?: 1 private var autoScanIgnoredClasses: List<KClass<*>> = emptyList() private var testCaseOrder: TestCaseOrder = userconf.testCaseOrder ?: TestCaseOrder.Sequential private var isolationMode: IsolationMode = userconf.isolationMode ?: IsolationMode.SingleInstance fun testCaseConfig() = userconf.testCaseConfig ?: TestCaseConfig() fun registerExtensions(vararg extensions: Extension) = extensions.forEach { registerExtension(it) } fun registerExtension(extension: Extension) { extensions = extensions + extension } fun deregisterExtension(extension: Extension) { extensions = extensions - extension } fun registerFilters(filters: Collection<Filter>) = filters.forEach { registerFilter(it) } fun registerFilter(filter: Filter) { filters = filters + filter } fun registerFilters(vararg filters: Filter) { registerFilters(filters.asList()) } fun registerListeners(vararg listeners: Listener) = listeners.forEach { registerListener(it) } fun registerListener(listener: Listener) { listeners = listeners + listener } fun extensions() = extensions .filterNot { autoScanIgnoredClasses().contains(it::class) } fun listeners() = listeners .filterNot { autoScanIgnoredClasses().contains(it::class) } @Deprecated("Use registerListener(Listener)") fun registerProjectListener(listener: Listener) { registerListener(listener) } fun specFailureFilePath(): String = specFailureFilePath /** * Uses the registerd [TagExtension]s to evaluate the currently included/excluded [Tag]s. */ fun tags(): Tags { val tags = tagExtensions().map { it.tags() } return if (tags.isEmpty()) Tags.Empty else tags.reduce { a, b -> a.combine(b) } } /** * Returns all registered [TestCaseFilter]. */ fun testCaseFilters(): List<TestCaseFilter> = filters .filterIsInstance<TestCaseFilter>() .filterNot { autoScanIgnoredClasses().contains(it::class) } fun specExtensions(): List<SpecExtension> = extensions .filterIsInstance<SpecExtension>() .filterNot { autoScanIgnoredClasses().contains(it::class) } /** * Returns the [SpecExecutionOrder] set by the user or defaults to [LexicographicSpecExecutionOrder]. * Note: This has no effect on non-JVM targets. */ fun specExecutionOrder(): SpecExecutionOrder { return specExecutionOrder } /** * Returns the default timeout for tests as specified in user config. * If not specified then defaults to [defaultTimeout] */ fun timeout(): Duration = timeout fun setTimeout(duration: Duration) { this.timeout = duration } fun tagExtensions(): List<TagExtension> = extensions .filterIsInstance<TagExtension>() .filterNot { autoScanIgnoredClasses().contains(it::class) } fun constructorExtensions(): List<ConstructorExtension> = extensions .filterIsInstance<ConstructorExtension>() .filterNot { autoScanIgnoredClasses().contains(it::class) } fun discoveryExtensions(): List<DiscoveryExtension> = extensions .filterIsInstance<DiscoveryExtension>() .filterNot { autoScanIgnoredClasses().contains(it::class) } fun testCaseExtensions(): List<TestCaseExtension> = extensions .filterIsInstance<TestCaseExtension>() .filterNot { autoScanIgnoredClasses().contains(it::class) } fun testListeners(): List<TestListener> = listeners .filterIsInstance<TestListener>() .filterNot { autoScanIgnoredClasses().contains(it::class) } fun projectListeners(): List<ProjectListener> = listeners .filterIsInstance<ProjectListener>() .filterNot { autoScanIgnoredClasses().contains(it::class) } fun isolationMode() = isolationMode fun testCaseOrder() = testCaseOrder /** * Returns the number of concurrent specs that can be executed. * Defaults to 1. */ fun parallelism(): Int = parallelism fun globalAssertSoftly(): Boolean = globalAssertSoftly fun writeSpecFailureFile(): Boolean = writeSpecFailureFile fun failOnIgnoredTests(): Boolean = failOnIgnoredTests fun setFailOnIgnoredTests(fail: Boolean) { failOnIgnoredTests = fail } fun autoScanIgnoredClasses() = autoScanIgnoredClasses fun setAutoScanIgnoredClasses(classes: List<KClass<*>>) { autoScanIgnoredClasses = classes } fun setGlobalAssertSoftly(g: Boolean) { globalAssertSoftly = g } } /** * Contains all the configuration details that can be set by a user supplied config object. */ @UseExperimental(ExperimentalTime::class) data class ProjectConf constructor( val extensions: List<Extension> = emptyList(), val listeners: List<Listener> = emptyList(), val filters: List<Filter> = emptyList(), val isolationMode: IsolationMode? = null, val assertionMode: AssertionMode? = null, val testCaseOrder: TestCaseOrder? = null, val specExecutionOrder: SpecExecutionOrder? = null, val failOnIgnoredTests: Boolean? = null, val globalAssertSoftly: Boolean? = null, val autoScanEnabled: Boolean = true, val autoScanIgnoredClasses: List<KClass<*>> = emptyList(), val writeSpecFailureFile: Boolean? = null, val specFailureFilePath: String? = null, val parallelism: Int? = null, val timeout: Duration? = null, val testCaseConfig: TestCaseConfig? = null ) /** * Loads a config object from the underlying target. * For example, on the JVM it may scan the classpath. */ expect fun detectConfig(): ProjectConf
kotest-core/src/commonMain/kotlin/io/kotest/core/config/Project.kt
3456106878
package com.sksamuel.kotest.matchers.iterator import io.kotest.core.spec.style.WordSpec import io.kotest.matchers.iterator.shouldBeEmpty import io.kotest.matchers.iterator.shouldNotBeEmpty class IteratorMatchersTest: WordSpec() { init { "shouldBeEmpty" should { "return true when the iterator does not have a next element" { emptyList<Int>().iterator().shouldBeEmpty() } "return false when the iterator has a next element" { listOf(1).iterator().shouldNotBeEmpty() } } } }
kotest-assertions/src/jvmTest/kotlin/com/sksamuel/kotest/matchers/iterator/IteratorMatchersTest.kt
2055385051
package com.sksamuel.kotest import io.kotest.core.spec.style.WordSpec import io.kotest.matchers.shouldBe class ProjectListener2Test : WordSpec() { init { "TestCase config" should { "only run beforeAll once" { // we are testing this in two places and it should therefore be 1 in both places TestProjectListener.beforeAll shouldBe 1 } "only run afterAll once" { // this test spec has not yet completed, and therefore this count should be 0 // we will also assert this in another test suite, where it should still be 0 // but at that point at least _one_ test suite will have completed // so that will confirm it is not being fired after every spec TestProjectListener.afterAll shouldBe 0 } } } }
kotest-tests/kotest-tests-projectlistener/src/jvmTest/kotlin/com/sksamuel/kotest/ProjectListener2Test.kt
3933197311
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.nlj.codec.vpx class VpxUtils { companion object { /** * The bitmask for the TL0PICIDX field. */ const val TL0PICIDX_MASK = 0xff /** * The bitmask for the extended picture id field. */ const val EXTENDED_PICTURE_ID_MASK = 0x7fff /** * Returns the delta between two VP8/VP9 extended picture IDs, taking into account * rollover. This will return the 'shortest' delta between the two * picture IDs in the form of the number you'd add to b to get a. e.g.: * getExtendedPictureIdDelta(1, 10) -> -9 (10 + -9 = 1) * getExtendedPictureIdDelta(1, 32760) -> 9 (32760 + 9 = 1) * @return the delta between two extended picture IDs (modulo 2^15). */ @JvmStatic fun getExtendedPictureIdDelta(a: Int, b: Int): Int { val diff = a - b return when { diff < -(1 shl 14) -> diff + (1 shl 15) diff > (1 shl 14) -> diff - (1 shl 15) else -> diff } } /** * Apply a delta to a given extended picture ID and return the result (taking * rollover into account) * @param start the starting extended picture ID * @param delta the delta to be applied * @return the extended picture ID resulting from doing "start + delta" */ @JvmStatic fun applyExtendedPictureIdDelta(start: Int, delta: Int): Int = (start + delta) and EXTENDED_PICTURE_ID_MASK /** * Returns the delta between two VP8/VP9 Tl0PicIdx values, taking into account * rollover. This will return the 'shortest' delta between the two * picture IDs in the form of the number you'd add to b to get a. e.g.: * getTl0PicIdxDelta(1, 10) -> -9 (10 + -9 = 1) * getTl0PicIdxDelta(1, 250) -> 7 (250 + 7 = 1) * * If either value is -1 (meaning tl0picidx not found) return 0. * @return the delta between two extended picture IDs (modulo 2^8). */ @JvmStatic fun getTl0PicIdxDelta(a: Int, b: Int): Int { if (a < 0 || b < 0) return 0 val diff = a - b return when { diff < -(1 shl 7) -> diff + (1 shl 8) diff > (1 shl 7) -> diff - (1 shl 8) else -> diff } } /** * Apply a delta to a given Tl0PidIcx and return the result (taking * rollover into account) * @param start the starting Tl0PicIdx * @param delta the delta to be applied * @return the Tl0PicIdx resulting from doing "start + delta" */ @JvmStatic fun applyTl0PicIdxDelta(start: Int, delta: Int): Int = (start + delta) and TL0PICIDX_MASK } }
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/codec/vpx/VpxUtils.kt
2156819993
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.nlj.util import org.jitsi.nlj.rtp.SsrcAssociationType import org.jitsi.nlj.stats.NodeStatsBlock import org.jitsi.nlj.transform.NodeStatsProducer import java.util.concurrent.CopyOnWriteArrayList typealias SsrcAssociationHandler = (SsrcAssociation) -> Unit class SsrcAssociationStore( private val name: String = "SSRC Associations" ) : NodeStatsProducer { private val ssrcAssociations: MutableList<SsrcAssociation> = CopyOnWriteArrayList() /** * The SSRC associations indexed by the primary SSRC. Since an SSRC may have * multiple secondary SSRC mappings, the primary SSRC maps to a list of its * SSRC associations */ private var ssrcAssociationsByPrimarySsrc = mapOf<Long, List<SsrcAssociation>>() private var ssrcAssociationsBySecondarySsrc = mapOf<Long, SsrcAssociation>() private val handlers: MutableList<SsrcAssociationHandler> = CopyOnWriteArrayList() /** * Each time an association is added, we want to invoke the handlers * and each time a handler is added, want to invoke it with all existing * associations. In order to make each of those operations a single, * atomic operation, we use this lock to synchronize them. */ private val lock = Any() fun addAssociation(ssrcAssociation: SsrcAssociation) { synchronized(lock) { ssrcAssociations.add(ssrcAssociation) rebuildMaps() handlers.forEach { it(ssrcAssociation) } } } private fun rebuildMaps() { ssrcAssociationsByPrimarySsrc = ssrcAssociations.groupBy(SsrcAssociation::primarySsrc) ssrcAssociationsBySecondarySsrc = ssrcAssociations.associateBy(SsrcAssociation::secondarySsrc) } fun getPrimarySsrc(secondarySsrc: Long): Long? = ssrcAssociationsBySecondarySsrc[secondarySsrc]?.primarySsrc fun getSecondarySsrc(primarySsrc: Long, associationType: SsrcAssociationType): Long? = ssrcAssociationsByPrimarySsrc[primarySsrc]?.find { it.type == associationType }?.secondarySsrc /** * When an SSRC has no associations at all (audio, for example), we consider it a * 'primary' SSRC. So to perform this check we assume the given SSRC has been * signalled and simply verify that it's *not* signaled as a secondary SSRC. * Note that this may mean there is a slight window before the SSRC associations are * processed during which we return true for an SSRC which will later be denoted * as a secondary ssrc. */ fun isPrimarySsrc(ssrc: Long): Boolean { return !ssrcAssociationsBySecondarySsrc.containsKey(ssrc) } fun onAssociation(handler: (SsrcAssociation) -> Unit) { synchronized(lock) { handlers.add(handler) ssrcAssociations.forEach(handler) } } override fun getNodeStats(): NodeStatsBlock = NodeStatsBlock(name).apply { addString("SSRC associations", ssrcAssociations.toString()) } }
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/util/SsrcAssociationStore.kt
2574367015
package com.github.emulio.ui.screens import com.badlogic.gdx.Gdx import com.badlogic.gdx.files.FileHandle import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.GL20 import com.badlogic.gdx.graphics.Pixmap import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.Batch import com.badlogic.gdx.graphics.g2d.BitmapFont import com.badlogic.gdx.graphics.g2d.GlyphLayout import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.math.Interpolation import com.badlogic.gdx.scenes.scene2d.Actor import com.badlogic.gdx.scenes.scene2d.Group import com.badlogic.gdx.scenes.scene2d.InputEvent import com.badlogic.gdx.scenes.scene2d.actions.Actions import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction import com.badlogic.gdx.scenes.scene2d.actions.TemporalAction import com.badlogic.gdx.scenes.scene2d.ui.* import com.badlogic.gdx.scenes.scene2d.utils.ClickListener import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable import com.badlogic.gdx.utils.Align import com.badlogic.gdx.utils.Scaling import com.badlogic.gdx.utils.Timer import com.github.emulio.Emulio import com.github.emulio.exceptions.ProcessCreationException import com.github.emulio.model.Game import com.github.emulio.model.Platform import com.github.emulio.model.RomsMode import com.github.emulio.model.RomsNaming import com.github.emulio.model.config.DummyInputConfig import com.github.emulio.model.config.InputConfig import com.github.emulio.model.theme.* import com.github.emulio.process.ProcessLauncher import com.github.emulio.ui.input.InputListener import com.github.emulio.ui.input.InputManager import com.github.emulio.ui.screens.dialogs.InfoDialog import com.github.emulio.ui.screens.keyboard.VirtualKeyboardDialog import com.github.emulio.utils.DateHelper import com.github.emulio.utils.translate import mu.KotlinLogging import java.io.File import java.util.Stack class GameListScreen( emulio: Emulio, val platform: Platform) : EmulioScreen(emulio), InputListener { val logger = KotlinLogging.logger { } private val inputController: InputManager = InputManager(this, emulio, stage) private val interpolation = Interpolation.fade private lateinit var items: List<Item> private var selectedListItem: Item? = null private lateinit var listView: GameList private lateinit var listScrollPane: ScrollPane private lateinit var descriptionScrollPane: ScrollPane private lateinit var gameImage: Image private lateinit var gameReleaseDate: TextField private lateinit var gameDescription: Label private lateinit var gamePlayCount: TextField private lateinit var gameLastPlayed: TextField private lateinit var gamePlayers: TextField private lateinit var gameGenre: TextField private lateinit var gamePublisher: TextField private lateinit var gameDeveloper: TextField private lateinit var root: Group private lateinit var logo: Image private lateinit var imageView: ViewImage private lateinit var ratingImages: RatingImages private lateinit var lastOpenedFolder: File private var lastTimer: Timer.Task? = null private var lastSequenceAction: SequenceAction? = null private val folderStack = Stack<File>() init { Gdx.input.inputProcessor = inputController prepareGamesList(emulio, findGames(emulio), true) } private fun prepareGamesList(emulio: Emulio, games: List<Game>, rootFolder: Boolean = false, overrideFolder: File? = null) { logger.info { "Preparing game list. (emulio instance: $emulio, games size: ${games.size}, folder: $rootFolder, override: $overrideFolder)" } if (platform.romsMode == RomsMode.NORMAL) { prepareGameListExpanded(games, rootFolder, overrideFolder) } else if (platform.romsMode == RomsMode.FLAT) { prepareGameListFlat(games) } initGUI() selectedListItem = items.first() updateGameSelected() } private fun prepareGameListFlat(games: List<Game>) { games.forEach { it.displayName = fetchGameName(it) } val sorted = games.sortedBy { it.displayName!!.toLowerCase() } this.items = sorted.map { GameItem(it) } } private fun fetchGameName(it: Game): String { if (it.displayName != null) { return it.displayName!! } if (platform.romsNaming == RomsNaming.FOLDER) { return it.path.parentFile.name } if (platform.romsNaming == RomsNaming.FIRST_FOLDER) { val root = platform.romsPath val path = findFirstPath(root, it.path) return path.name } return it.displayName ?: it.name ?: it.path.name } private fun findFirstPath(rootFolder: File, path: File): File { if (path.parentFile == rootFolder) { return path } return findFirstPath(rootFolder, path.parentFile) } private fun prepareGameListExpanded(games: List<Game>, rootFolder: Boolean, overrideFolder: File?) { logger.debug { "getting all absolute paths" } val absolutePaths = games.map { it.path.parentFile.absoluteFile } .toSortedSet(Comparator { file1, file2 -> file1.absolutePath.compareTo(file2.absolutePath) }) logger.debug { "filtering games" } val filteredGames = if ((rootFolder && absolutePaths.size > 1) || overrideFolder != null) { // roms are coming from more than one main directory (subFolders) val rootPath = overrideFolder ?: platform.romsPath lastOpenedFolder = rootPath val mergedGames = mutableListOf<Game>() val folders = rootPath.listFiles()?.filter { it.isDirectory && !it.isHidden } ?: emptyList() items = folders.map { PathItem(it.name, it) }.sortedBy { it.displayName }.filter { pathItem -> val folder = pathItem.path val found = games.find { game -> val path = game.path path.nameWithoutExtension == folder.nameWithoutExtension && path.parentFile.absolutePath == folder.absolutePath } if (found != null) { mergedGames.add(found) false } else { true } } games.filter { game -> game.path.parentFile.absolutePath == rootPath.absolutePath } + mergedGames } else { items = emptyList() games } val supportedExtensions = platform.romsExtensions val gamesMap = mutableMapOf<String, Game>() filteredGames.forEach { game -> val nameWithoutExtension = game.path.nameWithoutExtension val gameFound: Game? = gamesMap[nameWithoutExtension] if (gameFound != null) { if (gameFound.path.name != nameWithoutExtension) { if (!gamesMap.containsKey(nameWithoutExtension)) { gamesMap[nameWithoutExtension] = game game.displayName = nameWithoutExtension } } else if (gameFound.path.name == nameWithoutExtension) { val idxFound = supportedExtensions.indexOf(gameFound.path.extension) val idxGame = supportedExtensions.indexOf(game.path.extension) if (idxGame < idxFound) { val key = game.name!! gamesMap[nameWithoutExtension] = game game.displayName = key } } } else { val key = game.name ?: game.path.name game.displayName = key if (!gamesMap.containsKey(nameWithoutExtension)) { gamesMap[nameWithoutExtension] = game } } } logger.debug { "rootFolder: $rootFolder" } val folders = if (folderStack.isEmpty()) { items } else { listOf(PathUpItem) + items } this.items = folders + gamesMap.values.map { it.displayName = fetchGameName(it) it }.sortedBy { it.displayName!!.toLowerCase() }.map { GameItem(it) } } private fun findGames(emulio: Emulio, customFilter: ((Game) -> Boolean)? = null): List<Game> { return if (customFilter == null) { emulio.games!![platform]?.toList() ?: emptyList() } else { (emulio.games!![platform]?.toList() ?: emptyList()).filter(customFilter) } } private fun isBasicViewOnly(): Boolean { return items.filterIsInstance<GameItem>().map { it.game }.none { it.id != null || it.description != null || it.image != null } } private var guiReady: Boolean = false private fun initGUI() { stage.clear() val theme = emulio.theme[platform]!! val basicViewOnly = isBasicViewOnly() val view = theme.findView(if (basicViewOnly) "basic" else "detailed")!! buildCommonComponents(view) if (basicViewOnly) { buildBasicView(view) } else { buildDetailedView(view) } } override fun onScreenLoad() { logger.debug { "onScreenLoad" } guiReady = true if (items.size > 1) { listView.selectedIndex = 0 selectedListItem = items[0] updateGameSelected() } } private fun buildBasicView(basicView: View) { gameListView = basicView.findViewItem("gamelist") as TextList buildListScrollPane { buildListView() } } private var lastSelectedIndex: Int = -1 private fun buildListScrollPane(builder: () -> GameList) { listView = builder() listView.addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { val newIndex = listView.selectedIndex if (lastSelectedIndex == newIndex) { onConfirmButton(DummyInputConfig) return } selectedListItem = items[newIndex] updateGameSelected() lastSelectedIndex = listView.selectedIndex } }) listScrollPane = ScrollPane(listView, ScrollPane.ScrollPaneStyle()).apply { setFlickScroll(true) setScrollBarPositions(false, true) setScrollingDisabled(true, false) setSmoothScrolling(true) isTransform = true setSize(gameListView) setPosition(gameListView) } stage.addActor(listScrollPane) } private fun buildCommonComponents(view: View) { val backgroundView = view.findViewItem("background") as ViewImage? if (backgroundView != null) { stage.addActor(buildImage(backgroundView).apply { setScaling(Scaling.stretch) setPosition(0f, 0f) setSize(screenWidth, screenHeight) }) } else { val lightGrayTexture = createColorTexture(0xc5c6c7FF.toInt()) stage.addActor(Image(lightGrayTexture).apply { setFillParent(true) }) } val footer = view.findViewItem("footer") as ViewImage? val imgFooter: Image? if (footer != null) { imgFooter = buildImage(footer, Scaling.stretch) stage.addActor(imgFooter) } else { imgFooter = null } val header = view.findViewItem("header") as ViewImage? if (header != null) { stage.addActor(buildImage(header, Scaling.stretch)) } initRoot() initLogoSmall() val systemName1 = view.findViewItem("system_name_1")?.let { it as Text } if (systemName1 != null) { stage.addActor(buildTextField(systemName1)) } val systemName2 = view.findViewItem("system_name_2")?.let { it as Text } if (systemName2 != null) { stage.addActor(buildTextField(systemName2)) } val logo = view.findViewItem("logo") as ViewImage? if (logo != null) { val platformImage = buildImage(logo, Scaling.fit) stage.addActor(platformImage) } val footerHeight: Float val footerY: Float if (imgFooter != null) { footerHeight = imgFooter.height footerY = imgFooter.y } else { footerHeight = 10f footerY = 10f } initHelpHuds(footerY, footerHeight, HelpItems( txtSelect = "Options".translate().toUpperCase(), txtOptions = "Menu".translate().toUpperCase(), txtCancel = "Back".translate().toUpperCase(), txtConfirm = "Launch".translate().toUpperCase(), txtLeftRight = "System".translate().toUpperCase(), txtUpDown = "Choose".translate().toUpperCase(), alpha = 0.9f, txtColor = Color(0x666666FF) )) } private lateinit var gameListView: TextList private fun buildDetailedView(detailedView: View) { val descriptionView = detailedView.findViewItem("md_description") as Text? if (descriptionView != null) { gameDescription = buildLabel(descriptionView) gameDescription.setWrap(true) descriptionScrollPane = ScrollPane(gameDescription, ScrollPane.ScrollPaneStyle()).apply { setFlickScroll(true) setScrollBarPositions(false, true) setSmoothScrolling(true) setForceScroll(false, true) isTransform = true setSize(descriptionView) setPosition(descriptionView) } stage.addActor(descriptionScrollPane) } gameListView = detailedView.findViewItem("gamelist") as TextList buildListScrollPane { buildListView() } val imageView = detailedView.findViewItem("md_image") as ViewImage? if (imageView != null) { gameImage = buildImage(imageView) stage.addActor(gameImage) this.imageView = imageView } val lbRating = buildLabel(detailedView, "md_lbl_rating", "Rating:") buildLabel(detailedView, "md_lbl_releasedate", "Released:") buildLabel(detailedView, "md_lbl_developer", "Developer:") buildLabel(detailedView, "md_lbl_publisher", "Publisher:") buildLabel(detailedView, "md_lbl_genre", "Genre:") buildLabel(detailedView, "md_lbl_players", "Players:") buildLabel(detailedView, "md_lbl_lastplayed", "Last played:") buildLabel(detailedView, "md_lbl_playcount", "Times played:") val playCountView = detailedView.findViewItem("md_playcount") as Text? if (playCountView != null) { gamePlayCount = buildTextField(playCountView) stage.addActor(gamePlayCount) } val lastPlayedView = detailedView.findViewItem("md_lastplayed") as Text? if (lastPlayedView != null) { gameLastPlayed = buildTextField(lastPlayedView) stage.addActor(gameLastPlayed) } val playersView = detailedView.findViewItem("md_players") as Text? if (playersView != null) { gamePlayers = buildTextField(playersView) stage.addActor(gamePlayers) } val genreView = detailedView.findViewItem("md_genre") as Text? if (genreView != null) { gameGenre = buildTextField(genreView) stage.addActor(gameGenre) } val publisherView = detailedView.findViewItem("md_publisher") as Text? if (publisherView != null) { gamePublisher = buildTextField(publisherView) stage.addActor(gamePublisher) } val developerView = detailedView.findViewItem("md_developer") as Text? if (developerView != null) { gameDeveloper = buildTextField(developerView) stage.addActor(gameDeveloper) } val releaseDateView = detailedView.findViewItem("md_releasedate") as Text? if (releaseDateView != null) { gameReleaseDate = buildTextField(releaseDateView) stage.addActor(gameReleaseDate) } val ratingView = detailedView.findViewItem("md_rating") as Rating? if (ratingView != null) { buildRatingImages(ratingView, lbRating!!) } } data class RatingImages( val ratingImg1: Image, val ratingImg2: Image, val ratingImg3: Image, val ratingImg4: Image, val ratingImg5: Image, val ratingUnFilledTexture: Texture, val ratingFilledTexture: Texture, val ratingColor: Color ) private fun buildRatingImages(ratingView: Rating, lbRating: Label) { val ratingTexture = buildTexture("images/resources/star_unfilled_128_128.png") val ratingFilledTexture = buildTexture("images/resources/star_filled_128_128.png") val ratingWidth = lbRating.height val ratingHeight = lbRating.height val ratingImg1 = Image(ratingTexture).apply { setSize(ratingWidth, ratingHeight) val (viewX, viewY) = getPosition(ratingView) x = viewX y = viewY + 6f } stage.addActor(ratingImg1) val ratingImg2 = buildImage(ratingTexture, ratingWidth, ratingHeight, ratingImg1.x + ratingImg1.width, ratingImg1.y) stage.addActor(ratingImg2) val ratingImg3 = buildImage(ratingTexture, ratingWidth, ratingHeight, ratingImg2.x + ratingImg2.width, ratingImg1.y) stage.addActor(ratingImg3) val ratingImg4 = buildImage(ratingTexture, ratingWidth, ratingHeight, ratingImg3.x + ratingImg3.width, ratingImg1.y) stage.addActor(ratingImg4) val ratingImg5 = buildImage(ratingTexture, ratingWidth, ratingHeight, ratingImg4.x + ratingImg4.width, ratingImg1.y) stage.addActor(ratingImg5) val color = getColor(ratingView.color) ratingImages = RatingImages( ratingImg1, ratingImg2, ratingImg3, ratingImg4, ratingImg5, ratingTexture, ratingFilledTexture, color ) } private fun buildLabel(detailedView: View, viewName: String, viewText: String): Label? { val lbView = detailedView.findViewItem(viewName) as Text? if (lbView != null) { val lbl = buildLabel(lbView).apply { setText(viewText) } stage.addActor(lbl) return lbl } return null } private fun buildImage(image: ViewImage, scaling: Scaling = Scaling.fit, imagePath: File? = image.path): Image { val texture = if (imagePath != null) { Texture(FileHandle(imagePath), true) } else { val size = getSize(image) createColorTexture(0xFFCC00FF.toInt(), size.first.toInt(), size.second.toInt()) } texture.setFilter(Texture.TextureFilter.MipMap, Texture.TextureFilter.MipMap) return Image(texture).apply { setScaling(scaling) setSize(image) setPosition(image) setOrigin(image) setAlign(Align.left) isVisible = imagePath != null } } private fun buildTextField(textView: Text): TextField { val text = if (textView.forceUpperCase) { textView.text?.toUpperCase() ?: "" } else { textView.text ?: "" } val color = getColor(textView.textColor ?: textView.color) return TextField(text, TextField.TextFieldStyle().apply { font = getFont(getFontPath(textView), getFontSize(textView.fontSize), color) fontColor = color }).apply { alignment = when(textView.alignment) { TextAlignment.LEFT -> Align.left TextAlignment.RIGHT -> Align.right TextAlignment.CENTER -> Align.center TextAlignment.JUSTIFY -> Align.left //TODO } setSize(textView) setPosition(textView) } } private fun buildLabel(textView: Text): Label { val text = if (textView.forceUpperCase) { textView.text?.toUpperCase() ?: "" } else { textView.text ?: "" } val lbColor = getColor(textView.textColor ?: textView.color) val font = getFont(getFontPath(textView), getFontSize(textView.fontSize)) return Label(text, Label.LabelStyle(font, lbColor)).apply { setAlignment(Align.topLeft) setSize(textView) setPosition(textView) color = lbColor } } private fun buildListView(): GameList { return buildGameListView(gameListView, items) } class GameList(style: ListStyle?) : com.badlogic.gdx.scenes.scene2d.ui.List<Item>(style) { override fun drawItem(batch: Batch, font: BitmapFont, index: Int, item: Item, x1: Float, y: Float, width: Float): GlyphLayout { return drawText(item, x1, font, batch, y, width) } private fun drawText(item: Item, x1: Float, font: BitmapFont, batch: Batch, y: Float, width: Float): GlyphLayout { val text = textOf(item) val x = x1 + 5 return font.draw(batch, text, x, y, 0, text.length, width, Align.left, false, "...") } private fun drawWithIcon(item: Item, x1: Float, font: BitmapFont, batch: Batch, y: Float, width: Float): GlyphLayout { val text = textOf(item) val image = iconOf(item) val x = x1 + 5 val lineHeight = font.lineHeight val imgWidth = lineHeight - (lineHeight / 15) val imgHeight = lineHeight - (lineHeight / 15) val offsetY = (lineHeight / 5) batch.draw(image, x, y - imgHeight + offsetY, imgWidth, imgHeight) return font.draw(batch, text, x + imgWidth + 5, y, 0, text.length, width, Align.left, false, "...") } private fun iconOf(item: Item): Texture { return when (item) { is PathUpItem -> { Texture("images/icons/folder-up.png") } is PathItem -> { Texture("images/icons/folder.png") } is GameItem -> { val extension = item.game.path.extension if (setOf("7z", "zip", "rar", "ace", "jar", "tar", "gz", "bz2").contains(extension)) { Texture("images/icons/file-rom-archive.png") } else { Texture("images/icons/file-rom-file.png") } } else -> { error("Invalid state") } } } private fun textOf(item: Item): String { if (items.filter { it.displayName == item.displayName }.size > 1) { return item.path.name } return item.displayName } } private fun buildGameListView(gameListView: TextList, listItems: List<Item>): GameList { return GameList(com.badlogic.gdx.scenes.scene2d.ui.List.ListStyle().apply { fontColorUnselected = getColor(gameListView.primaryColor) fontColorSelected = getColor(gameListView.selectedColor) font = getFont(getFontPath(gameListView), getFontSize(gameListView.fontSize)) val selectorTexture = createColorTexture(Integer.parseInt(gameListView.selectorColor + "FF", 16)) selection = TextureRegionDrawable(TextureRegion(selectorTexture)) }).apply { setSize(gameListView) listItems.forEach { listItem -> items.add(listItem) } } } private fun Widget.setOrigin(viewItem: ViewItem) { if (viewItem.originX != null && viewItem.originY != null) { val originX = viewItem.originX!! val originY = viewItem.originY!! val offsetX = if (originX == 0f) { 0f } else { width * originX } val offsetY = when (originY) { 0f -> 0f 1f -> height else -> height * (1f - viewItem.originY!!) } setOrigin(offsetX, offsetY) x += offsetX y += offsetY } } private fun getSize(viewItem: ViewItem): Pair<Float, Float> { var width = if (viewItem.sizeX != null) { screenWidth * viewItem.sizeX!! } else { 200f } var height = if (viewItem.sizeY != null) { screenHeight * viewItem.sizeY!! } else { 200f } if (viewItem.maxSizeX != null) { width = width.coerceAtLeast(screenWidth * viewItem.maxSizeX!!) } if (viewItem.maxSizeY != null) { height = height.coerceAtLeast(screenHeight * viewItem.maxSizeY!!) } return Pair(width, height) } private fun Actor.setSize(viewItem: ViewItem) { var width = if (viewItem.sizeX != null) { screenWidth * viewItem.sizeX!! } else { this.width } var height = if (viewItem.sizeY != null) { screenHeight * viewItem.sizeY!! } else { this.height } if (viewItem.maxSizeX != null) { width = width.coerceAtMost(screenWidth * viewItem.maxSizeX!!) } if (viewItem.maxSizeY != null) { height = height.coerceAtMost(screenHeight * viewItem.maxSizeY!!) } setSize(width, height) } private fun Actor.setPosition(view: ViewItem) { val (x, y) = getPosition(view) setPosition(x, y) } private fun Actor.getPosition(view: ViewItem): Pair<Float, Float> { val x = screenWidth * view.positionX!! val y = (screenHeight * (1f - view.positionY!!)) - height return Pair(x, y) } private fun getFontPath(textView: Text): FileHandle { return if (textView.fontPath != null) { FileHandle(textView.fontPath!!.absolutePath) } else{ Gdx.files.internal("fonts/RopaSans-Regular.ttf") } } private fun getFontSize(fontSize: Float?): Int { return if (fontSize == null) { 90 } else { (fontSize * screenHeight).toInt() } } private fun initRoot() { root = Group().apply { width = screenWidth height = screenHeight x = 0f y = 0f } stage.addActor(root) } private fun initLogoSmall() { logo = Image(Texture("images/logo-small.png")).apply { x = screenWidth y = (height / 2) - 5f addAction(Actions.moveTo(screenWidth - width - 15f, y, 0.5f, interpolation)) } root.addActor(logo) } override fun hide() { } override fun render(delta: Float) { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT) stage.act(Gdx.graphics.deltaTime.coerceAtMost(1 / 30f)) stage.draw() inputController.update(delta) } override fun pause() { } override fun resume() { } override fun resize(width: Int, height: Int) { } override fun release() { inputController.dispose() } private fun launchGame() { if (listView.selectedIndex == -1) { error("No game was selected") } val selectedListItem = selectedListItem!! if (selectedListItem is PathItem) { return } check(selectedListItem is GameItem) val path = selectedListItem.game.path logger.info { "launchGame: ${path.name}" } val command = platform.runCommand.map { when { it.contains("%ROM_RAW%") -> it.replace("%ROM_RAW%", path.absolutePath) it.contains("%ROM%") -> it.replace("%ROM%", path.absolutePath) //TODO check EmulationStation documentation it.contains("%BASENAME%") -> it.replace("%BASENAME%", path.nameWithoutExtension) else -> it } } emulio.options.minimizeApplication() try { ProcessLauncher.executeProcess(command.toTypedArray()) } catch (ex: ProcessCreationException) { showErrorDialog("There was a problem launching this game. Check your config".translate()) } emulio.options.restoreApplication() } private fun selectNext(amount: Int = 1) { val nextIndex = listView.selectedIndex + amount if (amount < 0) { if (nextIndex < 0) { listView.selectedIndex = listView.items.size + amount } else { listView.selectedIndex = nextIndex } } if (amount > 0) { if (nextIndex >= listView.items.size) { listView.selectedIndex = 0 } else { listView.selectedIndex = nextIndex } } val list = items selectedListItem = list[listView.selectedIndex] updateGameSelected() checkVisible(nextIndex) } private fun updateGameSelected() { lastTimer?.cancel() lastSequenceAction?.reset() val selectedListItem = selectedListItem logger.debug { if (selectedListItem != null) { "updateGameSelected [${selectedListItem.displayName}] [${selectedListItem.path.name}]" } else { "no game" } } if (isBasicViewOnly()) { logger.trace { "basic view only, ignore update game selected" } return } if (selectedListItem == null || selectedListItem is PathItem) { logger.trace { "no selected list item, clearing info" } clearDetailedView() return } check(selectedListItem is GameItem) val game = selectedListItem.game val hasImage = game.image != null && game.image.isFile val texture = if (hasImage) { Texture(FileHandle(game.image), true) } else { Texture(0, 0, Pixmap.Format.RGB888) } texture.setFilter(Texture.TextureFilter.MipMap, Texture.TextureFilter.MipMap) gameImage.drawable = TextureRegionDrawable(TextureRegion(texture)) gameImage.isVisible = hasImage gameReleaseDate.text = safeValue(if (game.releaseDate != null) { DateHelper.format(game.releaseDate) } else { null }) gameDeveloper.text = safeValue(game.developer) gamePlayCount.text = "0" gameLastPlayed.text = "Never" gamePlayers.text = safeValue(game.players) gameGenre.text = safeValue(game.genre) gamePublisher.text = safeValue(game.publisher) gameDeveloper.text = safeValue(game.developer) descriptionScrollPane.scrollY = 0f gameDescription.setText(safeValue(game.description, "")) val gameRating = game.rating if (gameRating != null) { val rating = game.rating ratingImages.apply { ratingImg1.drawable = if (rating > 0.05) { TextureRegionDrawable(TextureRegion(ratingFilledTexture)) } else { TextureRegionDrawable(TextureRegion(ratingUnFilledTexture)) } ratingImg2.drawable = if (rating > 0.25) { TextureRegionDrawable(TextureRegion(ratingFilledTexture)) } else { TextureRegionDrawable(TextureRegion(ratingUnFilledTexture)) } ratingImg3.drawable = if (rating > 0.45) { TextureRegionDrawable(TextureRegion(ratingFilledTexture)) } else { TextureRegionDrawable(TextureRegion(ratingUnFilledTexture)) } ratingImg4.drawable = if (rating > 0.65) { TextureRegionDrawable(TextureRegion(ratingFilledTexture)) } else { TextureRegionDrawable(TextureRegion(ratingUnFilledTexture)) } ratingImg5.drawable = if (rating > 0.90) { TextureRegionDrawable(TextureRegion(ratingFilledTexture)) } else { TextureRegionDrawable(TextureRegion(ratingUnFilledTexture)) } ratingImg1.color = ratingColor ratingImg2.color = ratingColor ratingImg3.color = ratingColor ratingImg4.color = ratingColor ratingImg5.color = ratingColor } } else { ratingImages.apply { ratingImg1.drawable = TextureRegionDrawable(TextureRegion(ratingUnFilledTexture)) ratingImg2.drawable = TextureRegionDrawable(TextureRegion(ratingUnFilledTexture)) ratingImg3.drawable = TextureRegionDrawable(TextureRegion(ratingUnFilledTexture)) ratingImg4.drawable = TextureRegionDrawable(TextureRegion(ratingUnFilledTexture)) ratingImg5.drawable = TextureRegionDrawable(TextureRegion(ratingUnFilledTexture)) ratingImg1.color = ratingColor ratingImg2.color = ratingColor ratingImg3.color = ratingColor ratingImg4.color = ratingColor ratingImg5.color = ratingColor } } animateDescription() } private fun clearDetailedView() { gameImage.isVisible = false ratingImages.apply { ratingImg1.color = Color.CLEAR ratingImg2.color = Color.CLEAR ratingImg3.color = Color.CLEAR ratingImg4.color = Color.CLEAR ratingImg5.color = Color.CLEAR } gameDeveloper.text = "" gamePlayCount.text = "" gameLastPlayed.text = "" gamePlayers.text = "" gameGenre.text = "" gamePublisher.text = "" gameDeveloper.text = "" gameReleaseDate.text = "" gameDescription.setText("") } private fun animateDescription() { lastTimer = Timer.schedule(object : Timer.Task() { override fun run() { if (gameDescription.height <= descriptionScrollPane.height) { return } val scrollAmount = gameDescription.height - descriptionScrollPane.height val actionTime = scrollAmount * 0.05f val sequenceAction = SequenceAction( ScrollByAction(0f, scrollAmount, actionTime), Actions.delay(2f), ScrollByAction(0f, -scrollAmount, actionTime) ) lastSequenceAction = sequenceAction descriptionScrollPane.addAction(sequenceAction) } }, 2.5f) } private fun safeValue(string: String?, defaultText: String = "Unknown"): String { return string?.trim() ?: defaultText } private fun checkVisible(index: Int) { val itemHeight = listView.itemHeight val selectionY = index * itemHeight val selectionY2 = selectionY + itemHeight val minItemsVisible = itemHeight * 5 val itemsPerView = listScrollPane.height / itemHeight val gamesList = items if (listView.selectedIndex > (gamesList.size - itemsPerView)) { listScrollPane.scrollY = listView.height - listScrollPane.height return } if (listView.selectedIndex == 0) { listScrollPane.scrollY = 0f return } if ((selectionY2 + minItemsVisible) > listScrollPane.height) { listScrollPane.scrollY = (selectionY2 - listScrollPane.height) + minItemsVisible } val minScrollY = (selectionY - minItemsVisible).coerceAtLeast(0f) if (minScrollY < listScrollPane.scrollY) { listScrollPane.scrollY = minScrollY } } override fun buildImage(imgPath: String, imgWidth: Float, imgHeight: Float, x: Float, y: Float): Image { return buildImage(buildTexture(imgPath), imgWidth, imgHeight, x, y) } private fun buildImage(texture: Texture, imgWidth: Float, imgHeight: Float, x: Float, y: Float): Image { val imgButtonStart = Image(texture) imgButtonStart.setSize(imgWidth, imgHeight) imgButtonStart.x = x imgButtonStart.y = y return imgButtonStart } private fun buildTexture(imgPath: String): Texture { return Texture(Gdx.files.internal(imgPath), true).apply { setFilter(Texture.TextureFilter.MipMap, Texture.TextureFilter.MipMap) } } override fun onConfirmButton(input: InputConfig) { updateHelp() if (!guiReady) return val selectedListItem = selectedListItem ?: return when (selectedListItem) { is PathUpItem -> { goUpDir() } is PathItem -> { val selectedFolder = selectedListItem.path folderStack.push(selectedFolder.parentFile) val found = findGames(emulio) { game -> game.path.parentFile == selectedFolder } val hasSubFolders = selectedFolder.listFiles()!!.any { it.isDirectory } if (found.isEmpty() && !hasSubFolders) { showInfoDialog("No games found in this folder.") folderStack.pop() return } reloadGameListOnFolder(selectedFolder) listView.selectedIndex = 0 this.selectedListItem = items[0] } else -> { launchGame() } } } private fun reloadGameListOnFolder(folder: File) { prepareGamesList(emulio, findGames(emulio), false, folder) } override fun onCancelButton(input: InputConfig) { updateHelp() if (!guiReady) return if (folderStack.isEmpty()) { switchScreen(PlatformsScreen(emulio, platform)) } else { goUpDir() } } private fun goUpDir() { val lastOpenedFolder = lastOpenedFolder reloadGameListOnFolder(folderStack.pop()) val index = 0.coerceAtLeast( items.indexOf( items.find { it.path.absolutePath == lastOpenedFolder.absolutePath } ) ) listView.selectedIndex = index selectedListItem = items[index] } override fun onUpButton(input: InputConfig) { updateHelp() if (!guiReady) return selectNext(-1) } override fun onDownButton(input: InputConfig) { updateHelp() logger.debug { "onDownButton ${System.identityHashCode(this)} ${platform.platformName} $guiReady" } if (!guiReady) return selectNext() } override fun onLeftButton(input: InputConfig) { updateHelp() logger.debug { "onLeftButton ${System.identityHashCode(this)} ${platform.platformName} $guiReady" } if (!guiReady) return val platforms = emulio.platforms val index = platforms.indexOf(platform) val previousPlatform = if (index > 0) { index - 1 } else { platforms.size - 1 } switchScreen(GameListScreen(emulio, platforms[previousPlatform])) } override fun onRightButton(input: InputConfig) { updateHelp() logger.debug { "onRightButton ${System.identityHashCode(this)} ${platform.platformName} $guiReady" } if (!guiReady) return val platforms = emulio.platforms val index = platforms.indexOf(platform) val previousPlatform = if (index > platforms.size - 2) { 0 } else { index + 1 } switchScreen(GameListScreen(emulio, platforms[previousPlatform])) } override fun onFindButton(input: InputConfig) { updateHelp() logger.debug { "onFindButton ${System.identityHashCode(this)} ${platform.platformName} $guiReady" } if (!guiReady) return VirtualKeyboardDialog("Search", "Message", emulio, stage) { text -> handleSearch(filterByText(text)) }.show(stage) } override fun onOptionsButton(input: InputConfig) { updateHelp() Gdx.app.postRunnable { showMainMenu { GameListScreen(emulio, platform) } } } override fun onSelectButton(input: InputConfig) { updateHelp() logger.debug { "onSelectButton ${System.identityHashCode(this)} ${platform.platformName} $guiReady" } if (!guiReady) return Gdx.app.postRunnable { showOptionsMenu { response -> val searchDialogText = response.searchDialogText val jumpToLetter = response.jumpToLetter if (searchDialogText != null) { handleSearch(filterByText(searchDialogText)) } else if (jumpToLetter != null) { handleSearch(filterByLetter(jumpToLetter)) } } } } private fun filterByLetter(jumpToLetter: Char): (Game) -> Boolean { return { game -> val displayName = game.displayName val name = game.name val containsName = name?.toLowerCase()?.startsWith(jumpToLetter.toLowerCase()) ?: false val containsDisplayName = displayName?.toLowerCase()?.startsWith(jumpToLetter.toLowerCase()) ?: false containsName || containsDisplayName } } private fun filterByText(searchDialogText: String): (Game) -> Boolean { return { game -> val displayName = game.displayName val name = game.name val containsName = name?.toLowerCase()?.contains(searchDialogText) ?: false val containsDisplayName = displayName?.toLowerCase()?.contains(searchDialogText) ?: false containsName || containsDisplayName } } private fun handleSearch(customFilter: ((Game) -> Boolean)?) { val gamesFound = findGames(emulio, customFilter) if (gamesFound.isNotEmpty()) { stage.actors.clear() prepareGamesList(emulio, gamesFound) selectNext(1) } else { Gdx.app.postRunnable { InfoDialog( "No games found".translate(), "No games found, please change your criteria.".translate(), emulio).show(stage) } } } override fun onPageUpButton(input: InputConfig) { updateHelp() logger.debug { "onPageUpButton ${System.identityHashCode(this)} ${platform.platformName} $guiReady" } if (!guiReady) return selectNext(-10) } override fun onPageDownButton(input: InputConfig) { updateHelp() logger.debug { "onPageDownButton ${System.identityHashCode(this)} ${platform.platformName} $guiReady" } if (!guiReady) return selectNext(10) } override fun onExitButton(input: InputConfig) { updateHelp() if (!guiReady) return showCloseDialog() } } class ScrollByAction(private val endScrollX: Float, private val endScrollY: Float, duration: Float) : TemporalAction(duration) { private lateinit var scrollPane: ScrollPane private var startScrollX: Float = -1f private var startScrollY: Float = -1f override fun begin() { scrollPane = target as ScrollPane startScrollX = scrollPane.scrollX startScrollY = scrollPane.scrollY } override fun update(percent: Float) { scrollPane.scrollX = startScrollX + (endScrollX - startScrollX) * percent scrollPane.scrollY = startScrollY + (endScrollY - startScrollY) * percent } } open class Item(val displayName: String, val path: File) class GameItem(val game: Game) : Item(game.displayName ?: game.name ?: game.path.name, game.path) open class PathItem(displayName: String, path: File) : Item(displayName, path) object PathUpItem : PathItem("..", File("up file"))
core/src/main/com/github/emulio/ui/screens/GameListScreen.kt
2809968058
package fr.smarquis.fcm.data.db import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverter import androidx.room.TypeConverters import com.squareup.moshi.Moshi import com.squareup.moshi.Types import fr.smarquis.fcm.data.db.AppDatabase.MapConverter import fr.smarquis.fcm.data.db.AppDatabase.PayloadConverter import fr.smarquis.fcm.data.model.Message import fr.smarquis.fcm.data.model.Payload import org.koin.core.component.KoinComponent import org.koin.core.component.inject @Database(entities = [Message::class], version = 1) @TypeConverters(value = [MapConverter::class, PayloadConverter::class]) abstract class AppDatabase : RoomDatabase() { abstract fun dao(): MessageDao object PayloadConverter : KoinComponent { private val moshi by inject<Moshi>() private val adapter = moshi.adapter(Payload::class.java) @TypeConverter @JvmStatic fun fromJson(data: String): Payload? = adapter.fromJson(data) @TypeConverter @JvmStatic fun toJson(payload: Payload?): String = adapter.toJson(payload) } object MapConverter : KoinComponent { private val moshi by inject<Moshi>() private val adapter = moshi.adapter<Map<String, String>>(Types.newParameterizedType(Map::class.java, String::class.java, String::class.java)) @TypeConverter @JvmStatic fun stringToMap(data: String): Map<String, String> = adapter.fromJson(data).orEmpty() @TypeConverter @JvmStatic fun mapToString(map: Map<String, String>?): String = adapter.toJson(map) } }
app/src/main/java/fr/smarquis/fcm/data/db/AppDatabase.kt
2851380671
package com.jiangkang.ktools import android.content.Context import android.content.Intent import android.media.MediaPlayer import android.os.Bundle import android.speech.tts.TextToSpeech import android.speech.tts.TextToSpeech.OnInitListener import android.text.TextUtils import android.widget.EditText import androidx.appcompat.app.AppCompatActivity import com.jiangkang.annotations.Safe import com.jiangkang.ktools.audio.VoiceBroadcastReceiver import com.jiangkang.ktools.databinding.ActivityAudioBinding import com.jiangkang.tools.utils.ToastUtils import java.util.* /** * @author jiangkang */ class AudioActivity : AppCompatActivity() { private lateinit var binding:ActivityAudioBinding private val etTextContent: EditText by lazy { findViewById<EditText>(R.id.et_text_content) } private var onInitListener: OnInitListener? = null private var speech: TextToSpeech? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityAudioBinding.inflate(layoutInflater) setContentView(binding.root) binding.btnTextToSpeech.setOnClickListener { onBtnTextToSpeechClicked() } binding.btnPlaySingleSound.setOnClickListener { onBtnPlaySingleSoundClicked() } binding.btnPlayMultiSounds.setOnClickListener { onBtnPlayMultiSoundsClicked() } } override fun onDestroy() { super.onDestroy() if (speech != null) { speech!!.shutdown() } } private fun onBtnTextToSpeechClicked() { onInitListener = OnInitListener { status -> if (status == TextToSpeech.SUCCESS) { val result = speech!!.setLanguage(Locale.ENGLISH) if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { ToastUtils.showShortToast("语言不支持") } else { var content = "This is a default voice" if (!TextUtils.isEmpty(etTextContent.text.toString())) { content = etTextContent.text.toString() } speech!!.speak(content, TextToSpeech.QUEUE_FLUSH, null, null) } } } speech = TextToSpeech(this, onInitListener) } @Safe fun onBtnPlaySingleSoundClicked() { val player = MediaPlayer.create(this, R.raw.tts_success) player.start() } private fun onBtnPlayMultiSoundsClicked() { sendBroadcast(Intent(this, VoiceBroadcastReceiver::class.java)) } companion object { fun launch(context: Context, bundle: Bundle?) { val intent = Intent(context, AudioActivity::class.java) if (bundle != null) { intent.putExtras(bundle) } context.startActivity(intent) } } }
app/src/main/java/com/jiangkang/ktools/AudioActivity.kt
322282701
package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_13_R2 import com.github.shynixn.petblocks.api.business.proxy.ArmorstandPetProxy import com.github.shynixn.petblocks.api.business.proxy.EntityPetProxy import net.minecraft.server.v1_13_R2.EnumItemSlot import org.bukkit.craftbukkit.v1_13_R2.CraftServer import org.bukkit.craftbukkit.v1_13_R2.entity.CraftArmorStand import org.bukkit.craftbukkit.v1_13_R2.inventory.CraftItemStack import org.bukkit.inventory.ItemStack /** * Created by Shynixn 2019. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2019 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ class CraftPetArmorstand(server: CraftServer, nmsPet: NMSPetArmorstand) : CraftArmorStand(server, nmsPet), ArmorstandPetProxy { /** * Sets the helmet item stack securely if * blocked by the NMS call. */ override fun <I> setHelmetItemStack(item: I) { require(item is ItemStack?) (handle as NMSPetArmorstand).setSecureSlot(EnumItemSlot.HEAD, CraftItemStack.asNMSCopy(item)) } /** * Sets the boots item stack securely if * blocked by the NMS call. */ override fun <I> setBootsItemStack(item: I) { require(item is ItemStack?) (handle as NMSPetArmorstand).setSecureSlot(EnumItemSlot.FEET, CraftItemStack.asNMSCopy(item)) } /** * Removes this entity. */ override fun deleteFromWorld() { super.remove() } /** * Ignore all other plugins trying to remove this entity. This is the entity of PetBlocks, * no one else is allowed to modify this! */ override fun remove() { } /** * Pet should never be persistent. */ override fun isPersistent(): Boolean { return false } /** * Pet should never be persistent. */ override fun setPersistent(b: Boolean) {} /** * Custom type. */ override fun toString(): String { return "PetBlocks{ArmorstandEntity}" } }
petblocks-bukkit-plugin/petblocks-bukkit-nms-113R2/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_13_R2/CraftPetArmorstand.kt
2930900113
package net.println.kt13.module import dagger.Module import dagger.Provides import net.println.kt13.config.Settings import javax.inject.Singleton /** * Created by benny on 12/11/16. */ @Module class BaseUrlModule { companion object{ //测试环境 const val DEBUG_URL = "https://api.github.com" //线上环境 const val RELEASE_URL = "https://api.github.com" } @Singleton @Provides fun baseUrl(): String = if(Settings.DEBUG) DEBUG_URL else RELEASE_URL }
app/src/main/java/com/dgrlucky/extend/kotlin/_restful/module/BaseUrlModule.kt
464362016
package com.fastaccess.provider.theme import android.app.Activity import android.app.ActivityManager import android.graphics.BitmapFactory import android.support.annotation.StyleRes import com.danielstone.materialaboutlibrary.MaterialAboutActivity import com.fastaccess.R import com.fastaccess.helper.Logger import com.fastaccess.helper.PrefGetter import com.fastaccess.helper.ViewHelper import com.fastaccess.ui.base.BaseActivity import com.fastaccess.ui.modules.login.LoginActivity import com.fastaccess.ui.modules.login.chooser.LoginChooserActivity import com.fastaccess.ui.modules.main.donation.DonateActivity import com.fastaccess.ui.modules.reviews.changes.ReviewChangesActivity /** * Created by Kosh on 07 Jun 2017, 6:52 PM */ object ThemeEngine { fun apply(activity: BaseActivity<*, *>) { if (hasTheme(activity)) { return } val themeMode = PrefGetter.getThemeType(activity) val themeColor = PrefGetter.getThemeColor(activity) activity.setTheme(getTheme(themeMode, themeColor)) setTaskDescription(activity) applyNavBarColor(activity) } private fun applyNavBarColor(activity: Activity) { if (!PrefGetter.isNavBarTintingDisabled() && PrefGetter.getThemeType() != PrefGetter.LIGHT) { activity.window.navigationBarColor = ViewHelper.getPrimaryColor(activity) } } fun applyForAbout(activity: MaterialAboutActivity) { val themeMode = PrefGetter.getThemeType(activity) when (themeMode) { PrefGetter.LIGHT -> activity.setTheme(R.style.AppTheme_AboutActivity_Light) PrefGetter.DARK -> activity.setTheme(R.style.AppTheme_AboutActivity_Dark) PrefGetter.AMLOD -> activity.setTheme(R.style.AppTheme_AboutActivity_Amlod) PrefGetter.MID_NIGHT_BLUE -> activity.setTheme(R.style.AppTheme_AboutActivity_MidNightBlue) PrefGetter.BLUISH -> activity.setTheme(R.style.AppTheme_AboutActivity_Bluish) } setTaskDescription(activity) } fun applyDialogTheme(activity: BaseActivity<*, *>) { val themeMode = PrefGetter.getThemeType(activity) val themeColor = PrefGetter.getThemeColor(activity) activity.setTheme(getDialogTheme(themeMode, themeColor)) setTaskDescription(activity) } @StyleRes fun getTheme(themeMode: Int, themeColor: Int): Int { Logger.e(themeMode, themeColor) // I wish if I could simplify this :'( too many cases for the love of god. when (themeMode) { PrefGetter.LIGHT -> when (themeColor) { PrefGetter.RED -> return R.style.ThemeLight_Red PrefGetter.PINK -> return R.style.ThemeLight_Pink PrefGetter.PURPLE -> return R.style.ThemeLight_Purple PrefGetter.DEEP_PURPLE -> return R.style.ThemeLight_DeepPurple PrefGetter.INDIGO -> return R.style.ThemeLight_Indigo PrefGetter.BLUE -> return R.style.ThemeLight PrefGetter.LIGHT_BLUE -> return R.style.ThemeLight_LightBlue PrefGetter.CYAN -> return R.style.ThemeLight_Cyan PrefGetter.TEAL -> return R.style.ThemeLight_Teal PrefGetter.GREEN -> return R.style.ThemeLight_Green PrefGetter.LIGHT_GREEN -> return R.style.ThemeLight_LightGreen PrefGetter.LIME -> return R.style.ThemeLight_Lime PrefGetter.YELLOW -> return R.style.ThemeLight_Yellow PrefGetter.AMBER -> return R.style.ThemeLight_Amber PrefGetter.ORANGE -> return R.style.ThemeLight_Orange PrefGetter.DEEP_ORANGE -> return R.style.ThemeLight_DeepOrange else -> return R.style.ThemeLight } PrefGetter.DARK -> when (themeColor) { PrefGetter.RED -> return R.style.ThemeDark_Red PrefGetter.PINK -> return R.style.ThemeDark_Pink PrefGetter.PURPLE -> return R.style.ThemeDark_Purple PrefGetter.DEEP_PURPLE -> return R.style.ThemeDark_DeepPurple PrefGetter.INDIGO -> return R.style.ThemeDark_Indigo PrefGetter.BLUE -> return R.style.ThemeDark PrefGetter.LIGHT_BLUE -> return R.style.ThemeDark_LightBlue PrefGetter.CYAN -> return R.style.ThemeDark_Cyan PrefGetter.TEAL, PrefGetter.GREEN -> return R.style.ThemeDark_Green PrefGetter.LIGHT_GREEN -> return R.style.ThemeDark_LightGreen PrefGetter.LIME -> return R.style.ThemeDark_Lime PrefGetter.YELLOW -> return R.style.ThemeDark_Yellow PrefGetter.AMBER -> return R.style.ThemeDark_Amber PrefGetter.ORANGE -> return R.style.ThemeDark_Orange PrefGetter.DEEP_ORANGE -> return R.style.ThemeDark_DeepOrange else -> return R.style.ThemeDark } PrefGetter.AMLOD -> when (themeColor) { PrefGetter.RED -> return R.style.ThemeAmlod_Red PrefGetter.PINK -> return R.style.ThemeAmlod_Pink PrefGetter.PURPLE -> return R.style.ThemeAmlod_Purple PrefGetter.DEEP_PURPLE -> return R.style.ThemeAmlod_DeepPurple PrefGetter.INDIGO -> return R.style.ThemeAmlod_Indigo PrefGetter.BLUE -> return R.style.ThemeAmlod PrefGetter.LIGHT_BLUE -> return R.style.ThemeAmlod_LightBlue PrefGetter.CYAN -> return R.style.ThemeAmlod_Cyan PrefGetter.TEAL, PrefGetter.GREEN -> return R.style.ThemeAmlod_Green PrefGetter.LIGHT_GREEN -> return R.style.ThemeAmlod_LightGreen PrefGetter.LIME -> return R.style.ThemeAmlod_Lime PrefGetter.YELLOW -> return R.style.ThemeAmlod_Yellow PrefGetter.AMBER -> return R.style.ThemeAmlod_Amber PrefGetter.ORANGE -> return R.style.ThemeAmlod_Orange PrefGetter.DEEP_ORANGE -> return R.style.ThemeAmlod_DeepOrange else -> return R.style.ThemeAmlod } PrefGetter.MID_NIGHT_BLUE -> when (themeColor) { PrefGetter.RED -> return R.style.ThemeMidNighBlue_Red PrefGetter.PINK -> return R.style.ThemeMidNighBlue_Pink PrefGetter.PURPLE -> return R.style.ThemeMidNighBlue_Purple PrefGetter.DEEP_PURPLE -> return R.style.ThemeMidNighBlue_DeepPurple PrefGetter.INDIGO -> return R.style.ThemeMidNighBlue_Indigo PrefGetter.BLUE -> return R.style.ThemeMidNighBlue PrefGetter.LIGHT_BLUE -> return R.style.ThemeMidNighBlue_LightBlue PrefGetter.CYAN -> return R.style.ThemeMidNighBlue_Cyan PrefGetter.TEAL, PrefGetter.GREEN -> return R.style.ThemeMidNighBlue_Green PrefGetter.LIGHT_GREEN -> return R.style.ThemeMidNighBlue_LightGreen PrefGetter.LIME -> return R.style.ThemeMidNighBlue_Lime PrefGetter.YELLOW -> return R.style.ThemeMidNighBlue_Yellow PrefGetter.AMBER -> return R.style.ThemeMidNighBlue_Amber PrefGetter.ORANGE -> return R.style.ThemeMidNighBlue_Orange PrefGetter.DEEP_ORANGE -> return R.style.ThemeMidNighBlue_DeepOrange else -> return R.style.ThemeMidNighBlue } PrefGetter.BLUISH -> when (themeColor) { PrefGetter.RED -> return R.style.ThemeBluish_Red PrefGetter.PINK -> return R.style.ThemeBluish_Pink PrefGetter.PURPLE -> return R.style.ThemeBluish_Purple PrefGetter.DEEP_PURPLE -> return R.style.ThemeBluish_DeepPurple PrefGetter.INDIGO -> return R.style.ThemeBluish_Indigo PrefGetter.BLUE -> return R.style.ThemeBluish PrefGetter.LIGHT_BLUE -> return R.style.ThemeBluish_LightBlue PrefGetter.CYAN -> return R.style.ThemeBluish_Cyan PrefGetter.TEAL, PrefGetter.GREEN -> return R.style.ThemeBluish_Green PrefGetter.LIGHT_GREEN -> return R.style.ThemeBluish_LightGreen PrefGetter.LIME -> return R.style.ThemeBluish_Lime PrefGetter.YELLOW -> return R.style.ThemeBluish_Yellow PrefGetter.AMBER -> return R.style.ThemeBluish_Amber PrefGetter.ORANGE -> return R.style.ThemeBluish_Orange PrefGetter.DEEP_ORANGE -> return R.style.ThemeBluish_DeepOrange else -> return R.style.ThemeBluish } } return R.style.ThemeLight } @StyleRes fun getDialogTheme(themeMode: Int, themeColor: Int): Int { when (themeMode) { PrefGetter.LIGHT -> when (themeColor) { PrefGetter.RED -> return R.style.DialogThemeLight_Red PrefGetter.PINK -> return R.style.DialogThemeLight_Pink PrefGetter.PURPLE -> return R.style.DialogThemeLight_Purple PrefGetter.DEEP_PURPLE -> return R.style.DialogThemeLight_DeepPurple PrefGetter.INDIGO -> return R.style.DialogThemeLight_Indigo PrefGetter.BLUE -> return R.style.DialogThemeLight PrefGetter.LIGHT_BLUE -> return R.style.DialogThemeLight_LightBlue PrefGetter.CYAN -> return R.style.DialogThemeLight_Cyan PrefGetter.TEAL -> return R.style.DialogThemeLight_Teal PrefGetter.GREEN -> return R.style.DialogThemeLight_Green PrefGetter.LIGHT_GREEN -> return R.style.DialogThemeLight_LightGreen PrefGetter.LIME -> return R.style.DialogThemeLight_Lime PrefGetter.YELLOW -> return R.style.DialogThemeLight_Yellow PrefGetter.AMBER -> return R.style.DialogThemeLight_Amber PrefGetter.ORANGE -> return R.style.DialogThemeLight_Orange PrefGetter.DEEP_ORANGE -> return R.style.DialogThemeLight_DeepOrange else -> return R.style.DialogThemeLight } PrefGetter.DARK -> when (themeColor) { PrefGetter.RED -> return R.style.DialogThemeDark_Red PrefGetter.PINK -> return R.style.DialogThemeDark_Pink PrefGetter.PURPLE -> return R.style.DialogThemeDark_Purple PrefGetter.DEEP_PURPLE -> return R.style.DialogThemeDark_DeepPurple PrefGetter.INDIGO -> return R.style.DialogThemeDark_Indigo PrefGetter.BLUE -> return R.style.DialogThemeDark PrefGetter.LIGHT_BLUE -> return R.style.DialogThemeDark_LightBlue PrefGetter.CYAN -> return R.style.DialogThemeDark_Cyan PrefGetter.TEAL, PrefGetter.GREEN -> return R.style.DialogThemeDark_Green PrefGetter.LIGHT_GREEN -> return R.style.DialogThemeDark_LightGreen PrefGetter.LIME -> return R.style.DialogThemeDark_Lime PrefGetter.YELLOW -> return R.style.DialogThemeDark_Yellow PrefGetter.AMBER -> return R.style.DialogThemeDark_Amber PrefGetter.ORANGE -> return R.style.DialogThemeDark_Orange PrefGetter.DEEP_ORANGE -> return R.style.DialogThemeDark_DeepOrange else -> return R.style.DialogThemeDark } PrefGetter.AMLOD -> when (themeColor) { PrefGetter.RED -> return R.style.DialogThemeAmlod_Red PrefGetter.PINK -> return R.style.DialogThemeAmlod_Pink PrefGetter.PURPLE -> return R.style.DialogThemeAmlod_Purple PrefGetter.DEEP_PURPLE -> return R.style.DialogThemeAmlod_DeepPurple PrefGetter.INDIGO -> return R.style.DialogThemeAmlod_Indigo PrefGetter.BLUE -> return R.style.DialogThemeAmlod PrefGetter.LIGHT_BLUE -> return R.style.DialogThemeAmlod_LightBlue PrefGetter.CYAN -> return R.style.DialogThemeAmlod_Cyan PrefGetter.TEAL, PrefGetter.GREEN -> return R.style.DialogThemeAmlod_Green PrefGetter.LIGHT_GREEN -> return R.style.DialogThemeAmlod_LightGreen PrefGetter.LIME -> return R.style.DialogThemeAmlod_Lime PrefGetter.YELLOW -> return R.style.DialogThemeAmlod_Yellow PrefGetter.AMBER -> return R.style.DialogThemeAmlod_Amber PrefGetter.ORANGE -> return R.style.DialogThemeAmlod_Orange PrefGetter.DEEP_ORANGE -> return R.style.DialogThemeAmlod_DeepOrange else -> return R.style.DialogThemeAmlod } PrefGetter.MID_NIGHT_BLUE -> when (themeColor) { PrefGetter.RED -> return R.style.DialogThemeLight_Red PrefGetter.PINK -> return R.style.DialogThemeLight_Pink PrefGetter.PURPLE -> return R.style.DialogThemeLight_Purple PrefGetter.DEEP_PURPLE -> return R.style.DialogThemeLight_DeepPurple PrefGetter.INDIGO -> return R.style.DialogThemeLight_Indigo PrefGetter.BLUE -> return R.style.DialogThemeLight PrefGetter.LIGHT_BLUE -> return R.style.DialogThemeLight_LightBlue PrefGetter.CYAN -> return R.style.DialogThemeLight_Cyan PrefGetter.TEAL, PrefGetter.GREEN -> return R.style.DialogThemeLight_Green PrefGetter.LIGHT_GREEN -> return R.style.DialogThemeLight_LightGreen PrefGetter.LIME -> return R.style.DialogThemeLight_Lime PrefGetter.YELLOW -> return R.style.DialogThemeLight_Yellow PrefGetter.AMBER -> return R.style.DialogThemeLight_Amber PrefGetter.ORANGE -> return R.style.DialogThemeLight_Orange PrefGetter.DEEP_ORANGE -> return R.style.DialogThemeLight_DeepOrange else -> return R.style.DialogThemeLight } PrefGetter.BLUISH -> when (themeColor) { PrefGetter.RED -> return R.style.DialogThemeBluish_Red PrefGetter.PINK -> return R.style.DialogThemeBluish_Pink PrefGetter.PURPLE -> return R.style.DialogThemeBluish_Purple PrefGetter.DEEP_PURPLE -> return R.style.DialogThemeBluish_DeepPurple PrefGetter.INDIGO -> return R.style.DialogThemeBluish_Indigo PrefGetter.BLUE -> return R.style.DialogThemeBluish PrefGetter.LIGHT_BLUE -> return R.style.DialogThemeBluish_LightBlue PrefGetter.CYAN -> return R.style.DialogThemeBluish_Cyan PrefGetter.TEAL, PrefGetter.GREEN -> return R.style.DialogThemeBluish_Green PrefGetter.LIGHT_GREEN -> return R.style.DialogThemeBluish_LightGreen PrefGetter.LIME -> return R.style.DialogThemeBluish_Lime PrefGetter.YELLOW -> return R.style.DialogThemeBluish_Yellow PrefGetter.AMBER -> return R.style.DialogThemeBluish_Amber PrefGetter.ORANGE -> return R.style.DialogThemeBluish_Orange PrefGetter.DEEP_ORANGE -> return R.style.DialogThemeBluish_DeepOrange else -> return R.style.DialogThemeBluish } } return R.style.DialogThemeLight } private fun setTaskDescription(activity: Activity) { activity.setTaskDescription(ActivityManager.TaskDescription(activity.getString(R.string.app_name), BitmapFactory.decodeResource(activity.resources, R.mipmap.ic_launcher), ViewHelper.getPrimaryColor(activity))) } private fun hasTheme(activity: BaseActivity<*, *>) = (activity is LoginChooserActivity || activity is LoginActivity || activity is DonateActivity || activity is ReviewChangesActivity) }
app/src/main/java/com/fastaccess/provider/theme/ThemeEngine.kt
4073129549
package elite.math.trig import elite.math.trig.triangle.Adjacent import elite.math.trig.triangle.Hypotenuse /** * * @author CFerg (Elite) */ class Arcsecant { /** * */ var arcsecant: Double = 0.toDouble() /** * * @param a * @param h */ constructor(a: Adjacent, h: Hypotenuse) { this.arcsecant = a.adjacent / h.hypotenuse } /** * * @param sec */ constructor(sec: Secant) { this.arcsecant = 1 / sec.secant } /** * * @param cos */ constructor(cos: Cosine) { this.arcsecant = cos.cosine } }
ObjectAvoidance/kotlin/src/elite/math/trig/Arcsecant.kt
2491402007
package com.marcorighini.lib.anim import android.animation.ObjectAnimator import android.view.View import com.marcorighini.lib.AnchorOffset interface Transformation { fun transform(view: View, moveY: Int, anchorOffset: AnchorOffset) fun getAnimator(view: View, anchorOffset: AnchorOffset, toProgress: Float, duration: Long): ObjectAnimator }
lib/src/main/java/com/marcorighini/lib/anim/Transformation.kt
1684423706
/* * Copyright 2019 Stephane Nicolas * Copyright 2019 Daniel Molinero Reguera * * 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 toothpick.ktp import javax.inject.Named import javax.inject.Provider import javax.inject.Qualifier import org.amshove.kluent.When import org.amshove.kluent.calling import org.amshove.kluent.itReturns import org.amshove.kluent.shouldEqual import org.amshove.kluent.shouldNotBeNull import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension import org.mockito.Mock import org.mockito.junit.jupiter.MockitoExtension import toothpick.InjectConstructor import toothpick.Lazy import toothpick.ktp.delegate.inject import toothpick.ktp.delegate.lazy import toothpick.ktp.delegate.provider import toothpick.ktp.extension.getInstance import toothpick.ktp.extension.getLazy import toothpick.ktp.extension.getProvider import toothpick.testing.ToothPickExtension class TestRuntime { @JvmField @RegisterExtension val toothpickExtension = ToothPickExtension(this, "Foo") @JvmField @RegisterExtension val mockitoExtension = MockitoExtension() @Mock lateinit var dependency: Dependency @Mock @field:Named("name") lateinit var namedDependency: Dependency @Mock @field:QualifierName lateinit var qualifierDependency: Dependency @Test fun `field injection should inject mocks when they are defined`() { // GIVEN When calling dependency.num() itReturns 2 When calling namedDependency.num() itReturns 3 When calling qualifierDependency.num() itReturns 4 // WHEN val entryPoint = EntryPoint() // THEN assertDependencies(entryPoint, 2, 3, 4) } @Test fun `constructor injection by getInstance should inject dependencies when they are defined`() { // GIVEN When calling dependency.num() itReturns 2 When calling namedDependency.num() itReturns 3 When calling qualifierDependency.num() itReturns 4 // WHEN val nonEntryPoint: NonEntryPoint = KTP.openScope("Foo").getInstance() // THEN assertDependencies(nonEntryPoint, 2, 3, 4) } @Test fun `constructor injection byLazy should inject dependencies when they are defined`() { // GIVEN When calling dependency.num() itReturns 2 When calling namedDependency.num() itReturns 3 When calling qualifierDependency.num() itReturns 4 // WHEN val nonEntryPoint: Lazy<NonEntryPoint> = KTP.openScope("Foo").getLazy() // THEN assertDependencies(nonEntryPoint.get(), 2, 3, 4) } @Test fun `constructor injection by provider should inject dependencies when they are defined`() { // GIVEN When calling dependency.num() itReturns 2 When calling namedDependency.num() itReturns 3 When calling qualifierDependency.num() itReturns 4 // WHEN val nonEntryPoint: Provider<NonEntryPoint> = KTP.openScope("Foo").getProvider() // THEN assertDependencies(nonEntryPoint.get(), 2, 3, 4) } private fun assertDependencies( nonEntryPoint: NonEntryPoint, dependencyValue: Int, namedDependencyValue: Int, qualifierDependencyValue: Int ) { nonEntryPoint.shouldNotBeNull() nonEntryPoint.dependency.shouldNotBeNull() nonEntryPoint.lazyDependency.shouldNotBeNull() nonEntryPoint.providerDependency.shouldNotBeNull() nonEntryPoint.namedDependency.shouldNotBeNull() nonEntryPoint.namedLazyDependency.shouldNotBeNull() nonEntryPoint.namedProviderDependency.shouldNotBeNull() nonEntryPoint.qualifierDependency.shouldNotBeNull() nonEntryPoint.qualifierLazyDependency.shouldNotBeNull() nonEntryPoint.qualifierProviderDependency.shouldNotBeNull() nonEntryPoint.dependency.num() shouldEqual dependencyValue nonEntryPoint.lazyDependency.get().num() shouldEqual dependencyValue nonEntryPoint.providerDependency.get().num() shouldEqual dependencyValue nonEntryPoint.namedDependency.num() shouldEqual namedDependencyValue nonEntryPoint.namedLazyDependency.get().num() shouldEqual namedDependencyValue nonEntryPoint.namedProviderDependency.get().num() shouldEqual namedDependencyValue nonEntryPoint.qualifierDependency.num() shouldEqual qualifierDependencyValue nonEntryPoint.qualifierLazyDependency.get().num() shouldEqual qualifierDependencyValue nonEntryPoint.qualifierProviderDependency.get().num() shouldEqual qualifierDependencyValue } private fun assertDependencies( entryPoint: EntryPoint, dependencyValue: Int, namedDependencyValue: Int, qualifierDependencyValue: Int ) { entryPoint.shouldNotBeNull() entryPoint.dependency.shouldNotBeNull() entryPoint.lazyDependency.shouldNotBeNull() entryPoint.providerDependency.shouldNotBeNull() entryPoint.namedDependency.shouldNotBeNull() entryPoint.namedLazyDependency.shouldNotBeNull() entryPoint.namedProviderDependency.shouldNotBeNull() entryPoint.qualifierDependency.shouldNotBeNull() entryPoint.qualifierLazyDependency.shouldNotBeNull() entryPoint.qualifierProviderDependency.shouldNotBeNull() entryPoint.dependency.num() shouldEqual dependencyValue entryPoint.lazyDependency.num() shouldEqual dependencyValue entryPoint.providerDependency.num() shouldEqual dependencyValue entryPoint.namedDependency.num() shouldEqual namedDependencyValue entryPoint.namedLazyDependency.num() shouldEqual namedDependencyValue entryPoint.namedProviderDependency.num() shouldEqual namedDependencyValue entryPoint.qualifierDependency.num() shouldEqual qualifierDependencyValue entryPoint.qualifierLazyDependency.num() shouldEqual qualifierDependencyValue } class EntryPoint { val dependency: Dependency by inject() val lazyDependency: Dependency by lazy() val providerDependency: Dependency by provider() val namedDependency: Dependency by inject("name") val namedLazyDependency: Dependency by lazy("name") val namedProviderDependency: Dependency by provider("name") val qualifierDependency: Dependency by inject(QualifierName::class) val qualifierLazyDependency: Dependency by lazy(QualifierName::class) val qualifierProviderDependency: Dependency by provider(QualifierName::class) init { KTP.openScope("Foo").inject(this) } } @InjectConstructor class NonEntryPoint( val dependency: Dependency, val lazyDependency: Lazy<Dependency>, val providerDependency: Provider<Dependency>, @Named("name") val namedDependency: Dependency, @Named("name") val namedLazyDependency: Lazy<Dependency>, @Named("name") val namedProviderDependency: Provider<Dependency>, @QualifierName val qualifierDependency: Dependency, @QualifierName val qualifierLazyDependency: Lazy<Dependency>, @QualifierName val qualifierProviderDependency: Provider<Dependency> ) // open for mocking open class Dependency { open fun num(): Int { return 1 } } @Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class QualifierName }
ktp/src/test/kotlin/toothpick/ktp/TestRuntime.kt
3804247651
package nl.voidcorp.arduino import com.fazecast.jSerialComm.SerialPort import org.yaml.snakeyaml.Yaml import java.io.* import java.sql.Connection import java.sql.DriverManager import java.sql.SQLSyntaxErrorException import java.text.SimpleDateFormat import java.util.* /** * @author J00LZ * @version 1.0 * */ var globalconfig = Config() fun main(args: Array<String>) { initConfig() val serial = SerialPort.getCommPort(globalconfig.port) val dbstring = "jdbc:mysql://${globalconfig.mysqlHost}:3306/${globalconfig.mysqlDB}?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC" val connection = DriverManager.getConnection(dbstring, globalconfig.mysqlUser, globalconfig.mysqlPassword) serialStart(serial, connection) } /** * Initializes the configuration files. * * Used for loading the configs. */ fun initConfig(): Unit { val yaml = Yaml(WeekdayHider()) if (!File("conf.yml").exists()) { val conf = yaml.dumpAsMap(globalconfig) val fw = FileWriter("conf.yml", false) fw.write(conf) fw.close() println("Default config created, edit it so this actually works...") System.exit(0) } globalconfig = yaml.loadAs(FileReader("conf.yml"), Config::class.java) if (globalconfig.version != Config.currentVersion) { globalconfig.version = Config.currentVersion backupConfig() println("Config was updated, you might want to check any new values...") val conf = yaml.dumpAsMap(globalconfig) val fw = FileWriter("conf.yml", false) fw.write(conf) fw.close() System.err.println("This program will keep running, but beware, if it errors, check the config") System.err.println("The file was backed up to conf.yml.bak, but will be deleted with another upgrade...") } } /** * Starts the serial connection. * * It opens the serial with default settings, and reports any errors. * If the startup of the serial connection was successful it writes values to the mysql database */ fun serialStart(serial: SerialPort, connection: Connection): Unit { serial.openPort() serial.setComPortParameters(9600, 8, 1, SerialPort.NO_PARITY) serial.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 100, 0) serial.setFlowControl(SerialPort.FLOW_CONTROL_RTS_ENABLED) if (!serial.isOpen) { println("Run the program as an administrator, or as alternative run: \n" + "sudo usermod -a -G tty ${System.getProperty("user.name")}\n" + "sudo usermod -a -G dialout ${System.getProperty("user.name")}\n" + "And reboot or log off") System.exit(1) } val reader = BufferedReader(InputStreamReader(serial.inputStream)) while (true) { try { val line = reader.readLine() handle(line, connection) } catch (ex: IOException) { } } } var i = true /** * Creates the current table, with a postfix of the date of the last chosen start date */ fun createTables(x: Connection): Unit { var s = "CREATE TABLE `${globalconfig.mysqlTable}-${getStartOfWeek()}`(`Id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, " for (i in 1..globalconfig.amount) { s += "`${convertLessThanOneThousand(i)}` DOUBLE NOT NULL, " } s += " `time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (`Id`))" val st = x.prepareStatement(s) try { st.execute() println("Table Created: `${globalconfig.mysqlTable}-${getStartOfWeek()}`") } catch (ex: SQLSyntaxErrorException) { if (i) { println("Table exists: `${globalconfig.mysqlTable}-${getStartOfWeek()}`") i = false } } } /** * Inserts the values into the database */ fun insert(conn: Connection, vararg doubles: Double): Unit { var string = "INSERT INTO `${globalconfig.mysqlTable}-${getStartOfWeek()}`(" for (i in 1..globalconfig.amount) { string += "`${convertLessThanOneThousand(i)}`, " } string = string.subSequence(0, string.lastIndexOf(',')).toString() string += ") VALUES(" for (d in 0..doubles.lastIndex) { string += "`${doubles[d]}`, " } string = string.removeSuffix(", ") + ")" val st = conn.createStatement() try { st.executeUpdate(string) } catch (ex: SQLSyntaxErrorException) { createTables(conn) } } /** * Initializes the database, and if needed creates a database with a new name */ fun handle(string: String, connection: Connection): Unit { createTables(connection) val line = string.split(',').toMutableList() line.forEach { it.trim() } if (line.size != globalconfig.amount) { println("not enough entries: ${line.size}, needed ${globalconfig.amount}") } else { createTables(connection) val d = Array(globalconfig.amount, { line[it].toDouble() }).toDoubleArray() insert(connection, *d) } } /** * Gets the configured start of the week date, @see Config */ fun getStartOfWeek(): String { val cal = GregorianCalendar.getInstance(Locale.forLanguageTag("nl-NL")) cal.time = Date() cal.firstDayOfWeek = globalconfig.weekDay cal.set(Calendar.DAY_OF_WEEK, globalconfig.weekDay) val format = SimpleDateFormat("dd-MM-yy", Locale.forLanguageTag("nl-NL")) return format.format(cal.time) } /** * Backs up the config when there is an upgrade. */ fun backupConfig(): Unit { with(File("conf.yml.bak")) { if (this.exists()) { this.delete() } } File("conf.yml").copyTo(File("conf.yml.bak")) }
src/main/kotlin/nl/voidcorp/arduino/Main.kt
2642767249
package leakcanary import android.annotation.SuppressLint import android.app.ActivityManager import android.app.ActivityManager.MemoryInfo import android.app.ActivityManager.RunningAppProcessInfo import android.content.Context import android.os.Build.VERSION.SDK_INT import android.os.Process import android.os.SystemClock import android.system.Os import android.system.OsConstants import java.io.File import java.io.FileReader import leakcanary.ProcessInfo.AvailableRam.BelowThreshold import leakcanary.ProcessInfo.AvailableRam.LowRamDevice import leakcanary.ProcessInfo.AvailableRam.Memory interface ProcessInfo { val isImportanceBackground: Boolean val elapsedMillisSinceStart: Long fun availableDiskSpaceBytes(path: File): Long sealed class AvailableRam { object LowRamDevice : AvailableRam() object BelowThreshold : AvailableRam() class Memory(val bytes: Long) : AvailableRam() } fun availableRam(context: Context): AvailableRam @SuppressLint("NewApi") object Real : ProcessInfo { private val memoryOutState = RunningAppProcessInfo() private val memoryInfo = MemoryInfo() private val processStartUptimeMillis by lazy { Process.getStartUptimeMillis() } private val processForkRealtimeMillis by lazy { readProcessForkRealtimeMillis() } override val isImportanceBackground: Boolean get() { ActivityManager.getMyMemoryState(memoryOutState) return memoryOutState.importance >= RunningAppProcessInfo.IMPORTANCE_BACKGROUND } override val elapsedMillisSinceStart: Long get() = if (SDK_INT >= 24) { SystemClock.uptimeMillis() - processStartUptimeMillis } else { SystemClock.elapsedRealtime() - processForkRealtimeMillis } @SuppressLint("UsableSpace") override fun availableDiskSpaceBytes(path: File) = path.usableSpace override fun availableRam(context: Context): AvailableRam { val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager if (SDK_INT >= 19 && activityManager.isLowRamDevice) { return LowRamDevice } else { activityManager.getMemoryInfo(memoryInfo) return if (memoryInfo.lowMemory || memoryInfo.availMem <= memoryInfo.threshold) { BelowThreshold } else { val systemAvailableMemory = memoryInfo.availMem - memoryInfo.threshold val runtime = Runtime.getRuntime() val appUsedMemory = runtime.totalMemory() - runtime.freeMemory() val appAvailableMemory = runtime.maxMemory() - appUsedMemory val availableMemory = systemAvailableMemory.coerceAtMost(appAvailableMemory) Memory(availableMemory) } } } /** * See https://dev.to/pyricau/android-vitals-when-did-my-app-start-24p4#process-fork-time */ private fun readProcessForkRealtimeMillis(): Long { val myPid = Process.myPid() val ticksAtProcessStart = readProcessStartTicks(myPid) val ticksPerSecond = if (SDK_INT >= 21) { Os.sysconf(OsConstants._SC_CLK_TCK) } else { val tckConstant = try { Class.forName("android.system.OsConstants").getField("_SC_CLK_TCK").getInt(null) } catch (e: ClassNotFoundException) { Class.forName("libcore.io.OsConstants").getField("_SC_CLK_TCK").getInt(null) } val os = Class.forName("libcore.io.Libcore").getField("os").get(null)!! os::class.java.getMethod("sysconf", Integer.TYPE).invoke(os, tckConstant) as Long } return ticksAtProcessStart * 1000 / ticksPerSecond } // Benchmarked (with Jetpack Benchmark) on Pixel 3 running // Android 10. Median time: 0.13ms private fun readProcessStartTicks(pid: Int): Long { val path = "/proc/$pid/stat" val stat = FileReader(path).buffered().use { reader -> reader.readLine() } val fields = stat.substringAfter(") ") .split(' ') return fields[19].toLong() } } }
leakcanary-android-release/src/main/java/leakcanary/ProcessInfo.kt
3907809824
/** * ownCloud Android client application * * @author Juan Carlos Garrote Gascón * * Copyright (C) 2022 ownCloud GmbH. * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * <p> * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.presentation.ui.settings.fragments import android.app.Activity import android.content.DialogInterface import android.content.Intent import android.os.Build import android.os.Bundle import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AlertDialog import androidx.preference.CheckBoxPreference import androidx.preference.ListPreference import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceScreen import com.owncloud.android.R import com.owncloud.android.extensions.avoidScreenshotsIfNeeded import com.owncloud.android.extensions.showMessageInSnackbar import com.owncloud.android.presentation.ui.security.BiometricActivity import com.owncloud.android.presentation.ui.security.BiometricManager import com.owncloud.android.presentation.ui.security.LockTimeout import com.owncloud.android.presentation.ui.security.PREFERENCE_LOCK_TIMEOUT import com.owncloud.android.presentation.ui.security.PatternActivity import com.owncloud.android.presentation.ui.security.passcode.PassCodeActivity import com.owncloud.android.presentation.ui.settings.fragments.SettingsFragment.Companion.removePreferenceFromScreen import com.owncloud.android.presentation.viewmodels.settings.SettingsSecurityViewModel import com.owncloud.android.utils.DocumentProviderUtils.Companion.notifyDocumentProviderRoots import org.koin.androidx.viewmodel.ext.android.viewModel class SettingsSecurityFragment : PreferenceFragmentCompat() { // ViewModel private val securityViewModel by viewModel<SettingsSecurityViewModel>() private var screenSecurity: PreferenceScreen? = null private var prefPasscode: CheckBoxPreference? = null private var prefPattern: CheckBoxPreference? = null private var prefBiometric: CheckBoxPreference? = null private var prefLockApplication: ListPreference? = null private var prefLockAccessDocumentProvider: CheckBoxPreference? = null private var prefTouchesWithOtherVisibleWindows: CheckBoxPreference? = null private val enablePasscodeLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode != Activity.RESULT_OK) return@registerForActivityResult else { prefPasscode?.isChecked = true prefBiometric?.isChecked = securityViewModel.getBiometricsState() // Allow to use biometric lock, lock delay and access from document provider since Passcode lock has been enabled enableBiometricAndLockApplication() } } private val disablePasscodeLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode != Activity.RESULT_OK) return@registerForActivityResult else { prefPasscode?.isChecked = false // Do not allow to use biometric lock, lock delay nor access from document provider since Passcode lock has been disabled disableBiometric() prefLockApplication?.isEnabled = false } } private val enablePatternLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode != Activity.RESULT_OK) return@registerForActivityResult else { prefPattern?.isChecked = true prefBiometric?.isChecked = securityViewModel.getBiometricsState() // Allow to use biometric lock, lock delay and access from document provider since Pattern lock has been enabled enableBiometricAndLockApplication() } } private val disablePatternLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode != Activity.RESULT_OK) return@registerForActivityResult else { prefPattern?.isChecked = false // Do not allow to use biometric lock, lock delay nor access from document provider since Pattern lock has been disabled disableBiometric() prefLockApplication?.isEnabled = false } } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.settings_security, rootKey) screenSecurity = findPreference(SCREEN_SECURITY) prefPasscode = findPreference(PassCodeActivity.PREFERENCE_SET_PASSCODE) prefPattern = findPreference(PatternActivity.PREFERENCE_SET_PATTERN) prefBiometric = findPreference(BiometricActivity.PREFERENCE_SET_BIOMETRIC) prefLockApplication = findPreference<ListPreference>(PREFERENCE_LOCK_TIMEOUT)?.apply { entries = listOf( getString(R.string.prefs_lock_application_entries_immediately), getString(R.string.prefs_lock_application_entries_1minute), getString(R.string.prefs_lock_application_entries_5minutes), getString(R.string.prefs_lock_application_entries_30minutes) ).toTypedArray() entryValues = listOf( LockTimeout.IMMEDIATELY.name, LockTimeout.ONE_MINUTE.name, LockTimeout.FIVE_MINUTES.name, LockTimeout.THIRTY_MINUTES.name ).toTypedArray() isEnabled = !securityViewModel.isLockDelayEnforcedEnabled() } prefLockAccessDocumentProvider = findPreference(PREFERENCE_LOCK_ACCESS_FROM_DOCUMENT_PROVIDER) prefTouchesWithOtherVisibleWindows = findPreference(PREFERENCE_TOUCHES_WITH_OTHER_VISIBLE_WINDOWS) prefPasscode?.isVisible = !securityViewModel.isSecurityEnforcedEnabled() prefPattern?.isVisible = !securityViewModel.isSecurityEnforcedEnabled() // Passcode lock prefPasscode?.setOnPreferenceChangeListener { _: Preference?, newValue: Any -> if (securityViewModel.isPatternSet()) { showMessageInSnackbar(getString(R.string.pattern_already_set)) } else { val intent = Intent(activity, PassCodeActivity::class.java) if (newValue as Boolean) { intent.action = PassCodeActivity.ACTION_CREATE enablePasscodeLauncher.launch(intent) } else { intent.action = PassCodeActivity.ACTION_REMOVE disablePasscodeLauncher.launch(intent) } } false } // Pattern lock prefPattern?.setOnPreferenceChangeListener { _: Preference?, newValue: Any -> if (securityViewModel.isPasscodeSet()) { showMessageInSnackbar(getString(R.string.passcode_already_set)) } else { val intent = Intent(activity, PatternActivity::class.java) if (newValue as Boolean) { intent.action = PatternActivity.ACTION_REQUEST_WITH_RESULT enablePatternLauncher.launch(intent) } else { intent.action = PatternActivity.ACTION_CHECK_WITH_RESULT disablePatternLauncher.launch(intent) } } false } // Biometric lock if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { screenSecurity?.removePreferenceFromScreen(prefBiometric) } else if (prefBiometric != null) { if (!BiometricManager.isHardwareDetected()) { // Biometric not supported screenSecurity?.removePreferenceFromScreen(prefBiometric) } else { if (prefPasscode?.isChecked == false && prefPattern?.isChecked == false) { // Disable biometric lock if Passcode or Pattern locks are disabled disableBiometric() } prefBiometric?.setOnPreferenceChangeListener { _: Preference?, newValue: Any -> val incomingValue = newValue as Boolean // No biometric enrolled yet if (incomingValue && !BiometricManager.hasEnrolledBiometric()) { showMessageInSnackbar(getString(R.string.biometric_not_enrolled)) return@setOnPreferenceChangeListener false } true } } } // Lock application if (prefPasscode?.isChecked == false && prefPattern?.isChecked == false) { prefLockApplication?.isEnabled = false } // Lock access from document provider prefLockAccessDocumentProvider?.setOnPreferenceChangeListener { _: Preference?, newValue: Any -> securityViewModel.setPrefLockAccessDocumentProvider(true) notifyDocumentProviderRoots(requireContext()) true } // Touches with other visible windows prefTouchesWithOtherVisibleWindows?.setOnPreferenceChangeListener { _: Preference?, newValue: Any -> if (newValue as Boolean) { activity?.let { AlertDialog.Builder(it) .setTitle(getString(R.string.confirmation_touches_with_other_windows_title)) .setMessage(getString(R.string.confirmation_touches_with_other_windows_message)) .setNegativeButton(getString(R.string.common_no), null) .setPositiveButton( getString(R.string.common_yes) ) { _: DialogInterface?, _: Int -> securityViewModel.setPrefTouchesWithOtherVisibleWindows(true) prefTouchesWithOtherVisibleWindows?.isChecked = true } .show() .avoidScreenshotsIfNeeded() } return@setOnPreferenceChangeListener false } true } } private fun enableBiometricAndLockApplication() { prefBiometric?.apply { isEnabled = true summary = null } prefLockApplication?.isEnabled = !securityViewModel.isLockDelayEnforcedEnabled() } private fun disableBiometric() { prefBiometric?.apply { isChecked = false isEnabled = false summary = getString(R.string.prefs_biometric_summary) } } companion object { private const val SCREEN_SECURITY = "security_screen" const val PREFERENCE_LOCK_ACCESS_FROM_DOCUMENT_PROVIDER = "lock_access_from_document_provider" const val PREFERENCE_TOUCHES_WITH_OTHER_VISIBLE_WINDOWS = "touches_with_other_visible_windows" const val EXTRAS_LOCK_ENFORCED = "EXTRAS_LOCK_ENFORCED" const val PREFERENCE_LOCK_ATTEMPTS = "PrefLockAttempts" } }
owncloudApp/src/main/java/com/owncloud/android/presentation/ui/settings/fragments/SettingsSecurityFragment.kt
1372702478
/* * Copyright 2017 vinayagasundar * Copyright 2017 randhirgupta * * 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 you.devknights.minimalweather.network.model import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import you.devknights.minimalweather.database.entity.WeatherEntity class WeatherResponse { @SerializedName("coord") @Expose private var coord: Coord? = null @SerializedName("weather") @Expose private var weather: List<Weather>? = null @SerializedName("base") @Expose private var base: String? = null @SerializedName("main") @Expose private var main: Main? = null @SerializedName("visibility") @Expose private var visibility: Int = 0 @SerializedName("wind") @Expose private var wind: Wind? = null @SerializedName("clouds") @Expose private var clouds: Clouds? = null @SerializedName("dt") @Expose private var dt: Int = 0 @SerializedName("sys") @Expose private var sys: Sys? = null @SerializedName("id") @Expose private var id: Int = 0 @SerializedName("name") @Expose private var name: String? = null @SerializedName("cod") @Expose private var cod: Int = 0 fun buildWeather(): WeatherEntity { val weatherEntity = WeatherEntity() weatherEntity.placeId = id weatherEntity.placeName = name weatherEntity.placeLat = coord?.lat ?: 0.toDouble() weatherEntity.placeLon = coord?.lon ?: 0.toDouble() weather?.let { if (it.isNotEmpty()) { val weather = it[0] weatherEntity.weatherId = weather.id weatherEntity.weatherMain = weather.main weatherEntity.weatherDescription = weather.description weatherEntity.weatherIcon = weather.icon } } weatherEntity.temperature = main?.temp ?: 0.toFloat() weatherEntity.pressure = main?.pressure ?: 0.toFloat() weatherEntity.humidity = main?.humidity ?: 0.toFloat() weatherEntity.windSpeed = wind?.speed?.toFloat() ?: 0.toFloat() weatherEntity.sunriseTime = sys?.sunrise ?: 0 weatherEntity.sunsetTime = sys?.sunset ?: 0 return weatherEntity } }
app/src/main/java/you/devknights/minimalweather/network/model/WeatherResponse.kt
3005822573
/* * Copyright (c) 2021 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.lib.intent import android.content.Intent class ShareIntentFactory { /** * Make sharing message intent. * * @param message * @return Intent */ operator fun invoke(message: String, subject: String? = null): Intent { val intent = Intent().also { it.action = Intent.ACTION_SEND it.type = "text/plain" it.putExtra(Intent.EXTRA_TEXT, message) subject?.also { subject -> it.putExtra(Intent.EXTRA_SUBJECT, subject); } } return Intent.createChooser(intent, "Select app for share") } }
lib/src/main/java/jp/toastkid/lib/intent/ShareIntentFactory.kt
807570922
package com.s13g.aoc.aoc2019 import com.s13g.aoc.Result import com.s13g.aoc.Solver import java.lang.Integer.max /** https://adventofcode.com/2019/day/7 */ class Day7 : Solver { override fun solve(lines: List<String>): Result { val input = lines[0].split(",").map { it.toInt() } var maxThrusterA = 0 for (phasing in genPerms(0, mutableListOf())) { maxThrusterA = max(maxThrusterA, runA(phasing, input)) } var maxThrusterB = 0 for (phasing in genPerms(0, mutableListOf(), 5)) { maxThrusterB = max(maxThrusterB, runB(phasing, input)) } return Result("$maxThrusterA", "$maxThrusterB") } private fun genPerms(n: Int, list: MutableList<Int>, offset: Int = 0): MutableList<List<Int>> { if (n > 4) return mutableListOf(list) val result = mutableListOf<List<Int>>() for (x in offset..offset + 4) { if (x in list) continue val listX = ArrayList(list) listX.add(x) result.addAll(genPerms(n + 1, listX, offset)) } return result } private fun runA(phasing: List<Int>, program: List<Int>): Int { val vms = (0..4).map { createVm(program.toMutableList(), mutableListOf(phasing[it])) } var lastOutput = 0 for (vm in vms) { vm.addInput(lastOutput) lastOutput = vm.run() } return lastOutput } private fun runB(phasing: List<Int>, program: List<Int>): Int { val vms = (0..4).map { createVm(program.toMutableList(), mutableListOf(phasing[it])) } for (i in 0..4) { vms[i].sendOutputTo(vms[(i + 1) % vms.size]) } vms[0].addInput(0) while (!vms[4].isHalted) { for (vm in vms) { vm.step() } } return vms[4].lastOutput.toInt() } }
kotlin/src/com/s13g/aoc/aoc2019/Day7.kt
2552914498
@file:Suppress("unused", "UNUSED_TYPEALIAS_PARAMETER") package enzyme typealias StatelessComponent<Props> = (props: Props, context: Any? /* = null */) -> JsxElement? typealias ReactElement<@Suppress("UNUSED_TYPEALIAS_PARAMETER") P> = react.ReactElement // todo what should this be? typealias JsxElement = react.ReactElement typealias Intercepter<T> = (intercepter: T) -> Unit typealias Parameters<T> = Any
src/jsTest/kotlin/enzyme/enzyme_non_externals.kt
2017088528
/** * DO NOT EDIT THIS FILE. * * This source code was autogenerated from source code within the `app/src/gms` directory * and is not intended for modifications. If any edits should be made, please do so in the * corresponding file under the `app/src/gms` directory. */ /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.kotlindemos import android.graphics.Color import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.google.android.libraries.maps.CameraUpdateFactory import com.google.android.libraries.maps.GoogleMap import com.google.android.libraries.maps.SupportMapFragment import com.google.android.libraries.maps.model.BitmapDescriptorFactory import com.google.android.libraries.maps.model.Circle import com.google.android.libraries.maps.model.CircleOptions import com.google.android.libraries.maps.model.GroundOverlay import com.google.android.libraries.maps.model.GroundOverlayOptions import com.google.android.libraries.maps.model.LatLng import com.google.android.libraries.maps.model.LatLngBounds import com.google.android.libraries.maps.model.Marker import com.google.android.libraries.maps.model.MarkerOptions import com.google.android.libraries.maps.model.Polygon import com.google.android.libraries.maps.model.PolygonOptions import com.google.android.libraries.maps.model.Polyline import com.google.android.libraries.maps.model.PolylineOptions /** * This shows how to use setTag/getTag on API objects. */ class TagsDemoActivity : AppCompatActivity(), GoogleMap.OnCircleClickListener, GoogleMap.OnGroundOverlayClickListener, GoogleMap.OnMarkerClickListener, OnMapAndViewReadyListener.OnGlobalLayoutAndMapReadyListener, GoogleMap.OnPolygonClickListener, GoogleMap.OnPolylineClickListener { private lateinit var map: GoogleMap private lateinit var tagText: TextView private val places = mapOf( "BRISBANE" to LatLng(-27.47093, 153.0235), "MELBOURNE" to LatLng(-37.81319, 144.96298), "DARWIN" to LatLng(-12.4634, 130.8456), "SYDNEY" to LatLng(-33.87365, 151.20689), "ADELAIDE" to LatLng(-34.92873, 138.59995), "PERTH" to LatLng(-31.952854, 115.857342), "ALICE_SPRINGS" to LatLng(-24.6980, 133.8807), "HOBART" to LatLng(-42.8823388, 147.311042) ) /** * Class to store a tag to attach to a map object to keep track of * how many times it has been clicked */ private class CustomTag(private val description: String) { private var clickCount: Int = 0 fun incrementClickCount() { clickCount++ } override fun toString() = "The $description has been clicked $clickCount times." } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.tags_demo) tagText = findViewById(R.id.tag_text) val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment OnMapAndViewReadyListener(mapFragment, this) } override fun onMapReady(googleMap: GoogleMap?) { // return early if the map was not initialised properly map = googleMap ?: return // Add a circle, a ground overlay, a marker, a polygon and a polyline to the googleMap. addObjectsToMap() with(map.uiSettings) { // Turn off the map toolbar. isMapToolbarEnabled = false // Disable interaction with the map - other than clicking. isZoomControlsEnabled = false isScrollGesturesEnabled = false isZoomGesturesEnabled = false isTiltGesturesEnabled = false isRotateGesturesEnabled = false } with(map) { // Set listeners for click events. See the bottom of this class for their behavior. setOnCircleClickListener(this@TagsDemoActivity) setOnGroundOverlayClickListener(this@TagsDemoActivity) setOnMarkerClickListener(this@TagsDemoActivity) setOnPolygonClickListener(this@TagsDemoActivity) setOnPolylineClickListener(this@TagsDemoActivity) // Override the default content description on the view, for accessibility mode. // Ideally this string would be localised. setContentDescription(getString(R.string.tags_demo_map_description)) // include all places we have markers for in the initial view of the map val boundsBuilder = LatLngBounds.Builder() places.keys.map { boundsBuilder.include(places.getValue(it)) } // Move the camera to view all listed locations moveCamera(CameraUpdateFactory.newLatLngBounds(boundsBuilder.build(), 100)) } } private fun addObjectsToMap() { with(map) { // A circle centered on Adelaide. addCircle(CircleOptions().apply { center(places.getValue("ADELAIDE")) radius(500000.0) fillColor(Color.argb(150, 66, 173, 244)) strokeColor(Color.rgb(66, 173, 244)) clickable(true) }).run { // add a tag to the circle to count clicks //tag = String("Adelaide circle") tag = "hello" } // A ground overlay at Sydney. addGroundOverlay(GroundOverlayOptions().apply { image(BitmapDescriptorFactory.fromResource(R.drawable.harbour_bridge)) position(places.getValue("SYDNEY"), 700000f) clickable(true) }).run { // add a tag to the overlay to count clicks tag = CustomTag("Sydney ground overlay") } // A marker at Hobart. addMarker(MarkerOptions().apply { position(places.getValue("HOBART")) }).run { // add a tag to the marker to count clicks tag = CustomTag("Hobart marker") } // A polygon centered at Darwin. addPolygon(PolygonOptions().apply{ add(LatLng(places.getValue("DARWIN").latitude + 3, places.getValue("DARWIN").longitude - 3), LatLng(places.getValue("DARWIN").latitude + 3, places.getValue("DARWIN").longitude + 3), LatLng(places.getValue("DARWIN").latitude - 3, places.getValue("DARWIN").longitude + 3), LatLng(places.getValue("DARWIN").latitude - 3, places.getValue("DARWIN").longitude - 3)) fillColor(Color.argb(150, 34, 173, 24)) strokeColor(Color.rgb(34, 173, 24)) clickable(true) }).run { // add a tag to the marker to count clicks tag = CustomTag("Darwin polygon") } // A polyline from Perth to Brisbane. addPolyline(PolylineOptions().apply{ add(places.getValue("PERTH"), places.getValue("BRISBANE")) color(Color.rgb(103, 24, 173)) width(30f) clickable(true) }).run { // add a tag to the polyline to count clicks tag = CustomTag("Perth to Brisbane polyline") } } } // Click event listeners. private fun onClick(tag: CustomTag) { tag.incrementClickCount() tagText.text = tag.toString() } override fun onCircleClick(circle: Circle) { onClick(circle.tag as? CustomTag ?: return) } override fun onGroundOverlayClick(groundOverlay: GroundOverlay) { onClick(groundOverlay.tag as? CustomTag ?: return) } override fun onMarkerClick(marker: Marker): Boolean { onClick(marker.tag as? CustomTag ?: return false) // We return true to indicate that we have consumed the event and that we do not wish // for the default behavior to occur (which is for the camera to move such that the // marker is centered and for the marker's info window to open, if it has one). return true } override fun onPolygonClick(polygon: Polygon) { onClick(polygon.tag as? CustomTag ?: return) } override fun onPolylineClick(polyline: Polyline) { onClick(polyline.tag as? CustomTag ?: return) } }
ApiDemos/kotlin/app/src/v3/java/com/example/kotlindemos/TagsDemoActivity.kt
1426308913
package com.eden.orchid.impl.compilers.pebble import com.eden.orchid.api.events.OrchidEventListener import com.eden.orchid.api.registration.OrchidModule import com.mitchellbosecke.pebble.attributes.AttributeResolver import com.mitchellbosecke.pebble.extension.Extension class PebbleModule : OrchidModule() { override fun configure() { // Pebble Extensions addToSet(AttributeResolver::class.java) // addToSet(AttributeResolver.class, // GetMethodAttributeResolver.class); addToSet( Extension::class.java, CorePebbleExtension::class.java ) addToSet( OrchidEventListener::class.java, PebbleCompiler::class.java ) } }
OrchidCore/src/main/kotlin/com/eden/orchid/impl/compilers/pebble/PebbleModule.kt
2341252094
package com.tomash.testapp import android.content.Context import com.tomash.androidcontacts.contactgetter.entity.ContactData import com.tomash.androidcontacts.contactgetter.main.contactsDeleter.ContactsDeleter class DeleteExample( val deleter: ContactsDeleter ) { fun create(context: Context) { val contactsDeleter = ContactsDeleter(context) } fun deleteOneContact(contactData: ContactData) { //usual delete with no need of callbacks deleter.deleteContact(contactData) //full range of callbacks, implement any you need deleter.deleteContact(contactData) { onCompleted { } onFailure { } onResult { } doFinally { } } } fun deleteMultipleContacts(contactDatas: List<ContactData>) { //usual delete with no need of callbacks deleter.deleteContacts(contactDatas) //full range of callbacks, implement any you need deleter.deleteContacts(contactDatas) { onCompleted { } onFailure { } onResult { } doFinally { } } } }
testapp/src/main/java/com/tomash/testapp/DeleteExample.kt
804250769
package org.jetbrains.dokka import org.jetbrains.dokka.DokkaConfiguration.ExternalDocumentationLink import java.net.URL fun ExternalDocumentationLink.Companion.jdk(jdkVersion: Int): ExternalDocumentationLinkImpl = ExternalDocumentationLink( url = if (jdkVersion < 11) "https://docs.oracle.com/javase/${jdkVersion}/docs/api/" else "https://docs.oracle.com/en/java/javase/${jdkVersion}/docs/api/", packageListUrl = if (jdkVersion < 11) "https://docs.oracle.com/javase/${jdkVersion}/docs/api/package-list" else "https://docs.oracle.com/en/java/javase/${jdkVersion}/docs/api/element-list" ) fun ExternalDocumentationLink.Companion.kotlinStdlib(): ExternalDocumentationLinkImpl = ExternalDocumentationLink("https://kotlinlang.org/api/latest/jvm/stdlib/") fun ExternalDocumentationLink.Companion.androidSdk(): ExternalDocumentationLinkImpl = ExternalDocumentationLink("https://developer.android.com/reference/kotlin/") fun ExternalDocumentationLink.Companion.androidX(): ExternalDocumentationLinkImpl = ExternalDocumentationLink( url = URL("https://developer.android.com/reference/kotlin/"), packageListUrl = URL("https://developer.android.com/reference/kotlin/androidx/package-list") )
core/src/main/kotlin/defaultExternalLinks.kt
1608991854
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 example.grpc import com.google.api.kgax.grpc.StubFactory import com.google.cloud.language.v1.AnalyzeEntitiesRequest import com.google.cloud.language.v1.Document import com.google.cloud.language.v1.LanguageServiceGrpc import kotlinx.coroutines.runBlocking import java.io.File /** * Simple example of calling the Language API with KGax. * * Run this example using your service account as follows: * * ``` * $ CREDENTIALS=<path_to_your_service_account.json> ./gradlew examples:run --args language * ``` */ fun languageExample(credentials: String) = runBlocking { // create a stub factory val factory = StubFactory( LanguageServiceGrpc.LanguageServiceFutureStub::class, "language.googleapis.com", 443 ) // create a stub val stub = File(credentials).inputStream().use { factory.fromServiceAccount(it, listOf("https://www.googleapis.com/auth/cloud-platform")) } // call the API val response = stub.execute { it.analyzeEntities( AnalyzeEntitiesRequest.newBuilder().apply { document = Document.newBuilder().apply { content = "Hi there Joe" type = Document.Type.PLAIN_TEXT }.build() }.build() ) } println("The API says: $response") // shutdown all connections factory.shutdown() }
examples/src/main/kotlin/example/grpc/Language.kt
672558826
package com.github.shynixn.blockball.core.logic.persistence.event import com.github.shynixn.blockball.api.business.proxy.BallProxy class BallDeathEventEntity(ball: BallProxy) : BallEventEntity(ball)
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/persistence/event/BallDeathEventEntity.kt
1385650416
package com.philsoft.metrotripper.app.state.transformer import com.philsoft.metrotripper.app.state.AppState import com.philsoft.metrotripper.app.state.MapUiEvent.MarkerClicked import com.philsoft.metrotripper.app.state.NexTripAction import com.philsoft.metrotripper.app.state.SlidingPanelUiEvent.SlidingPanelExpanded import com.philsoft.metrotripper.app.state.StopHeadingUiEvent.ScheduleButtonClicked import com.philsoft.metrotripper.app.state.StopListUiEvent.StopSearched import com.philsoft.metrotripper.app.state.StopListUiEvent.StopSelectedFromDrawer import com.philsoft.metrotripper.model.Stop class NexTripApiActionTransformer : ViewActionTransformer<NexTripAction>() { override fun handleEvent(state: AppState) = state.run { when (appUiEvent) { is ScheduleButtonClicked -> handleScheduleButtonClicked(selectedStop) is MarkerClicked -> handleMarkerClicked(appUiEvent.stopId) is StopSearched -> handleStopSearched(appUiEvent.stopId) is StopSelectedFromDrawer -> handleStopSelected(appUiEvent.stop) is SlidingPanelExpanded -> handlePanelExpanded(selectedStop) } Unit } private fun handleStopSelected(stop: Stop) { send(NexTripAction.GetTrips(stop.stopId)) } private fun handlePanelExpanded(selectedStop: Stop?) { if (selectedStop != null) { send(NexTripAction.GetTrips(selectedStop.stopId)) } } private fun handleMarkerClicked(stopId: Long) { send(NexTripAction.GetTrips(stopId)) } private fun handleScheduleButtonClicked(selectedStop: Stop?) { if (selectedStop != null) { send(NexTripAction.GetTrips(selectedStop.stopId)) } } private fun handleStopSearched(stopId: Long) { send(NexTripAction.GetTrips(stopId)) } }
app/src/main/java/com/philsoft/metrotripper/app/state/transformer/NexTripApiActionTransformer.kt
800306723
package link.kotlin.scripts import link.kotlin.scripts.dsl.Category import link.kotlin.scripts.dsl.Subcategory import link.kotlin.scripts.model.Link import link.kotlin.scripts.utils.Cache import org.jsoup.Jsoup import java.time.LocalDate import java.time.format.DateTimeFormatter private val trending = listOf( "Monthly" to "https://github.com/trending/kotlin?since=monthly", "Weekly" to "https://github.com/trending/kotlin?since=weekly", "Daily" to "https://github.com/trending/kotlin?since=daily" ) interface GithubTrending { suspend fun fetch(): Category? companion object } private class CachedGithubTrending( private val cache: Cache, private val githubTrending: GithubTrending ) : GithubTrending { override suspend fun fetch(): Category? { val date = DateTimeFormatter.BASIC_ISO_DATE.format(LocalDate.now()) val cacheKey = "github-trending-$date" val cacheValue = cache.get(cacheKey, Category::class) return if (cacheValue == null) { val result = githubTrending.fetch() result ?: cache.put(cacheKey, result) result } else cacheValue } } private class JSoupGithubTrending( ) : GithubTrending { override suspend fun fetch(): Category? { val subcategories = trending.mapNotNull { it.toSubcategory() } .deleteDuplicates() .toMutableList() return if (subcategories.isNotEmpty()) { Category( name = "Github Trending", subcategories = subcategories ) } else null } private fun List<Subcategory>.deleteDuplicates(): List<Subcategory> { val pool = mutableSetOf<Link>() return this.map { subcategory -> val filtered = subcategory.links.subtract(pool) val result = subcategory.copy(links = filtered.toMutableList()) pool.addAll(subcategory.links) result } } private fun Pair<String, String>.toSubcategory(): Subcategory? { val doc = Jsoup.connect(this.second).get() val isAvailable = doc.select(".Box-row").isNotEmpty() return if (isAvailable) { val links = doc.select(".Box-row").map { Link( github = it.select("h1 a").attr("href").removePrefix("/") ) } return Subcategory( name = this.first, links = links.toMutableList() ) } else { null } } } fun GithubTrending.Companion.default( cache: Cache ): GithubTrending { val jSoupGithubTrending = JSoupGithubTrending() return CachedGithubTrending( cache = cache, githubTrending = jSoupGithubTrending ) }
src/main/kotlin/link/kotlin/scripts/GithubTrending.kt
2726482676
package com.pollvaults.deming.adapters import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.pollvaults.deming.models.firebase.PollModel class PollAdapter(val polls : List<PollModel>) : RecyclerView.Adapter<PollViewHolder>() { override fun onBindViewHolder(holder: PollViewHolder, position: Int) { val textView = holder.itemView as TextView textView.setText(this.polls.get(position).title) } override fun getItemCount(): Int { return this.polls.size } override fun onCreateViewHolder(parent: ViewGroup, position: Int): PollViewHolder { val v = LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_1, null) return PollViewHolder(v) } } class PollViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
PollVaults/app/src/main/java/com/pollvaults/deming/adapters/PollAdapter.kt
642148945
package com.airbnb.mvrx import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry class TestLifecycleOwner : LifecycleOwner { private val _lifecycle = LifecycleRegistry(this) override fun getLifecycle(): LifecycleRegistry = _lifecycle }
mvrx/src/test/kotlin/com/airbnb/mvrx/TestLifecycleOwner.kt
277135914
package org.http4k.filter import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.http4k.core.ContentType import org.http4k.core.Method.POST import org.http4k.core.MultipartFormBody import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.core.with import org.http4k.hamkrest.hasBody import org.http4k.lens.Header import org.http4k.lens.MultipartFormFile import org.junit.jupiter.api.Test class FiltersTest { @Test fun `process files filter and convert form from multipart webform`() { val form = MultipartFormBody("bob") + ("field" to "bar") + ("file" to MultipartFormFile("foo.txt", ContentType.TEXT_PLAIN, "content".byteInputStream())) + ("field" to "bar") val req = Request(POST, "") .with(Header.CONTENT_TYPE of ContentType.MultipartFormWithBoundary(form.boundary)) .body(form) val files = mutableListOf<String>() val service = ServerFilters.ProcessFiles { files.add(it.file.filename) it.file.filename }.then { r: Request -> Response(OK).body(r.body) } val response = service(req) assertThat(files, equalTo(listOf("foo.txt"))) assertThat(response, hasBody("field=bar&file=foo.txt&field=bar")) } }
http4k-multipart/src/test/kotlin/org/http4k/filter/FiltersTest.kt
1749378314
/* * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 org.springframework.boot.docs.actuator.metrics.supported.mongodb.connectionpool import com.mongodb.event.ConnectionPoolCreatedEvent import io.micrometer.core.instrument.Tag import io.micrometer.core.instrument.binder.mongodb.MongoConnectionPoolTagsProvider class CustomConnectionPoolTagsProvider : MongoConnectionPoolTagsProvider { override fun connectionPoolTags(event: ConnectionPoolCreatedEvent): Iterable<Tag> { return emptyList() } }
spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/actuator/metrics/supported/mongodb/connectionpool/CustomConnectionPoolTagsProvider.kt
2444123640
package com.mifos.mifosxdroid.online.datatable import com.mifos.mifosxdroid.base.MvpView import com.mifos.objects.noncore.DataTable /** * Created by Rajan Maurya on 12/02/17. */ interface DataTableMvpView : MvpView { fun showUserInterface() fun showDataTables(dataTables: List<DataTable>?) fun showEmptyDataTables() fun showResetVisibility() fun showError(message: Int) }
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/datatable/DataTableMvpView.kt
1979642985
/* * This project is licensed under the open source MPL V2. * See https://github.com/openMF/android-client/blob/master/LICENSE.md */ package com.mifos.mifosxdroid.online import android.os.Bundle import android.util.Log import android.view.View import android.widget.Button import android.widget.TextView import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.viewpager.widget.PagerAdapter import androidx.viewpager.widget.ViewPager import androidx.viewpager.widget.ViewPager.OnPageChangeListener import butterknife.BindView import butterknife.ButterKnife import butterknife.OnClick import com.google.gson.Gson import com.mifos.mifosxdroid.R import com.mifos.mifosxdroid.adapters.SurveyPagerAdapter import com.mifos.mifosxdroid.core.MifosBaseActivity import com.mifos.mifosxdroid.online.SurveyQuestionFragment.OnAnswerSelectedListener import com.mifos.mifosxdroid.online.surveysubmit.SurveySubmitFragment.Companion.newInstance import com.mifos.mifosxdroid.online.surveysubmit.SurveySubmitFragment.DisableSwipe import com.mifos.objects.survey.Scorecard import com.mifos.objects.survey.ScorecardValues import com.mifos.objects.survey.Survey import com.mifos.utils.Constants import com.mifos.utils.PrefManager import java.util.* /** * Created by Nasim Banu on 28,January,2016. */ class SurveyQuestionActivity : MifosBaseActivity(), OnAnswerSelectedListener, DisableSwipe, OnPageChangeListener { @JvmField @BindView(R.id.surveyPager) var mViewPager: ViewPager? = null @JvmField @BindView(R.id.btnNext) var btnNext: Button? = null @JvmField @BindView(R.id.tv_surveyEmpty) var tv_surveyEmpty: TextView? = null @JvmField @BindView(R.id.toolbar) var mToolbar: Toolbar? = null private val fragments: MutableList<Fragment> = Vector() private val listScorecardValues: MutableList<ScorecardValues> = ArrayList() private var survey: Survey? = null private val mScorecard = Scorecard() private var mScorecardValue: ScorecardValues? = null private var mMapScores = HashMap<Int, ScorecardValues>() private var clientId = 0 private var mCurrentQuestionPosition = 1 var fragmentCommunicator: Communicator? = null private var mPagerAdapter: PagerAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_survey_question) ButterKnife.bind(this) //Getting Survey Gson Object val mIntent = intent survey = Gson().fromJson(mIntent.getStringExtra(Constants.SURVEYS), Survey::class.java) clientId = mIntent.getIntExtra(Constants.CLIENT_ID, 1) setSubtitleToolbar() mPagerAdapter = SurveyPagerAdapter(supportFragmentManager, fragments) mViewPager!!.adapter = mPagerAdapter mViewPager!!.addOnPageChangeListener(this) loadSurvey(survey) val actionBar = supportActionBar actionBar!!.setDisplayHomeAsUpEnabled(true) } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} override fun onPageSelected(position: Int) { updateAnswerList() mCurrentQuestionPosition = position + 1 setSubtitleToolbar() } override fun onPageScrollStateChanged(state: Int) {} @OnClick(R.id.btnNext) fun onClickButtonNext() { updateAnswerList() mViewPager!!.setCurrentItem(mViewPager!!.currentItem + 1, true) setSubtitleToolbar() } override fun answer(scorecardValues: ScorecardValues?) { mScorecardValue = scorecardValues } fun loadSurvey(survey: Survey?) { if (survey != null) { if (survey.questionDatas != null && survey.questionDatas.size > 0) { for (i in survey.questionDatas.indices) { fragments.add(SurveyQuestionFragment.newInstance(Gson().toJson(survey .questionDatas[i]))) } fragments.add(newInstance()) mPagerAdapter!!.notifyDataSetChanged() } else { mViewPager!!.visibility = View.GONE btnNext!!.visibility = View.GONE tv_surveyEmpty!!.visibility = View.VISIBLE } } } fun setUpScoreCard() { listScorecardValues.clear() for ((_, value) in mMapScores) { listScorecardValues.add(value) } mScorecard.clientId = clientId mScorecard.userId = PrefManager.getUserId() mScorecard.createdOn = Date() mScorecard.scorecardValues = listScorecardValues } fun updateAnswerList() { if (mScorecardValue != null) { Log.d(LOG_TAG, "" + mScorecardValue!!.questionId + mScorecardValue!! .responseId + mScorecardValue!!.value) mMapScores[mScorecardValue!!.questionId] = mScorecardValue!! mScorecardValue = null } nextButtonState() if (fragmentCommunicator != null) { setUpScoreCard() fragmentCommunicator!!.passScoreCardData(mScorecard, survey!!.id) } } fun nextButtonState() { if (mViewPager!!.currentItem == mPagerAdapter!!.count - 1) { btnNext!!.visibility = View.GONE } else { btnNext!!.visibility = View.VISIBLE } } fun setSubtitleToolbar() { if (survey!!.questionDatas.size == 0) { mToolbar!!.subtitle = resources.getString(R.string.survey_subtitle) } else if (mCurrentQuestionPosition <= survey!!.questionDatas.size) { mToolbar!!.subtitle = mCurrentQuestionPosition.toString() + resources.getString(R.string.slash) + survey!!.questionDatas.size } else { mToolbar!!.subtitle = resources.getString(R.string.submit_survey) } } override fun disableSwipe() { mViewPager!!.beginFakeDrag() mToolbar!!.subtitle = null } public override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putSerializable(Constants.ANSWERS, mMapScores) } public override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) mMapScores = savedInstanceState.getSerializable(Constants.ANSWERS) as HashMap<Int, ScorecardValues> } companion object { val LOG_TAG = SurveyQuestionActivity::class.java.simpleName } }
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/SurveyQuestionActivity.kt
569533880
package io.envoyproxy.envoymobile /** * Mock implementation of `StreamClient` which produces `MockStreamPrototype` values. * * @param onStartStream Closure that may be set to observe the creation of new streams. * It will be called each time `newStreamPrototype()` is executed. * Typically, this is used to capture streams on creation before sending values through them. */ class MockStreamClient(var onStartStream: ((MockStream) -> Unit)?) : StreamClient { override fun newStreamPrototype(): StreamPrototype { return MockStreamPrototype { onStartStream?.invoke(it) } } }
mobile/library/kotlin/io/envoyproxy/envoymobile/mocks/MockStreamClient.kt
1064920950
/* * Copyright 2017 Farbod Salamat-Zadeh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package co.timetableapp.ui.classes import android.app.Activity import android.content.Intent import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v7.widget.Toolbar import android.text.Html import android.view.View import android.widget.LinearLayout import android.widget.TextView import co.timetableapp.R import co.timetableapp.TimetableApplication import co.timetableapp.data.handler.* import co.timetableapp.data.query.Filters import co.timetableapp.data.query.Query import co.timetableapp.data.schema.AssignmentsSchema import co.timetableapp.data.schema.ExamsSchema import co.timetableapp.model.Class import co.timetableapp.model.ClassTime import co.timetableapp.model.Color import co.timetableapp.model.Subject import co.timetableapp.ui.agenda.AgendaActivity import co.timetableapp.ui.base.ItemDetailActivity import co.timetableapp.ui.base.ItemEditActivity import co.timetableapp.ui.components.CardOfItems import co.timetableapp.util.DateUtils import co.timetableapp.util.UiUtils /** * Shows the details of a class. * * @see Class * @see ClassesActivity * @see ClassEditActivity * @see ItemDetailActivity */ class ClassDetailActivity : ItemDetailActivity<Class>() { private lateinit var mColor: Color override fun initializeDataHandler() = ClassHandler(this) override fun getLayoutResource() = R.layout.activity_class_detail override fun onNullExtras() { val intent = Intent(this, ClassEditActivity::class.java) ActivityCompat.startActivityForResult(this, intent, REQUEST_CODE_ITEM_EDIT, null) } override fun setupLayout() { setupToolbar() setupClassDetailCard() findViewById(R.id.main_card).setBackgroundColor( ContextCompat.getColor(this, mColor.getLightAccentColorRes(this))) setupRelatedItemCards() } private fun setupToolbar() { val subject = Subject.create(this, mItem.subjectId) val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) toolbar.navigationIcon = UiUtils.tintDrawable(this, R.drawable.ic_arrow_back_black_24dp) toolbar.setNavigationOnClickListener { saveEditsAndClose() } supportActionBar!!.title = mItem.makeName(subject) mColor = Color(subject.colorId) UiUtils.setBarColors(mColor, this, toolbar) } /** * Adds content to a card displaying details about the class (such as locations, teachers, and * the times of the class). */ private fun setupClassDetailCard() { val locationBuilder = StringBuilder() val teacherBuilder = StringBuilder() val allClassTimes = ArrayList<ClassTime>() // Add locations, teachers, and times to StringBuilders or ArrayLists, with no duplicates ClassDetailHandler.getClassDetailsForClass(this, mItem.id).forEach { classDetail -> classDetail.formatLocationName()?.let { if (!locationBuilder.contains(it)) { locationBuilder.append(it).append("\n") } } if (classDetail.hasTeacher()) { if (!teacherBuilder.contains(classDetail.teacher)) { teacherBuilder.append(classDetail.teacher).append("\n") } } allClassTimes.addAll(ClassTimeHandler.getClassTimesForDetail(this, classDetail.id)) } setClassDetailTexts( locationBuilder.toString().removeSuffix("\n"), teacherBuilder.toString().removeSuffix("\n"), produceClassTimesText(allClassTimes)) } /** * @return the list of class times as a formatted string */ private fun produceClassTimesText(classTimes: ArrayList<ClassTime>): String { classTimes.sort() val stringBuilder = StringBuilder() // Add all time texts - not expecting duplicate values for times classTimes.forEach { val dayString = it.day.toString() val formattedDayString = dayString.substring(0, 1).toUpperCase() + dayString.substring(1).toLowerCase() stringBuilder.append(formattedDayString) val weekText = it.getWeekText(this) if (weekText.isNotEmpty()) { stringBuilder.append(" ") .append(weekText) } stringBuilder.append(", ") .append(it.startTime.toString()) .append(" - ") .append(it.endTime.toString()) .append("\n") } return stringBuilder.toString().removeSuffix("\n") } /** * Sets the text on the TextViews for the class detail data. * Appropriate parts of the UI will not be displayed (i.e. when there is no text for an item). * * @param locations text to be displayed for the class locations * @param teachers text to be displayed for the teachers of the class * @param classTimes text to be displayed for the class times */ private fun setClassDetailTexts(locations: String, teachers: String, classTimes: String) { val locationVisibility = if (locations.isEmpty()) View.GONE else View.VISIBLE findViewById(R.id.viewGroup_location).visibility = locationVisibility if (locations.isNotEmpty()) { (findViewById(R.id.textView_location) as TextView).text = locations } val teacherVisibility = if (teachers.isEmpty()) View.GONE else View.VISIBLE findViewById(R.id.viewGroup_teacher).visibility = teacherVisibility if (teachers.isNotEmpty()) { (findViewById(R.id.textView_teacher) as TextView).text = teachers } // No need to check if it's empty - all class details must have a class time val textViewTimes = findViewById(R.id.textView_times) as TextView textViewTimes.text = classTimes } /** * Sets up the UI for cards displaying items related to this class, such as assignments and * exams for this class. */ private fun setupRelatedItemCards() { val cardContainer = findViewById(R.id.card_container) as LinearLayout val assignmentsCard = CardOfItems.Builder(this, cardContainer) .setTitle(R.string.title_assignments) .setItems(createAssignmentItems()) .setItemsIconResource(R.drawable.ic_homework_black_24dp) .setButtonProperties(R.string.view_all, View.OnClickListener { startActivity(Intent(this@ClassDetailActivity, AgendaActivity::class.java)) }) .build() .view cardContainer.addView(assignmentsCard) val examsCard = CardOfItems.Builder(this, cardContainer) .setTitle(R.string.title_exams) .setItems(createExamItems()) .setItemsIconResource(R.drawable.ic_assessment_black_24dp) .setButtonProperties(R.string.view_all, View.OnClickListener { startActivity(Intent(this@ClassDetailActivity, AgendaActivity::class.java)) }) .build() .view cardContainer.addView(examsCard) } private fun createAssignmentItems(): ArrayList<CardOfItems.CardItem> { val timetableId = (application as TimetableApplication).currentTimetable!!.id // Get assignments for this class val query = Query.Builder() .addFilter(Filters.equal(AssignmentsSchema.COL_TIMETABLE_ID, timetableId.toString())) .addFilter(Filters.equal(AssignmentsSchema.COL_CLASS_ID, mItem.id.toString())) .build() // Create items val items = ArrayList<CardOfItems.CardItem>() val formatter = DateUtils.FORMATTER_FULL_DATE AssignmentHandler(this).getAllItems(query).forEach { if (it.isUpcoming() || it.isOverdue()) { val subtitle = if (it.isOverdue()) { "<font color=\"#F44336\"><b>${getString(R.string.due_overdue)}</b> \u2022 " + "${it.dueDate.format(formatter)}</font>" } else { it.dueDate.format(formatter) } items.add(CardOfItems.CardItem( it.title, Html.fromHtml(subtitle) )) } } return items } private fun createExamItems(): ArrayList<CardOfItems.CardItem> { val timetableId = (application as TimetableApplication).currentTimetable!!.id // Get exams for this class (actually for the subject of the class) val query = Query.Builder() .addFilter(Filters.equal(ExamsSchema.COL_TIMETABLE_ID, timetableId.toString())) .addFilter(Filters.equal(ExamsSchema.COL_SUBJECT_ID, mItem.subjectId.toString())) .build() // Create items val items = ArrayList<CardOfItems.CardItem>() val formatter = DateUtils.FORMATTER_FULL_DATE val subject = Subject.create(this, mItem.subjectId) ExamHandler(this).getAllItems(query).forEach { if (it.isUpcoming()) { items.add(CardOfItems.CardItem( it.makeName(subject), Html.fromHtml(it.date.format(formatter)) )) } } return items } override fun onMenuEditClick() { val intent = Intent(this, ClassEditActivity::class.java) intent.putExtra(ItemEditActivity.EXTRA_ITEM, mItem) ActivityCompat.startActivityForResult(this, intent, REQUEST_CODE_ITEM_EDIT, null) } override fun cancelAndClose() { setResult(Activity.RESULT_CANCELED) supportFinishAfterTransition() } override fun saveEditsAndClose() { setResult(Activity.RESULT_OK) // to reload any changes in ClassesActivity supportFinishAfterTransition() } override fun saveDeleteAndClose() { setResult(Activity.RESULT_OK) // to reload any changes in ClassesActivity finish() } }
app/src/main/java/co/timetableapp/ui/classes/ClassDetailActivity.kt
3573697202
package com.byagowi.persiancalendar.ui.shared import android.content.Context import android.graphics.Typeface import android.util.AttributeSet import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.byagowi.persiancalendar.R import com.byagowi.persiancalendar.databinding.CalendarItemBinding import com.byagowi.persiancalendar.databinding.CalendarsViewBinding import com.byagowi.persiancalendar.utils.* import io.github.persiancalendar.calendar.CivilDate import io.github.persiancalendar.praytimes.Clock import java.util.* import kotlin.math.abs class CalendarsView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : FrameLayout(context, attrs) { private val calendarItemAdapter = CalendarItemAdapter(context) private val binding: CalendarsViewBinding = CalendarsViewBinding.inflate(context.layoutInflater, this, true).apply { root.setOnClickListener { expand(!calendarItemAdapter.isExpanded) } extraInformationContainer.visibility = View.GONE calendarsRecyclerView.apply { layoutManager = LinearLayoutManager(context).apply { orientation = RecyclerView.HORIZONTAL } adapter = calendarItemAdapter } } fun hideMoreIcon() { binding.moreCalendar.visibility = View.GONE } fun expand(expanded: Boolean) { calendarItemAdapter.isExpanded = expanded binding.moreCalendar.setImageResource( if (expanded) R.drawable.ic_keyboard_arrow_up else R.drawable.ic_keyboard_arrow_down ) binding.extraInformationContainer.visibility = if (expanded) View.VISIBLE else View.GONE } fun showCalendars( jdn: Long, chosenCalendarType: CalendarType, calendarsToShow: List<CalendarType> ) { val context = context ?: return calendarItemAdapter.setDate(calendarsToShow, jdn) binding.weekDayName.text = getWeekDayName(CivilDate(jdn)) binding.zodiac.apply { text = getZodiacInfo(context, jdn, true) visibility = if (text.isEmpty()) View.GONE else View.VISIBLE } val selectedDayAbsoluteDistance = abs(getTodayJdn() - jdn) if (selectedDayAbsoluteDistance == 0L) { if (isForcedIranTimeEnabled) binding.weekDayName.text = "%s (%s)".format( getWeekDayName(CivilDate(jdn)), context.getString(R.string.iran_time) ) binding.diffDate.visibility = View.GONE } else { binding.diffDate.visibility = View.VISIBLE val civilBase = CivilDate(2000, 1, 1) val civilOffset = CivilDate(civilBase.toJdn() + selectedDayAbsoluteDistance) val yearDiff = civilOffset.year - 2000 val monthDiff = civilOffset.month - 1 val dayOfMonthDiff = civilOffset.dayOfMonth - 1 var text = context.getString(R.string.date_diff_text).format( formatNumber(selectedDayAbsoluteDistance.toInt()), formatNumber(yearDiff), formatNumber(monthDiff), formatNumber(dayOfMonthDiff) ) if (selectedDayAbsoluteDistance <= 31) text = text.split(" (")[0] binding.diffDate.text = text } val mainDate = getDateFromJdnOfCalendar(chosenCalendarType, jdn) val startOfYear = getDateOfCalendar( chosenCalendarType, mainDate.year, 1, 1 ) val startOfNextYear = getDateOfCalendar( chosenCalendarType, mainDate.year + 1, 1, 1 ) val startOfYearJdn = startOfYear.toJdn() val endOfYearJdn = startOfNextYear.toJdn() - 1 val currentWeek = calculateWeekOfYear(jdn, startOfYearJdn) val weeksCount = calculateWeekOfYear(endOfYearJdn, startOfYearJdn) val startOfYearText = context.getString(R.string.start_of_year_diff).format( formatNumber((jdn - startOfYearJdn).toInt()), formatNumber(currentWeek), formatNumber(mainDate.month) ) val endOfYearText = context.getString(R.string.end_of_year_diff).format( formatNumber((endOfYearJdn - jdn).toInt()), formatNumber(weeksCount - currentWeek), formatNumber(12 - mainDate.month) ) binding.startAndEndOfYearDiff.text = listOf(startOfYearText, endOfYearText).joinToString("\n") var equinox = "" if (mainCalendar == chosenCalendarType && chosenCalendarType == CalendarType.SHAMSI) { if (mainDate.month == 12 && mainDate.dayOfMonth >= 20 || mainDate.month == 1 && mainDate.dayOfMonth == 1) { val addition = if (mainDate.month == 12) 1 else 0 val springEquinox = getSpringEquinox(mainDate.toJdn()) equinox = context.getString(R.string.spring_equinox).format( formatNumber(mainDate.year + addition), Clock(springEquinox[Calendar.HOUR_OF_DAY], springEquinox[Calendar.MINUTE]) .toFormattedString(forcedIn12 = true) ) } } binding.equinox.apply { text = equinox visibility = if (equinox.isEmpty()) View.GONE else View.VISIBLE } binding.root.contentDescription = getA11yDaySummary( context, jdn, selectedDayAbsoluteDistance == 0L, emptyEventsStore(), withZodiac = true, withOtherCalendars = true, withTitle = true ) } class CalendarItemAdapter internal constructor(context: Context) : RecyclerView.Adapter<CalendarItemAdapter.ViewHolder>() { private val calendarFont: Typeface = getCalendarFragmentFont(context) private var calendars: List<CalendarType> = emptyList() internal var isExpanded = false set(expanded) { field = expanded calendars.indices.forEach(::notifyItemChanged) } private var jdn: Long = 0 internal fun setDate(calendars: List<CalendarType>, jdn: Long) { this.calendars = calendars this.jdn = jdn calendars.indices.forEach(::notifyItemChanged) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder( CalendarItemBinding.inflate(parent.context.layoutInflater, parent, false) ) override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(position) override fun getItemCount(): Int = calendars.size inner class ViewHolder(private val binding: CalendarItemBinding) : RecyclerView.ViewHolder(binding.root), OnClickListener { init { val applyLineMultiplier = !isCustomFontEnabled binding.monthYear.typeface = calendarFont binding.day.typeface = calendarFont if (applyLineMultiplier) binding.monthYear.setLineSpacing(0f, .6f) binding.container.setOnClickListener(this) binding.linear.setOnClickListener(this) } fun bind(position: Int) { val date = getDateFromJdnOfCalendar(calendars[position], jdn) binding.linear.text = toLinearDate(date) binding.linear.contentDescription = toLinearDate(date) val firstCalendarString = formatDate(date) binding.container.contentDescription = firstCalendarString binding.day.contentDescription = "" binding.day.text = formatNumber(date.dayOfMonth) binding.monthYear.contentDescription = "" binding.monthYear.text = listOf(getMonthName(date), formatNumber(date.year)).joinToString("\n") } override fun onClick(view: View?) = copyToClipboard(view, "converted date", view?.contentDescription) } } }
PersianCalendar/src/main/java/com/byagowi/persiancalendar/ui/shared/CalendarsView.kt
4057804775
package de.westnordost.streetcomplete.quests.diet_type import android.os.Bundle import android.view.View import androidx.core.os.bundleOf import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.databinding.QuestDietTypeExplanationBinding import de.westnordost.streetcomplete.quests.AbstractQuestAnswerFragment import de.westnordost.streetcomplete.quests.AnswerItem import de.westnordost.streetcomplete.quests.diet_type.DietAvailability.* class AddDietTypeForm : AbstractQuestAnswerFragment<DietAvailability>() { override val contentLayoutResId = R.layout.quest_diet_type_explanation private val binding by contentViewBinding(QuestDietTypeExplanationBinding::bind) override val buttonPanelAnswers = listOf( AnswerItem(R.string.quest_generic_hasFeature_no) { applyAnswer(DIET_NO) }, AnswerItem(R.string.quest_generic_hasFeature_yes) { applyAnswer(DIET_YES) }, AnswerItem(R.string.quest_hasFeature_only) { applyAnswer(DIET_ONLY) }, ) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val resId = arguments?.getInt(ARG_DIET) ?: 0 if (resId > 0) { binding.descriptionLabel.setText(resId) } else { binding.descriptionLabel.visibility = View.GONE } } companion object { private const val ARG_DIET = "diet_explanation" fun create(dietExplanationResId: Int): AddDietTypeForm { val form = AddDietTypeForm() form.arguments = bundleOf(ARG_DIET to dietExplanationResId) return form } } }
app/src/main/java/de/westnordost/streetcomplete/quests/diet_type/AddDietTypeForm.kt
1164246014
package com.boardgamegeek.ui import android.content.Context import android.content.Intent import android.os.Bundle import android.view.MenuItem import androidx.fragment.app.Fragment import com.boardgamegeek.R import com.boardgamegeek.entities.ForumEntity import com.boardgamegeek.extensions.* import com.boardgamegeek.provider.BggContract import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.logEvent class ThreadActivity : SimpleSinglePaneActivity() { private var threadId = BggContract.INVALID_ID private var threadSubject = "" private var forumId = BggContract.INVALID_ID private var forumTitle: String = "" private var objectId = BggContract.INVALID_ID private var objectName = "" private var objectType = ForumEntity.ForumType.REGION override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (objectName.isBlank()) { supportActionBar?.title = forumTitle supportActionBar?.subtitle = threadSubject } else { supportActionBar?.title = "$threadSubject - $forumTitle" supportActionBar?.subtitle = objectName } if (savedInstanceState == null) { firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM) { param(FirebaseAnalytics.Param.CONTENT_TYPE, "Thread") param(FirebaseAnalytics.Param.ITEM_ID, threadId.toString()) param(FirebaseAnalytics.Param.ITEM_NAME, threadSubject) } } } override fun readIntent(intent: Intent) { threadId = intent.getIntExtra(KEY_THREAD_ID, BggContract.INVALID_ID) threadSubject = intent.getStringExtra(KEY_THREAD_SUBJECT).orEmpty() forumId = intent.getIntExtra(KEY_FORUM_ID, BggContract.INVALID_ID) forumTitle = intent.getStringExtra(KEY_FORUM_TITLE).orEmpty() objectId = intent.getIntExtra(KEY_OBJECT_ID, BggContract.INVALID_ID) objectName = intent.getStringExtra(KEY_OBJECT_NAME).orEmpty() objectType = intent.getSerializableExtra(KEY_OBJECT_TYPE) as ForumEntity.ForumType } override fun onCreatePane(intent: Intent): Fragment { return ThreadFragment.newInstance(threadId, forumId, forumTitle, objectId, objectName, objectType) } override val optionsMenuId = R.menu.view_share override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { ForumActivity.startUp(this, forumId, forumTitle, objectId, objectName, objectType) finish() } R.id.menu_view -> { linkToBgg("thread", threadId) } R.id.menu_share -> { val description = if (objectName.isBlank()) String.format(getString(R.string.share_thread_text), threadSubject, forumTitle) else String.format(getString(R.string.share_thread_game_text), threadSubject, forumTitle, objectName) val link = createBggUri("thread", threadId).toString() share( getString(R.string.share_thread_subject), """ $description $link """.trimIndent(), R.string.title_share ) firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SHARE) { param(FirebaseAnalytics.Param.CONTENT_TYPE, "Thread") param(FirebaseAnalytics.Param.ITEM_ID, threadId.toString()) param( FirebaseAnalytics.Param.ITEM_NAME, if (objectName.isBlank()) "$forumTitle | $threadSubject" else "$objectName | $forumTitle | $threadSubject" ) } } else -> return super.onOptionsItemSelected(item) } return true } companion object { private const val KEY_FORUM_ID = "FORUM_ID" private const val KEY_FORUM_TITLE = "FORUM_TITLE" private const val KEY_OBJECT_ID = "OBJECT_ID" private const val KEY_OBJECT_NAME = "OBJECT_NAME" private const val KEY_OBJECT_TYPE = "OBJECT_TYPE" private const val KEY_THREAD_ID = "THREAD_ID" private const val KEY_THREAD_SUBJECT = "THREAD_SUBJECT" fun start( context: Context, threadId: Int, threadSubject: String, forumId: Int, forumTitle: String, objectId: Int, objectName: String, objectType: ForumEntity.ForumType ) { context.startActivity(createIntent(context, threadId, threadSubject, forumId, forumTitle, objectId, objectName, objectType)) } fun startUp( context: Context, threadId: Int, threadSubject: String, forumId: Int, forumTitle: String, objectId: Int, objectName: String, objectType: ForumEntity.ForumType ) { context.startActivity(createIntent(context, threadId, threadSubject, forumId, forumTitle, objectId, objectName, objectType).clearTop()) } private fun createIntent( context: Context, threadId: Int, threadSubject: String, forumId: Int, forumTitle: String, objectId: Int, objectName: String, objectType: ForumEntity.ForumType, ): Intent { return context.intentFor<ThreadActivity>( KEY_THREAD_ID to threadId, KEY_THREAD_SUBJECT to threadSubject, KEY_FORUM_ID to forumId, KEY_FORUM_TITLE to forumTitle, KEY_OBJECT_ID to objectId, KEY_OBJECT_NAME to objectName, KEY_OBJECT_TYPE to objectType, ) } } }
app/src/main/java/com/boardgamegeek/ui/ThreadActivity.kt
6742273
package com.boardgamegeek.export.model import com.google.gson.annotations.Expose class Color(@Expose val color: String)
app/src/main/java/com/boardgamegeek/export/model/Color.kt
2182024607
package org.wordpress.android.fluxc.model.list import com.yarolegovich.wellsql.core.Identifiable import com.yarolegovich.wellsql.core.annotation.Column import com.yarolegovich.wellsql.core.annotation.PrimaryKey import com.yarolegovich.wellsql.core.annotation.RawConstraints import com.yarolegovich.wellsql.core.annotation.Table @Table @RawConstraints( "FOREIGN KEY(LIST_ID) REFERENCES ListModel(_id) ON DELETE CASCADE", "UNIQUE(LIST_ID, REMOTE_ITEM_ID) ON CONFLICT IGNORE" ) class ListItemModel(@PrimaryKey @Column private var id: Int = 0) : Identifiable { constructor(listId: Int, remoteItemId: Long) : this() { this.listId = listId this.remoteItemId = remoteItemId } @Column var listId: Int = 0 @Column var remoteItemId: Long = 0 override fun getId(): Int = id override fun setId(id: Int) { this.id = id } }
fluxc/src/main/java/org/wordpress/android/fluxc/model/list/ListItemModel.kt
2694021618
/* * Copyright 2017 Hex <[email protected]> * and other copyright owners as documented in the project's IP log. * * 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.basinmc.faucet.event.filter /** * Annotates an event handler method to designate that it should treat all given filter annotations * as excludes rather than includes - that is, instead of only matching events which meet all filter * requirements, it would only match events that meet *none* of them. */ @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER) annotation class Blacklist
faucet/src/main/kotlin/org/basinmc/faucet/event/filter/Blacklist.kt
2258117362
/* * Copyright 2017 Aleksey Dobrynin * * 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 one.trifle.lurry.connection /** * An enum for resolve database driver name to normal usage name * this enum also contains class with specific methods for database * * @author Aleksey Dobrynin */ enum class DatabaseType constructor(private val driver: String, private val type: String, val mixed: Class<*>) { MYSQL("com.mysql.jdbc.Driver", "MySQL", MySqlSafeString::class.java), ORACLE("oracle.jdbc.OracleDriver", "Oracle", DefaultSafeString::class.java), POSTGRE("org.postgresql.Driver", "PostgreSQL", DefaultSafeString::class.java), H2("org.h2.Driver", "H2", DefaultSafeString::class.java), DB2("com.ibm.db2.jcc.DB2Driver", "Db2", DefaultSafeString::class.java), MSSQL("com.microsoft.sqlserver.jdbc.SQLServerDriver", "SQLServer", DefaultSafeString::class.java), SQLITE("org.sqlite.JDBC", "SQLite", DefaultSafeString::class.java), CASSANDRA("org.apache.cassandra.cql.jdbc.CassandraDriver", "Cassandra", DefaultSafeString::class.java), DEFAULT("", "", DefaultSafeString::class.java); companion object { @JvmStatic fun of(name: String): DatabaseType = if (name.contains('.')) { values().find { type -> type.driver.equals(name, ignoreCase = true) } } else { values().find { type -> type.type.equals(name, ignoreCase = true) } } ?: DEFAULT } }
src/main/kotlin/one/trifle/lurry/connection/DatabaseType.kt
3385100297
@file:Suppress("SpellCheckingInspection", "NOTHING_TO_INLINE") package pref.ext import android.content.SharedPreferences.OnSharedPreferenceChangeListener import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.channels.sendBlocking import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import pref.Pref import kotlin.reflect.KProperty0 @ExperimentalCoroutinesApi @JvmOverloads inline fun <T> Pref.asFlow( prop: KProperty0<T>, key: String? = null ): Flow<T> = callbackFlow { val listenKey = key ?: prop.name val listener = OnSharedPreferenceChangeListener { _, changeKey -> if (listenKey == changeKey && !isClosedForSend) this.sendBlocking(prop.get()) } preferences.registerOnSharedPreferenceChangeListener(listener) awaitClose { preferences.unregisterOnSharedPreferenceChangeListener(listener) } }
app/src/main/java/pref/ext/PrefFlowableExt.kt
531816360
/* * Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.protobuf import kotlinx.serialization.* import kotlin.test.* class ProtobufPolymorphismTest { @Test fun testAbstract() { val obj = PolyBox(SimpleStringInheritor("str", 133)) assertSerializedToBinaryAndRestored(obj, PolyBox.serializer(), ProtoBuf { encodeDefaults = true; serializersModule = SimplePolymorphicModule }) } @Test fun testSealed() { val obj = SealedBox( listOf( SimpleSealed.SubSealedB(33), SimpleSealed.SubSealedA("str") ) ) assertSerializedToBinaryAndRestored(obj, SealedBox.serializer(), ProtoBuf) } @Serializable sealed class Single { @Serializable data class Impl(val i: Int) : Single() } @Test fun testSingleSealedClass() { val expected = "0a436b6f746c696e782e73657269616c697a6174696f6e2e70726f746f6275662e50726f746f627566506f6c796d6f72706869736d546573742e53696e676c652e496d706c1202082a" assertEquals(expected, ProtoBuf.encodeToHexString(Single.serializer(), Single.Impl(42))) assertEquals(Single.Impl(42), ProtoBuf.decodeFromHexString(Single.serializer(), expected)) } }
formats/protobuf/commonTest/src/kotlinx/serialization/protobuf/ProtobufPolymorphismTest.kt
3319968962
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.vanilla.packet.type.play import org.lanternpowered.server.network.packet.Packet import org.spongepowered.api.util.Direction import org.spongepowered.math.vector.Vector3i data class ClientDiggingPacket( val action: Action, val position: Vector3i, val face: Direction ) : Packet { enum class Action { START, CANCEL, FINISH } }
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/type/play/ClientDiggingPacket.kt
2154826322
package com.zzkun.util.web import org.junit.Test /** * Created by kun on 2016/10/22. */ class HDUWebGetterTest { @Test fun userACPbs() { } @Test fun allPbInfo() { } }
src/test/java/com/zzkun/util/web/HDUWebGetterTest.kt
4195030922
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.data import org.spongepowered.api.data.DataProvider import org.spongepowered.api.data.value.Value /** * A wrapper to turn a [DataProvider] into a [IDataProvider]. */ internal class WrappedDataProvider<V : Value<E>, E : Any>(val delegate: DataProvider<V, E>) : IDataProvider<V, E>, DataProvider<V, E> by delegate
src/main/kotlin/org/lanternpowered/server/data/WrappedDataProvider.kt
2598612390
import io.gitlab.arturbosch.detekt.Detekt import io.gitlab.arturbosch.detekt.extensions.DetektExtension import io.gitlab.arturbosch.detekt.report.ReportMergeTask import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.configure @Suppress("unused") class ScipamatoDetektPlugin : Plugin<Project> { override fun apply(target: Project) { target.plugins.apply("io.gitlab.arturbosch.detekt") target.plugins.withId("io.gitlab.arturbosch.detekt") { val rootProject = target.rootProject // specify base path to make file locations relative target.extensions.configure<DetektExtension> { buildUponDefaultConfig = true allRules = true baseline = target.file("detekt-baseline.xml") basePath = rootProject.projectDir.absolutePath config.setFrom("${rootProject.projectDir}/config/detekt/detekt.yml") } // enable SARIF report val detektTask = target.tasks.named("detekt", Detekt::class.java) detektTask.configure { reports.sarif.required.set(true) reports.xml.required.set(true) } // add detekt output to inputs of ReportMergeTask // mustRunAfter should be used here otherwise the merged report won't be generated on fail rootProject.plugins.withId( "scipamato-collect-sarif") { rootProject.tasks.named( CollectSarifPlugin.MERGE_DETEKT_TASK_NAME, ReportMergeTask::class.java ) { input.from(detektTask.map { it.sarifReportFile }.orNull) mustRunAfter(detektTask) } } } target.rootProject.tasks.named("sonarqube") { dependsOn(target.tasks.getByName("detekt")) } } }
gradle-plugins/verification/src/main/kotlin/ScipamatoDetektPlugin.kt
2022636669
package com.cypress.Levels import com.badlogic.gdx.Gdx import com.badlogic.gdx.Input import com.badlogic.gdx.Screen import com.badlogic.gdx.graphics.GL20 import com.badlogic.gdx.graphics.OrthographicCamera import com.badlogic.gdx.graphics.g2d.Animation import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.utils.Array import com.cypress.CGHelpers.AssetLoader import com.cypress.CGHelpers.Controls import com.cypress.GameObjects.* import com.cypress.GameObjects.Enemies.* import com.cypress.Screens.GameOverScreen import com.cypress.Screens.StatsScreen import com.cypress.codenameghost.CGGame import java.util.* /** Contains definition of first level. */ public class Level1(private val game : CGGame, private val player : Player) : Screen { private val assets = AssetLoader.getInstance() private val batcher = SpriteBatch() private var runTime = 0f private val controls = Controls(game, player, this) private val blockList = ArrayList<Block>() private val enemyList = ArrayList<Warrior>() private val itemsList = ArrayList<Item>() private val removedBullets = ArrayList<Bullet>() private val deadEnemies = ArrayList<Warrior>() private val removedItems = ArrayList<Item>() private val camera = OrthographicCamera(Gdx.graphics.width.toFloat(), Gdx.graphics.height.toFloat()) private var stage = Stage() private var fan = Animation(0.02f, Array<TextureRegion>()) private var index = assets.gunNames.indexOf(player.gunType) private var fanSoundOn = false private var hmmSoundOn = true private var gameStart = false private var counter = 0 private var doorOpened = false init { stage = controls.getStage() assets.activeMusic = assets.levelsMusic[1] // adding blocks val hSnow = TextureRegion(assets.levelsFP[1], 28, 924, 911, 73) val vSnow = TextureRegion(assets.levelsFP[1], 907, 174, 100, 618) val crate = TextureRegion(assets.levelsFP[1], 316, 46, 256, 128) val roof = TextureRegion(assets.levelsFP[1], 314, 348, 386, 73) val roof1 = TextureRegion(assets.levelsFP[1], 311, 451, 214, 46) val roof2 = TextureRegion(assets.levelsFP[1], 313, 529, 416, 24) val wall = TextureRegion(assets.levelsFP[1], 754, 201, 25, 225) val door = TextureRegion(assets.levelsFP[1], 742, 448, 152, 257) blockList.add(Block(Vector2( 86f, 950f), 911f, 73f, hSnow)) blockList.add(Block(Vector2( 86f, 656f), 911f, 73f, hSnow)) blockList.add(Block(Vector2( 997f, 950f), 125f, 73f, hSnow)) blockList.add(Block(Vector2( 520f, 390f), 465f, 73f, hSnow)) blockList.add(Block(Vector2(1330f, 374f), 880f, 73f, hSnow)) blockList.add(Block(Vector2(-166f, 68f), 256f, 128f, crate)) blockList.add(Block(Vector2( 80f, 68f), 256f, 128f, crate)) blockList.add(Block(Vector2(-110f, 190f), 256f, 128f, crate)) blockList.add(Block(Vector2( 664f, 448f), 100f, 550f, vSnow)) blockList.add(Block(Vector2( 897f, 448f), 100f, 550f, vSnow)) blockList.add(Block(Vector2(1317f, 892f), 100f, 618f, vSnow)) blockList.add(Block(Vector2(1317f, 413f), 100f, 618f, vSnow)) blockList.add(Block(Vector2(2129f, 380f), 100f, 370f, vSnow)) blockList.add(Block(Vector2(3230f, 403f), 386f, 73f, roof)) blockList.add(Block(Vector2(4376f, 929f), 386f, 73f, roof)) blockList.add(Block(Vector2(4763f, 616f), 386f, 73f, roof)) blockList.add(Block(Vector2(4559f, 357f), 214f, 46f, roof1)) blockList.add(Block(Vector2(5860f, 434f), 416f, 24f, roof2)) //blockList.add(Block(Vector2(6005f, 357f), 416f, 24f, roof2)) blockList.add(Block(Vector2(5860f, 434f), 25f, 225f, wall)) blockList.add(Block(Vector2(5999f, 100f), 152f, 257f, door)) // adding enemies enemyList.add(Warrior(Vector2( 43f, 364f), player)) enemyList.add(Warrior(Vector2( 444f, 101f), player)) enemyList.add(Warrior(Vector2(2120f, 105f), player)) enemyList.add(Warrior(Vector2(3241f, 110f), player)) enemyList.add(Warrior(Vector2(3360f, 485f), player)) enemyList.add(Warrior(Vector2(4394f, 1013f), player)) enemyList.add(Warrior(Vector2(4608f, 404f), player)) enemyList.add(Warrior(Vector2(4612f, 110f), player)) enemyList.add(Warrior(Vector2(4821f, 700f), player)) enemyList.add(Warrior(Vector2(5850f, 110f), player)) // adding items itemsList.add(Item(Vector2( 525f, 490f), assets.gunNames[1])) itemsList.add(Item(Vector2(3405f, 478f), assets.ammoNames[1])) itemsList.add(Item(Vector2(4530f, 1005f), "keyCard")) itemsList.add(Item(Vector2(4637f, 495f), "medikit")) // animation of fan val fanPos = arrayOf(582, 732, 878) val fanArray = Array<TextureRegion>() fanArray.addAll(Array(3, {i -> TextureRegion(assets.levelsFP[1], fanPos[i], 14, 141, 134)}), 0, 3) fan = Animation(0.02f, fanArray, Animation.PlayMode.LOOP) } /** Updates level information. */ private fun update() { // if level completed if (player.getX() >= player.mapLength) { assets.snow?.stop() assets.fan?.stop() player.data[1] = 2 - player.lives if (player.data[3] != 0) player.data[5] = (player.data[4].toFloat() / player.data[3].toFloat() * 100).toInt() game.availableLevels[2] = true game.screen = StatsScreen(game, player.data) } // playing level1 music and sounds if (assets.musicOn) { if (!(assets.activeMusic?.isPlaying ?: false)) { assets.activeMusic?.volume = 0.5f assets.activeMusic?.play() } if ((player.shouldGoToLeft || player.shouldGoToRight) && player.onGround && player.getX() < 3096f) assets.snow?.play() else assets.snow?.stop() if (player.getX() > 5345f && player.getX() < 6197f) { if (!fanSoundOn) { assets.fan?.setVolume(1, 0.5f) assets.fan?.loop() fanSoundOn = true } } else { assets.fan?.stop() fanSoundOn = false } } // player should shoot index = assets.gunNames.indexOf(player.gunType) if ((player.shouldShoot || Gdx.input.isKeyPressed(Input.Keys.ENTER)) && counter % assets.rateOfFire[index] == 0 && index != 6) { controls.shoot() counter = 0 } // player has a key if (player.hasKey) { blockList.removeAt(blockList.size - 1) player.hasKey = false doorOpened = true } // checking collision of bullets with enemies for (bullet in assets.bulletsList) { for (enemy in enemyList) { if (bullet.getBounds().overlaps(enemy.getBound())) { if(!bullet.enemyBulllet) { enemy.health -= bullet.damage if (bullet.damage == assets.bulletDamage[6]) bullet.shouldExplode = true else if (!bullet.shouldExplode) removedBullets.add(bullet) player.data[4]++ } } } } // checking collision of bullets with player for (bullet in assets.bulletsList) { if (bullet.getBounds().overlaps(player.getBound()) && bullet.enemyBulllet && !player.isDead ) { player.health -= bullet.damage if (player.health <= 0) { player.health = 100 player.lives -= 1 player.isDead = true // game over if (player.lives < 0) { assets.snow?.stop() assets.fan?.stop() assets.activeMusic?.stop() assets.activeMusic = assets.gameOver game.screen = GameOverScreen(game) } } removedBullets.add(bullet) } } // deleting dead enemy ... for (enemy in deadEnemies) // ... if he has already drawn his animation if (!enemy.isDead) enemyList.remove(enemy) // removing picked up items for (item in removedItems) itemsList.remove(item) // checking collision of bullets with blocks for (bullet in assets.bulletsList) for (block in blockList) if(bullet.getBounds().overlaps(block.getBounds())) if (bullet.damage == assets.bulletDamage[6]) bullet.shouldExplode = true else if (!bullet.shouldExplode) removedBullets.add(bullet) // removing bullets, which hit player or block for (bullet in removedBullets) assets.bulletsList.remove(bullet) } /** Draws level. */ public override fun render(delta: Float) { if (player.onGround) gameStart = true runTime += delta update() counter++ // drawing background color Gdx.gl.glClearColor(1f, 1f, 1f, 1f) Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT) // setting camera if (!gameStart) camera.position.set(120f, 1243f, 0f) else camera.position.set(player.getX() + 100, player.getY() + 220, 0f) camera.zoom = assets.zoom batcher.projectionMatrix = camera.combined camera.update() // drawing background batcher.begin() if (player.getX() < 3096f) batcher.draw(assets.levelsBG[1][0], -400f, 0f, 4096f, 2048f) else batcher.draw(assets.levelsBG[1][1], 2696f, 0f, 4096f, 2048f) batcher.end() // drawing blocks for (block in blockList) block.draw(batcher) // check collision with picked up items for (item in itemsList) { item.draw(batcher) if (player.getBound().overlaps(item.getBounds())) { item.activity(player) removedItems.add(item) } } // drawing terminal and hint batcher.begin() if (doorOpened) batcher.draw(TextureRegion(assets.levelsFP[1], 171, 835, 94, 70), 5799f, 162f, 94f, 70f) // info else { batcher.draw(TextureRegion(assets.levelsFP[1], 28, 835, 94, 70), 5799f, 162f, 94f, 70f) // info if (player.getX() >= 5799 && player.getX() <= 5893 && player.getY() <= 100f) { var hint = TextureRegion(assets.levelsFP[1], 319, 568, 249, 163) if (assets.language != "english") hint = TextureRegion(assets.levelsFP[1], 319, 748, 249, 163) batcher.draw(hint, 5831f, 281f, 249f, 163f) if (hmmSoundOn) { assets.neutral[(Math.random() * 1000).toInt() % 3]?.play() hmmSoundOn = false } } else hmmSoundOn = true } batcher.end() // drawing bullets if (!assets.bulletsList.isEmpty() && assets.bulletsList[0].distance() > 600) assets.bulletsList.removeFirst() for (b in assets.bulletsList) b.draw(runTime, batcher) // drawing player if (player.lives >= 0) { player.update() player.checkCollision(blockList) player.draw(runTime, batcher) } // drawing enemies for (enemy in enemyList) { if(enemy.health <= 0 && !enemy.isDead) { enemy.isDead = true deadEnemies.add(enemy) player.data[0] += 50 player.data[2]++ } if (enemy.health > 0) { enemy.update(runTime) enemy.checkCollision(blockList) } enemy.draw(runTime, batcher) } // drawing first plan objects batcher.begin() batcher.enableBlending() batcher.draw(TextureRegion(assets.levelsFP[1], 19, 0, 221, 417), 350f, 980f, 221f, 417f) // spruce batcher.draw(TextureRegion(assets.levelsFP[1], 29, 437, 236, 356), 6151f, 77f, 236f, 356f) // fence batcher.draw(fan.getKeyFrame(runTime), 5885f, 527f, 141f, 132f) batcher.end() // drawing stage if (gameStart && !player.isDead) { controls.update() stage.act(runTime) stage.draw() } } public override fun resize(width : Int, height : Int) {} public override fun show() {} public override fun hide() {} public override fun pause() {} /** Restores screen after pause. */ public override fun resume() { game.screen = this Gdx.input.inputProcessor = stage } /** Dispose level 1. */ public override fun dispose() { stage.dispose() game.dispose() } }
core/src/com/cypress/Levels/Level1.kt
1874998958
package voice.logging.debug import android.util.Log import voice.logging.core.LogWriter import voice.logging.core.Logger import java.util.regex.Pattern internal class DebugLogWriter : LogWriter { /** * This logic was borrowed from Timber: https://github.com/JakeWharton/timber */ override fun log(severity: Logger.Severity, message: String, throwable: Throwable?) { val tag = Throwable().stackTrace .first { it.className !in fqcnIgnore } .let(::createStackElementTag) val priority = severity.priority if (message.length < MAX_LOG_LENGTH) { if (priority == Log.ASSERT) { Log.wtf(tag, message) } else { Log.println(priority, tag, message) } return } // Split by line, then ensure each line can fit into Log's maximum length. var i = 0 val length = message.length while (i < length) { var newline = message.indexOf('\n', i) newline = if (newline != -1) newline else length do { val end = newline.coerceAtMost(i + MAX_LOG_LENGTH) val part = message.substring(i, end) if (priority == Log.ASSERT) { Log.wtf(tag, part) } else { Log.println(priority, tag, part) } i = end } while (i < newline) i++ } } } private val fqcnIgnore = listOf( DebugLogWriter::class.java.name, Logger::class.java.name, ) private const val MAX_LOG_LENGTH = 4000 private val ANONYMOUS_CLASS = Pattern.compile("(\\$\\d+)+$") private fun createStackElementTag(element: StackTraceElement): String { var tag = element.className.substringAfterLast('.') val matcher = ANONYMOUS_CLASS.matcher(tag) if (matcher.find()) { tag = matcher.replaceAll("") } return "$tag:${element.lineNumber}" } private val Logger.Severity.priority: Int get() = when (this) { Logger.Severity.Verbose -> Log.VERBOSE Logger.Severity.Debug -> Log.DEBUG Logger.Severity.Info -> Log.INFO Logger.Severity.Warn -> Log.WARN Logger.Severity.Error -> Log.ERROR }
logging/debug/src/main/kotlin/voice/logging/debug/DebugLogWriter.kt
3534671332
package voice.bookOverview.deleteBook import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Checkbox import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import voice.bookOverview.R @Composable internal fun DeleteBookDialog( viewState: DeleteBookViewState, onDismiss: () -> Unit, onConfirmDeletion: () -> Unit, onDeleteCheckBoxChecked: (Boolean) -> Unit, ) { AlertDialog( onDismissRequest = onDismiss, title = { Text(stringResource(R.string.delete_book_dialog_title)) }, confirmButton = { Button( onClick = onConfirmDeletion, enabled = viewState.deleteCheckBoxChecked, colors = ButtonDefaults.buttonColors( containerColor = MaterialTheme.colorScheme.errorContainer, contentColor = MaterialTheme.colorScheme.error, ), ) { Text(stringResource(id = R.string.delete)) } }, dismissButton = { TextButton( onClick = onDismiss, ) { Text(stringResource(id = R.string.dialog_cancel)) } }, text = { Column { Text(stringResource(id = R.string.delete_book_dialog_content)) Spacer(modifier = Modifier.heightIn(8.dp)) Text(viewState.fileToDelete, style = MaterialTheme.typography.bodyLarge) Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .padding(top = 8.dp) .fillMaxWidth() .clickable { onDeleteCheckBoxChecked(!viewState.deleteCheckBoxChecked) }, ) { Checkbox( checked = viewState.deleteCheckBoxChecked, onCheckedChange = onDeleteCheckBoxChecked, ) Text(stringResource(id = R.string.delete_book_dialog_deletion_confirmation)) } } }, ) }
bookOverview/src/main/kotlin/voice/bookOverview/deleteBook/DeleteBookDialog.kt
4134411223
package cc.aoeiuv020.panovel.api.site import cc.aoeiuv020.base.jar.textList import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext /** * Created by AoEiuV020 on 2018.06.08-18:30:24. */ class Zhuishu : DslJsoupNovelContext() {init { // timeout, hide = true site { name = "追书网" baseUrl = "https://www.mangg.net" logo = "https://www.mangg.net/images/logo.gif" } search { get { // https://www.mangg.net/search.php?q=%E9%83%BD%E5%B8%82 url = "/search.php" data { "q" to it } } document { items("div.result-list > div") { name("> div.result-game-item-detail > h3 > a") author("> div.result-game-item-detail > div > p:nth-child(1) > span:nth-child(2)") } } } // https://www.zhuishu.tw/id58054/ bookIdRegex = "/id(\\d+)" detailPageTemplate = "/id%s/" detail { document { novel { name("#info > h1") author("#info > p:nth-child(2)", block = pickString("作\\s*者:(\\S*)")) } image("#fmimg > img") update("#info > p:nth-child(4)", format = "yyyy-MM-dd HH:mm:ss", block = pickString("最后更新:(.*)")) introduction("#intro") } } chapters { document { items("#list > dl > dd > a") lastUpdate("#info > p:nth-child(4)", format = "yyyy-MM-dd HH:mm:ss", block = pickString("最后更新:(.*)")) } } // https://www.zhuishu.tw/id58054/200787.html bookIdWithChapterIdRegex = "/id(\\d+/\\d+)" contentPageTemplate = "/id%s.html" content { document { items("#content", block = { e -> // 这网站正文第一行开关都有个utf8bom,不会被当成空白符过滤掉, e.textList().map { it.removePrefix("\ufeff").trimStart() } }) } } } }
api/src/main/java/cc/aoeiuv020/panovel/api/site/zhuishu.kt
3208171178
package ademar.study.reddit.model data class ErrorViewModel( val code: Int, val message: String )
Projects/Reddit/app/src/main/java/ademar/study/reddit/model/ErrorViewModel.kt
1561920954
package io.gitlab.arturbosch.detekt.rules.bugs import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution import io.gitlab.arturbosch.detekt.rules.safeAs import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.psi.KtCatchClause import org.jetbrains.kotlin.psi.KtTryExpression import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf /** * Reports unreachable catch blocks. * Catch blocks can be unreachable if the exception has already been caught in the block above. * * <noncompliant> * fun test() { * try { * foo() * } catch (t: Throwable) { * bar() * } catch (e: Exception) { * // Unreachable * baz() * } * } * </noncompliant> * * <compliant> * fun test() { * try { * foo() * } catch (e: Exception) { * baz() * } catch (t: Throwable) { * bar() * } * } * </compliant> * */ @RequiresTypeResolution class UnreachableCatchBlock(config: Config = Config.empty) : Rule(config) { override val issue = Issue( javaClass.simpleName, Severity.Warning, "Unreachable catch block detected.", Debt.FIVE_MINS ) @Suppress("ReturnCount") override fun visitCatchSection(catchClause: KtCatchClause) { super.visitCatchSection(catchClause) if (bindingContext == BindingContext.EMPTY) return val tryExpression = catchClause.getStrictParentOfType<KtTryExpression>() ?: return val prevCatchClauses = tryExpression.catchClauses.takeWhile { it != catchClause } if (prevCatchClauses.isEmpty()) return val catchClassDescriptor = catchClause.catchClassDescriptor() ?: return if (prevCatchClauses.any { catchClassDescriptor.isSubclassOf(it) }) { report(CodeSmell(issue, Entity.from(catchClause), "This catch block is unreachable.")) } } private fun KtCatchClause.catchClassDescriptor(): ClassDescriptor? { val typeReference = catchParameter?.typeReference ?: return null return bindingContext[BindingContext.TYPE, typeReference]?.constructor?.declarationDescriptor?.safeAs() } private fun ClassDescriptor.isSubclassOf(catchClause: KtCatchClause): Boolean { val catchClassDescriptor = catchClause.catchClassDescriptor() ?: return false return isSubclassOf(catchClassDescriptor) } }
detekt-rules-errorprone/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/UnreachableCatchBlock.kt
382995179
package nl.sogeti.android.gpstracker.v2.wear.common import android.app.Application import android.os.StrictMode import nl.sogeti.android.gpstracker.v2.wear.BuildConfig import timber.log.Timber class WearApplication : Application() { var debug = BuildConfig.DEBUG override fun onCreate() { super.onCreate() setupDebugTree() } private fun setupDebugTree() { if (debug) { Timber.plant(Timber.DebugTree()) if (StrictMode.ThreadPolicy.Builder().build() != null) { StrictMode.setThreadPolicy( StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .build()) } } } }
studio/wear/src/main/java/nl/sogeti/android/gpstracker/v2/wear/common/WearApplication.kt
1999912460
package com.renard.ocr.util import android.app.DownloadManager import android.content.Context import android.os.Environment import android.os.Environment.MEDIA_MOUNTED import android.os.StatFs import com.renard.ocr.R import java.io.File object AppStorage { private const val EXTERNAL_APP_DIRECTORY = "textfee" private const val IMAGE_DIRECTORY = "pictures" private const val CACHE_DIRECTORY = "thumbnails" private const val OCR_DATA_DIRECTORY = "tessdata" @JvmStatic fun getImageDirectory(context: Context) = getAppDirectory(context)?.requireDirectory(IMAGE_DIRECTORY) @JvmStatic fun getCacheDirectory(context: Context) = getAppDirectory(context)?.requireDirectory(CACHE_DIRECTORY) @JvmStatic fun getTrainingDataDir(context: Context) = getAppDirectory(context)?.requireDirectory(OCR_DATA_DIRECTORY) @JvmStatic fun getPDFDir(context: Context) = getAppDirectory(context)?.requireDirectory(context.getString(R.string.config_pdf_file_dir)) private fun getAppDirectory(context: Context) = if(Environment.getExternalStorageState()== MEDIA_MOUNTED){ context.getExternalFilesDir(EXTERNAL_APP_DIRECTORY)!!.also { it.mkdirs() } } else { null } @JvmStatic fun setTrainedDataDestinationForDownload(context: Context, request: DownloadManager.Request, trainedDataFileName: String) { request.setDestinationInExternalFilesDir(context, EXTERNAL_APP_DIRECTORY, "$OCR_DATA_DIRECTORY/$trainedDataFileName") } private fun File.requireDirectory(dir: String) = File(this, dir).also { it.mkdirs() } /** * @return the free space on sdcard in bytes */ @JvmStatic fun getFreeSpaceInBytes(context: Context): Long { return try { val stat = StatFs(getAppDirectory(context).toString()) val availableBlocks = stat.availableBlocks.toLong() availableBlocks * stat.blockSize } catch (ex: Exception) { -1 } } }
app/src/main/java/com/renard/ocr/util/AppStorage.kt
4160710163
package com.aglushkov.general.networkstatus import android.content.Context import android.net.Network import android.net.NetworkCapabilities import android.net.NetworkInfo import android.net.NetworkRequest import android.os.Build import com.aglushkov.modelcore.resource.CustomStateFlow class ConnectivityManager constructor(val context: Context) { private var connectivityManager = getConnectivityManager() private val stateFlow = CustomStateFlow<Boolean>(false) val flow = stateFlow.flow @Volatile var isDeviceOnline = false private set @Volatile var isWifiMode = false private set private var networkCallback = object : android.net.ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { super.onAvailable(network) checkNetworkState() } override fun onLost(network: Network) { super.onLost(network) checkNetworkState() } } fun register() { registerNetworkCallback() } fun unregister() { connectivityManager.unregisterNetworkCallback(networkCallback) } private fun registerNetworkCallback() { val builder = NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) connectivityManager.registerNetworkCallback(builder.build(), networkCallback) } fun checkNetworkState() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val network = connectivityManager.activeNetwork updateCapabilities(network) } else { updateCapabilitiesLegacy(connectivityManager.activeNetworkInfo) } if (stateFlow.value != isDeviceOnline) { stateFlow.offer(isDeviceOnline) } } private fun updateCapabilities(network: Network?) { val capabilities = if (network != null) connectivityManager.getNetworkCapabilities(network) else null capabilities?.let { isDeviceOnline = true isWifiMode = it.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) } ?: run { isDeviceOnline = false isWifiMode = false } } private fun updateCapabilitiesLegacy(networkInfo: NetworkInfo?) { if (networkInfo?.isConnected == true && networkInfo?.isAvailable) { isDeviceOnline = true val isWifi = networkInfo.type == android.net.ConnectivityManager.TYPE_WIFI val isWiMax = networkInfo.type == android.net.ConnectivityManager.TYPE_WIMAX isWifiMode = isWifi || isWiMax } else { isDeviceOnline = false isWifiMode = false } } private fun getConnectivityManager() = context.getSystemService(Context.CONNECTIVITY_SERVICE) as android.net.ConnectivityManager }
app_wordteacher/src/main/java/com/aglushkov/general/networkstatus/ConnectivityManager.kt
2832803678
package io.gitlab.arturbosch.detekt.core.settings import io.github.detekt.tooling.api.spec.LoggingSpec import java.io.PrintStream import java.io.PrintWriter interface LoggingAware { val outputChannel: Appendable val errorChannel: Appendable fun info(msg: String) fun error(msg: String, error: Throwable) fun debug(msg: () -> String) } internal fun Throwable.printStacktraceRecursively(logger: Appendable) { when (logger) { is PrintStream -> this.printStackTrace(logger) is PrintWriter -> this.printStackTrace(logger) else -> { stackTrace.forEach { logger.appendLine(it.toString()) } cause?.printStacktraceRecursively(logger) } } } internal class LoggingFacade( val spec: LoggingSpec ) : LoggingAware { override val outputChannel: Appendable = spec.outputChannel override val errorChannel: Appendable = spec.errorChannel override fun info(msg: String) { outputChannel.appendLine(msg) } override fun error(msg: String, error: Throwable) { errorChannel.appendLine(msg) error.printStacktraceRecursively(errorChannel) } override fun debug(msg: () -> String) { if (spec.debug) { outputChannel.appendLine(msg()) } } }
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/settings/LoggingAware.kt
214712396
package org.tvheadend.tvhclient.ui.features.dvr.series_recordings import android.os.Bundle import android.view.* import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProvider import org.tvheadend.data.entity.SeriesRecording import org.tvheadend.tvhclient.R import org.tvheadend.tvhclient.databinding.SeriesRecordingDetailsFragmentBinding import org.tvheadend.tvhclient.ui.base.BaseFragment import org.tvheadend.tvhclient.ui.common.* import org.tvheadend.tvhclient.ui.common.interfaces.ClearSearchResultsOrPopBackStackInterface import org.tvheadend.tvhclient.ui.common.interfaces.RecordingRemovedInterface import org.tvheadend.tvhclient.util.extensions.gone import org.tvheadend.tvhclient.util.extensions.visible class SeriesRecordingDetailsFragment : BaseFragment(), RecordingRemovedInterface, ClearSearchResultsOrPopBackStackInterface { private lateinit var seriesRecordingViewModel: SeriesRecordingViewModel private var recording: SeriesRecording? = null private lateinit var binding: SeriesRecordingDetailsFragmentBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = DataBindingUtil.inflate(inflater, R.layout.series_recording_details_fragment, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) seriesRecordingViewModel = ViewModelProvider(requireActivity())[SeriesRecordingViewModel::class.java] if (!isDualPane) { toolbarInterface.setTitle(getString(R.string.details)) toolbarInterface.setSubtitle("") } arguments?.let { seriesRecordingViewModel.currentIdLiveData.value = it.getString("id", "") } seriesRecordingViewModel.recordingLiveData.observe(viewLifecycleOwner, { recording = it showRecordingDetails() }) } private fun showRecordingDetails() { recording?.let { binding.recording = it binding.htspVersion = htspVersion binding.isDualPane = isDualPane binding.duplicateDetectionText = if (it.dupDetect < seriesRecordingViewModel.duplicateDetectionList.size) { seriesRecordingViewModel.duplicateDetectionList[it.dupDetect] } else { seriesRecordingViewModel.duplicateDetectionList[0] } // The toolbar is hidden as a default to prevent pressing any icons if no recording // has been loaded yet. The toolbar is shown here because a recording was loaded binding.nestedToolbar.visible() activity?.invalidateOptionsMenu() } ?: run { binding.scrollview.gone() binding.status.text = getString(R.string.error_loading_recording_details) binding.status.visible() } } override fun onPrepareOptionsMenu(menu: Menu) { val recording = this.recording ?: return preparePopupOrToolbarSearchMenu(menu, recording.title, isConnectionToServerAvailable) binding.nestedToolbar.menu.findItem(R.id.menu_edit_recording)?.isVisible = true binding.nestedToolbar.menu.findItem(R.id.menu_remove_recording)?.isVisible = true } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.external_search_options_menu, menu) binding.nestedToolbar.inflateMenu(R.menu.recording_details_toolbar_menu) binding.nestedToolbar.setOnMenuItemClickListener { this.onOptionsItemSelected(it) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { val ctx = context ?: return super.onOptionsItemSelected(item) val recording = this.recording ?: return super.onOptionsItemSelected(item) return when (item.itemId) { R.id.menu_edit_recording -> editSelectedSeriesRecording(requireActivity(), recording.id) R.id.menu_remove_recording -> showConfirmationToRemoveSelectedSeriesRecording(ctx, recording, this) R.id.menu_search_imdb -> return searchTitleOnImdbWebsite(ctx, recording.title) R.id.menu_search_fileaffinity -> return searchTitleOnFileAffinityWebsite(ctx, recording.title) R.id.menu_search_youtube -> return searchTitleOnYoutube(ctx, recording.title) R.id.menu_search_google -> return searchTitleOnGoogle(ctx, recording.title) R.id.menu_search_epg -> return searchTitleInTheLocalDatabase(requireActivity(), baseViewModel, recording.title) else -> super.onOptionsItemSelected(item) } } override fun onRecordingRemoved() { if (!isDualPane) { activity?.onBackPressed() } else { val detailsFragment = activity?.supportFragmentManager?.findFragmentById(R.id.details) if (detailsFragment != null) { activity?.supportFragmentManager?.beginTransaction()?.also { it.remove(detailsFragment) it.commit() } } } } companion object { fun newInstance(id: String): SeriesRecordingDetailsFragment { val f = SeriesRecordingDetailsFragment() val args = Bundle() args.putString("id", id) f.arguments = args return f } } }
app/src/main/java/org/tvheadend/tvhclient/ui/features/dvr/series_recordings/SeriesRecordingDetailsFragment.kt
4135850965
package demo fun getGreeting(): String { val words = mutableListOf<String>() words.add("Hello,") words.add("world!") return words.joinToString(separator = " ") } fun main(args: Array<String>) { println(getGreeting()) println(JavaClass().foo) }
libraries/kotlinlibrary/src/main/java/demo/helloWorld.kt
1337601076
package net.nemerosa.ontrack.model.structure /** * Search request. * * @param token Free text for the search * @param type Type of search, linked to [SearchResultType.id] * @param offset Offset for the results * @param size Number of results returned after [offset] */ class SearchRequest @JvmOverloads constructor( val token: String, val type: String? = null, val offset: Int = 0, val size: Int = 10 )
ontrack-model/src/main/java/net/nemerosa/ontrack/model/structure/SearchRequest.kt
1581731218
/** * 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.schedule.email.service import com.hp.gagawa.java.elements.A import com.mycollab.common.MonitorTypeConstants import com.mycollab.core.MyCollabException import com.mycollab.core.utils.StringUtils import com.mycollab.html.LinkUtils import com.mycollab.module.project.ProjectLinkGenerator import com.mycollab.module.project.ProjectTypeConstants import com.mycollab.module.project.domain.ProjectRelayEmailNotification import com.mycollab.module.project.domain.SimpleMessage import com.mycollab.module.project.i18n.MessageI18nEnum import com.mycollab.module.project.service.MessageService import com.mycollab.module.user.AccountLinkGenerator import com.mycollab.schedule.email.ItemFieldMapper import com.mycollab.schedule.email.MailContext import com.mycollab.schedule.email.project.MessageRelayEmailNotificationAction import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.config.BeanDefinition import org.springframework.context.annotation.Scope import org.springframework.stereotype.Service /** * @author MyCollab Ltd * @since 6.0.0 */ @Service @Scope(BeanDefinition.SCOPE_PROTOTYPE) class MessageRelayEmailNotificationActionImpl : SendMailToAllMembersAction<SimpleMessage>(), MessageRelayEmailNotificationAction { @Autowired private lateinit var messageService: MessageService override fun getItemName(): String = StringUtils.trim(bean!!.title, 100) override fun getProjectName(): String = bean!!.projectName!! override fun getCreateSubject(context: MailContext<SimpleMessage>): String = context.getMessage( MessageI18nEnum.MAIL_CREATE_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName()) override fun getCreateSubjectNotification(context: MailContext<SimpleMessage>): String = context.getMessage( MessageI18nEnum.MAIL_CREATE_ITEM_SUBJECT, projectLink(), userLink(context), messageLink()) override fun getUpdateSubject(context: MailContext<SimpleMessage>): String = context.getMessage( MessageI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName()) override fun getUpdateSubjectNotification(context: MailContext<SimpleMessage>): String = context.getMessage( MessageI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, projectLink(), userLink(context), messageLink()) override fun getCommentSubject(context: MailContext<SimpleMessage>): String = context.getMessage( MessageI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName()) override fun getCommentSubjectNotification(context: MailContext<SimpleMessage>): String = context.getMessage( MessageI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, projectLink(), userLink(context), messageLink()) private fun projectLink() = A(ProjectLinkGenerator.generateProjectLink(bean!!.projectid)).appendText(bean!!.projectName).write() private fun userLink(context: MailContext<SimpleMessage>) = A(AccountLinkGenerator.generateUserLink(context.user.username)).appendText(context.changeByUserFullName).write() private fun messageLink() = A(ProjectLinkGenerator.generateMessagePreviewLink(bean!!.projectid, bean!!.id)).appendText(getItemName()).write() override fun getItemFieldMapper(): ItemFieldMapper = ItemFieldMapper() override fun getBeanInContext(notification: ProjectRelayEmailNotification): SimpleMessage? = messageService.findById(notification.typeid.toInt(), notification.saccountid) override fun getType(): String = ProjectTypeConstants.MESSAGE override fun getTypeId(): String = "${bean!!.id}" override fun buildExtraTemplateVariables(context: MailContext<SimpleMessage>) { val emailNotification = context.emailNotification val summary = bean!!.title val summaryLink = ProjectLinkGenerator.generateMessagePreviewFullLink(siteUrl, bean!!.projectid, bean!!.id) val avatarId = if (projectMember != null) projectMember!!.memberAvatarId else "" val userAvatar = LinkUtils.newAvatar(avatarId) val makeChangeUser = "${userAvatar.write()} ${emailNotification.changeByUserFullName}" val actionEnum = when (emailNotification.action) { MonitorTypeConstants.CREATE_ACTION -> MessageI18nEnum.MAIL_CREATE_ITEM_HEADING MonitorTypeConstants.UPDATE_ACTION -> MessageI18nEnum.MAIL_UPDATE_ITEM_HEADING MonitorTypeConstants.ADD_COMMENT_ACTION -> MessageI18nEnum.MAIL_COMMENT_ITEM_HEADING else -> throw MyCollabException("Not support action ${emailNotification.action}") } contentGenerator.putVariable("projectName", bean!!.projectName!!) contentGenerator.putVariable("projectNotificationUrl", ProjectLinkGenerator.generateProjectSettingFullLink(siteUrl, bean!!.projectid)) contentGenerator.putVariable("actionHeading", context.getMessage(actionEnum, makeChangeUser)) contentGenerator.putVariable("name", summary) contentGenerator.putVariable("summaryLink", summaryLink) contentGenerator.putVariable("message", bean!!.message) } }
mycollab-scheduler/src/main/java/com/mycollab/module/project/schedule/email/service/MessageRelayEmailNotificationActionImpl.kt
3231758780
package com.github.shynixn.astraledit.bukkit.logic.business.service import com.github.shynixn.astraledit.api.business.service.ConcurrencyService import org.bukkit.plugin.Plugin /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ class ConcurrencyServiceImpl(private val plugin: Plugin) : ConcurrencyService { /** * Runs the given [function] synchronised with the given [delayTicks] and [repeatingTicks]. */ override fun runTaskSync(delayTicks: Long, repeatingTicks: Long, function: Runnable) { if (repeatingTicks > 0) { plugin.server.scheduler.runTaskTimer(plugin, function, delayTicks, repeatingTicks) } else { plugin.server.scheduler.runTaskLater(plugin, function, delayTicks) } } /** * Runs the given [function] asynchronous with the given [delayTicks] and [repeatingTicks]. */ override fun runTaskAsync(delayTicks: Long, repeatingTicks: Long, function: Runnable) { if (repeatingTicks > 0) { plugin.server.scheduler.runTaskTimerAsynchronously(plugin, function, delayTicks, repeatingTicks) } else { plugin.server.scheduler.runTaskLaterAsynchronously(plugin, function, delayTicks) } } }
astraledit-bukkit-plugin/src/main/java/com/github/shynixn/astraledit/bukkit/logic/business/service/ConcurrencyServiceImpl.kt
1543935993
/* * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2021 Chris Narkiewicz <[email protected]> * * 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.nextcloud.client.files.downloader import com.owncloud.android.operations.UploadFileOperation /** * Upload transfer trigger. */ enum class UploadTrigger(val value: Int) { /** * Transfer triggered manually by the user. */ USER(UploadFileOperation.CREATED_BY_USER), /** * Transfer triggered automatically by taking a photo. */ PHOTO(UploadFileOperation.CREATED_AS_INSTANT_PICTURE), /** * Transfer triggered automatically by making a video. */ VIDEO(UploadFileOperation.CREATED_AS_INSTANT_VIDEO); companion object { @JvmStatic fun fromValue(value: Int) = when (value) { UploadFileOperation.CREATED_BY_USER -> USER UploadFileOperation.CREATED_AS_INSTANT_PICTURE -> PHOTO UploadFileOperation.CREATED_AS_INSTANT_VIDEO -> VIDEO else -> USER } } }
app/src/main/java/com/nextcloud/client/files/downloader/UploadTrigger.kt
3474102875
/* * Copyright (C) 2015 Antonio Leiva * * 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.antonioleiva.bandhookkotlin.data.lastfm.model import com.google.gson.annotations.SerializedName class LastFmArtistList ( @SerializedName("artist") val artists: List<LastFmArtist> )
app/src/main/java/com/antonioleiva/bandhookkotlin/data/lastfm/model/LastFmArtistList.kt
3981971773
/* * This file is part of BOINC. * http://boinc.berkeley.edu * Copyright (C) 2020 University of California * * BOINC 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. * * BOINC 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 BOINC. If not, see <http://www.gnu.org/licenses/>. */ package edu.berkeley.boinc.rpc import android.os.Parcel import android.os.Parcelable import androidx.core.os.ParcelCompat.readBoolean import androidx.core.os.ParcelCompat.writeBoolean data class Notice( var seqno: Int = -1, var title: String = "", var description: String = "", var createTime: Double = 0.0, var arrivalTime: Double = 0.0, /** * Assigned by RSS source. Reserved values: * "client": generated by client * "server": scheduler RPC message */ var category: String = "", /** * URL where original message can be seen, if any */ var link: String = "", /** * If notice is associated with a project */ var projectName: String = "", var isPrivate: Boolean = false, var isServerNotice: Boolean = false, var isClientNotice: Boolean = false ) : Parcelable { private constructor(parcel: Parcel) : this(seqno = parcel.readInt(), title = parcel.readString() ?: "", description = parcel.readString() ?: "", createTime = parcel.readDouble(), arrivalTime = parcel.readDouble(), category = parcel.readString() ?: "", link = parcel.readString() ?: "", projectName = parcel.readString() ?: "", isPrivate = readBoolean(parcel), isServerNotice = readBoolean(parcel), isClientNotice = readBoolean(parcel)) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(seqno) dest.writeString(title) dest.writeString(description) dest.writeDouble(createTime) dest.writeDouble(arrivalTime) dest.writeString(category) dest.writeString(link) dest.writeString(projectName) writeBoolean(dest, isPrivate) writeBoolean(dest, isServerNotice) writeBoolean(dest, isClientNotice) } object Fields { const val SEQNO = "seqno" const val TITLE = "title" const val CREATE_TIME = "create_time" const val ARRIVAL_TIME = "arrival_time" const val Category = "category" const val LINK = "link" } companion object { @JvmField val CREATOR: Parcelable.Creator<Notice> = object : Parcelable.Creator<Notice> { override fun createFromParcel(parcel: Parcel) = Notice(parcel) override fun newArray(size: Int) = arrayOfNulls<Notice>(size) } } }
android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/Notice.kt
3219908428
package com.e16din.incl import com.e16din.incl.BaseIncl.InsertionType.* class InclButterKnife : BaseIncl() { companion object { const val VER = "8.4.0" const val CLASSPATH_BUTTERKNIFE = "classpath 'com.jakewharton:butterknife-gradle-plugin:$VER'" const val PLUGIN_BUTTERKNIFE = "com.jakewharton.butterknife" const val VERSION_BUTTERKNIFE = """def ver_butterkinife = "$VER"""" const val COMPILE_BUTTERKNIFE = """compile "com.jakewharton:butterknife:${'$'}{ver_butterkinife}"""" const val APT_BUTTERKNIFE = """apt "com.jakewharton:butterknife-compiler:${'$'}{ver_butterkinife}"""" } override fun name() = "ButterKnife" override fun include() { includeApt() insert(TYPE_APPLY_PLUGIN, PLUGIN_BUTTERKNIFE) insertToGradleBlock(GRADLE_BLOCK_DEPENDENCIES, VERSION_BUTTERKNIFE) insertToGradleBlock(GRADLE_BLOCK_DEPENDENCIES, COMPILE_BUTTERKNIFE) insertToGradleBlock(GRADLE_BLOCK_DEPENDENCIES, APT_BUTTERKNIFE) insert(TYPE_ALL_PROJECTS_REPOSITORY, "\n $REPOSITORY_MAVEN_CENTRAL") insert(TYPE_DEPENDENCIES_CLASSPATH, CLASSPATH_BUTTERKNIFE) } }
src/com/e16din/incl/InclButterKnife.kt
312406627
package io.gitlab.arturbosch.tinbo.finance import io.gitlab.arturbosch.tinbo.api.config.ConfigDefaults import io.gitlab.arturbosch.tinbo.api.config.Defaults import io.gitlab.arturbosch.tinbo.api.config.HomeFolder import io.gitlab.arturbosch.tinbo.api.config.TinboConfig import io.gitlab.arturbosch.tinbo.api.model.AbstractDataHolder import io.gitlab.arturbosch.tinbo.api.model.AbstractPersister import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component /** * @author artur */ @Component class FinanceDataHolder @Autowired constructor(persister: FinancePersister, private val config: TinboConfig) : AbstractDataHolder<FinanceEntry, FinanceData>(persister) { override val lastUsedData: String get() = config.getKey(ConfigDefaults.FINANCE) .getOrElse(ConfigDefaults.LAST_USED, { Defaults.FINANCE_NAME }) override fun newData(name: String, entriesInMemory: List<FinanceEntry>): FinanceData { return FinanceData(name, entriesInMemory) } override fun getEntriesFilteredBy(filter: String): List<FinanceEntry> { return getEntries().filter { it.category.equals(filter, ignoreCase = true) } } override fun changeCategory(oldName: String, newName: String) { val updatedEntries = getEntries().map { if (it.category.equals(oldName, ignoreCase = true)) { it.copy(category = newName) } else { it } } saveData(data.name, updatedEntries) } } @Component class FinancePersister @Autowired constructor(config: TinboConfig) : AbstractPersister<FinanceEntry, FinanceData>(HomeFolder.getDirectory(ConfigDefaults.FINANCE), config) { override fun restore(name: String): FinanceData { return load(name, FinanceData(name), FinanceEntry::class.java) } }
tinbo-finance/src/main/kotlin/io/gitlab/arturbosch/tinbo/finance/FinanceData.kt
2546170857
// // (C) Copyright 2018-2019 Martin E. Nordberg III // Apache 2.0 License // package o.katydid.css.stylesheets import o.katydid.css.styles.builders.KatydidStyleBuilderDsl //--------------------------------------------------------------------------------------------------------------------- /** * Class representing the @charset declaration at the beginning of a style sheet. */ @KatydidStyleBuilderDsl interface KatydidCharSetAtRule : KatydidCssRule { /** The (unquoted) character set of the rule. */ val characterSet: String } //---------------------------------------------------------------------------------------------------------------------
Katydid-CSS-JS/src/main/kotlin/o/katydid/css/stylesheets/KatydidCharSetAtRule.kt
1604734718
// // (C) Copyright 2018-2019 Martin E. Nordberg III // Apache 2.0 License // package jvm.katydid.vdom.builders.edits import jvm.katydid.vdom.api.checkBuild import o.katydid.vdom.application.katydid import org.junit.jupiter.api.Test import x.katydid.vdom.types.KatyDateTime import java.time.ZoneOffset @Suppress("RemoveRedundantBackticks") class EditsTests { @Test fun `A del element produces correct HTML`() { val vdomNode = katydid<Unit> { del(cite = "http://somewhere.com/citation", datetime = KatyDateTime.of(2001, 9, 8, 21, 46, 40, 0, ZoneOffset.ofHours(-4))) { text("this was deleted") } } val html = """<del cite="http://somewhere.com/citation" datetime="2001-09-08T21:46:40-04:00"> | this was deleted |</del>""".trimMargin() checkBuild(html, vdomNode) } @Test fun `An ins element produces correct HTML`() { val vdomNode = katydid<Unit> { ins(cite = "http://somewhere.com/citation", datetime = KatyDateTime.of(2001, 9, 8, 21, 46, 40, 0, ZoneOffset.ofHours(-4))) { text("this was deleted") } } val html = """<ins cite="http://somewhere.com/citation" datetime="2001-09-08T21:46:40-04:00"> | this was deleted |</ins>""".trimMargin() checkBuild(html, vdomNode) } }
Katydid-VDOM-JVM/src/test/kotlin/jvm/katydid/vdom/builders/edits/EditsTests.kt
529131988
package chat.rocket.android.server.domain import javax.inject.Inject class GetAccountsInteractor @Inject constructor(val repository: AccountsRepository) { fun get() = repository.load() }
app/src/main/java/chat/rocket/android/server/domain/GetAccountsInteractor.kt
3441989912
/* * Copyright (C) 2022 panpf <[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 com.github.panpf.sketch.test.utils import com.github.panpf.sketch.decode.BitmapDecodeInterceptor import com.github.panpf.sketch.decode.BitmapDecodeResult class Test2BitmapDecodeInterceptor : BitmapDecodeInterceptor { override val key: String? = null override val sortWeight: Int = 0 override suspend fun intercept(chain: BitmapDecodeInterceptor.Chain): BitmapDecodeResult { throw UnsupportedOperationException() } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false return true } override fun hashCode(): Int { return javaClass.hashCode() } override fun toString(): String { return "Test2BitmapDecodeInterceptor(sortWeight=$sortWeight)" } }
sketch/src/androidTest/java/com/github/panpf/sketch/test/utils/Test2BitmapDecodeInterceptor.kt
4065939550
package br.com.edsilfer.android.starwarswiki.model.dictionary import com.google.gson.Gson /** * Created by ferna on 2/22/2017. */ class TMDBResponseDictionary { val vote_average = "" val backdrop_path = "" val adult = "" val id : Long = 0.toLong() val title = "" val overview = "" val original_language = "" val genre_ids = mutableListOf<String>() val release_date = "" val original_title = "" val vote_count = "" val poster_path = "" val video = "" val popularity = "" val homepage = "" override fun toString(): String { return Gson().toJson(this) } }
app/src/main/java/br/com/edsilfer/android/starwarswiki/model/dictionary/TMDBResponseDictionary.kt
4006714770