repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | platform/credential-store-ui/src/CredentialStoreUiServiceImpl.kt | 4 | 5334 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.credentialStore
import com.intellij.credentialStore.kdbx.IncorrectMasterPasswordException
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationType
import com.intellij.notification.SingletonNotificationManager
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.NlsContexts.*
import com.intellij.ui.components.JBPasswordField
import com.intellij.ui.components.dialog
import com.intellij.ui.dsl.builder.COLUMNS_MEDIUM
import com.intellij.ui.dsl.builder.columns
import com.intellij.ui.dsl.builder.panel
import com.intellij.util.SmartList
import java.awt.Component
import javax.swing.JPasswordField
internal val NOTIFICATION_MANAGER by lazy { SingletonNotificationManager("Password Safe", NotificationType.ERROR) }
class CredentialStoreUiServiceImpl : CredentialStoreUiService {
override fun notify(@NotificationTitle title: String, @NotificationContent content: String, project: Project?, action: NotificationAction?) {
NOTIFICATION_MANAGER.notify(title, content, project) {
if (action != null) {
it.addAction(action)
}
}
}
override fun showChangeMasterPasswordDialog(contextComponent: Component?,
setNewMasterPassword: (current: CharArray, new: CharArray) -> Boolean): Boolean =
doShowChangeMasterPasswordDialog(contextComponent, setNewMasterPassword)
override fun showRequestMasterPasswordDialog(@DialogTitle title: String,
@DialogMessage topNote: String?,
contextComponent: Component?,
@DialogMessage ok: (value: ByteArray) -> String?): Boolean =
doShowRequestMasterPasswordDialog(title, topNote, contextComponent, ok)
override fun showErrorMessage(parent: Component?, title: String, message: String) {
Messages.showErrorDialog(parent, message, title)
}
override fun openSettings(project: Project?) {
ShowSettingsUtil.getInstance().showSettingsDialog(project, PasswordSafeConfigurable::class.java)
}
}
internal fun doShowRequestMasterPasswordDialog(@DialogTitle title: String,
@DialogMessage topNote: String? = null,
contextComponent: Component? = null,
@DialogMessage ok: (value: ByteArray) -> String?): Boolean {
lateinit var passwordField: JBPasswordField
val panel = panel {
topNote?.let {
row {
text(it)
}
}
row(CredentialStoreBundle.message("kee.pass.row.master.password")) {
passwordField = passwordField()
.focused()
.component
}
}
return dialog(title = title, panel = panel, parent = contextComponent) {
val errors = SmartList<ValidationInfo>()
val value = checkIsEmpty(passwordField, errors)
if (errors.isEmpty()) {
val result = value!!.toByteArrayAndClear()
ok(result)?.let {
errors.add(ValidationInfo(it, passwordField))
}
if (!errors.isEmpty()) {
result.fill(0)
}
}
errors
}.showAndGet()
}
private fun checkIsEmpty(field: JPasswordField, errors: MutableList<ValidationInfo>): CharArray? {
val chars = field.getTrimmedChars()
if (chars == null) {
errors.add(ValidationInfo(CredentialStoreBundle.message("kee.pass.validation.info.current.password.incorrect.current.empty"), field))
}
return chars
}
internal fun doShowChangeMasterPasswordDialog(contextComponent: Component?,
setNewMasterPassword: (current: CharArray, new: CharArray) -> Boolean): Boolean {
val currentPasswordField = JPasswordField()
val newPasswordField = JPasswordField()
val panel = com.intellij.ui.dsl.builder.panel {
row(CredentialStoreBundle.message("kee.pass.row.current.password")) {
cell(currentPasswordField)
.columns(COLUMNS_MEDIUM)
.focused()
}
row(CredentialStoreBundle.message("kee.pass.row.new.password")) {
cell(newPasswordField)
.columns(COLUMNS_MEDIUM)
}
row {
comment(CredentialStoreBundle.message("kee.pass.row.comment"))
}
}
return dialog(title = CredentialStoreBundle.message("kee.pass.dialog.default.title"), panel = panel, parent = contextComponent) {
val errors = SmartList<ValidationInfo>()
val current = checkIsEmpty(currentPasswordField, errors)
val new = checkIsEmpty(newPasswordField, errors)
if (errors.isEmpty()) {
try {
if (setNewMasterPassword(current!!, new!!)) {
return@dialog errors
}
}
catch (e: IncorrectMasterPasswordException) {
errors.add(
ValidationInfo(CredentialStoreBundle.message("kee.pass.validation.info.current.password.incorrect"), currentPasswordField))
new?.fill(0.toChar())
}
}
else {
current?.fill(0.toChar())
new?.fill(0.toChar())
}
errors
}.showAndGet()
}
| apache-2.0 | 333d412879769c1f7d744f51f8a379b9 | 37.934307 | 143 | 0.683165 | 4.948052 | false | false | false | false |
NineWorlds/serenity-android | emby-lib/src/main/kotlin/us/nineworlds/serenity/emby/server/api/EmbyAPIClient.kt | 2 | 15220 | package us.nineworlds.serenity.emby.server.api
import android.content.Context
import android.preference.PreferenceManager
import android.util.Log
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import github.nisrulz.easydeviceinfo.base.EasyDeviceMod
import github.nisrulz.easydeviceinfo.base.EasyIdMod
import me.jessyan.retrofiturlmanager.RetrofitUrlManager
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.joda.time.LocalDateTime
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import us.nineworlds.serenity.common.media.model.IMediaContainer
import us.nineworlds.serenity.common.rest.SerenityClient
import us.nineworlds.serenity.common.rest.SerenityUser
import us.nineworlds.serenity.emby.BuildConfig
import us.nineworlds.serenity.emby.adapters.MediaContainerAdaptor
import us.nineworlds.serenity.emby.moshi.LocalDateJsonAdapter
import us.nineworlds.serenity.emby.server.model.AuthenticateUserByName
import us.nineworlds.serenity.emby.server.model.AuthenticationResult
import us.nineworlds.serenity.emby.server.model.PublicUserInfo
import us.nineworlds.serenity.emby.server.model.QueryFilters
import us.nineworlds.serenity.emby.server.model.QueryResult
import java.io.File
class EmbyAPIClient(val context: Context, baseUrl: String = "http://localhost:8096") : SerenityClient {
private val usersService: UsersService
private val filterService: FilterService
var baseUrl: String
var accessToken: String? = null
lateinit var serverId: String
var userId: String? = null
var deviceId: String
var deviceName: String
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
init {
this.baseUrl = baseUrl
val logger = HttpLoggingInterceptor()
val cacheDir = File(context.cacheDir, "EmbyClient")
val cacheSize = 10 * 1024 * 1024 // 10 MiB
val cache = Cache(cacheDir, cacheSize.toLong())
val okClient = RetrofitUrlManager.getInstance().with(OkHttpClient.Builder())
logger.level = HttpLoggingInterceptor.Level.BODY
okClient.addInterceptor(logger)
okClient.cache(cache)
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.add(LocalDateTime::class.java, LocalDateJsonAdapter()).build()
val builder = Retrofit.Builder()
val embyRetrofit = builder.baseUrl(baseUrl)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.client(okClient.build())
.build()
usersService = embyRetrofit.create(UsersService::class.java)
filterService = embyRetrofit.create(FilterService::class.java)
val easyDeviceMod = EasyDeviceMod(context)
deviceId = EasyIdMod(context).pseudoUniqueID
deviceName = "${easyDeviceMod.manufacturer} ${easyDeviceMod.model}"
Log.d(this::class.java.simpleName, "Device Id: $deviceId")
Log.d(this::class.java.simpleName, "Device Name : $deviceName")
}
fun fetchAllPublicUsers(): List<PublicUserInfo> {
val allPublicUsers = usersService.allPublicUsers()
return allPublicUsers.execute().body()!!
}
fun userImageUrl(userId: String): String {
return "$baseUrl/Users/$userId/Images/Primary"
}
fun authenticate(userName: String, password: String = ""): AuthenticationResult {
val authenticationResul = AuthenticateUserByName(userName, "", password, password)
val call = usersService.authenticate(authenticationResul, headerMap())
val response = call.execute()
if (response.isSuccessful) {
val body = response.body()
accessToken = body!!.accesToken
serverId = body.serverId
userId = body.userInfo.id!!
val prefEditor = prefs.edit()
prefEditor.putString("userId", userId)
prefEditor.putString("embyAccessToken", accessToken)
prefEditor.apply()
return response.body()!!
}
throw IllegalStateException("error logging user in to Emby Server")
}
fun currentUserViews(): QueryResult {
if (userId == null) {
userId = fetchUserId()
}
val call = usersService.usersViews(headerMap(), userId!!)
return call.execute().body()!!
}
fun filters(itemId: String? = null, tags: List<String>? = null): QueryFilters {
if (userId == null) {
userId = fetchUserId()
}
val call = filterService.availableFilters(headerMap(), userId!!)
return call.execute().body()!!
}
fun fetchItem(id: String): QueryResult {
if (userId == null) {
userId = fetchUserId()
}
val call = usersService.fetchItem(headerMap(), userId!!, id)
return call.execute().body()!!
}
fun fetchItemQuery(id: String): QueryResult {
if (userId == null) {
userId = fetchUserId()
}
val call = usersService.fetchItemQuery(headerMap(), userId!!, id, genre = null)
return call.execute().body()!!
}
private fun headerMap(): Map<String, String> {
val headers = HashMap<String, String>()
val authorizationValue =
"Emby Client=\"Android\", Device=\"$deviceName\", DeviceId=\"$deviceId\", Version=\"${BuildConfig.CLIENT_VERSION}.0\""
headers["X-Emby-Authorization"] = authorizationValue
if (accessToken != null) {
headers["X-Emby-Token"] = accessToken!!
}
return headers
}
override fun userInfo(userId: String?): SerenityUser {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun allAvailableUsers(): MutableList<SerenityUser> {
val allPublicUsers = fetchAllPublicUsers()
val allUsers = ArrayList<SerenityUser>()
for (user in allPublicUsers) {
val builder = us.nineworlds.serenity.common.rest.impl.SerenityUser.builder()
val sernityUser = builder.userName(user.name)
.userId(user.id)
.hasPassword(user.hasPassword)
.build()
allUsers.add(sernityUser)
}
return allUsers
}
override fun authenticateUser(user: SerenityUser): SerenityUser {
val authenticatedUser = authenticate(user.userName)
return us.nineworlds.serenity.common.rest.impl.SerenityUser.builder()
.accessToken(authenticatedUser.accesToken)
.userName(user.userName)
.userId(user.userId)
.hasPassword(user.hasPassword())
.build()
}
override fun retrieveRootData(): IMediaContainer {
if (userId == null) {
userId = fetchUserId()
}
val call = usersService.usersViews(headerMap(), userId!!)
val queryResult = call.execute().body()
return MediaContainerAdaptor().createMainMenu(queryResult!!.items)
}
override fun retrieveLibrary(): IMediaContainer {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun retrieveItemByCategories(): IMediaContainer {
if (userId == null) {
userId = fetchUserId()
}
val call = usersService.usersViews(headerMap(), userId!!)
val queryResult = call.execute().body()
return MediaContainerAdaptor().createMainMenu(queryResult!!.items)
}
override fun retrieveItemByIdCategory(key: String?): IMediaContainer {
if (userId == null) {
userId = fetchUserId()
}
val call = filterService.availableFilters(headerMap(), userId = userId!!, itemId = key)
val queryResult = call.execute().body()
return MediaContainerAdaptor().createCategory(queryResult!!.genres!!)
}
override fun retrieveItemByIdCategory(key: String, category: String): IMediaContainer {
var genre: String? = null
var isPlayed: Boolean? = null
genre = when (category) {
"all", "unwatched" -> null
else -> category
}
if (userId == null) {
userId = fetchUserId()
}
val call = if (category == "ondeck") {
usersService.resumableItems(headerMap(), userId = userId!!, parentId = key)
} else if (category == "recentlyAdded") {
usersService.latestItems(headerMap(), userId = userId!!, parentId = key)
} else if (category == "unwatched") {
usersService.unwatchedItems(headerMap(), userId = userId!!, parentId = key)
} else {
usersService.fetchItemQuery(headerMap(), userId = userId!!, parentId = key, genre = genre, isPlayed = isPlayed)
}
val results = call.execute().body()
return MediaContainerAdaptor().createVideoList(results!!.items)
}
override fun retrieveItemByCategories(key: String?, category: String?, secondaryCategory: String?): IMediaContainer {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun retrieveSeasons(key: String): IMediaContainer {
if (userId == null) {
userId = fetchUserId()
}
val call = usersService.fetchItemQuery(
headerMap(),
userId = userId!!,
parentId = key,
includeItemType = "Season",
genre = null
)
val results = call.execute().body()
return MediaContainerAdaptor().createSeriesList(results!!.items)
}
override fun retrieveMusicMetaData(key: String?): IMediaContainer {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun retrieveEpisodes(key: String): IMediaContainer {
if (userId == null) {
userId = fetchUserId()
}
val call = usersService.fetchItemQuery(
headerMap(),
userId = userId!!,
parentId = key,
includeItemType = "Episode",
genre = null
)
val results = call.execute().body()
return MediaContainerAdaptor().createVideoList(results!!.items)
}
override fun retrieveMovieMetaData(key: String?): IMediaContainer {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun searchMovies(key: String?, query: String): IMediaContainer {
if (userId == null) {
userId = fetchUserId()
}
val call = usersService.search(headerMap(), userId!!, query)
val results = call.execute().body()
val itemIds = mutableListOf<String>()
for (searchHint in results!!.searchHints!!) {
itemIds.add(searchHint.id!!)
}
val itemCall = usersService.fetchItemQuery(
headerMap(),
userId = userId!!,
ids = itemIds.joinToString(separator = ","),
genre = null,
parentId = null
)
val itemResults = itemCall.execute().body()
return MediaContainerAdaptor().createVideoList(itemResults!!.items)
}
override fun searchEpisodes(key: String?, query: String?): IMediaContainer? {
return null
}
override fun updateBaseUrl(baseUrl: String) {
this.baseUrl = baseUrl
RetrofitUrlManager.getInstance().setGlobalDomain(baseUrl)
}
override fun baseURL(): String = baseUrl
override fun watched(key: String): Boolean {
if (userId == null) {
userId = fetchUserId()
}
val call = usersService.played(headerMap(), userId!!, key)
val result = call.execute()
return result.isSuccessful
}
override fun unwatched(key: String): Boolean {
if (userId == null) {
userId = fetchUserId()
}
val call = usersService.unplayed(headerMap(), userId!!, key)
val result = call.execute()
return result.isSuccessful
}
override fun progress(key: String, offset: String): Boolean {
if (userId == null) {
userId = fetchUserId()
}
var position = offset.toLong()
position = position.times(10000)
val call = usersService.progress(headerMap(), userId!!, key, null, position)
val result = call.execute()
return result.isSuccessful
}
override fun createMediaTagURL(resourceType: String?, resourceName: String?, identifier: String?): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createSectionsURL(key: String?, category: String?): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createSectionsURL(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createSectionsUrl(key: String?): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createMovieMetadataURL(key: String?): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createEpisodesURL(key: String?): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createSeasonsURL(key: String?): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createImageURL(url: String?, width: Int, height: Int): String {
return url!!
}
override fun createTranscodeUrl(id: String, offset: Int): String {
var startOffset: Long = 0
if (offset > 0) {
startOffset = offset.toLong().times(10000)
}
return "${baseUrl}emby/Videos/$id/stream.mkv?DeviceId=$deviceId&AudioCodec=aac&VideoCodec=h264&CopyTimeStamps=true&EnableAutoStreamCopy=true&StartTimeTicks=$startOffset"
}
override fun reinitialize() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createUserImageUrl(user: SerenityUser, width: Int, height: Int): String {
return "$baseUrl/Emby/Users/${user.userId}/Images/Primary?Width=$width&Height=$height"
}
override fun startPlaying(itemId: String) {
if (userId == null) {
userId = fetchUserId()
}
val call = usersService.startPlaying(headerMap(), userId!!, itemId)
call.execute()
}
override fun stopPlaying(itemId: String, offset: Long) {
if (userId == null) {
userId = fetchUserId()
}
val positionTicks = offset.times(10000)
val call = usersService.stopPlaying(headerMap(), userId!!, itemId, null, positionTicks.toString())
call.execute()
}
override fun retrieveSeriesById(key: String, categoryId: String): IMediaContainer {
var genre: String? = null
val isPlayed: Boolean? = null
val itemType = "Series"
genre = when (categoryId) {
"all", "unwatched" -> null
else -> categoryId
}
if (userId == null) {
userId = fetchUserId()
}
val call = usersService.fetchItemQuery(
headerMap(),
userId = userId!!,
parentId = key,
genre = genre,
isPlayed = isPlayed,
includeItemType = itemType,
limitCount = 5
)
val results = call.execute().body()
return MediaContainerAdaptor().createSeriesList(results!!.items)
}
override fun retrieveSeriesCategoryById(key: String?): IMediaContainer {
if (userId == null) {
userId = fetchUserId()
}
val call = filterService.availableFilters(headerMap(), userId!!, key)
val queryResult = call.execute().body()
return MediaContainerAdaptor().createCategory(queryResult!!.genres!!, true)
}
fun fetchUserId() = prefs.getString("userId", "")
fun fetchAccessToken() = prefs.getString("embyAccessToken", "")
override fun supportsMultipleUsers(): Boolean = true
} | mit | f849997b5f56102a697a4384ad4b6e88 | 31.044211 | 173 | 0.694941 | 4.525721 | false | false | false | false |
loxal/FreeEthereum | free-ethereum-core/src/test/java/org/ethereum/core/genesis/GenesisLoadTest.kt | 1 | 7034 | /*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package org.ethereum.core.genesis
import com.typesafe.config.ConfigFactory
import com.typesafe.config.ConfigValueFactory
import org.ethereum.config.BlockchainConfig
import org.ethereum.config.SystemProperties
import org.ethereum.config.blockchain.*
import org.ethereum.util.FastByteComparisons
import org.ethereum.util.FastByteComparisons.equal
import org.ethereum.util.blockchain.StandaloneBlockchain
import org.hamcrest.CoreMatchers.instanceOf
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.spongycastle.util.encoders.Hex
import java.io.File
import java.math.BigInteger
import java.net.URISyntaxException
/**
* Testing system exit
* http://stackoverflow.com/questions/309396/java-how-to-test-methods-that-call-system-exit
*/
class GenesisLoadTest {
@Test
fun shouldLoadGenesis_whenShortWay() {
loadGenesis(null, "frontier-test.json")
assertTrue(true)
}
@Test
@Throws(URISyntaxException::class)
fun shouldLoadGenesis_whenFullPathSpecified() {
val url = GenesisLoadTest::class.java.classLoader.getResource("genesis/frontier-test.json")
// full path
println("url.getPath() " + url!!.path)
loadGenesis(url.path, null)
val path = File(url.toURI()).toPath()
val curPath = File("").absoluteFile.toPath()
val relPath = curPath.relativize(path).toFile().path
println("Relative path: " + relPath)
loadGenesis(relPath, null)
assertTrue(true)
}
@Test
fun shouldLoadGenesisFromFile_whenBothSpecified() {
val url = GenesisLoadTest::class.java.classLoader.getResource("genesis/frontier-test.json")
// full path
println("url.getPath() " + url!!.path)
loadGenesis(url.path, "NOT_EXIST")
assertTrue(true)
}
@Test(expected = RuntimeException::class)
fun shouldError_whenWrongPath() {
loadGenesis("NON_EXISTED_PATH", null)
assertTrue(false)
}
@Test
fun shouldLoadGenesis_whenManyOrderedConfigs() {
val properties = loadGenesis(null, "genesis-with-config.json")
properties.genesis
val bnc = properties.blockchainConfig
assertThat<BlockchainConfig>(bnc.getConfigForBlock(0), instanceOf<BlockchainConfig>(FrontierConfig::class.java))
assertThat<BlockchainConfig>(bnc.getConfigForBlock(149), instanceOf<BlockchainConfig>(FrontierConfig::class.java))
assertThat<BlockchainConfig>(bnc.getConfigForBlock(150), instanceOf<BlockchainConfig>(HomesteadConfig::class.java))
assertThat<BlockchainConfig>(bnc.getConfigForBlock(299), instanceOf<BlockchainConfig>(HomesteadConfig::class.java))
assertThat<BlockchainConfig>(bnc.getConfigForBlock(300), instanceOf<BlockchainConfig>(DaoHFConfig::class.java))
assertThat<BlockchainConfig>(bnc.getConfigForBlock(300), instanceOf<BlockchainConfig>(DaoHFConfig::class.java))
val daoHFConfig = bnc.getConfigForBlock(300) as DaoHFConfig
assertThat<BlockchainConfig>(bnc.getConfigForBlock(450), instanceOf<BlockchainConfig>(Eip150HFConfig::class.java))
assertThat<BlockchainConfig>(bnc.getConfigForBlock(10000000), instanceOf<BlockchainConfig>(Eip150HFConfig::class.java))
}
@Test
fun shouldLoadGenesis_withCodeAndNonceInAlloc() {
val genesis = GenesisLoader.loadGenesis(
javaClass.getResourceAsStream("/genesis/genesis-alloc.json"))
val bc = StandaloneBlockchain()
bc.withGenesis(genesis)
val account = Hex.decode("cd2a3d9f938e13cd947ec05abc7fe734df8dd826")
val expectedCode = Hex.decode("00ff00")
val expectedNonce: Long = 255 //FF
val actualNonce = bc.blockchain.repository.getNonce(account)
val actualCode = bc.blockchain.repository.getCode(account)
assertEquals(BigInteger.valueOf(expectedNonce), actualNonce)
assertTrue(equal(expectedCode, actualCode))
}
@Test
fun shouldLoadGenesis_withSameBlockManyConfigs() {
val properties = loadGenesis(null, "genesis-alloc.json")
properties.genesis
val bnc = properties.blockchainConfig
assertThat<BlockchainConfig>(bnc.getConfigForBlock(0), instanceOf<BlockchainConfig>(FrontierConfig::class.java))
assertThat<BlockchainConfig>(bnc.getConfigForBlock(1999), instanceOf<BlockchainConfig>(FrontierConfig::class.java))
assertThat<BlockchainConfig>(bnc.getConfigForBlock(2000), instanceOf<BlockchainConfig>(Eip160HFConfig::class.java))
assertThat<BlockchainConfig>(bnc.getConfigForBlock(10000000), instanceOf<BlockchainConfig>(Eip160HFConfig::class.java))
// check DAO extradata for mining
val SOME_EXTRA_DATA = "some-extra-data".toByteArray()
val inDaoForkExtraData = bnc.getConfigForBlock(2000).getExtraData(SOME_EXTRA_DATA, 2000)
val pastDaoForkExtraData = bnc.getConfigForBlock(2200).getExtraData(SOME_EXTRA_DATA, 2200)
assertTrue(FastByteComparisons.equal(AbstractDaoConfig.DAO_EXTRA_DATA, inDaoForkExtraData))
assertTrue(FastByteComparisons.equal(SOME_EXTRA_DATA, pastDaoForkExtraData))
}
private fun loadGenesis(genesisFile: String?, genesisResource: String?): SystemProperties {
var config = ConfigFactory.empty()
if (genesisResource != null) {
config = config.withValue("genesis",
ConfigValueFactory.fromAnyRef(genesisResource))
}
if (genesisFile != null) {
config = config.withValue("genesisFile",
ConfigValueFactory.fromAnyRef(genesisFile))
}
val properties = SystemProperties(config)
properties.genesis
return properties
}
}
| mit | 9daf533d3ae15537d9a8600ca15d2467 | 40.869048 | 127 | 0.72704 | 4.645971 | false | true | false | false |
android/storage-samples | ScopedStorage/app/src/main/java/com/samples/storage/scopedstorage/saf/SelectDocumentFileScreen.kt | 1 | 4903 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.samples.storage.scopedstorage.saf
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.material.Button
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.samples.storage.scopedstorage.Demos
import com.samples.storage.scopedstorage.HomeRoute
import com.samples.storage.scopedstorage.R
import com.samples.storage.scopedstorage.common.DocumentFilePreviewCard
import com.samples.storage.scopedstorage.mediastore.IntroCard
const val GENERIC_MIMETYPE = "*/*"
const val PDF_MIMETYPE = "application/pdf"
const val ZIP_MIMETYPE = "application/zip"
@ExperimentalFoundationApi
@Composable
fun SelectDocumentFileScreen(
navController: NavController,
viewModel: SelectDocumentFileViewModel = viewModel()
) {
val scaffoldState = rememberScaffoldState()
val error by viewModel.errorFlow.collectAsState(null)
val selectedFile by viewModel.selectedFile.observeAsState()
val selectFile =
rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
uri?.let { viewModel.onFileSelect(it) }
}
LaunchedEffect(error) {
error?.let { scaffoldState.snackbarHostState.showSnackbar(it) }
}
Scaffold(
scaffoldState = scaffoldState,
topBar = {
TopAppBar(
title = { Text(stringResource(Demos.SelectDocumentFile.name)) },
navigationIcon = {
IconButton(onClick = { navController.popBackStack(HomeRoute, false) }) {
Icon(
Icons.Filled.ArrowBack,
contentDescription = stringResource(R.string.back_button_label)
)
}
}
)
},
content = { paddingValues ->
Column(Modifier.padding(paddingValues)) {
if (selectedFile != null) {
DocumentFilePreviewCard(selectedFile!!)
} else {
IntroCard()
}
LazyVerticalGrid(cells = GridCells.Fixed(1)) {
item {
Button(
modifier = Modifier.padding(4.dp),
onClick = { selectFile.launch(arrayOf(GENERIC_MIMETYPE)) }) {
Text(stringResource(R.string.demo_select_any_document))
}
}
item {
Button(
modifier = Modifier.padding(4.dp),
onClick = { selectFile.launch(arrayOf(PDF_MIMETYPE)) }) {
Text(stringResource(R.string.demo_select_pdf_document))
}
}
item {
Button(
modifier = Modifier.padding(4.dp),
onClick = { selectFile.launch(arrayOf(ZIP_MIMETYPE)) }) {
Text(stringResource(R.string.demo_select_zip_document))
}
}
}
}
}
)
}
| apache-2.0 | e6ff0d6198753e47062e3b032ddebf70 | 38.861789 | 92 | 0.644911 | 5.221512 | false | false | false | false |
cy6erGn0m/kotlin-frontend-plugin | examples/frontend-only/src/main/kotlin/test/hello/main.kt | 1 | 881 | package test.hello
import kotlin.browser.*
import kotlin.dom.*
fun main(args: Array<String>) {
var application: ApplicationBase? = null
val state: dynamic = module.hot?.let { hot ->
hot.accept()
hot.dispose { data ->
data.appState = application?.dispose()
application = null
}
hot.data
}
if (document.body != null) {
application = start(state)
} else {
application = null
document.addEventListener("DOMContentLoaded", { application = start(state) })
}
}
fun start(state: dynamic): ApplicationBase? {
if (document.body?.hasClass("testApp") ?: false) {
val application = MainApplication()
@Suppress("UnsafeCastFromDynamic")
application.start(state?.appState ?: emptyMap())
return application
} else {
return null
}
}
| apache-2.0 | ac77e1d04f18bb50a5e0ab9c87a41e61 | 21.025 | 85 | 0.594779 | 4.494898 | false | false | false | false |
excref/kotblog | blog/service/core/src/main/kotlin/com/excref/kotblog/blog/service/common/UuidAwareDomain.kt | 1 | 865 | package com.excref.kotblog.blog.service.common
import java.util.*
import javax.persistence.MappedSuperclass
/**
* @author Arthur Asatryan
* @since 6/4/17 8:26 PM
*/
@MappedSuperclass
abstract class UuidAwareDomain(val uuid: String = UUID.randomUUID().toString()) : BasicDomain() {
//region Equals, HashCode and ToString
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is UuidAwareDomain) return false
if (!super.equals(other)) return false
if (uuid != other.uuid) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + uuid.hashCode()
return result
}
override fun toString(): String {
return "UuidAwareDomain(uuid='$uuid') ${super.toString()}"
}
//endregion
} | apache-2.0 | bf8a956a86d9ac3107d5405f648930e2 | 26.935484 | 97 | 0.645087 | 4.199029 | false | false | false | false |
softappeal/yass | kotlin/yass/test/ch/softappeal/yass/transport/socket/ContextSocketTransportTest.kt | 1 | 2841 | package ch.softappeal.yass.transport.socket
import ch.softappeal.yass.*
import ch.softappeal.yass.remote.*
import ch.softappeal.yass.remote.session.*
import ch.softappeal.yass.serialize.*
import ch.softappeal.yass.transport.*
import java.util.concurrent.*
import kotlin.test.*
private val Serializer = ContextMessageSerializer(JavaSerializer, messageSerializer(JavaSerializer))
private fun print(message: String) {
println("$message - thread ${Thread.currentThread().id} : context ${cmsContext}")
}
private fun test(serverInterceptor: Interceptor, clientInterceptor: Interceptor) {
useExecutor { executor, done ->
socketServer(
ServerSetup(Server(Service(calculatorId, CalculatorImpl, serverInterceptor)), Serializer),
executor
)
.start(executor, socketBinder(address)).use {
TimeUnit.MILLISECONDS.sleep(200L)
val calculator = socketClient(ClientSetup(Serializer), socketConnector(address))
.proxy(calculatorId, clientInterceptor)
assertNull(cmsContext)
assertEquals(3, calculator.divide(12, 4))
assertNull(cmsContext)
}
done()
}
TimeUnit.MILLISECONDS.sleep(200L)
}
class ContextSocketTransportTest {
@Test
fun bidirectional() {
test(
{ _, _, invocation ->
print("server")
try {
invocation()
} finally {
cmsContext = "server"
}
},
{ _, _, invocation ->
cmsContext = "client"
try {
invocation()
} finally {
print("client")
cmsContext = null
}
}
)
}
@Test
fun client2server() {
test(
{ _, _, invocation ->
print("server")
try {
invocation()
} finally {
cmsContext = null
}
},
{ _, _, invocation ->
cmsContext = "client"
try {
invocation()
} finally {
cmsContext = null
}
}
)
}
@Test
fun server2client() {
test(
{ _, _, invocation ->
try {
invocation()
} finally {
cmsContext = "server"
}
},
{ _, _, invocation ->
try {
invocation()
} finally {
print("client")
cmsContext = null
}
}
)
}
}
| bsd-3-clause | 9a66981e31e66f68ce962e5394b55474 | 26.852941 | 102 | 0.460401 | 5.570588 | false | true | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/ui/settings/fingerprint/FingerprintSettingsHandler.kt | 1 | 1975 | /**
* BreadWallet
*
* Created by Pablo Budelli <[email protected]> on 10/25/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.settings.fingerprint
import com.breadwallet.tools.manager.BRSharedPrefs
import com.breadwallet.ui.settings.fingerprint.FingerprintSettings.E
import com.breadwallet.ui.settings.fingerprint.FingerprintSettings.F
import drewcarlson.mobius.flow.subtypeEffectHandler
fun createFingerprintSettingsHandler() = subtypeEffectHandler<F, E> {
addFunction<F.LoadCurrentSettings> {
E.OnSettingsLoaded(
sendMoney = BRSharedPrefs.sendMoneyWithFingerprint,
unlockApp = BRSharedPrefs.unlockWithFingerprint
)
}
addConsumer<F.UpdateFingerprintSetting> { effect ->
BRSharedPrefs.unlockWithFingerprint = effect.unlockApp
BRSharedPrefs.sendMoneyWithFingerprint = effect.sendMoney
}
}
| mit | b3468633d213ac48bd602b7d4d96ebb3 | 44.930233 | 80 | 0.766076 | 4.658019 | false | false | false | false |
quran/quran_android | app/src/main/java/com/quran/labs/androidquran/presenter/recitation/PagerActivityRecitationPresenter.kt | 2 | 8835 | package com.quran.labs.androidquran.presenter.recitation
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.Lifecycle.Event.ON_CREATE
import androidx.lifecycle.Lifecycle.Event.ON_DESTROY
import androidx.lifecycle.Lifecycle.Event.ON_PAUSE
import androidx.lifecycle.Lifecycle.Event.ON_RESUME
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.quran.data.core.QuranInfo
import com.quran.data.model.SuraAyah
import com.quran.data.model.selection.startSuraAyah
import com.quran.labs.androidquran.common.toolbar.R
import com.quran.labs.androidquran.ui.PagerActivity
import com.quran.labs.androidquran.ui.helpers.SlidingPagerAdapter
import com.quran.labs.androidquran.view.AudioStatusBar
import com.quran.page.common.toolbar.AyahToolBar
import com.quran.reading.common.ReadingEventPresenter
import com.quran.recitation.common.RecitationSession
import com.quran.recitation.events.RecitationEventPresenter
import com.quran.recitation.events.RecitationPlaybackEventPresenter
import com.quran.recitation.events.RecitationSelection
import com.quran.recitation.presenter.RecitationPlaybackPresenter
import com.quran.recitation.presenter.RecitationPresenter
import com.quran.recitation.presenter.RecitationSettings
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import timber.log.Timber
import javax.inject.Inject
class PagerActivityRecitationPresenter @Inject constructor(
private val quranInfo: QuranInfo,
private val readingEventPresenter: ReadingEventPresenter,
private val recitationPresenter: RecitationPresenter,
private val recitationEventPresenter: RecitationEventPresenter,
private val recitationPlaybackPresenter: RecitationPlaybackPresenter,
private val recitationPlaybackEventPresenter: RecitationPlaybackEventPresenter,
private val recitationSettings: RecitationSettings,
) : AudioStatusBar.AudioBarRecitationListener, DefaultLifecycleObserver, LifecycleEventObserver {
private val scope = MainScope()
private lateinit var bridge: Bridge
class Bridge(
val isDualPageVisible: () -> Boolean,
val currentPage: () -> Int,
val audioStatusBar: () -> AudioStatusBar?,
val ayahToolBar: () -> AyahToolBar?,
val ensurePage: (ayah: SuraAyah) -> Unit,
val showSlider: (sliderPage: Int) -> Unit,
)
private fun isRecitationEnabled(): Boolean {
return recitationPresenter.isRecitationEnabled()
}
fun bind(activity: PagerActivity, bridge: Bridge) {
if (!isRecitationEnabled()) return
this.bridge = bridge
activity.lifecycle.addObserver(this)
}
fun unbind(activity: PagerActivity) {
activity.lifecycle.removeObserver(this)
scope.cancel()
}
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
if (!isRecitationEnabled()) return
val activity = source as PagerActivity
when (event) {
ON_CREATE -> {
recitationPresenter.bind(activity)
bridge.audioStatusBar()?.setAudioBarRecitationListener(this)
// Show recitation button in audio bar and ayah toolbar
onRecitationEnabledStateChanged(isEnabled = true)
subscribe()
}
ON_RESUME -> {
recitationPlaybackPresenter.bind(activity)
}
ON_PAUSE -> {
recitationPlaybackPresenter.unbind(activity)
}
ON_DESTROY -> {
recitationPresenter.unbind(activity)
unbind(activity)
}
else -> {}
}
}
private fun subscribe() {
// Handle Changes to Recitation Enabled
recitationPresenter.isRecitationEnabledFlow()
.onEach { onRecitationEnabledStateChanged(it) }
.launchIn(scope)
// Recitation Events
recitationEventPresenter.listeningStateFlow
.onEach { onListeningStateChange(it) }
.launchIn(scope)
recitationEventPresenter.recitationChangeFlow
.onEach { onRecitationChange(it) }
.launchIn(scope)
recitationEventPresenter.recitationSessionFlow
.onEach { onRecitationSessionChange(it) }
.launchIn(scope)
recitationEventPresenter.recitationSelectionFlow
.onEach { onRecitationSelection(it) }
.launchIn(scope)
// Recitation Playback Events
recitationPlaybackEventPresenter.playingStateFlow
.onEach { onRecitationPlayingState(it) }
.launchIn(scope)
recitationPlaybackPresenter.recitationPlaybackFlow
.onEach { onRecitationPlayback(it) }
.launchIn(scope)
}
fun onSessionEnd() {
// End recitation service if running
if (isRecitationEnabled() && recitationEventPresenter.hasRecitationSession()) {
recitationPresenter.endSession()
}
}
fun onPermissionsResult(requestCode: Int, grantResults: IntArray) {
recitationPresenter.onRequestPermissionsResult(requestCode, grantResults)
}
// Recitation Events
private fun onRecitationEnabledStateChanged(isEnabled: Boolean) {
bridge.audioStatusBar()?.apply {
if (isRecitationEnabled != isEnabled) {
isRecitationEnabled = isEnabled
switchMode(currentMode, true)
}
}
bridge.ayahToolBar()?.apply {
if (isRecitationEnabled != isEnabled) {
isRecitationEnabled = isEnabled
setMenuItemVisibility(R.id.cab_recite_from_here, isEnabled)
}
}
}
private fun onListeningStateChange(isListening: Boolean) {
refreshAudioStatusBarRecitationState()
}
private fun onRecitationChange(ayah: SuraAyah) {
val curAyah = recitationEventPresenter.recitationSession()?.currentAyah() ?: ayah
bridge.ensurePage(curAyah)
// temp workaround for forced into stopped mode on rotation because of audio service CONNECT
refreshAudioStatusBarRecitationState()
}
private fun onRecitationSessionChange(session: RecitationSession?) {
refreshAudioStatusBarRecitationState()
}
private fun onRecitationSelection(selection: RecitationSelection) {
selection.ayah()?.let { bridge.ensurePage(it) }
}
private fun onRecitationPlayingState(isPlaying: Boolean) {
refreshAudioStatusBarRecitationState()
}
private fun onRecitationPlayback(playback: RecitationSelection) {
playback.ayah()?.let { bridge.ensurePage(it) }
// temp workaround for forced into stopped mode on rotation because of audio service CONNECT
refreshAudioStatusBarRecitationState()
}
private fun refreshAudioStatusBarRecitationState() {
val audioStatusBar = bridge.audioStatusBar() ?: return
val hasSession = recitationEventPresenter.hasRecitationSession()
val isListening = recitationEventPresenter.isListening()
val isPlaying = recitationPlaybackEventPresenter.isPlaying()
val curMode = audioStatusBar.currentMode
val newMode = when {
!hasSession -> AudioStatusBar.STOPPED_MODE // 1
isListening -> AudioStatusBar.RECITATION_LISTENING_MODE // 7
isPlaying -> AudioStatusBar.RECITATION_PLAYING_MODE // 9
else -> AudioStatusBar.RECITATION_STOPPED_MODE // 8
}
if (newMode != curMode) audioStatusBar.switchMode(newMode)
}
// AudioBarRecitationListener
override fun onRecitationPressed() {
recitationPresenter.startOrStopRecitation({ ayahToStartFrom() })
}
override fun onRecitationLongPressed() {
recitationPresenter.startOrStopRecitation({ ayahToStartFrom() }, true)
}
override fun onRecitationTranscriptPressed() {
if (recitationEventPresenter.hasRecitationSession()) {
bridge.showSlider(SlidingPagerAdapter.TRANSCRIPT_PAGE)
} else {
Timber.e("Transcript pressed but we don't have a session; this should never happen")
}
}
override fun onHideVersesPressed() {
recitationSettings.toggleAyahVisibility()
}
override fun onEndRecitationSessionPressed() {
recitationPresenter.endSession()
}
override fun onPlayRecitationPressed() {
recitationPlaybackPresenter.play()
}
override fun onPauseRecitationPressed() {
recitationPlaybackPresenter.pauseIfPlaying()
}
private fun ayahToStartFrom(): SuraAyah {
val page = if (bridge.isDualPageVisible()) {
// subtracting 1 because in dual mode currentPage gives 2, 4, 6.. instead of 1, 3, 5..
// but we want to start from the first ayah of the first visible page
bridge.currentPage() - 1
} else {
bridge.currentPage()
}
// If we're in ayah mode, start from selected ayah
return readingEventPresenter.currentAyahSelection().startSuraAyah()
// If a sura starts on this page, assume the user meant to start there
?: quranInfo.getListOfSurahWithStartingOnPage(page).firstNotNullOfOrNull { SuraAyah(it, 1) }
// Otherwise, start from the beginning of the page
?: SuraAyah(quranInfo.getSuraOnPage(page), quranInfo.getFirstAyahOnPage(page))
}
}
| gpl-3.0 | a461b77fe016dd2b90168a5b7eab3083 | 34.199203 | 98 | 0.752915 | 5.068847 | false | false | false | false |
EMResearch/EvoMaster | e2e-tests/spring-rest-openapi-v3/src/test/kotlin/com/foo/rest/examples/spring/openapi/v3/SpringController.kt | 1 | 1940 | package com.foo.rest.examples.spring.openapi.v3
import org.evomaster.client.java.controller.EmbeddedSutController
import org.evomaster.client.java.controller.api.dto.AuthenticationDto
import org.evomaster.client.java.controller.api.dto.SutInfoDto
import org.evomaster.client.java.controller.internal.db.DbSpecification
import org.evomaster.client.java.controller.problem.ProblemInfo
import org.evomaster.client.java.controller.problem.RestProblem
import org.springframework.boot.SpringApplication
import org.springframework.context.ConfigurableApplicationContext
abstract class SpringController(protected val applicationClass: Class<*>) : EmbeddedSutController() {
init {
super.setControllerPort(0)
}
protected var ctx: ConfigurableApplicationContext? = null
override fun startSut(): String {
ctx = SpringApplication.run(applicationClass, "--server.port=0")
return "http://localhost:$sutPort"
}
protected val sutPort: Int
get() = (ctx!!.environment
.propertySources["server.ports"].source as Map<*, *>)["local.server.port"] as Int
override fun isSutRunning(): Boolean {
return ctx != null && ctx!!.isRunning
}
override fun stopSut() {
ctx?.stop()
ctx?.close()
}
override fun getPackagePrefixesToCover(): String {
return "com.foo."
}
override fun resetStateOfSUT() { //nothing to do
}
override fun getProblemInfo(): ProblemInfo {
return RestProblem(
"http://localhost:$sutPort/v3/api-docs",
null
)
}
override fun getInfoForAuthentication(): List<AuthenticationDto> {
return listOf()
}
override fun getDbSpecifications(): MutableList<DbSpecification>? {
return null
}
override fun getPreferredOutputFormat(): SutInfoDto.OutputFormat {
return SutInfoDto.OutputFormat.KOTLIN_JUNIT_5
}
} | lgpl-3.0 | a201010eb25b22d563eb879e4790a6d1 | 27.970149 | 101 | 0.69433 | 4.663462 | false | false | false | false |
google/audio-to-tactile | extras/android/java/com/google/audio_to_tactile/DfuFragment.kt | 1 | 8492 | /* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.audio_to_tactile
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.CheckBox
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.google.android.material.progressindicator.LinearProgressIndicator
import com.google.android.material.textfield.TextInputLayout
import dagger.hilt.android.AndroidEntryPoint
import no.nordicsemi.android.dfu.DfuProgressListener
import no.nordicsemi.android.dfu.DfuProgressListenerAdapter
import no.nordicsemi.android.dfu.DfuServiceInitiator
import no.nordicsemi.android.dfu.DfuServiceListenerHelper
/**
* Define the DFU fragment, accessed from the nav drawer. This fragment will enable the user to do a
* BLE device firmware update (DFU), sending new firmware to the wearable device.
*
* TODO: Add a test for DfuFragment.
*/
@AndroidEntryPoint class DfuFragment : Fragment() {
// Those views will be initialized later in onCreateView.
private lateinit var dfuStatusText: TextView
private lateinit var dfuProgressBar: LinearProgressIndicator
private lateinit var dfuCurrentlyConnectedDeviceCheckBox: CheckBox
private lateinit var dfuForceBootloaderCheckBox: CheckBox
private lateinit var dfuOtherDeviceCheckBox: CheckBox
private lateinit var dfuOtherDeviceAddressText: TextInputLayout
private val bleViewModel: BleViewModel by activityViewModels()
private var connectedAddress = "00:00:00:00:00:00" // Placeholder value for device address.
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root: View = inflater.inflate(R.layout.fragment_dfu, container, false)
val dfuStartButton: Button = root.findViewById(R.id.dfu_start_button)
dfuProgressBar = root.findViewById(R.id.dfu_progress_bar)
dfuStatusText = root.findViewById(R.id.dfu_status_text)
dfuCurrentlyConnectedDeviceCheckBox = root.findViewById(R.id.dfu_upload_to_connected_checkbox)
dfuForceBootloaderCheckBox = root.findViewById(R.id.prepare_for_bootloading_checkbox)
dfuOtherDeviceCheckBox = root.findViewById(R.id.dfu_to_other_device_checkbox)
dfuOtherDeviceAddressText = root.findViewById(R.id.dfu_alternative_address)
dfuProgressBar.max = 100
dfuStartButton.setOnClickListener {
// Choose the firmware file (has to be a zip file).
val intent = Intent().setType("application/zip").setAction(Intent.ACTION_GET_CONTENT)
startActivityForResult(Intent.createChooser(intent, "Select a file"), PICK_ZIP_FILE)
// Start the DFU notifications.
DfuServiceInitiator.createDfuNotificationChannel(requireContext())
DfuServiceListenerHelper.registerProgressListener(requireContext(), dfuProgressListener)
// If forcing bootloader is enabled, send the forcing command now, before DFU is started.
if (dfuForceBootloaderCheckBox.isChecked() && bleViewModel.isConnected.value == true) {
bleViewModel.prepareForBootloading()
}
}
// Do some UI logic to make sure that uploading to connected device and unconnected device
// at same time is not possible.
dfuOtherDeviceCheckBox.setOnClickListener {
if (dfuOtherDeviceCheckBox.isChecked() == false) {
dfuForceBootloaderCheckBox.setEnabled(true)
dfuOtherDeviceAddressText.setEnabled(false)
}
if (dfuOtherDeviceCheckBox.isChecked() == true) {
dfuForceBootloaderCheckBox.setEnabled(false)
dfuOtherDeviceAddressText.setEnabled(true)
dfuCurrentlyConnectedDeviceCheckBox.setChecked(false)
dfuForceBootloaderCheckBox.setChecked(false)
}
}
dfuCurrentlyConnectedDeviceCheckBox.setOnClickListener {
if (dfuCurrentlyConnectedDeviceCheckBox.isChecked() == true) {
dfuOtherDeviceCheckBox.setChecked(false)
dfuForceBootloaderCheckBox.setEnabled(true)
dfuOtherDeviceAddressText.setEnabled(false)
}
}
return root
}
private val dfuProgressListener: DfuProgressListener =
object : DfuProgressListenerAdapter() {
override fun onDeviceConnecting(deviceAddress: String) {
Toast.makeText(context, "Connecting", Toast.LENGTH_SHORT).show()
dfuStatusText.text = "Connecting"
}
override fun onDeviceConnected(deviceAddress: String) {
Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show()
dfuStatusText.text = "Connected"
}
override fun onDfuProcessStarting(deviceAddress: String) {
Toast.makeText(context, "Starting DFU", Toast.LENGTH_SHORT).show()
dfuStatusText.text = "Starting DFU"
}
override fun onDfuProcessStarted(deviceAddress: String) {
Toast.makeText(context, "Started DFU", Toast.LENGTH_SHORT).show()
dfuStatusText.text = "Started DFU"
}
override fun onProgressChanged(
deviceAddress: String,
percent: Int,
speed: Float,
avgSpeed: Float,
currentPart: Int,
partsTotal: Int
) {
dfuProgressBar.progress = percent
dfuStatusText.text = "Uploading Code..."
}
override fun onDeviceDisconnecting(deviceAddress: String?) {
Toast.makeText(context, "Disconnecting", Toast.LENGTH_SHORT).show()
dfuStatusText.text = "Disconnecting"
}
override fun onDeviceDisconnected(deviceAddress: String) {
Toast.makeText(context, "Disconnected", Toast.LENGTH_SHORT).show()
dfuStatusText.text = "Disconnected"
}
override fun onDfuCompleted(deviceAddress: String) {
Toast.makeText(context, "Finished", Toast.LENGTH_SHORT).show()
dfuStatusText.text = "Finished"
}
override fun onDfuAborted(deviceAddress: String) {
Toast.makeText(context, "Aborted", Toast.LENGTH_SHORT).show()
dfuStatusText.text = "Aborted"
}
override fun onError(deviceAddress: String, error: Int, errorType: Int, message: String?) {
dfuStatusText.text = "Error $error, $errorType, $message"
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show()
}
}
// Actions when the firmware file is chosen.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PICK_ZIP_FILE && resultCode == RESULT_OK) {
// The URI with the location of the file. Returns on null.
val selectedFile = data?.data ?: return
val address =
if (dfuCurrentlyConnectedDeviceCheckBox.isChecked() &&
bleViewModel.isConnected.value == true
) {
bleViewModel.deviceBleAddress
} else if (dfuOtherDeviceCheckBox.isChecked()) {
dfuOtherDeviceAddressText.getEditText()?.getText().toString()
} else {
"00:00:00:00:00:00" // Placeholder.
}
// Make sure the address is defined and is the right size before uploading to device.
val ADDRESS_LENGTH = 17
if (address == "00:00:00:00:00:00" || address.length != ADDRESS_LENGTH) {
Toast.makeText(context, "Invalid address-$address", Toast.LENGTH_LONG).show()
} else {
// Start the upload.
val starter =
DfuServiceInitiator(address)
.setKeepBond(false)
.setForceDfu(true)
.setPacketsReceiptNotificationsEnabled(false)
.setUnsafeExperimentalButtonlessServiceInSecureDfuEnabled(true)
.setZip(selectedFile, null)
starter.start(requireContext(), DfuService::class.java)
}
}
}
private companion object {
const val PICK_ZIP_FILE = 111
const val TAG = "dfuFragment"
}
}
| apache-2.0 | ed412782f0730d59bc29df74502e5535 | 39.056604 | 100 | 0.718205 | 4.754759 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/rest/resource/dependency/RelatedTo.kt | 1 | 1022 | package org.evomaster.core.problem.rest.resource.dependency
/**
* key relies on target
*/
open class RelatedTo(
private val key: String,
open val targets : MutableList<out Any>,
var probability: Double,
var additionalInfo : String = ""
){
companion object {
private const val DIRECT_DEPEND = "$->$"
fun generateKeyForMultiple(keys : List<String>) : String = if(keys.isEmpty()) "" else if( keys.size == 1) keys.first() else "{${keys.joinToString(",")}}"
fun parseMultipleKey(key : String) : List<String> {
if(key.startsWith("{") && key.endsWith("}")){
return key.substring(1, key.length - 1).split(",")
}
return listOf(key)
}
}
open fun notateKey() : String = key
open fun originalKey() : String = key
open fun getTargetsName () : String = generateKeyForMultiple(targets.map { it.toString() })
open fun getName() : String = "${notateKey()}$DIRECT_DEPEND${getTargetsName()}"
} | lgpl-3.0 | ebdb6e5f482fd21834f999aedc832eb5 | 34.275862 | 162 | 0.599804 | 4.188525 | false | false | false | false |
andersonFaro9/AppAbcAprender | app/src/main/java/com/kot/faro/myapplication/DevsActivity.kt | 1 | 2270 | package com.kot.faro.myapplication
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import com.kot.faro.myapplication.animaismath.MathTwoBearActivity
import com.kot.faro.myapplication.fruitsmath.MathOrangeFourActivity
class DevsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_devs)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem) : Boolean {
when (item.itemId) {
R.id.letras_frutas -> {
val intent = Intent(this@DevsActivity, GrapeActivity::class.java)
startActivity (intent)
return true
}
R.id.dev -> {
val intent = Intent(this@DevsActivity, DevsActivity::class.java)
startActivity (intent)
return true
}
R.id.menu_inicial -> {
val intent = Intent(this@DevsActivity, MenuActivity::class.java)
startActivity (intent)
return true
}
R.id.sobre -> {
val intent = Intent(this@DevsActivity, SobreActivity::class.java)
startActivity (intent)
return true
}
R.id.letras_animais -> {
val intent = Intent(this@DevsActivity, PortuguesBearActivity::class.java)
startActivity (intent)
return true
}
R.id.matematica_animais -> {
val intent = Intent(this@DevsActivity, MathTwoBearActivity::class.java)
startActivity (intent)
return true
}
R.id.matematica_frutas -> {
val intent = Intent(this@DevsActivity, MathOrangeFourActivity::class.java)
startActivity (intent)
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
}
| apache-2.0 | 4e6c485086a755f1d6d09e495d0522e7 | 23.945055 | 90 | 0.577533 | 4.956332 | false | false | false | false |
cnsgcu/KotlinKoans | src/v_builders/_40_BuildersHowItWorks.kt | 1 | 1963 | package v_builders.builders
import util.questions.Answer
import util.questions.Answer.*
fun todoTask40(): Nothing = TODO(
"""
Task 40.
Look at the questions below and give your answers:
change 'insertAnswerHere()' in task26's map to your choice (a, b or c).
All the constants are imported via 'util.questions.Answer.*', so they can be accessed by name.
"""
)
fun insertAnswerHere() = todoTask40()
fun task40() = linkedMapOf<Int, Answer>(
/*
1. In the Kotlin code
tr {
td {
text("Product")
}
td {
text("Popularity")
}
}
'td' is:
a. special built-in syntactic construct
b. function declaration
c. function invocation
*/
1 to c,
/*
2. In the Kotlin code
tr (color = "yellow") {
td {
text("Product")
}
td {
text("Popularity")
}
}
'color' is:
a. new variable declaration
b. argument name
c. argument value
*/
2 to b,
/*
3. The block
{
text("Product")
}
from the previous question is:
a. block inside built-in syntax construction 'td'
b. function literal (or "lambda")
c. something mysterious
*/
3 to b,
/*
4. For the code
tr (color = "yellow") {
this.td {
text("Product")
}
td {
text("Popularity")
}
}
which of the following is true:
a. this code doesn't compile
b. 'this' refers to an instance of an outer class
c. 'this' refers to a receiver parameter TR of the function literal:
tr (color = "yellow") { TR.(): Unit ->
this.td {
text("Product")
}
}
*/
4 to c
)
| mit | 1d432ebf8516b65def40d13922f367cc | 21.306818 | 102 | 0.478349 | 4.451247 | false | false | false | false |
yuttadhammo/BodhiTimer | app/src/main/java/org/yuttadhammo/BodhiTimer/Models/TimerList.kt | 1 | 1956 | package org.yuttadhammo.BodhiTimer.Models
import android.text.TextUtils
import org.yuttadhammo.BodhiTimer.Const.SessionTypes
import timber.log.Timber
class TimerList {
class Timer {
val duration: Int
val uri: String
val sessionType: SessionTypes
constructor(mDuration: Int, mUri: String) : super() {
duration = mDuration
uri = mUri
sessionType = SessionTypes.REAL
}
constructor(mDuration: Int, mUri: String, mSessionType: SessionTypes) : super() {
duration = mDuration
uri = mUri
sessionType = mSessionType
}
}
val timers: ArrayList<Timer>
constructor(advTimeString: String) {
timers = timeStringToList(advTimeString)
}
constructor() {
timers = ArrayList()
}
val string: String
get() = listToTimeString(timers)
companion object {
fun timeStringToList(advTimeString: String): ArrayList<Timer> {
val list = ArrayList<Timer>()
val advTime = advTimeString.split("^").toTypedArray()
for (s in advTime) {
// advTime[n] will be of format timeInMs#pathToSound
val thisAdvTime = s.split("#").toTypedArray()
var duration: Int
try {
duration = thisAdvTime[0].toInt()
val timer = Timer(duration, thisAdvTime[1])
list.add(timer)
} catch (e: Exception) {
Timber.e(e)
}
}
return list
}
fun listToTimeString(list: ArrayList<Timer>): String {
val stringArray = ArrayList<String?>()
for (timer in list) {
stringArray.add(timer.duration.toString() + "#" + timer.uri + "#" + timer.sessionType)
}
return TextUtils.join("^", stringArray)
}
}
} | gpl-3.0 | 981b8553129a4827aed581af7e066bd1 | 28.651515 | 102 | 0.546012 | 4.853598 | false | false | false | false |
Esri/arcgis-runtime-samples-android | kotlin/display-device-location-with-nmea-data-sources/src/main/java/com/esri/arcgisruntime/sample/displaydevicelocationwithnmeadatasources/MainActivity.kt | 1 | 11060 | /* Copyright 2021 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.displaydevicelocationwithnmeadatasources
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.SpatialReferences
import com.esri.arcgisruntime.location.LocationDataSource
import com.esri.arcgisruntime.location.NmeaLocationDataSource
import com.esri.arcgisruntime.location.NmeaSatelliteInfo
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.LocationDisplay
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.displaydevicelocationwithnmeadatasources.databinding.ActivityMainBinding
import com.google.android.material.floatingactionbutton.FloatingActionButton
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.nio.charset.StandardCharsets
import java.util.*
import kotlin.collections.ArrayList
import kotlin.concurrent.timerTask
class MainActivity : AppCompatActivity() {
private val TAG = MainActivity::class.java.simpleName
// Create a new NMEA location data source
private val nmeaLocationDataSource: NmeaLocationDataSource =
NmeaLocationDataSource(SpatialReferences.getWgs84())
// Location datasource listener
private var locationDataSourceListener: LocationDataSource.StatusChangedListener? = null
// Create a timer to simulate a stream of NMEA data
private var timer = Timer()
// Keeps track of the timer during play/pause
private var count = 0
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
private val accuracyTV: TextView by lazy {
activityMainBinding.accuracyTV
}
private val satelliteCountTV: TextView by lazy {
activityMainBinding.satelliteCountTV
}
private val satelliteIDsTV: TextView by lazy {
activityMainBinding.satelliteIDsTV
}
private val systemTypeTV: TextView by lazy {
activityMainBinding.systemTypeTV
}
private val playPauseFAB: FloatingActionButton by lazy {
activityMainBinding.playPauseFAB
}
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 with the Basemap style and set it to the MapView
val map = ArcGISMap(BasemapStyle.ARCGIS_NAVIGATION)
mapView.map = map
// Set a viewpoint on the map view centered on Redlands, California
mapView.setViewpoint(
Viewpoint(
Point(-117.191, 34.0306, SpatialReferences.getWgs84()),
100000.0
)
)
// Set the NMEA location data source onto the map view's location display
val locationDisplay = mapView.locationDisplay
locationDisplay.locationDataSource = nmeaLocationDataSource
locationDisplay.autoPanMode = LocationDisplay.AutoPanMode.RECENTER
// Disable map view interaction, the location display will automatically center on the mock device location
mapView.interactionOptions.isPanEnabled = false
mapView.interactionOptions.isZoomEnabled = false
playPauseFAB.setOnClickListener {
if (!nmeaLocationDataSource.isStarted) {
// Start location data source
displayDeviceLocation()
setLocationStatus(true)
} else {
// Stop receiving and displaying location data
nmeaLocationDataSource.stop()
setLocationStatus(false)
}
}
}
/**
* Sets the FAB button to "Start"/"Stop" based on the argument [isShowingLocation]
*/
private fun setLocationStatus(isShowingLocation: Boolean) = if (isShowingLocation) {
playPauseFAB.setImageDrawable(
AppCompatResources.getDrawable(
this,
R.drawable.ic_round_pause_24
)
)
} else {
playPauseFAB.setImageDrawable(
AppCompatResources.getDrawable(
this,
R.drawable.ic_round_play_arrow_24
)
)
}
/**
* Initializes the location data source, reads the mock data NMEA sentences, and displays location updates from that file
* on the location display. Data is pushed to the data source using a timeline to simulate live updates, as they would
* appear if using real-time data from a GPS dongle
*/
private fun displayDeviceLocation() {
val simulatedNmeaDataFile = File(getExternalFilesDir(null)?.path + "/Redlands.nmea")
if (simulatedNmeaDataFile.exists()) {
try {
// Read the nmea file contents using a buffered reader and store the mock data sentences in a list
val bufferedReader = BufferedReader(FileReader(simulatedNmeaDataFile.path))
// Add carriage return for NMEA location data source parser
val nmeaSentences: MutableList<String> = mutableListOf()
var line = bufferedReader.readLine()
while (line != null) {
nmeaSentences.add(line + "\n")
line = bufferedReader.readLine()
}
bufferedReader.close()
// Set up the accuracy for each location change
nmeaLocationDataSource.addLocationChangedListener {
//Convert from Meters to Foot
val horizontalAccuracy = it.location.horizontalAccuracy * 3.28084
val verticalAccuracy = it.location.verticalAccuracy * 3.28084
accuracyTV.text = "Accuracy- Horizontal: %.1fft, Vertical: %.1fft".format(
horizontalAccuracy,
verticalAccuracy
)
}
// Handle when LocationDataSource status is changed
locationDataSourceListener = LocationDataSource.StatusChangedListener {
if (it.status == LocationDataSource.Status.STARTED) {
// Add a satellite changed listener to the NMEA location data source and display satellite information
setupSatelliteChangedListener()
timer = Timer()
// Push the mock data NMEA sentences into the data source every 250 ms
timer.schedule(timerTask {
// Only push data when started
if (it.status == LocationDataSource.Status.STARTED)
nmeaLocationDataSource.pushData(
nmeaSentences[count++].toByteArray(
StandardCharsets.UTF_8
)
)
// Reset the count after the last data point is reached
if (count == nmeaSentences.size)
count = 0
}, 250, 250)
setLocationStatus(true)
}
if (it.status == LocationDataSource.Status.STOPPED) {
timer.cancel()
nmeaLocationDataSource.removeStatusChangedListener(
locationDataSourceListener
)
setLocationStatus(false)
}
}
// Initialize the location data source and prepare to begin receiving location updates when data is pushed
// As updates are received, they will be displayed on the map
nmeaLocationDataSource.addStatusChangedListener(locationDataSourceListener)
nmeaLocationDataSource.startAsync()
} catch (e: Exception) {
Toast.makeText(
this,
"Error while setting up NmeaLocationDataSource: " + e.message,
Toast.LENGTH_SHORT
).show()
Log.e(TAG, "Error while setting up NmeaLocationDataSource: " + e.message.toString())
}
} else {
Toast.makeText(this, "NMEA File not found", Toast.LENGTH_SHORT).show()
}
}
/**
* Obtains NMEA satellite information from the NMEA location data source, and displays satellite information on the app
*/
private fun setupSatelliteChangedListener() {
nmeaLocationDataSource.addSatellitesChangedListener {
val uniqueSatelliteIDs: HashSet<Int> = hashSetOf()
// Get satellite information from the NMEA location data source every time the satellites change
val nmeaSatelliteInfoList: List<NmeaSatelliteInfo> = it.satelliteInfos
// Set the text of the satellite count label
satelliteCountTV.text = "Satellite count- " + nmeaSatelliteInfoList.size
for (satInfo in nmeaSatelliteInfoList) {
// Collect unique satellite ids
uniqueSatelliteIDs.add(satInfo.id)
// Sort the ids numerically
val sortedIds: MutableList<Int> = ArrayList(uniqueSatelliteIDs)
sortedIds.sort()
// Display the satellite system and id information
systemTypeTV.text = "System- " + satInfo.system
satelliteIDsTV.text = "Satellite IDs- $sortedIds"
}
}
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onDestroy() {
nmeaLocationDataSource.stop()
mapView.dispose()
super.onDestroy()
}
}
| apache-2.0 | ff15a21057a48abd2adec62a7906be67 | 39.512821 | 126 | 0.632731 | 5.6 | false | false | false | false |
xwiki-contrib/android-authenticator | app/src/main/java/org/xwiki/android/sync/utils/SharedPrefsUtils.kt | 1 | 4977 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This 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 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.android.sync.utils
import android.content.Context
import java.util.*
/**
* Settings shared preferences name.
*/
private val SETTING = "Setting"
/**
* Put value into shared preferences.
*
* @param context Context for getting shared preferences
* @param key Key to add
* @param value Value to add
*/
fun putValue(context: Context, key: String, value: Int) {
val sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE).edit()
sp.putInt(key, value)
sp.apply()
}
/**
* Put value into shared preferences.
*
* @param context Context for getting shared preferences
* @param key Key to add
* @param value Value to add
*/
fun putValue(context: Context, key: String, value: Boolean) {
val sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE).edit()
sp.putBoolean(key, value)
sp.apply()
}
/**
* Put value into shared preferences.
*
* @param context Context for getting shared preferences
* @param key Key to add
* @param value Value to add
*/
fun putValue(context: Context, key: String, value: String) {
val sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE).edit()
sp.putString(key, value)
sp.apply()
}
/**
* Put value into shared preferences.
*
* @param context Context for getting shared preferences
* @param key Key to add
* @param list Value to add
*/
fun putArrayList(context: Context, key: String, list: List<String>) {
val sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE)
val edit = sp.edit()
val set = HashSet(list)
edit.putStringSet(key, set)
edit.apply()
}
/**
* Get value from shared preferences.
*
* @param context Context for getting shared preferences
* @param key Key for getting
* @return List value if exists or null
*/
fun getArrayList(context: Context, key: String): MutableList<String>? {
val sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE)
val set = sp.getStringSet(key, null) ?: return null
return ArrayList(set)
}
/**
* Clear all data from shared preferences.
*
* @param context Context for getting shared preferences
*/
fun clearAll(context: Context) {
val sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE)
sp.edit().clear().apply()
}
/**
* Get value from shared preferences.
*
* @param context Context for getting shared preferences
* @param key Key for getting
* @param defValue Value which will be returned if value by key is absent
* @return int value if exists or defValue
*/
fun getValue(context: Context, key: String, defValue: Int): Int {
val sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE)
return sp.getInt(key, defValue)
}
/**
* Get value from shared preferences.
*
* @param context Context for getting shared preferences
* @param key Key for getting
* @param defValue Value which will be returned if value by key is absent
* @return boolean value if exists or defValue
*/
fun getValue(context: Context, key: String, defValue: Boolean): Boolean {
val sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE)
return sp.getBoolean(key, defValue)
}
/**
* Get value from shared preferences.
*
* @param context Context for getting shared preferences
* @param key Key for getting
* @param defValue Value which will be returned if value by key is absent
* @return String value if exists or defValue
*/
fun getValue(context: Context, key: String, defValue: String?): String {
val sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE)
return sp.getString(key, defValue) ?: defValue ?: error("Can't get value for key $key")
}
/**
* Remove value from shared preferences by key.
*
* @param context Context for getting shared preferences
* @param key Key for removing
*/
fun removeKeyValue(context: Context, key: String) {
val sp = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE)
sp.edit().remove(key).apply()
}
/**
* Utils for shared preferences
*
* @version $Id: f6a4505e6593fc031f5b944abcf6ab3632b3014b $
*/
class SharedPrefsUtils
| lgpl-2.1 | 218f87acebee022382149523008969e4 | 29.163636 | 91 | 0.722122 | 3.96258 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/ui/TabStripAdapter.kt | 1 | 3272 | package com.battlelancer.seriesguide.ui
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.battlelancer.seriesguide.util.ThemeUtils.setDefaultStyle
import com.uwetrottmann.seriesguide.widgets.SlidingTabLayout
/**
* Helper class for easy setup of a {@link SlidingTabLayout} with a mutable set of tabs.
* Requires that tabs each have a unique title string resource
* as it is used to uniquely identify a tab.
*/
open class TabStripAdapter(
private val fragmentActivity: FragmentActivity,
private val viewPager: ViewPager2,
private val tabLayout: SlidingTabLayout
) : FragmentStateAdapter(fragmentActivity) {
private val tabs = ArrayList<TabInfo>()
private val tabTitleSupplier = SlidingTabLayout.TabTitleSupplier { position ->
val tabInfo = tabs.getOrNull(position)
return@TabTitleSupplier if (tabInfo != null) {
tabLayout.context.getString(tabInfo.titleRes)
} else ""
}
init {
// Preload next/previous page for smoother swiping.
viewPager.offscreenPageLimit = 1
viewPager.adapter = this
tabLayout.setDefaultStyle()
tabLayout.setViewPager2(viewPager, tabTitleSupplier)
}
/**
* Adds a new tab at the end.
*
* Make sure to call [notifyTabsChanged] after you have added them all.
*/
fun addTab(@StringRes titleRes: Int, fragmentClass: Class<*>, args: Bundle?) {
tabs.add(tabs.size, TabInfo(fragmentClass, args, titleRes))
}
/**
* Adds a new tab at the given position.
*
* Make sure to call [notifyTabsChanged] after you have added them all.
*/
fun addTab(@StringRes titleRes: Int, fragmentClass: Class<*>, args: Bundle?, position: Int) {
tabs.add(position, TabInfo(fragmentClass, args, titleRes))
}
/**
* Notifies the adapter and tab strip that the tabs have changed.
*/
@SuppressLint("NotifyDataSetChanged")
fun notifyTabsChanged() {
notifyDataSetChanged()
// update tabs
tabLayout.setViewPager2(viewPager, tabTitleSupplier)
}
// Using titleRes instead of introducing an ID property as it is unique for tabs of this app.
override fun getItemId(position: Int): Long {
return if (position < tabs.size) {
tabs[position].titleRes.toLong()
} else {
RecyclerView.NO_ID
}
}
override fun containsItem(itemId: Long): Boolean =
tabs.find { it.titleRes.toLong() == itemId } != null
override fun getItemCount(): Int = tabs.size
override fun createFragment(position: Int): Fragment {
val tab = tabs[position]
return fragmentActivity.supportFragmentManager.fragmentFactory.instantiate(
fragmentActivity.classLoader,
tab.fragmentClass.name
).apply { tab.args?.let { arguments = it } }
}
data class TabInfo(
val fragmentClass: Class<*>,
val args: Bundle?,
val titleRes: Int
)
} | apache-2.0 | ac9fae9336510f97c76de87f2869f54d | 32.397959 | 97 | 0.68643 | 4.797654 | false | false | false | false |
AlmasB/FXGL | fxgl-tools/src/main/kotlin/com/almasb/fxgl/tools/dialogues/PersistentStorageHandler.kt | 1 | 2184 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.tools.dialogues
import com.almasb.fxgl.core.EngineService
import com.almasb.fxgl.core.collection.PropertyMap
import com.almasb.fxgl.core.serialization.Bundle
import com.almasb.fxgl.cutscene.dialogue.DialogueNodeType
import com.almasb.fxgl.dsl.getSaveLoadService
import com.almasb.fxgl.logging.Logger
import com.almasb.fxgl.profile.DataFile
import com.almasb.fxgl.profile.SaveLoadHandler
import javafx.scene.paint.Color
import java.io.Serializable
/**
* TODO: save properties (game vars) to bundle, also consider easy API to read/write PropertyMap
*
* @author Almas Baimagambetov ([email protected])
*/
class PersistentStorageService : EngineService() {
override fun onMainLoopStarting() {
getSaveLoadService().addHandler(PersistentStorageHandler())
getSaveLoadService().readAndLoadTask("fxgl-dialogue-editor.prefs").run()
}
override fun onExit() {
getSaveLoadService().saveAndWriteTask("fxgl-dialogue-editor.prefs").run()
}
}
class PersistentStorageHandler : SaveLoadHandler {
override fun onSave(data: DataFile) {
val bundle = Bundle("preferences")
NodeView.colors.forEach { (key, color) ->
bundle.put("color_${key}", color.value.toSerializable())
}
data.putBundle(bundle)
}
override fun onLoad(data: DataFile) {
val bundle = data.getBundle("preferences")
bundle.data.forEach { (key, color) ->
if (key.startsWith("color_")) {
val type = key.removePrefix("color_")
val nodeType = DialogueNodeType.valueOf(type)
NodeView.colors[nodeType]?.value = (color as SerializableColor).toColor()
}
}
}
}
private class SerializableColor(
val r: Double,
val g: Double,
val b: Double,
val a: Double
) : Serializable {
fun toColor(): Color = Color.color(r, g, b, a)
}
private fun Color.toSerializable(): SerializableColor = SerializableColor(this.red, this.green, this.blue, this.opacity) | mit | bd2bba3146b76e341cd34c8faf1aadf7 | 28.931507 | 120 | 0.684066 | 4.120755 | false | false | false | false |
AlmasB/FXGL | fxgl-core/src/main/kotlin/com/almasb/fxgl/input/UserAction.kt | 1 | 1698 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.input
/**
* Represents a user action which is typically triggered when a key
* or a mouse event has occurred. User actions have unique names so that they
* are easily identifiable. An action can be bound to a key or mouse event
* using Input.
*
* @author Almas Baimagambetov (AlmasB) ([email protected])
*/
abstract class UserAction(
/**
* Constructs new user action with given name. Name examples:
* Walk Forward, Shoot, Use, Aim, etc.
*/
val name: String) {
override fun equals(other: Any?): Boolean {
return other is UserAction && name == other.name
}
override fun hashCode(): Int {
return name.hashCode()
}
override fun toString(): String {
return name
}
internal fun begin() = onActionBegin()
internal fun action() = onAction()
internal fun end() = onActionEnd()
internal fun beginDoubleAction() = onDoubleActionBegin()
/**
* Called once in the same tick when triggered.
*/
protected open fun onActionBegin() {}
/**
* Called as long as the trigger is being held (pressed).
* Starts from the next tick from the one when was triggered.
*/
protected open fun onAction() {}
/**
* Called once in the same tick when trigger was released.
*/
protected open fun onActionEnd() {}
/**
* Called once in the same tick when triggered for the second time
* within a specified period of time.
*/
protected open fun onDoubleActionBegin() {}
} | mit | e78adc3126a9ce88a1e3cbf10c8122b3 | 25.968254 | 77 | 0.638398 | 4.43342 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/action/TitleBarActionRegistrar.kt | 1 | 1923 | package cn.yiiguxing.plugin.translate.action
import cn.yiiguxing.plugin.translate.util.IdeVersion
import cn.yiiguxing.plugin.translate.util.Plugin
import cn.yiiguxing.plugin.translate.util.w
import com.intellij.ide.AppLifecycleListener
import com.intellij.ide.plugins.DynamicPluginListener
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.Constraints
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.impl.ActionManagerImpl
import com.intellij.openapi.diagnostic.Logger
class TitleBarActionRegistrar : AppLifecycleListener, DynamicPluginListener {
override fun appFrameCreated(commandLineArgs: MutableList<String>) {
if (IdeVersion >= IdeVersion.IDE2022_2) {
registerAction()
}
}
override fun pluginLoaded(pluginDescriptor: IdeaPluginDescriptor) {
if (IdeVersion >= IdeVersion.IDE2022_2 && pluginDescriptor.pluginId.idString == Plugin.PLUGIN_ID) {
registerAction()
}
}
private fun registerAction() {
try {
val actionManager = ActionManager.getInstance() as ActionManagerImpl
val group = actionManager.getAction(TITLE_BAR_ACTION_GROUP_ID) as? DefaultActionGroup ?: return
val action = actionManager.getAction(TRANSLATION_TITLE_BAR_ACTION_ID) ?: return
if (!group.containsAction(action)) {
actionManager.addToGroup(group, action, Constraints.FIRST)
}
} catch (e: Throwable) {
LOG.w(e)
}
}
companion object {
private const val TRANSLATION_TITLE_BAR_ACTION_ID = "TranslationTitleBar"
private const val TITLE_BAR_ACTION_GROUP_ID = "ExperimentalToolbarActions"
private val LOG: Logger = Logger.getInstance(TitleBarActionRegistrar::class.java)
}
} | mit | d5365cf8657a2fe461181ac96fe58fb9 | 38.265306 | 107 | 0.725949 | 4.759901 | false | false | false | false |
zhengjiong/ZJ_KotlinStudy | src/main/kotlin/com/zj/example/kotlin/helloworld/2.NumberExample.kt | 1 | 659 | package com.zj.example.kotlin.helloworld
/**
*
* CreateTime: 17/9/6 10:40
* @author 郑炯
*/
val aInt: Int = 1
val bInt: Int = 0xFF
val cInt: Int = 0b00000011
val aLong: Long = 1;
val bLong: Long = Long.MAX_VALUE
val aFloat: Float = 1F
val nanFloat: Float = Float.NaN
val aDouble: Double = 1.0
val bDouble: Double = Double.NaN
fun main(args: Array<String>) {
println(aInt)
println(bInt)
println(cInt)
//输出 1 + 255 = 256
println("$aInt + $bInt = ${aInt + bInt}")
println(aLong)
println(bLong)
println(aFloat)
println(nanFloat)
println(aDouble)
println(bDouble)
println(0f / 0f)//输入NaN
} | mit | b9880f5b8dcf7b9e73e151f40ed16c4d | 14.804878 | 45 | 0.632148 | 2.85022 | false | false | false | false |
proxer/ProxerAndroid | src/main/kotlin/me/proxer/app/anime/resolver/Mp4UploadStreamResolver.kt | 1 | 2610 | package me.proxer.app.anime.resolver
import io.reactivex.Single
import me.proxer.app.MainApplication.Companion.GENERIC_USER_AGENT
import me.proxer.app.exception.StreamResolutionException
import me.proxer.app.util.extension.buildSingle
import me.proxer.app.util.extension.toBodySingle
import me.proxer.app.util.extension.toPrefixedUrlOrNull
import okhttp3.Request
/**
* @author Ruben Gees
*/
object Mp4UploadStreamResolver : StreamResolver() {
private val packedRegex = Regex("return p.*?'(.*?)',(\\d+),(\\d+),'(.*?)'")
private val urlRegex = Regex("player.src\\(\"(.*?)\"\\)")
override val name = "MP4Upload"
override fun resolve(id: String): Single<StreamResolutionResult> = api.anime.link(id)
.buildSingle()
.flatMap { url ->
client
.newCall(
Request.Builder()
.get()
.url(url.toPrefixedUrlOrNull() ?: throw StreamResolutionException())
.header("User-Agent", GENERIC_USER_AGENT)
.header("Connection", "close")
.build()
)
.toBodySingle()
}
.map {
val packedFunction = packedRegex.find(it) ?: throw StreamResolutionException()
val p = packedFunction.groupValues[1]
val a = packedFunction.groupValues[2].toIntOrNull() ?: throw StreamResolutionException()
val c = packedFunction.groupValues[3].toIntOrNull() ?: throw StreamResolutionException()
val k = packedFunction.groupValues[4].split("|")
if (p.isBlank() || k.size != c) {
throw StreamResolutionException()
}
val unpacked = unpack(p, a, c, k)
val urlRegexResult = urlRegex.find(unpacked) ?: throw StreamResolutionException()
val url = urlRegexResult.groupValues[1]
url.toPrefixedUrlOrNull() ?: throw StreamResolutionException()
}
.map {
StreamResolutionResult.Video(
it,
"video/mp4",
referer = "https://www.mp4upload.com/",
internalPlayerOnly = true
)
}
private fun unpack(p: String, a: Int, c: Int, k: List<String>): String {
return (c - 1 downTo 0).fold(
p,
{ acc, next ->
if (k[next].isNotEmpty()) {
acc.replace(Regex("\\b" + next.toString(a) + "\\b"), k[next])
} else {
acc
}
}
)
}
}
| gpl-3.0 | 657ec1afbef706a7c4e7b1a8f00bf9be | 33.8 | 100 | 0.544444 | 4.815498 | false | false | false | false |
LorittaBot/Loritta | web/embed-editor/embed-editor/src/main/kotlin/net/perfectdreams/loritta/embededitor/editors/EmbedDescriptionEditor.kt | 1 | 1758 | package net.perfectdreams.loritta.embededitor.editors
import kotlinx.html.CommonAttributeGroupFacade
import kotlinx.html.FlowContent
import kotlinx.html.classes
import kotlinx.html.js.onClickFunction
import net.perfectdreams.loritta.embededitor.EmbedEditor
import net.perfectdreams.loritta.embededitor.data.DiscordEmbed
import net.perfectdreams.loritta.embededitor.data.DiscordMessage
import net.perfectdreams.loritta.embededitor.generator.EmbedAuthorGenerator
import net.perfectdreams.loritta.embededitor.generator.EmbedDescriptionGenerator
import net.perfectdreams.loritta.embededitor.utils.lovelyButton
object EmbedDescriptionEditor : EditorBase {
val isNotNull: ELEMENT_CONFIGURATION = { m, discordMessage, currentElement, renderInfo ->
currentElement.classes += "clickable"
currentElement.onClickFunction = {
descriptionPopup(discordMessage.embed!!, m)
}
}
val isNull: ELEMENT_CONFIGURATION = { m, discordMessage, currentElement, renderInfo ->
lovelyButton(
"fas fa-align-justify",
"Adicionar Descrição"
) {
descriptionPopup(discordMessage.embed!!, m)
}
}
fun descriptionPopup(embed: DiscordEmbed, m: EmbedEditor) = genericPopupTextAreaWithSaveAndDelete(
m,
{
m.activeMessage!!.copy(
embed = m.activeMessage!!.embed!!.copy(description = it)
)
},
{
m.activeMessage!!.copy(
embed = m.activeMessage!!.embed!!.copy(description = null)
)
},
embed.description ?: "Loritta é muito fofa!",
DiscordEmbed.MAX_DESCRIPTION_LENGTH
)
} | agpl-3.0 | 804c9156a35d507218cb463c3db1574c | 36.361702 | 102 | 0.665527 | 5.207715 | false | false | false | false |
cbeyls/fosdem-companion-android | app/src/main/java/be/digitalia/fosdem/settings/UserSettingsProvider.kt | 1 | 2930 | package be.digitalia.fosdem.settings
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.preference.PreferenceManager
import be.digitalia.fosdem.R
import be.digitalia.fosdem.utils.DateUtils
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import java.time.ZoneId
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class UserSettingsProvider @Inject constructor(@ApplicationContext context: Context) {
private val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
init {
PreferenceManager.setDefaultValues(context, R.xml.settings, false)
}
private val conferenceZoneIdFlow: Flow<ZoneId> = flowOf(DateUtils.conferenceZoneId)
private val deviceZoneIdFlow: StateFlow<ZoneId> by lazy(LazyThreadSafetyMode.NONE) {
val zoneIdFlow = MutableStateFlow(ZoneId.systemDefault())
context.registerReceiver(object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
zoneIdFlow.value = ZoneId.systemDefault()
}
}, IntentFilter(Intent.ACTION_TIMEZONE_CHANGED))
zoneIdFlow.asStateFlow()
}
@OptIn(ExperimentalCoroutinesApi::class)
val zoneId: Flow<ZoneId>
get() = sharedPreferences.getBooleanAsFlow(PreferenceKeys.USE_DEVICE_TIME_ZONE)
.flatMapLatest { if (it) deviceZoneIdFlow else conferenceZoneIdFlow }
val theme: Flow<Int?>
get() = sharedPreferences.getStringAsFlow(PreferenceKeys.THEME)
.map { it?.toInt() }
val isNotificationsEnabled: Flow<Boolean>
get() = sharedPreferences.getBooleanAsFlow(PreferenceKeys.NOTIFICATIONS_ENABLED)
fun updateNotificationsEnabled(notificationsEnabled: Boolean) {
sharedPreferences.edit()
.putBoolean(PreferenceKeys.NOTIFICATIONS_ENABLED, notificationsEnabled)
.apply()
}
val isNotificationsVibrationEnabled: Flow<Boolean>
get() = sharedPreferences.getBooleanAsFlow(PreferenceKeys.NOTIFICATIONS_VIBRATE)
val isNotificationsLedEnabled: Flow<Boolean>
get() = sharedPreferences.getBooleanAsFlow(PreferenceKeys.NOTIFICATIONS_LED)
val notificationsDelayInMillis: Flow<Long>
get() = sharedPreferences.getStringAsFlow(PreferenceKeys.NOTIFICATIONS_DELAY)
.map {
// Convert from minutes to milliseconds
TimeUnit.MINUTES.toMillis(it?.toLong() ?: 0L)
}
} | apache-2.0 | 708aff4bd57a6731b442968a1053cc41 | 39.150685 | 90 | 0.752901 | 5.10453 | false | false | false | false |
AlmasB/GroupNet | src/main/kotlin/icurves/algorithm/VoronoiAdapter.kt | 1 | 2022 | package icurves.algorithm
import icurves.algorithm.voronoi.Voronoi
import icurves.diagram.Zone
import icurves.guifx.SettingsController
import javafx.geometry.Point2D
import javafx.scene.shape.Line
import math.geom2d.polygon.Polygon2D
/**
*
*
* @author Almas Baimagambetov ([email protected])
*/
object VoronoiAdapter {
private val voronoi = Voronoi(15.0)
fun adapt(zone: Zone): List<Line> {
val polygon = zone.getPolygonShape()
val bbox = polygon.boundingBox()
val xValues = polygon.vertices().map { it.x() }
val yValues = polygon.vertices().map { it.y() }
SettingsController.debugPoints.addAll(polygon.vertices().map { Point2D(it.x(), it.y()) })
SettingsController.debugPoints.add(zone.center)
val edges = voronoi.generateVoronoi(xValues.toDoubleArray(), yValues.toDoubleArray(), bbox.minX, bbox.maxX, bbox.minY, bbox.maxY)
return edges.filter { polygon.contains(it.x1, it.y1) && polygon.contains(it.x2, it.y2) }
.filter { polygon.boundary().signedDistance(it.x1, it.y1) < -40 && polygon.boundary().signedDistance(it.x2, it.y2) < -40 }
.map { Line(it.x1, it.y1, it.x2, it.y2) }
}
fun adapt(polygon: Polygon2D): List<Line> {
val bbox = polygon.boundingBox()
val xValues = polygon.vertices().map { it.x() }
val yValues = polygon.vertices().map { it.y() }
SettingsController.debugPoints.addAll(polygon.vertices().map { Point2D(it.x(), it.y()) })
//SettingsController.debugPoints.add(zone.center)
val edges = voronoi.generateVoronoi(xValues.toDoubleArray(), yValues.toDoubleArray(), bbox.minX, bbox.maxX, bbox.minY, bbox.maxY)
return edges
.filter { polygon.contains(it.x1, it.y1) && polygon.contains(it.x2, it.y2) }
.filter { polygon.boundary().signedDistance(it.x1, it.y1) < -140 && polygon.boundary().signedDistance(it.x2, it.y2) < -140 }
.map { Line(it.x1, it.y1, it.x2, it.y2) }
}
} | apache-2.0 | dff37c13b7d5f78199816738e8c6bbee | 37.903846 | 140 | 0.648863 | 3.438776 | false | false | false | false |
simonorono/pradera_baja | commons/src/main/kotlin/pb/common/gui/Message.kt | 1 | 1578 | package pb.common.gui
/*
* Copyright 2016 Simón Oroño
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import javafx.scene.control.Alert
import javafx.scene.control.TextInputDialog
object Message {
private fun show(type: Alert.AlertType, str: String) {
val alert = Alert(type, str)
alert.headerText = null
alert.title = when (type) {
Alert.AlertType.ERROR -> "Error"
Alert.AlertType.INFORMATION -> "Mensaje"
else -> ""
}
alert.showAndWait()
}
private fun showInput(t: String): String {
val dialog = TextInputDialog("")
dialog.headerText = null
dialog.contentText = t
val r = dialog.showAndWait()
if (r.isPresent) {
return r.get()
} else {
return ""
}
}
@JvmStatic
fun info(str: String) = show(Alert.AlertType.INFORMATION, str)
@JvmStatic
fun error(str: String) = show(Alert.AlertType.ERROR, str)
@JvmStatic
fun get(str: String): String = showInput(str)
}
| apache-2.0 | 30ebe59931cde4f43b07aa8e7abea474 | 26.172414 | 75 | 0.640863 | 4.147368 | false | false | false | false |
sampsonjoliver/Firestarter | app/src/main/java/com/sampsonjoliver/firestarter/views/channel/ChannelActivity.kt | 1 | 15778 | package com.sampsonjoliver.firestarter.views.channel
import android.app.Activity
import android.content.Intent
import android.location.Location
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.support.design.widget.Snackbar
import android.support.v4.content.FileProvider
import android.support.v7.widget.LinearLayoutManager
import android.text.format.DateUtils
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.google.android.gms.maps.model.LatLng
import com.google.firebase.database.*
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageMetadata
import com.sampsonjoliver.firestarter.LocationAwareActivity
import com.sampsonjoliver.firestarter.R
import com.sampsonjoliver.firestarter.models.Message
import com.sampsonjoliver.firestarter.models.Session
import com.sampsonjoliver.firestarter.service.FirebaseService
import com.sampsonjoliver.firestarter.service.References
import com.sampsonjoliver.firestarter.service.SessionManager
import com.sampsonjoliver.firestarter.utils.*
import kotlinx.android.synthetic.main.activity_channel.*
import android.app.ProgressDialog
import android.graphics.Bitmap.CompressFormat
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
import com.sampsonjoliver.firestarter.utils.IntentUtils.dispatchTakePictureIntent
import com.sampsonjoliver.firestarter.views.gallery.GalleryActivity
import com.sampsonjoliver.firestarter.views.gallery.GalleryActivity.Companion.EXTRA_MESSAGES
import com.sampsonjoliver.firestarter.views.gallery.GalleryActivity.Companion.EXTRA_TITLE
import com.sampsonjoliver.firestarter.views.gallery.GalleryItemFragment
import java.io.ByteArrayOutputStream
import java.util.*
class ChannelActivity : LocationAwareActivity(),
ChannelMessageRecyclerAdapter.ChatListener,
ChildEventListener {
companion object {
const val EXTRA_SESSION_ID = "EXTRA_SESSION_ID"
}
var session: Session? = null
var location: Location? = null
val sessionId: String? by lazy { intent.getStringExtra(EXTRA_SESSION_ID) }
var isSessionOwner: Boolean = false
val adapter by lazy { ChannelMessageRecyclerAdapter(SessionManager.getUid(), this) }
var currentPhotoPath: String? = null
val sessionSubscriberListener = object : ValueEventListener {
override fun onCancelled(p0: DatabaseError?) {
Log.w([email protected], "onCancelled")
}
override fun onDataChange(p0: DataSnapshot?) {
val numSubscribers = p0?.getValue(Int::class.java)
users.text = numSubscribers.toString()
}
}
val userSubscriptionListener = object : ValueEventListener {
override fun onCancelled(p0: DatabaseError?) {
Log.w("${[email protected]}:${this.TAG}", "onCancelled")
}
override fun onDataChange(p0: DataSnapshot?) {
Log.w("${[email protected]}:${this.TAG}", "onDataChange: ${p0?.key}")
setUserSubscriptionState(p0?.getValue(Boolean::class.java) ?: false)
}
}
fun setUserSubscriptionState(isUserSubscribed: Boolean) {
joinGroup.appear = !isUserSubscribed
bottomView.isEnabled = isUserSubscribed
messageText.isEnabled = isUserSubscribed
sendButton.isEnabled = isUserSubscribed
}
val sessionListener = object : ValueEventListener {
override fun onCancelled(p0: DatabaseError?) {
Log.w([email protected], "onCancelled")
}
override fun onDataChange(p0: DataSnapshot?) {
Log.w([email protected], "onDataChange: ${p0?.key}")
val session = p0?.getValue(Session::class.java)
session?.sessionId = p0?.key
[email protected] = session
isSessionOwner = session?.userId == SessionManager.getUid()
supportInvalidateOptionsMenu()
banner.setImageURI(session?.bannerUrl)
collapsingToolbar.title = session?.topic
title = session?.topic
time.text = DateUtils.formatDateRange(this@ChannelActivity, session?.startDate ?: 0, session?.startDate?.plus(session.durationMs) ?: 0, DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_ABBREV_TIME)
onLocationChanged([email protected])
}
}
override fun onLocationChanged(location: Location?) {
[email protected] = location
val geoDistance = DistanceUtils.latLngDistance(session?.getLocation() ?: LatLng(0.0, 0.0), LatLng(location?.latitude ?: 0.0, location?.longitude ?: 0.0))
distance.text = DistanceUtils.formatDistance(geoDistance[0])
}
override fun onConnected(connectionHint: Bundle?) {
super.onConnected(connectionHint)
startLocationUpdatesWithChecks()
}
override fun onItemInsertedListener() {
recycler.smoothScrollToPosition(0)
}
override fun onMessageLongPress(message: Message) {
Snackbar.make(messageText, R.string.copied_to_clipboard, Snackbar.LENGTH_SHORT).show()
this.copyToClipboard(message.messageId, message.message)
}
override fun onMessageClick(message: Message) {
message.contentUri.isNullOrEmpty().not().whenEqual(true) {
val photos = adapter.messages.flatMap { it.messages }.filter { it.contentUri.isNullOrEmpty().not() }.sortedBy { it.getTimestampLong() }
val position = photos.indexOfFirst { message.contentUri == it.contentUri }
GalleryItemFragment.newInstance(ArrayList(photos), position).show(fragmentManager, "")
}
}
override fun onChildMoved(p0: DataSnapshot?, previousChildName: String?) = Unit
override fun onChildChanged(p0: DataSnapshot?, previousChildName: String?) {
Log.w(this.TAG, "onChildChanged: ${p0?.key}")
val key = p0?.key ?: ""
val message = p0?.getValue(Message::class.java)
// todo need to update message inside of its message group; this is likely to be an expensive
// op with our current data model
}
override fun onChildAdded(dataSnapshot: DataSnapshot?, previousChildName: String?) {
Log.w(this.TAG, "onChildAdded: ${dataSnapshot?.key}")
dataSnapshot?.getValue(Message::class.java)?.let {
adapter.addMessage(it)
}
}
override fun onChildRemoved(p0: DataSnapshot?) {
Log.w(this.TAG, "onChildRemoved: ${p0?.key}")
val key = p0?.key ?: ""
// todo need to update message inside of its message group; this is likely to be an expensive
// op with our current local data model
}
override fun onCancelled(p0: DatabaseError?) {
Log.w(this.TAG, "onCancelled", p0?.toException());
Toast.makeText(this@ChannelActivity, "Failed to load chat.",
Toast.LENGTH_SHORT).show()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_channel, menu)
menu?.findItem(R.id.menu_leave)?.isVisible = isSessionOwner.not()
return super.onCreateOptionsMenu(menu)
}
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
menu?.findItem(R.id.menu_leave)?.isVisible = isSessionOwner.not()
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.menu_leave -> {
sessionId?.let { FirebaseService.updateSessionSubscription(it, true, { finish() }) }
return true
}
R.id.menu_content -> { return consume {
startActivity(Intent(this@ChannelActivity, GalleryActivity::class.java).apply {
val x = adapter.messages.flatMap { it.messages }.filter { it.contentUri.isNullOrEmpty().not() }.sortedBy { it.getTimestampLong() }
putParcelableArrayListExtra(EXTRA_MESSAGES, ArrayList(x))
putExtra(EXTRA_TITLE, session?.topic)
})
}}
else -> return super.onOptionsItemSelected(item)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_channel)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
toolbar.setOnClickListener { appBarLayout.setExpanded(true, true) }
messageText.setOnClickListener { appBarLayout.setExpanded(false, true) }
setUserSubscriptionState(false)
distance.setOnClickListener {
if (session?.getLocation() != null)
IntentUtils.launchMaps(this@ChannelActivity, session?.getLocation()!!, session?.topic)
}
sessionId?.let { sessionId ->
joinBtn.setOnClickListener { FirebaseService.updateSessionSubscription(sessionId, false) }
}
recycler.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)
recycler.adapter = adapter
attachDataListener()
sendButton.setOnClickListener { sendNewMessage(messageText) }
photoButton.setOnClickListener { addPhoto() }
photoButton.appear = FirebaseRemoteConfig.getInstance().getBoolean("photo_messages_enabled")
messageText.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_SEND) {
sendNewMessage(messageText)
return@OnEditorActionListener true
}
false
})
}
fun sendNewMessage(messageWidget: EditText) {
if (messageWidget.text.isNullOrBlank().not()) {
// Upload the message to firebase and clear the message textbox
sendNewMessage(messageWidget.text.toString(), SessionManager.getUid())
messageWidget.setText("")
}
}
fun sendNewMessage(messageText: String, userId: String, contentUri: String? = null, contentThumbUri: String? = null) {
val message = Message(userId, SessionManager.getUserPhotoUrl(), sessionId ?: "", messageText, contentUri, contentThumbUri, session?.topic)
FirebaseService.sendMessage(message)
}
fun attachDataListener(detach: Boolean = false) {
val ref = FirebaseService.getReference(References.Messages)
.child(sessionId)
.orderByChild("timestamp")
.limitToLast(100)
if (detach)
ref.removeEventListener(this)
else
ref.addChildEventListener(this)
FirebaseService.getReference(References.Sessions).child(sessionId).run {
when (detach) {
true -> this.removeEventListener(sessionListener)
else -> this.addValueEventListener(sessionListener)
}
}
FirebaseService.getReference(References.SessionSubscriptions)
.child(sessionId).child("numUsers")
.run {
when (detach) {
true -> this.removeEventListener(sessionSubscriberListener)
else -> this.addValueEventListener(sessionSubscriberListener)
}
}
FirebaseService.getReference(References.UserSubscriptions)
.child(SessionManager.getUid())
.child(sessionId)
.run {
when (detach) {
true -> this.removeEventListener(userSubscriptionListener)
false -> this.addValueEventListener(userSubscriptionListener)
}
}
}
override fun onDestroy() {
super.onDestroy()
attachDataListener(true)
}
fun addPhoto() {
currentPhotoPath = dispatchTakePictureIntent(this)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
IntentUtils.REQUEST_IMAGE_CAPTURE -> {
if (resultCode == Activity.RESULT_OK) {
Uri.parse(currentPhotoPath)?.run {
val progressDialog = ProgressDialog(this@ChannelActivity)
progressDialog.setMessage(getString(R.string.uploading_image, 0f))
progressDialog.show()
FirebaseStorage.getInstance().getReference("${References.Images}/$sessionId/${SessionManager.getUsername()}_${this.lastPathSegment}")
.putFile(this, StorageMetadata.Builder()
.setContentType("image/jpg")
.setCustomMetadata("uid", SessionManager.getUid())
.setCustomMetadata("sessionId", sessionId)
.build()
).addOnFailureListener {
Log.d(TAG, "Upload Failed: " + it.message)
progressDialog.dismiss()
}.addOnProgressListener {
Log.d(TAG, "Upload Progress: ${it.bytesTransferred} / ${it.totalByteCount}")
progressDialog.setMessage(getString(R.string.uploading_image, (it.bytesTransferred.toFloat() / it.totalByteCount.toFloat()) * 100f))
}.addOnSuccessListener { photoIt ->
val thumb = BitmapUtils.decodeSampledBitmap(currentPhotoPath!!, 100, 100)
val bos = ByteArrayOutputStream()
thumb.compress(CompressFormat.PNG, 100, bos)
val thumbData = bos.toByteArray()
FirebaseStorage.getInstance().getReference("${References.Images}/public/thumb_${this.lastPathSegment}")
.putBytes(thumbData, StorageMetadata.Builder()
.setContentType("image/jpg")
.setCustomMetadata("uid", SessionManager.getUid())
.setCustomMetadata("sessionId", sessionId)
.build()
).addOnSuccessListener {
sendNewMessage("", SessionManager.getUid(), photoIt.downloadUrl.toString(), it.downloadUrl.toString())
progressDialog.dismiss()
}.addOnFailureListener {
Log.d(TAG, "Upload Thumbnail Failed: " + it.message)
progressDialog.dismiss()
}.addOnProgressListener {
Log.d(TAG, "Upload Thumbnail Progress: ${it.bytesTransferred} / ${it.totalByteCount}")
progressDialog.setMessage(getString(R.string.generating_thumbnail, (it.bytesTransferred.toFloat() / it.totalByteCount.toFloat()) * 100f))
}
}
}
}
}
else -> super.onActivityResult(requestCode, resultCode, data)
}
}
} | apache-2.0 | bbdeec04978ce5ebfd73754c3d1078fb | 43.323034 | 207 | 0.621688 | 5.450086 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/gui/components/buttons/ClickButton.kt | 2 | 1972 | package com.cout970.magneticraft.systems.gui.components.buttons
import com.cout970.magneticraft.IVector2
import com.cout970.magneticraft.misc.guiTexture
import com.cout970.magneticraft.misc.vector.Vec2d
import com.cout970.magneticraft.misc.vector.contains
import com.cout970.magneticraft.misc.vector.vec2Of
import com.cout970.magneticraft.systems.gui.render.IComponent
import com.cout970.magneticraft.systems.gui.render.IGui
import com.cout970.magneticraft.systems.gui.render.isMouseButtonDown
class ClickButton(
override val pos: IVector2,
val id: String = "no-id",
var onClick: () -> Unit = {}
) : IComponent {
override lateinit var gui: IGui
override val size: IVector2 = vec2Of(18, 18)
val backgroundUV = vec2Of(55, 100)
val hoverUV = vec2Of(183, 10)
val pressUV = vec2Of(164, 10)
var state = States.NORMAL
override fun drawFirstLayer(mouse: Vec2d, partialTicks: Float) {
gui.bindTexture(guiTexture("misc"))
gui.drawTexture(
gui.pos + pos,
size,
backgroundUV
)
state = if (mouse in (gui.pos + pos to size)) {
if (isMouseButtonDown(0)) States.PRESS else States.HOVER
} else {
States.NORMAL
}
}
override fun drawSecondLayer(mouse: Vec2d) {
if (state == States.HOVER) {
gui.bindTexture(guiTexture("misc"))
gui.drawTexture(
pos,
size,
hoverUV
)
} else if (state == States.PRESS) {
gui.bindTexture(guiTexture("misc"))
gui.drawTexture(
pos,
size,
pressUV
)
}
}
override fun onMouseClick(mouse: Vec2d, mouseButton: Int): Boolean {
val inBounds = mouse in (gui.pos + pos to size)
if (inBounds) onClick()
return inBounds
}
enum class States {
NORMAL, HOVER, PRESS
}
} | gpl-2.0 | 3b1b583a39e824cad2d23eb4640b74a2 | 27.594203 | 72 | 0.609026 | 4.057613 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl-provider-plugins/src/main/kotlin/org/gradle/kotlin/dsl/provider/plugins/precompiled/tasks/GenerateScriptPluginAdapters.kt | 1 | 3360 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.provider.plugins.precompiled.tasks
import org.gradle.api.DefaultTask
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.provider.plugins.precompiled.PrecompiledScriptPlugin
import org.gradle.kotlin.dsl.provider.plugins.precompiled.scriptPluginFilesOf
import org.gradle.kotlin.dsl.support.normaliseLineSeparators
import java.io.File
@CacheableTask
abstract class GenerateScriptPluginAdapters : DefaultTask() {
@get:OutputDirectory
abstract val outputDirectory: DirectoryProperty
@get:Internal
internal
lateinit var plugins: List<PrecompiledScriptPlugin>
@get:InputFiles
@get:PathSensitive(PathSensitivity.RELATIVE)
@Suppress("unused")
internal
val scriptFiles: Set<File>
get() = scriptPluginFilesOf(plugins)
@TaskAction
@Suppress("unused")
internal
fun generate() =
outputDirectory.withOutputDirectory { outputDir ->
for (scriptPlugin in plugins) {
scriptPlugin.writeScriptPluginAdapterTo(outputDir)
}
}
}
internal
fun PrecompiledScriptPlugin.writeScriptPluginAdapterTo(outputDir: File) {
val (packageDir, packageDeclaration) =
packageName?.let { packageName ->
packageDir(outputDir, packageName) to "package $packageName"
} ?: outputDir to ""
val outputFile =
packageDir.resolve("$simplePluginAdapterClassName.kt")
outputFile.writeText("""
$packageDeclaration
/**
* Precompiled [$scriptFileName][$compiledScriptTypeName] script plugin.
*
* @see $compiledScriptTypeName
*/
class $simplePluginAdapterClassName : org.gradle.api.Plugin<$targetType> {
override fun apply(target: $targetType) {
try {
Class
.forName("$compiledScriptTypeName")
.getDeclaredConstructor($targetType::class.java)
.newInstance(target)
} catch (e: java.lang.reflect.InvocationTargetException) {
throw e.targetException
}
}
}
""".normaliseLineSeparators().replaceIndent().trim() + "\n")
}
private
fun packageDir(outputDir: File, packageName: String) =
outputDir.mkdir(packageName.replace('.', '/'))
private
fun File.mkdir(relative: String) =
resolve(relative).apply { mkdirs() }
| apache-2.0 | f9bf5f0fd0e706040766dc82c7381e2f | 29.545455 | 82 | 0.688988 | 4.705882 | false | false | false | false |
albertoruibal/karballo | karballo-jvm/src/test/kotlin/karballo/SeeTest.kt | 1 | 1538 | package karballo
import karballo.util.JvmPlatformUtils
import karballo.util.Utils
import org.junit.Assert.assertEquals
import org.junit.Test
class SeeTest {
constructor() {
Utils.instance = JvmPlatformUtils()
}
private fun testSee(fen: String, moveString: String, expectedSee: Int) {
val board = Board()
board.fen = fen
print(board)
val move = Move.getFromString(board, moveString, true)
val calculatedSee = board.see(Move.getFromIndex(move), Move.getToIndex(move), Move.getPieceMoved(move), Move.getPieceCaptured(board, move))
println(moveString + " SEE = " + calculatedSee)
assertEquals("Bad SEE", expectedSee.toLong(), calculatedSee.toLong())
}
@Test
fun test1() {
testSee("1k1r4/1pp4p/p7/4p3/8/P5P1/1PP4P/2K1R3 w - -", "Rxe5", 100)
}
@Test
fun test2() {
testSee("5K1k/8/8/8/8/8/1r6/Rr6 w QKqk - 0 0", "a1b1", 0)
}
@Test
fun test3() {
testSee("5K1k/8/8/8/8/8/b7/RrR5 w QKqk - 0 0", "a1b1", 330)
}
@Test
fun test4() {
testSee("1k1r3q/1ppn3p/p4b2/4p3/8/P2N2P1/1PP1R1BP/2K1Q3 w - -", "Ne5", -225)
}
@Test
fun testNoOtherPiecesAttack() {
testSee("rq2r1k1/5pp1/p7/5NP1/1p2P2P/8/PQ4K1/5R1R b - - 0 2", "Re8xe4", 100)
}
@Test
fun testSeeError() {
testSee("8/1kb2p2/4b1p1/8/2Q2NB1/8/8/K7 w - - 0 1", "Nf4xe6", 105)
}
@Test
fun testSeeEnpassant() {
testSee("7k/8/8/8/2pP1n2/8/2B5/7K b - d3 0 1", "c4xd3", 100)
}
} | mit | 7c5e73235ec2a25ef08bad5597519b52 | 25.534483 | 147 | 0.60143 | 2.602369 | false | true | false | false |
jdinkla/groovy-java-ray-tracer | src/main/kotlin/net/dinkla/raytracer/math/Matrix.kt | 1 | 3166 | package net.dinkla.raytracer.math
import java.util.Arrays
class Matrix private constructor() {
private var m: DoubleArray = DoubleArray(4 * 4)
operator fun get(i: Int, j: Int) = m[index(i, j)]
operator fun set(i: Int, j: Int, value: Double) {
m[index(i, j)] = value
}
constructor(ls: List<Double>) : this() {
val n = ls.size
for (j in 0..3) {
for (i in 0..3) {
this[i, j] = ls[index(i, j) % n]
}
}
}
operator fun plus(matrix: Matrix): Matrix {
val result = Matrix()
for (j in 0..3) {
for (i in 0..3) {
val idx = index(i, j)
result.m[idx] = m[idx] + matrix.m[idx]
}
}
return result
}
operator fun times(matrix: Matrix): Matrix {
val result = Matrix()
for (j in 0..3) {
for (i in 0..3) {
var sum = 0.0
for (k in 0..3) {
sum += m[i, k] * matrix.m[k, j]
}
result.m[i, j] = sum
}
}
return result
}
operator fun times(p: Point3D): Point3D {
fun add(i: Int) =m[i, 0] * p.x + m[i, 1] * p.y + m[i, 2] * p.z + m[i, 3]
return Point3D(add(0), add(1), add(2))
}
operator fun times(v: Vector3D): Vector3D {
fun add(i: Int) =m[i, 0] * v.x + m[i, 1] * v.y + m[i, 2] * v.z
return Vector3D(add(0), add(1), add(2))
}
// transformed m^t * n
operator fun times(n: Normal): Normal {
fun add(i: Int) =m[i, 0] * n.x + m[i, 1] * n.y + m[i, 2] * n.z
return Normal(add(0), add(1), add(2))
}
operator fun div(value: Double): Matrix {
val result = Matrix()
for (j in 0..3) {
for (i in 0..3) {
result[i, j] = m[i, j] / value
}
}
return result
}
fun setIdentity() {
for (j in 0..3) {
for (i in 0..3) {
this[i, j] = if (i == j) 1.0 else 0.0
}
}
}
override fun equals(other: Any?): Boolean {
if (null == other || other !is Matrix) {
return false
} else {
for (y in 0..3) {
for (x in 0..3) {
if (this[x, y] != other[x, y]) {
return false
}
}
}
return true
}
}
override fun hashCode(): Int {
return Arrays.hashCode(m)
}
override fun toString() = buildString {
fun line(i: Int) = "${m[i, 0]}, ${m[i, 1]}, ${m[i, 2]}, ${m[i, 3]} "
append(line(0))
append(line(1))
append(line(2))
append(line(3))
}
companion object {
fun identity(): Matrix = Matrix().apply { setIdentity() }
fun zero(): Matrix = Matrix()
fun index(i: Int, j: Int) = 4 * i + j
operator fun DoubleArray.get(i: Int, j: Int): Double = this[index(i, j)]
operator fun DoubleArray.set(i: Int, j: Int, value: Double) {
this[index(i, j)] = value
}
}
}
| apache-2.0 | f80db23537bf413ace7e0033e7341d0e | 24.126984 | 80 | 0.427669 | 3.301356 | false | false | false | false |
vase4kin/TeamCityApp | features/manage-accounts/src/main/java/teamcityapp/features/manage_accounts/viewmodel/ManageAccountsViewModel.kt | 1 | 2979 | /*
* Copyright 2020 Andrey Tolpeev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package teamcityapp.features.manage_accounts.viewmodel
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.xwray.groupie.Group
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.GroupieViewHolder
import teamcityapp.features.manage_accounts.router.ManageAccountsRouter
import teamcityapp.features.manage_accounts.tracker.ManageAccountsTracker
import teamcityapp.features.manage_accounts.view.AccountItemFactory
import teamcityapp.libraries.cache_manager.CacheManager
import teamcityapp.libraries.storage.Storage
import teamcityapp.libraries.storage.models.UserAccount
class ManageAccountsViewModel(
private val storage: Storage,
private val router: ManageAccountsRouter,
private val tracker: ManageAccountsTracker,
private val cacheManager: CacheManager,
private val itemFactory: AccountItemFactory,
val adapter: GroupAdapter<GroupieViewHolder>
) : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
val items: List<Group> = createItems()
adapter.updateAsync(items)
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
tracker.trackView()
}
fun onFabClick() {
router.openCreateNewAccount()
}
private fun createItems(): List<Group> = storage.userAccounts.map {
itemFactory.create(
userAccount = it,
onAccountRemove = onAccountRemove(it)
)
}
@VisibleForTesting
internal fun onAccountRemove(account: UserAccount): () -> Unit = {
when {
storage.userAccounts.size == 1 -> {
tracker.trackAccountRemove()
storage.removeUserAccount(account)
cacheManager.evictAllCache()
router.openLogin()
}
account.isActive -> {
tracker.trackAccountRemove()
storage.removeUserAccount(account)
storage.setOtherUserActive()
router.openHome()
}
else -> {
tracker.trackAccountRemove()
storage.removeUserAccount(account)
val items: List<Group> = createItems()
adapter.updateAsync(items)
}
}
}
}
| apache-2.0 | 08f0559f2d4cced5820667910e1f3746 | 33.241379 | 75 | 0.690164 | 4.915842 | false | false | false | false |
roylanceMichael/yaorm | yaorm/src/main/java/org/roylance/yaorm/services/EntityService.kt | 1 | 17418 | package org.roylance.yaorm.services
import org.roylance.yaorm.YaormModel
import org.roylance.yaorm.models.db.GenericModel
import org.roylance.yaorm.utilities.ProjectionUtilities
import org.roylance.yaorm.utilities.YaormUtils
import java.util.*
class EntityService(private val granularDatabaseService: IGranularDatabaseService,
private val sqlGeneratorService: ISQLGeneratorService) : IEntityService {
override fun getJoinTableRecords(joinTable: YaormModel.JoinTable): YaormModel.Records {
val joinTableSQL = sqlGeneratorService.buildJoinSql(joinTable)
val joinTableDefinition = ProjectionUtilities.buildTableDefinitionFromJoinTable(joinTable)
return granularDatabaseService.executeSelectQuery(joinTableDefinition, joinTableSQL).getRecords()
}
override fun getReport(): YaormModel.DatabaseExecutionReport {
return granularDatabaseService.getReport()
}
override val connectionSourceFactory: IConnectionSourceFactory
get() = granularDatabaseService.connectionSourceFactory
override val insertSameAsUpdate: Boolean
get() = this.sqlGeneratorService.insertSameAsUpdate
override fun buildDefinitionFromSql(customSql: String, rowCount: Int): YaormModel.TableDefinition {
return this.granularDatabaseService.buildTableDefinitionFromQuery(customSql, rowCount)
}
override fun getIdsStream(definition: YaormModel.TableDefinition,
streamer: IStreamer) {
if (!this.granularDatabaseService.isAvailable()) {
return
}
val selectSql = this.sqlGeneratorService.buildSelectIds(definition)
this.granularDatabaseService
.executeSelectQuery(definition, selectSql)
.getRecords()
.recordsList
.map {
streamer.stream(it)
}
}
override fun getIds(definition: YaormModel.TableDefinition): List<String> {
if (!this.granularDatabaseService.isAvailable()) {
return ArrayList()
}
val selectSql = this.sqlGeneratorService.buildSelectIds(definition)
return this.granularDatabaseService.executeSelectQuery(definition, selectSql)
.getRecords().recordsList.map {
YaormUtils.getIdColumn(it.columnsList)!!.stringHolder
}
}
override fun getManyStream(definition: YaormModel.TableDefinition,
streamer: IStreamer,
limit: Int,
offset: Int) {
if (!this.granularDatabaseService.isAvailable()) {
return
}
val allSql =
this.sqlGeneratorService.buildSelectAll(definition, limit, offset)
this.granularDatabaseService.executeSelectQueryStream(definition, allSql, streamer)
}
override fun createTable(definition: YaormModel.TableDefinition): Boolean {
if (!this.granularDatabaseService.isAvailable()) {
return false
}
val createTableSql = this.sqlGeneratorService
.buildCreateTable(definition) ?: return false
return this.granularDatabaseService
.executeUpdateQuery(createTableSql)
.successful
}
override fun dropTable(definition: YaormModel.TableDefinition): Boolean {
if (!this.granularDatabaseService.isAvailable()) {
return false
}
val dropTableSql = this.sqlGeneratorService
.buildDropTable(definition)
return this.granularDatabaseService
.executeUpdateQuery(dropTableSql)
.successful
}
override fun createIndex(indexModel: YaormModel.Index,
definition: YaormModel.TableDefinition): Boolean {
if (!this.granularDatabaseService.isAvailable()) {
return false
}
val createIndexSql = this.sqlGeneratorService.buildCreateIndex(
definition,
indexModel.columnNamesList.associateBy { it.name },
indexModel.includeNamesList.associateBy { it.name }) ?: return false
return this.granularDatabaseService
.executeUpdateQuery(createIndexSql)
.successful
}
override fun dropIndex(indexModel: YaormModel.Index,
definition: YaormModel.TableDefinition): Boolean {
if (!this.granularDatabaseService.isAvailable()) {
return false
}
val dropIndexSql = this.sqlGeneratorService.buildDropIndex(
definition,
indexModel.columnNamesList.associateBy { it.name }) ?: return false
return this.granularDatabaseService
.executeUpdateQuery(dropIndexSql)
.successful
}
override fun createColumn(propertyDefinition: YaormModel.ColumnDefinition,
definition: YaormModel.TableDefinition): Boolean {
if (!this.granularDatabaseService.isAvailable()) {
return false
}
val addColumnSql = this.sqlGeneratorService.buildCreateColumn(
definition,
propertyDefinition) ?: return false
return this.granularDatabaseService
.executeUpdateQuery(addColumnSql)
.successful
}
override fun dropColumn(propertyDefinition: YaormModel.ColumnDefinition,
definition: YaormModel.TableDefinition): Boolean {
if (!this.granularDatabaseService.isAvailable()) {
return false
}
val dropTableSqlStatements = this.sqlGeneratorService.buildDropColumn(
definition,
propertyDefinition) ?: return false
return this.granularDatabaseService
.executeUpdateQuery(dropTableSqlStatements)
.successful
}
override fun getCount(definition: YaormModel.TableDefinition): Long {
if (!this.granularDatabaseService.isAvailable()) {
return 0L
}
val countSql = this.sqlGeneratorService.buildCountSql(definition)
val cursor = this.granularDatabaseService.
executeSelectQuery(GenericModel.buildProtoDefinitionModel(), countSql)
val allRecords = cursor.getRecords()
if (allRecords.recordsCount > 0) {
val foundRecord = allRecords.recordsList[0]
val longValColumn = foundRecord.columnsList.firstOrNull { it.definition.name == GenericModel.LongValName }
if (longValColumn != null) {
return longValColumn.int64Holder
}
}
return -1
}
override fun getCustom(customSql: String, definition: YaormModel.TableDefinition): YaormModel.Records {
if (!this.granularDatabaseService.isAvailable()) {
return YaormModel.Records.newBuilder().build()
}
return this.granularDatabaseService
.executeSelectQuery(definition, customSql)
.getRecords()
}
override fun getCustomStream(customSql: String, definition: YaormModel.TableDefinition, streamer: IStreamer) {
if (!this.granularDatabaseService.isAvailable()) {
return
}
this.granularDatabaseService.executeSelectQueryStream(definition, customSql, streamer)
}
override fun get(id: String, definition: YaormModel.TableDefinition): YaormModel.Record? {
if (!this.granularDatabaseService.isAvailable()) {
return YaormModel.Record.getDefaultInstance()
}
val propertyHolder = YaormModel.Column.newBuilder()
.setStringHolder(id)
.setDefinition(YaormModel.ColumnDefinition.newBuilder()
.setType(YaormModel.ProtobufType.STRING)
.setName(YaormUtils.IdName).setIsKey(true))
.build()
val whereClause = YaormModel.WhereClause.newBuilder()
.setNameAndProperty(propertyHolder)
.setOperatorType(YaormModel.WhereClause.OperatorType.EQUALS)
.build()
val whereSql = this.sqlGeneratorService
.buildWhereClause(definition, whereClause) ?: return YaormModel.Record.newBuilder().build()
val resultSet = this.granularDatabaseService.executeSelectQuery(
definition,
whereSql)
val records = resultSet.getRecords()
if (records.recordsCount > 0) {
return records.recordsList.first()
}
return null
}
override fun getMany(definition: YaormModel.TableDefinition,
limit: Int,
offset: Int): YaormModel.Records {
if (!this.granularDatabaseService.isAvailable()) {
return YaormModel.Records.getDefaultInstance()
}
val allSql =
this.sqlGeneratorService.buildSelectAll(definition, limit, offset)
return this.granularDatabaseService.executeSelectQuery(definition, allSql).getRecords()
}
override fun where(whereClauseItem: YaormModel.WhereClause,
definition: YaormModel.TableDefinition): YaormModel.Records {
if (!this.granularDatabaseService.isAvailable()) {
return YaormModel.Records.getDefaultInstance()
}
val whereSql =
this.sqlGeneratorService.buildWhereClause(
definition,
whereClauseItem) ?: return YaormModel.Records.getDefaultInstance()
return this.granularDatabaseService.executeSelectQuery(definition, whereSql).getRecords()
}
override fun bulkInsert(instances: YaormModel.Records, definition: YaormModel.TableDefinition): Boolean {
if (!this.granularDatabaseService.isAvailable()) {
return false
}
// let's split this into items of limit each... for now
val temporaryList = YaormModel.Records.newBuilder()
val results = ArrayList<Boolean>()
instances
.recordsList
.forEach {
temporaryList.addRecords(it)
if (temporaryList.recordsCount >= this.sqlGeneratorService.bulkInsertSize) {
val bulkInsertSql = this.sqlGeneratorService
.buildBulkInsert(definition, temporaryList.build())
val result = this.granularDatabaseService
.executeUpdateQuery(bulkInsertSql)
results.add(result.successful)
temporaryList.clearRecords()
}
}
if (temporaryList.recordsCount > 0) {
val bulkInsertSql = this.sqlGeneratorService.buildBulkInsert(definition, temporaryList.build())
val result = this.granularDatabaseService
.executeUpdateQuery(bulkInsertSql)
results.add(result.successful)
}
return results.all { it }
}
override fun createOrUpdate(entity: YaormModel.Record, definition: YaormModel.TableDefinition): Boolean {
val idColumn = YaormUtils.getIdColumn(entity.columnsList) ?: return false
if (!this.granularDatabaseService.isAvailable()) {
return false
}
val foundItemInDatabase = this.get(idColumn.stringHolder, definition)
if (foundItemInDatabase != null) {
return this.update(entity, definition)
}
return this.create(entity, definition)
}
override fun create(entity: YaormModel.Record, definition: YaormModel.TableDefinition): Boolean {
YaormUtils.getIdColumn(entity.columnsList) ?: return false
if (!this.granularDatabaseService.isAvailable()) {
return false
}
// create
val insertSql = this.sqlGeneratorService
.buildInsertIntoTable(definition, entity) ?: return false
val result = this.granularDatabaseService
.executeUpdateQuery(insertSql)
return result.successful
}
override fun update(entity: YaormModel.Record, definition: YaormModel.TableDefinition): Boolean {
if (YaormUtils.getIdColumn(entity.columnsList) == null) {
return false
}
if (!this.granularDatabaseService.isAvailable()) {
return false
}
// update
val updateSql = this
.sqlGeneratorService
.buildUpdateTable(definition, entity) ?: return false
val result = this.granularDatabaseService
.executeUpdateQuery(updateSql)
return result.successful
}
override fun updateWithCriteria(newValues: YaormModel.Record,
whereClauseItem: YaormModel.WhereClause,
definition: YaormModel.TableDefinition): Boolean {
if (!this.granularDatabaseService.isAvailable()) {
return false
}
val updateSql = this.sqlGeneratorService.buildUpdateWithCriteria(
definition,
newValues,
whereClauseItem) ?: return false
return this.granularDatabaseService
.executeUpdateQuery(updateSql)
.successful
}
override fun updateCustom(customSql: String): Boolean {
if (!this.granularDatabaseService.isAvailable()) {
return false
}
this.granularDatabaseService.executeUpdateQuery(customSql)
return true
}
override fun delete(id: String, definition: YaormModel.TableDefinition): Boolean {
if (!this.granularDatabaseService.isAvailable()) {
return false
}
val propertyHolder = YaormModel.Column.newBuilder()
.setStringHolder(id)
.setDefinition(YaormModel.ColumnDefinition.newBuilder()
.setType(YaormModel.ProtobufType.STRING)
.setName(YaormUtils.IdName).setIsKey(true))
.build()
val deleteSql =
this.sqlGeneratorService
.buildDeleteTable(definition, propertyHolder) ?: return false
return this.granularDatabaseService
.executeUpdateQuery(deleteSql)
.successful
}
override fun deleteAll(definition: YaormModel.TableDefinition): Boolean {
if (!this.granularDatabaseService.isAvailable()) {
return false
}
val sql = this.sqlGeneratorService.buildDeleteAll(definition)
return this.granularDatabaseService
.executeUpdateQuery(sql)
.successful
}
override fun getSchemaNames(): List<String> {
val schemaNamesSql = this.sqlGeneratorService.getSchemaNames()
val columnNameRecords = this.granularDatabaseService.executeSelectQuery(schemaNamesSql)
return columnNameRecords.recordsList.map {
val firstColumn = it.columnsList.firstOrNull()
if (firstColumn == null) {
YaormUtils.EmptyString
}
else {
firstColumn.stringHolder
}
}.filter(String::isNotEmpty)
}
override fun getTableNames(schemaName: String): List<String> {
val tableNamesSql = this.sqlGeneratorService.getTableNames(schemaName)
val tableNameRecords = this.granularDatabaseService.executeSelectQuery(tableNamesSql)
return tableNameRecords.recordsList.map {
val firstColumn = it.columnsList.firstOrNull()
if (firstColumn == null) {
YaormUtils.EmptyString
}
else {
firstColumn.stringHolder
}
}.filter(String::isNotEmpty)
}
override fun getTableDefinition(schemaName: String, tableName: String): YaormModel.TableDefinition {
val tableDefinitionSql = this.sqlGeneratorService.buildTableDefinitionSQL(schemaName, tableName)
val tableDefinitionRecords = this.granularDatabaseService.executeSelectQuery(tableDefinitionSql)
val tableDefinition = this.sqlGeneratorService.buildTableDefinition(tableName, tableDefinitionRecords)
return tableDefinition
}
override fun getTableDefinitionFromProjection(projection: YaormModel.Projection): YaormModel.TableDefinition {
return ProjectionUtilities.buildTableDefinitionFromProjection(projection)
}
override fun getRecordsFromProjection(projection: YaormModel.Projection): YaormModel.Records {
val tableDefinition = ProjectionUtilities.buildTableDefinitionFromProjection(projection)
val projectionSQL = ProjectionUtilities.buildProjectionSQL(projection, sqlGeneratorService)
return granularDatabaseService.executeSelectQuery(tableDefinition, projectionSQL).getRecords()
}
override fun getRecordsFromProjectionStream(projection: YaormModel.Projection, streamer: IStreamer) {
val tableDefinition = ProjectionUtilities.buildTableDefinitionFromProjection(projection)
val projectionSQL = ProjectionUtilities.buildProjectionSQL(projection, sqlGeneratorService)
granularDatabaseService.executeSelectQueryStream(tableDefinition, projectionSQL, streamer)
}
override fun close() {
this.granularDatabaseService.close()
}
}
| mit | 2cdcf61d02c556e7b9c087c47b9e7435 | 36.865217 | 118 | 0.644908 | 6.100876 | false | false | false | false |
Zukkari/nirdizati-training-ui | src/main/kotlin/cs/ut/engine/item/ModelParameter.kt | 1 | 1369 | package cs.ut.engine.item
/**
* Class that represents model parameter that are used to train models
* @param id identifier of given model parameter
* @param parameter which value to use when passing parameter to the script
* @param type type of the parameter (e.g. encoding, bucketing, learner or predictiontype)
* @param properties hyper parameter properties for given model parameter
*/
data class ModelParameter(
var id: String,
var parameter: String,
var type: String,
var enabled: Boolean,
var properties: MutableList<Property>
) {
var translate = true
/**
* Get translation key for given parameter
*/
fun getTranslateName() = this.type + "." + this.id
constructor() : this("", "", "", false, mutableListOf())
override fun equals(other: Any?): Boolean {
return other is ModelParameter
&& this.id == other.id
&& this.enabled == other.enabled
&& this.type == other.type
&& this.parameter == other.parameter
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + parameter.hashCode()
result = 31 * result + type.hashCode()
result = 31 * result + enabled.hashCode()
return result
}
override fun toString(): String = "$type.$id"
} | lgpl-3.0 | 6d359c527c36c8ac7b1245528a392d8a | 30.136364 | 90 | 0.617239 | 4.688356 | false | false | false | false |
Gu3pardo/PasswordSafe-AndroidClient | mobile/src/main/java/guepardoapps/passwordsafe/services/restprovider/RestProviderService.kt | 1 | 1673 | package guepardoapps.passwordsafe.services.restprovider
import com.google.gson.Gson
import io.ktor.client.HttpClient
import io.ktor.client.request.*
import io.ktor.content.TextContent
import io.ktor.http.ContentType
import kotlin.reflect.full.declaredMemberProperties
@Suppress("UNCHECKED_CAST")
internal class RestProviderService : IRestProviderService {
private val httpClient: HttpClient = HttpClient()
override suspend fun <T> get(url: String, request: Any?): T? {
return httpClient.get<Any> {
url("$url${queryFromRequest(request)}")
} as? T
}
override suspend fun <T> put(url: String, request: Any): T? {
return httpClient.put<Any> {
url(url)
body = TextContent(Gson().toJson(request), contentType = ContentType.Application.Json)
} as? T
}
override suspend fun <T> post(url: String, request: Any): T? {
return httpClient.post<Any> {
url(url)
body = TextContent(Gson().toJson(request), contentType = ContentType.Application.Json)
} as? T
}
override suspend fun <T> delete(url: String, request: Any): T? {
return httpClient.delete<Any> {
url(url)
body = TextContent(Gson().toJson(request), contentType = ContentType.Application.Json)
} as? T
}
private fun queryFromRequest(request: Any?): String {
var queryString = ""
if (request == null) {
return queryString
}
request::class.declaredMemberProperties.forEach { property -> queryString += "&${property.name}=${property.getter.call(request)}" }
return queryString
}
} | mit | 9cf14ca5b7fbb7ed94d836c345057884 | 31.823529 | 139 | 0.643156 | 4.334197 | false | false | false | false |
WindSekirun/RichUtilsKt | demo/src/main/java/pyxis/uzuki/live/richutilskt/demo/MainActivity.kt | 1 | 2666 | package pyxis.uzuki.live.richutilskt.demo
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main_item.view.*
import pyxis.uzuki.live.pyxinjector.base.InjectActivity
import pyxis.uzuki.live.richutilskt.demo.item.MainItem
import pyxis.uzuki.live.richutilskt.utils.browse
import pyxis.uzuki.live.richutilskt.utils.inflate
class MainActivity : InjectActivity() {
private val itemList = ArrayList<MainItem>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val adapter = ListAdapter {
val intent = Intent(this@MainActivity, IndexActivity::class.java)
intent.putExtra("index", it)
startActivity(intent)
}
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = adapter
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (dy > 0 && fab.visibility == View.VISIBLE) {
fab.hide()
} else if (dy < 0 && fab.visibility != View.VISIBLE) {
fab.show()
}
}
})
itemList.addAll(getMainData().filter { it.content.isNotEmpty() })
itemList.sortBy { it.title }
adapter.notifyDataSetChanged()
fab.setOnClickListener {
browse("https://github.com/windsekirun/RichUtilsKt")
}
}
inner class ListAdapter(private val callback: (MainItem) -> Unit) : RecyclerView.Adapter<ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
ViewHolder(inflate(R.layout.activity_main_item, parent), callback)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindData(itemList[position])
}
override fun getItemCount(): Int = itemList.size
}
class ViewHolder(itemView: View, private val callback: (MainItem) -> Unit) : RecyclerView.ViewHolder(itemView) {
fun bindData(item: MainItem) {
itemView.txtTitle.text = item.title
itemView.txtSummary.text = item.content
itemView.setOnClickListener { callback(item) }
}
}
}
| apache-2.0 | 612feb55df45114a0d305fc84fb41162 | 36.549296 | 116 | 0.666167 | 4.693662 | false | false | false | false |
hellenxu/AndroidAdvanced | CrashCases/app/src/main/java/six/ca/crashcases/fragment/data/profile/Profile.kt | 1 | 882 | package six.ca.crashcases.fragment.data.profile
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* @author hellenxu
* @date 2020-08-21
* Copyright 2020 Six. All rights reserved.
*/
data class Profile(
val account: Account,
val achievements: List<Achievement>
)
@Entity(tableName = "account")
data class Account(
@ColumnInfo(name = "user_name")
val userName: String = "",
@PrimaryKey
val id: String = "",
val email: String = ""
)
@Entity(tableName = "achievement")
data class Achievement(
@PrimaryKey
@ColumnInfo(name = "account_id")
var accountId: String = "",
@ColumnInfo(name = "current_title")
val currentTitle: String = "",
@ColumnInfo(name = "current_score")
val currentScore: Int = 0,
@ColumnInfo(name = "next_level_title")
val nextLevelTitle: String = ""
) | apache-2.0 | 688cd4321ee160aee8fde0c1758d376b | 22.864865 | 47 | 0.674603 | 3.785408 | false | false | false | false |
ykrank/S1-Next | app/src/main/java/me/ykrank/s1next/widget/span/QuoteSpan.kt | 1 | 1790 | package me.ykrank.s1next.widget.span
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.text.Layout
import android.text.SpannableString
import android.text.Spanned
import android.text.style.LeadingMarginSpan
import android.text.style.QuoteSpan
import com.github.ykrank.androidtools.util.ResourceUtil
import me.ykrank.s1next.R
class QuoteSpan(private val stripeColor: Int, private val stripeWidth: Float, private val gap: Float) : LeadingMarginSpan {
override fun drawLeadingMargin(c: Canvas?, p: Paint?, x: Int, dir: Int, top: Int, baseline: Int, bottom: Int, text: CharSequence?, start: Int, end: Int, first: Boolean, layout: Layout?) {
p ?: return
c ?: return
val style = p.style
val paintColor = p.color
p.style = Paint.Style.FILL
p.color = stripeColor
c.drawRect(x.toFloat(), top.toFloat(), x + dir * stripeWidth, bottom.toFloat(), p)
p.style = style
p.color = paintColor
return
}
override fun getLeadingMargin(first: Boolean): Int {
return (stripeWidth + gap).toInt()
}
}
fun Spanned.replaceQuoteSpans(context: Context): Spanned {
val quoteSpans = getSpans(0, length, QuoteSpan::class.java)
var spannableString = SpannableString(this)
for (quoteSpan in quoteSpans) {
val start = getSpanStart(quoteSpan)
val end = getSpanEnd(quoteSpan)
val flags = getSpanFlags(quoteSpan)
spannableString.removeSpan(quoteSpan)
spannableString.setSpan(QuoteSpan(
ResourceUtil.getAttrColorInt(context, R.attr.colorPrimaryDark),
10f,
15f),
start,
end,
flags)
}
return spannableString
} | apache-2.0 | 03f144702b9e52598729a6fb6c137708 | 34.117647 | 191 | 0.669274 | 4.221698 | false | false | false | false |
GeoffreyMetais/vlc-android | application/television/src/main/java/org/videolan/television/ui/dialogs/ConfirmationTvDialog.kt | 1 | 2104 | package org.videolan.television.ui.dialogs
import android.os.Bundle
import androidx.leanback.app.GuidedStepSupportFragment
import androidx.leanback.widget.GuidanceStylist
import androidx.leanback.widget.GuidedAction
import org.videolan.vlc.R
import org.videolan.television.ui.dialogs.ConfirmationTvActivity.Companion.ACTION_ID_NEGATIVE
import org.videolan.television.ui.dialogs.ConfirmationTvActivity.Companion.ACTION_ID_POSITIVE
import org.videolan.television.ui.dialogs.ConfirmationTvActivity.Companion.CONFIRMATION_DIALOG_TEXT
import org.videolan.television.ui.dialogs.ConfirmationTvActivity.Companion.CONFIRMATION_DIALOG_TITLE
class ConfirmationTvDialog : GuidedStepSupportFragment() {
override fun onCreateGuidance(savedInstanceState: Bundle?): GuidanceStylist.Guidance {
return GuidanceStylist.Guidance(arguments!!.getString(CONFIRMATION_DIALOG_TITLE),
arguments!!.getString(CONFIRMATION_DIALOG_TEXT),
"", null)
}
override fun onCreateActions(actions: MutableList<GuidedAction>, savedInstanceState: Bundle?) {
var action = GuidedAction.Builder(requireActivity())
.id(ACTION_ID_POSITIVE.toLong())
.title(getString(R.string.yes)).build()
actions.add(action)
action = GuidedAction.Builder(requireActivity())
.id(ACTION_ID_NEGATIVE.toLong())
.title(getString(R.string.no)).build()
actions.add(action)
}
override fun onGuidedActionClicked(action: GuidedAction?) {
if (ACTION_ID_POSITIVE.toLong() == action!!.id) {
requireActivity().setResult(ACTION_ID_POSITIVE)
} else {
requireActivity().setResult(ACTION_ID_NEGATIVE)
}
requireActivity().finish()
}
companion object {
fun newInstance(title: String, text: String): ConfirmationTvDialog = ConfirmationTvDialog().also {
val args = Bundle()
args.putString(CONFIRMATION_DIALOG_TITLE, title)
args.putString(CONFIRMATION_DIALOG_TEXT, text)
it.arguments = args
}
}
} | gpl-2.0 | 40cb84e1dbe22195c5c6f9db4594de49 | 41.959184 | 106 | 0.705323 | 4.825688 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/gui/dialogs/PlaybackSpeedDialog.kt | 1 | 6541 | /**
* **************************************************************************
* PickTimeFragment.java
* ****************************************************************************
* Copyright © 2015 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* ***************************************************************************
*/
package org.videolan.vlc.gui.dialogs
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.ObsoleteCoroutinesApi
import kotlinx.coroutines.flow.onEach
import org.videolan.tools.formatRateString
import org.videolan.vlc.PlaybackService
import org.videolan.vlc.R
import org.videolan.vlc.gui.helpers.OnRepeatListener
import org.videolan.vlc.util.launchWhenStarted
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
class PlaybackSpeedDialog : VLCBottomSheetDialogFragment() {
private lateinit var speedValue: TextView
private lateinit var seekSpeed: SeekBar
private var playbackService: PlaybackService? = null
private var textColor: Int = 0
private val seekBarListener = object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
if (playbackService == null || playbackService!!.currentMediaWrapper == null)
return
if (fromUser) {
val rate = Math.pow(4.0, progress.toDouble() / 100.toDouble() - 1).toFloat()
playbackService!!.setRate(rate, true)
updateInterface()
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
}
private val resetListener = View.OnClickListener {
if (playbackService == null || playbackService!!.rate.toDouble() == 1.0 || playbackService!!.currentMediaWrapper == null)
return@OnClickListener
playbackService!!.setRate(1f, true)
setRateProgress()
}
private val speedUpListener = View.OnClickListener {
if (playbackService == null)
return@OnClickListener
changeSpeed(0.05f)
setRateProgress()
}
private val speedDownListener = View.OnClickListener {
if (playbackService == null)
return@OnClickListener
changeSpeed(-0.05f)
setRateProgress()
}
override fun initialFocusedView(): View {
return seekSpeed
}
@SuppressLint("ClickableViewAccessibility")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.dialog_playback_speed, container)
speedValue = view.findViewById(R.id.playback_speed_value)
seekSpeed = view.findViewById(R.id.playback_speed_seek)
val playbackSpeedPlus = view.findViewById<ImageView>(R.id.playback_speed_plus)
val playbackSpeedMinus = view.findViewById<ImageView>(R.id.playback_speed_minus)
seekSpeed.setOnSeekBarChangeListener(seekBarListener)
playbackSpeedPlus.setOnClickListener(speedUpListener)
playbackSpeedMinus.setOnClickListener(speedDownListener)
speedValue.setOnClickListener(resetListener)
playbackSpeedMinus.setOnTouchListener(OnRepeatListener(speedDownListener))
playbackSpeedPlus.setOnTouchListener(OnRepeatListener(speedUpListener))
textColor = speedValue.currentTextColor
dialog?.setCancelable(true)
dialog?.setCanceledOnTouchOutside(true)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
PlaybackService.serviceFlow.onEach { onServiceChanged(it) }.launchWhenStarted(lifecycleScope)
}
private fun setRateProgress() {
var speed = playbackService!!.rate.toDouble()
speed = 100 * (1 + Math.log(speed) / Math.log(4.0))
seekSpeed.progress = speed.toInt()
updateInterface()
}
private fun changeSpeed(delta: Float) {
var initialRate = Math.round(playbackService!!.rate * 100.0) / 100.0
initialRate = if (delta > 0)
Math.floor((initialRate + 0.005) / 0.05) * 0.05
else
Math.ceil((initialRate - 0.005) / 0.05) * 0.05
val rate = Math.round((initialRate + delta) * 100f) / 100f
if (rate < 0.25f || rate > 4f || playbackService!!.currentMediaWrapper == null)
return
playbackService!!.setRate(rate, true)
}
private fun updateInterface() {
val rate = playbackService!!.rate
speedValue.text = rate.formatRateString()
if (rate != 1.0f) {
speedValue.setTextColor(ContextCompat.getColor(requireActivity(), R.color.orange500))
} else {
speedValue.setTextColor(textColor)
}
}
private fun onServiceChanged(service: PlaybackService?) {
if (service != null) {
playbackService = service
setRateProgress()
} else
playbackService = null
}
override fun getDefaultState(): Int {
return com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_EXPANDED
}
override fun needToManageOrientation(): Boolean {
return true
}
companion object {
const val TAG = "VLC/PlaybackSpeedDialog"
fun newInstance(): PlaybackSpeedDialog {
return PlaybackSpeedDialog()
}
}
}
| gpl-2.0 | 5582879549ea2bf909c0497505c311f1 | 35.741573 | 129 | 0.665138 | 5.07764 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/preferences/fragments/Backups.kt | 1 | 10776 | package org.tasks.preferences.fragments
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.activityViewModels
import androidx.preference.Preference
import androidx.preference.SwitchPreferenceCompat
import com.todoroo.andlib.utility.DateUtilities
import dagger.hilt.android.AndroidEntryPoint
import org.tasks.PermissionUtil
import org.tasks.R
import org.tasks.dialogs.ExportTasksDialog
import org.tasks.dialogs.ImportTasksDialog
import org.tasks.drive.DriveLoginActivity
import org.tasks.extensions.Context.toast
import org.tasks.files.FileHelper
import org.tasks.injection.InjectingPreferenceFragment
import org.tasks.preferences.FragmentPermissionRequestor
import org.tasks.preferences.PermissionRequestor
import org.tasks.preferences.Preferences
import org.tasks.preferences.PreferencesViewModel
import java.util.*
import javax.inject.Inject
private const val REQUEST_CODE_BACKUP_DIR = 10001
const val REQUEST_DRIVE_BACKUP = 12002
private const val REQUEST_PICKER = 10003
private const val REQUEST_BACKUP_NOW = 10004
private const val FRAG_TAG_EXPORT_TASKS = "frag_tag_export_tasks"
private const val FRAG_TAG_IMPORT_TASKS = "frag_tag_import_tasks"
@AndroidEntryPoint
class Backups : InjectingPreferenceFragment() {
@Inject lateinit var preferences: Preferences
@Inject lateinit var permissionRequestor: FragmentPermissionRequestor
@Inject lateinit var locale: Locale
private val viewModel: PreferencesViewModel by activityViewModels()
override fun getPreferenceXml() = R.xml.preferences_backups
override suspend fun setupPreferences(savedInstanceState: Bundle?) {
findPreference(R.string.p_backup_dir)
.setOnPreferenceClickListener {
FileHelper.newDirectoryPicker(
this, REQUEST_CODE_BACKUP_DIR, preferences.backupDirectory
)
false
}
findPreference(R.string.backup_BAc_import)
.setOnPreferenceClickListener {
startActivityForResult(
FileHelper.newFilePickerIntent(activity, preferences.backupDirectory),
REQUEST_PICKER
)
false
}
findPreference(R.string.backup_BAc_export)
.setOnPreferenceClickListener {
ExportTasksDialog.newExportTasksDialog(this, REQUEST_BACKUP_NOW)
.show(parentFragmentManager, FRAG_TAG_EXPORT_TASKS)
false
}
findPreference(R.string.google_drive_backup)
.setOnPreferenceChangeListener(this@Backups::onGoogleDriveCheckChanged)
findPreference(R.string.p_google_drive_backup_account)
.setOnPreferenceClickListener {
requestGoogleDriveLogin()
false
}
findPreference(R.string.p_backups_android_backup_enabled)
.setOnPreferenceChangeListener(this@Backups::onAndroidBackupCheckChanged)
findPreference(R.string.p_backups_ignore_warnings).setOnPreferenceChangeListener { _, newValue ->
if (newValue is Boolean) {
preferences.setBoolean(R.string.p_backups_ignore_warnings, newValue)
updateWarnings()
true
} else {
false
}
}
openUrl(R.string.documentation, R.string.url_backups)
viewModel.lastBackup.observe(this, this::updateLastBackup)
viewModel.lastDriveBackup.observe(this, this::updateDriveBackup)
viewModel.lastAndroidBackup.observe(this, this::updateAndroidBackup)
}
private fun updateLastBackup(timestamp: Long? = viewModel.lastBackup.value) {
findPreference(R.string.backup_BAc_export).summary =
getString(
R.string.last_backup,
timestamp
?.takeIf { it >= 0 }
?.let { DateUtilities.getLongDateStringWithTime(it, locale) }
?: getString(R.string.last_backup_never)
)
}
private fun updateDriveBackup(timestamp: Long? = viewModel.lastDriveBackup.value) {
val pref = findPreference(R.string.google_drive_backup)
if (viewModel.staleRemoteBackup) {
pref.setIcon(R.drawable.ic_outline_error_outline_24px)
tintIcons(pref, requireContext().getColor(R.color.overdue))
} else {
pref.icon = null
}
pref.summary =
getString(
R.string.last_backup,
timestamp
?.takeIf { it >= 0 }
?.let { DateUtilities.getLongDateStringWithTime(it, locale) }
?: getString(R.string.last_backup_never)
)
}
private fun updateAndroidBackup(timestamp: Long? = viewModel.lastAndroidBackup.value) {
val pref = findPreference(R.string.p_backups_android_backup_enabled) as SwitchPreferenceCompat
if (viewModel.staleRemoteBackup) {
pref.setIcon(R.drawable.ic_outline_error_outline_24px)
tintIcons(pref, requireContext().getColor(R.color.overdue))
} else {
pref.icon = null
}
pref.summary =
getString(
R.string.last_backup,
timestamp
?.takeIf { it >= 0 }
?.let { DateUtilities.getLongDateStringWithTime(it, locale) }
?: getString(R.string.last_backup_never)
)
}
override fun onResume() {
super.onResume()
updateWarnings()
updateDriveAccount()
val driveBackup = findPreference(R.string.google_drive_backup) as SwitchPreferenceCompat
val driveAccount = viewModel.driveAccount
driveBackup.isChecked = driveAccount != null
}
private fun updateWarnings() {
updateLastBackup()
updateDriveBackup()
updateAndroidBackup()
updateBackupDirectory()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
if (requestCode == PermissionRequestor.REQUEST_GOOGLE_ACCOUNTS) {
if (PermissionUtil.verifyPermissions(grantResults)) {
requestGoogleDriveLogin()
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_CODE_BACKUP_DIR) {
if (resultCode == RESULT_OK && data != null) {
val uri = data.data!!
context?.contentResolver
?.takePersistableUriPermission(
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
)
preferences.setUri(R.string.p_backup_dir, uri)
updateBackupDirectory()
viewModel.updateLocalBackup()
}
} else if (requestCode == REQUEST_PICKER) {
if (resultCode == RESULT_OK) {
val uri = data!!.data
val extension = FileHelper.getExtension(requireContext(), uri!!)
if (!("json".equals(extension, ignoreCase = true) || "xml".equals(
extension,
ignoreCase = true
))
) {
context?.toast(R.string.invalid_backup_file)
} else {
ImportTasksDialog.newImportTasksDialog(uri, extension)
.show(parentFragmentManager, FRAG_TAG_IMPORT_TASKS)
}
}
} else if (requestCode == REQUEST_DRIVE_BACKUP) {
if (resultCode == RESULT_OK) {
viewModel.updateDriveBackup()
} else {
data?.getStringExtra(DriveLoginActivity.EXTRA_ERROR)?.let { context?.toast(it) }
}
} else if (requestCode == REQUEST_BACKUP_NOW) {
if (resultCode == RESULT_OK) {
viewModel.updateLocalBackup()
}
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
private fun onAndroidBackupCheckChanged(preference: Preference, newValue: Any?): Boolean {
if (newValue is Boolean) {
(preference as SwitchPreferenceCompat).isChecked = newValue
updateAndroidBackup()
}
return true
}
private fun onGoogleDriveCheckChanged(preference: Preference, newValue: Any?) = when {
newValue as Boolean -> {
requestGoogleDriveLogin()
false
}
else -> {
preference.summary = null
preference.icon = null
preferences.remove(R.string.p_backups_drive_last)
preferences.remove(R.string.p_google_drive_backup_account)
updateDriveAccount()
viewModel.updateDriveBackup()
true
}
}
private fun updateDriveAccount() {
val account = viewModel.driveAccount
val pref = findPreference(R.string.p_google_drive_backup_account)
pref.isEnabled = account != null
pref.summary =
account
?.takeIf { it.isNotBlank() }
?: getString(R.string.none)
}
private fun requestGoogleDriveLogin() {
if (permissionRequestor.requestAccountPermissions()) {
startActivityForResult(
Intent(context, DriveLoginActivity::class.java),
REQUEST_DRIVE_BACKUP
)
}
}
private fun updateBackupDirectory() {
val pref = findPreference(R.string.p_backup_dir)
val location = FileHelper.uri2String(preferences.backupDirectory)
pref.summary = location
if (preferences.showBackupWarnings() && viewModel.usingPrivateStorage) {
pref.setIcon(R.drawable.ic_outline_error_outline_24px)
tintIcons(pref, requireContext().getColor(R.color.overdue))
pref.summary = """
$location
${requireContext().getString(R.string.backup_location_warning, FileHelper.uri2String(preferences.externalStorage))}
""".trimIndent()
} else {
pref.icon = null
pref.summary = location
}
}
} | gpl-3.0 | dcd058224c2a7b7c4449207a1a2cc442 | 37.489286 | 131 | 0.597717 | 5.233609 | false | false | false | false |
jereksel/LibreSubstratum | app/src/main/kotlin/com/jereksel/libresubstratum/activities/main/MainView.kt | 1 | 5548 | /*
* Copyright (C) 2017 Andrzej Ressel ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.jereksel.libresubstratum.activities.main
import android.app.Dialog
import android.arch.lifecycle.ViewModelProvider
import android.arch.lifecycle.ViewModelProviders
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AlertDialog.Builder
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.view.Menu
import android.view.MenuItem
import com.jereksel.changelogdialog.ChangeLogDialog
import com.jereksel.libresubstratum.App
import com.jereksel.libresubstratum.R
import com.jereksel.libresubstratum.activities.about.AboutActivity
import com.jereksel.libresubstratum.activities.detailed.DetailedActivityStarter
import com.jereksel.libresubstratum.activities.installed.InstalledView
import com.jereksel.libresubstratum.activities.priorities.PrioritiesView
import com.jereksel.libresubstratum.data.Changelog
import com.jereksel.libresubstratum.databinding.ActivityMainBinding
import com.jereksel.libresubstratum.extensions.getLogger
import com.jereksel.libresubstratum.utils.LiveDataUtils.observe
import com.jereksel.libresubstratum.utils.ViewModelUtils.get
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.async
import org.jetbrains.anko.startActivity
import javax.inject.Inject
open class MainView : AppCompatActivity() {
val log = getLogger()
@Inject lateinit var factory: ViewModelProvider.Factory
lateinit var viewModel: IMainViewViewModel
lateinit var binding: ActivityMainBinding
private var dialog: Dialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(application as App).getAppComponent(this).inject(this)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
setSupportActionBar(toolbar)
viewModel = ViewModelProviders.of(this, factory).get()
binding.viewModel = viewModel
with(recyclerView) {
layoutManager = LinearLayoutManager(this@MainView)
itemAnimator = DefaultItemAnimator()
adapter = MainViewAdapter(viewModel)
}
viewModel.getDialogContent().observe(this) { message ->
dismissDialog()
if (!message.isNullOrEmpty()) {
showUndismissableDialog(message!!)
}
}
viewModel.getPermissions().observe(this) { permissions ->
if (permissions == null || permissions.isEmpty()) {
return@observe
}
ActivityCompat.requestPermissions(this, permissions.toTypedArray(), 123)
}
viewModel.getAppToOpen().observe(this) { appId ->
if (!appId.isNullOrEmpty()) {
viewModel.getAppToOpen().postValue(null)
DetailedActivityStarter.start(this, appId)
}
}
viewModel.init()
ChangeLogDialog.show(this, Changelog.changelog)
}
override fun onResume() {
super.onResume()
async(UI) {
viewModel.tickChecks()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem) =
when (item.itemId) {
R.id.action_installed -> {
startActivity<InstalledView>()
true
}
R.id.action_about -> {
startActivity<AboutActivity>()
true
}
R.id.action_priorities -> {
startActivity<PrioritiesView>()
true
}
else ->
super.onOptionsItemSelected(item)
}
private fun dismissDialog() {
if (dialog?.isShowing == true) {
dialog?.dismiss()
}
}
private fun showUndismissableDialog(message: String) {
val builder = Builder(this)
builder.setTitle("Required action")
builder.setMessage(message)
builder.setCancelable(false)
dialog = builder.show()
}
override fun onDestroy() {
super.onDestroy()
dismissDialog()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (requestCode == 123 && permissions.isNotEmpty()) {
async(UI) {
viewModel.tickChecks()
}
}
}
}
| mit | b09cae278ef82e8993ace3da03660ba4 | 32.221557 | 119 | 0.673937 | 5.048226 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-issues/src/main/java/net/nemerosa/ontrack/extension/issues/model/IssueServiceConfigurationIdentifier.kt | 1 | 1003 | package net.nemerosa.ontrack.extension.issues.model
/**
* Representation of the ID of an [net.nemerosa.ontrack.extension.issues.model.IssueServiceConfiguration].
*/
data class IssueServiceConfigurationIdentifier(
val serviceId: String,
val name: String
) {
fun format(): String = "$serviceId$DELIMITER$name"
companion object {
const val DELIMITER = "//"
@JvmStatic
fun parse(value: String?): IssueServiceConfigurationIdentifier? {
return if (value.isNullOrBlank()) {
null
} else {
val serviceId = value.substringBefore(DELIMITER, missingDelimiterValue = "").trim()
val name = value.substringAfter(DELIMITER, missingDelimiterValue = "").trim()
if (serviceId.isNotBlank() && name.isNotBlank()) {
IssueServiceConfigurationIdentifier(serviceId, name)
} else {
null
}
}
}
}
}
| mit | 5136dba4e4ec3a102e29b77d6961a4a3 | 29.393939 | 106 | 0.589232 | 5.421622 | false | true | false | false |
antoniolg/Bandhook-Kotlin | app/src/main/java/com/antonioleiva/bandhookkotlin/di/subcomponent/album/AlbumActivityModule.kt | 1 | 1942 | package com.antonioleiva.bandhookkotlin.di.subcomponent.album
import android.content.Context
import android.support.v7.widget.LinearLayoutManager
import com.antonioleiva.bandhookkotlin.di.ActivityModule
import com.antonioleiva.bandhookkotlin.di.scope.ActivityScope
import com.antonioleiva.bandhookkotlin.domain.interactor.GetAlbumDetailInteractor
import com.antonioleiva.bandhookkotlin.domain.interactor.base.Bus
import com.antonioleiva.bandhookkotlin.domain.interactor.base.InteractorExecutor
import com.antonioleiva.bandhookkotlin.ui.adapter.TracksAdapter
import com.antonioleiva.bandhookkotlin.ui.entity.mapper.AlbumDetailDataMapper
import com.antonioleiva.bandhookkotlin.ui.entity.mapper.TrackDataMapper
import com.antonioleiva.bandhookkotlin.ui.presenter.AlbumPresenter
import com.antonioleiva.bandhookkotlin.ui.screens.album.AlbumActivity
import com.antonioleiva.bandhookkotlin.ui.view.AlbumView
import dagger.Module
import dagger.Provides
@Module
class AlbumActivityModule(activity: AlbumActivity) : ActivityModule(activity) {
@Provides @ActivityScope
fun provideAlbumView(): AlbumView = activity as AlbumView
@Provides @ActivityScope
fun provideAlbumDataMapper() = AlbumDetailDataMapper()
@Provides @ActivityScope
fun provideTrackDataMapper() = TrackDataMapper()
@Provides @ActivityScope
fun provideLinearLayoutManager(context: Context) = LinearLayoutManager(context)
@Provides @ActivityScope
fun provideTracksAdapter() = TracksAdapter()
@Provides @ActivityScope
fun provideAlbumPresenter(view: AlbumView,
bus: Bus,
albumInteractor: GetAlbumDetailInteractor,
interactorExecutor: InteractorExecutor,
albumDetailDataMapper: AlbumDetailDataMapper)
= AlbumPresenter(view, bus, albumInteractor,
interactorExecutor, albumDetailDataMapper)
} | apache-2.0 | 2f55cbc4aa63a4a8eca04ab77bf68a36 | 42.177778 | 83 | 0.779609 | 5.234501 | false | false | false | false |
ibaton/3House | mobile/src/main/java/treehou/se/habit/ui/sitemaps/sitemaplist/SitemapListFragment.kt | 1 | 5586 | package treehou.se.habit.ui.sitemaps.sitemaplist
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_sitemaplist_list.*
import se.treehou.ng.ohcommunicator.connector.models.OHServer
import se.treehou.ng.ohcommunicator.connector.models.OHSitemap
import treehou.se.habit.R
import treehou.se.habit.dagger.HasActivitySubcomponentBuilders
import treehou.se.habit.dagger.fragment.SitemapListComponent
import treehou.se.habit.dagger.fragment.SitemapListModule
import treehou.se.habit.mvp.BaseDaggerFragment
import treehou.se.habit.ui.adapter.SitemapListAdapter
import treehou.se.habit.ui.adapter.SitemapListAdapter.ServerState
import treehou.se.habit.ui.sitemaps.sitemap.SitemapFragment
import javax.inject.Inject
import javax.net.ssl.SSLPeerUnverifiedException
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
class SitemapListFragment : BaseDaggerFragment<SitemapListContract.Presenter>(), SitemapListContract.View {
@Inject lateinit var sitemapListPresenter: SitemapListContract.Presenter
private var sitemapAdapter: SitemapListAdapter? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_sitemaplist_list, container, false)
}
private fun setupSitemapListAdapter() {
val gridLayoutManager = GridLayoutManager(activity, 1)
listView.layoutManager = gridLayoutManager
listView.itemAnimator = DefaultItemAnimator()
sitemapAdapter = SitemapListAdapter()
sitemapAdapter!!.setSitemapSelectedListener(object : SitemapListAdapter.SitemapSelectedListener {
override fun onSelected(server: OHServer, sitemap: OHSitemap?) {
sitemapListPresenter.openSitemap(server, sitemap)
}
override fun onErrorSelected(server: OHServer) {
Log.d(TAG, "Reloading server: " + server.displayName)
sitemapListPresenter.reloadSitemaps(server)
}
override fun onCertificateErrorSelected(server: OHServer) {
}
})
listView.adapter = sitemapAdapter
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupActionBar()
setupSitemapListAdapter()
}
/**
* Open fragment showing sitemap.
*
* @param server the server of default sitemap.
* @param sitemap the name of sitemap to show.
*/
override fun showSitemap(server: OHServer, sitemap: OHSitemap) {
val fragmentManager = activity!!.supportFragmentManager
fragmentManager.beginTransaction()
.replace(R.id.page_container, SitemapFragment.newInstance(server, sitemap))
.addToBackStack(null)
.commit()
}
/**
* Setup actionbar.
*/
private fun setupActionBar() {
val actionBar = (activity as AppCompatActivity).supportActionBar
actionBar?.setTitle(R.string.sitemaps)
}
override fun hideEmptyView() {
emptyView.visibility = View.GONE
}
/**
* Clears list of sitemaps.
*/
override fun clearList() {
emptyView.visibility = View.VISIBLE
sitemapAdapter!!.clear()
}
override fun showServerError(server: OHServer, error: Throwable) {
if (error is SSLPeerUnverifiedException) {
sitemapAdapter!!.setServerState(server, ServerState.STATE_CERTIFICATE_ERROR)
} else {
sitemapAdapter!!.setServerState(server, ServerState.STATE_ERROR)
}
}
override fun populateSitemaps(server: OHServer, sitemaps: List<OHSitemap>) {
for (sitemap in sitemaps) {
sitemapAdapter!!.add(server, sitemap)
}
}
override fun getPresenter(): SitemapListContract.Presenter? {
return sitemapListPresenter
}
override fun injectMembers(hasActivitySubcomponentBuilders: HasActivitySubcomponentBuilders) {
(hasActivitySubcomponentBuilders.getFragmentComponentBuilder(SitemapListFragment::class.java) as SitemapListComponent.Builder)
.fragmentModule(SitemapListModule(this, arguments!!))
.build().injectMembers(this)
}
companion object {
private val TAG = "SitemapSelectFragment"
val ARG_SHOW_SITEMAP = "showSitemap"
/**
* Create fragment where user can select sitemap.
*
* @return Fragment
*/
fun newInstance(): SitemapListFragment {
val fragment = SitemapListFragment()
val args = Bundle()
fragment.arguments = args
return fragment
}
/**
* Load sitemaps for servers.
* Open provided sitemap if loaded.
*
* @param sitemap name of sitemap to load
* @return Fragment
*/
fun newInstance(sitemap: String): SitemapListFragment {
val fragment = SitemapListFragment()
val args = Bundle()
args.putString(ARG_SHOW_SITEMAP, sitemap)
fragment.arguments = args
return fragment
}
}
}
| epl-1.0 | 9dfaba6c7e7eaa1e167620ceb46dfdf5 | 33.481481 | 134 | 0.682062 | 5.264844 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/utils/extensions/PlayServicesExtensions.kt | 1 | 1230 | @file:JvmName("PlayServicesUtil")
package de.xikolo.utils.extensions
import android.app.Activity
import android.content.Context
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
private const val PLAY_SERVICES_RESOLUTION_REQUEST = 9000
fun <T : Activity> T.checkPlayServicesWithDialog(): Boolean {
val googleAPI = GoogleApiAvailability.getInstance()
val result = googleAPI.isGooglePlayServicesAvailable(this)
when (result) {
ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED, ConnectionResult.SERVICE_DISABLED -> {
googleAPI.getErrorDialog(this, result, PLAY_SERVICES_RESOLUTION_REQUEST).show()
return false
}
ConnectionResult.SERVICE_MISSING, ConnectionResult.SERVICE_MISSING_PERMISSION, ConnectionResult.SERVICE_INVALID, ConnectionResult.SERVICE_UPDATING -> return false
}
return true
}
val <T : Context> T.hasPlayServices: Boolean
get() {
val googleAPI = GoogleApiAvailability.getInstance()
val result = googleAPI.isGooglePlayServicesAvailable(this)
return result == ConnectionResult.SUCCESS
}
| bsd-3-clause | b90a0ebf5b868e5d998fc4760d9d5aad | 36.272727 | 170 | 0.713821 | 5.082645 | false | false | false | false |
yukuku/androidbible | Alkitab/src/main/java/yuku/alkitab/datatransfer/process/ReadWriteStorageImpl.kt | 1 | 1963 | package yuku.alkitab.datatransfer.process
import java.util.Date
import yuku.alkitab.base.S
import yuku.alkitab.base.storage.InternalDbTxWrapper
import yuku.alkitab.base.util.History
import yuku.alkitab.base.util.Sqlitil
import yuku.alkitab.datatransfer.model.Pin
import yuku.alkitab.datatransfer.model.Rpp
import yuku.alkitab.model.Label
import yuku.alkitab.model.Marker
import yuku.alkitab.model.Marker_Label
import yuku.alkitab.model.ProgressMark
import yuku.alkitab.util.IntArrayList
class ReadWriteStorageImpl : ReadonlyStorageImpl(), ReadWriteStorageInterface {
override fun transact(action: (ReadWriteStorageInterface.TxHandle) -> Unit) {
InternalDbTxWrapper.transact(S.getDb()) { handle ->
action { handle.commit() }
}
}
override fun replaceMarkerLabel(markerLabel: Marker_Label) {
S.getDb().insertOrUpdateMarker_Label(markerLabel)
}
override fun replaceHistory(entries: List<History.Entry>) {
History.replaceAllEntries(entries)
}
/**
* [marker] must have the correct _id for this to work correctly (0 for new).
*/
override fun replaceMarker(marker: Marker) {
S.getDb().insertOrUpdateMarker(marker)
}
/**
* [label] must have the correct _id for this to work correctly (0 for new).
*/
override fun replaceLabel(label: Label) {
S.getDb().insertOrUpdateLabel(label)
}
override fun replacePin(pin: Pin) {
val pm = ProgressMark().apply {
preset_id = pin.preset_id
ari = pin.ari
caption = pin.caption
modifyTime = Sqlitil.toDate(pin.modifyTime)
}
S.getDb().insertOrUpdateProgressMark(pm)
}
override fun replaceRpp(rpp: Rpp) {
val readingCodes = IntArrayList(rpp.done.size)
rpp.done.forEach { readingCodes.add(it) }
S.getDb().replaceReadingPlanProgress(rpp.gid.value, readingCodes, System.currentTimeMillis())
}
}
| apache-2.0 | 9b1fc12744d3416c7ac7b3eebe27fd19 | 31.180328 | 101 | 0.69027 | 4.072614 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/view/ViewRenderToBitmap.kt | 1 | 907 | package com.soywiz.korge.view
import com.soywiz.korge.render.*
import com.soywiz.korim.bitmap.*
import kotlinx.coroutines.*
/**
* Asynchronously renders this [View] (with the provided [views]) to a [Bitmap32] and returns it.
* The rendering will happen before the next frame.
*/
suspend fun View.renderToBitmap(views: Views): Bitmap32 {
val view = this
val bounds = getLocalBoundsOptimizedAnchored()
val done = CompletableDeferred<Bitmap32>()
views.onBeforeRender.once {
done.complete(Bitmap32(bounds.width.toInt(), bounds.height.toInt()).also { bmp ->
val ctx = RenderContext(views.ag, coroutineContext = views.coroutineContext)
views.ag.renderToBitmap(bmp) {
ctx.useBatcher { batch ->
batch.setViewMatrixTemp(view.globalMatrixInv) {
view.render(ctx)
}
}
}
})
}
return done.await()
}
| apache-2.0 | 9f62b02c4cfe4306d0c3bbef16b55fb9 | 29.233333 | 97 | 0.661521 | 3.876068 | false | false | false | false |
255BITS/hypr | app/src/main/java/hypr/hypergan/com/hypr/Util/ImageSaver.kt | 1 | 2358 | package hypr.hypergan.com.hypr.Util
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.*
class ImageSaver {
fun saveImageToInternalStorage(focusedImageBitmap: Bitmap?, context: Context, folderName: String = "hyprimages"): Boolean {
val root = Environment.getExternalStoragePublicDirectory(folderName).toString()
val myDir = File(root)
if (!myDir.exists()) {
myDir.mkdir()
}
val formatter = SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSSSS")
val now = Date()
val fileName = formatter.format(now)
val fname = "/Image_$fileName.jpg"
val file = File(myDir, fname)
try {
val out = FileOutputStream(file)
focusedImageBitmap?.compress(Bitmap.CompressFormat.JPEG, 100, out)
out.close()
} catch (e: Exception) {
e.printStackTrace()
}
val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file))
context.sendBroadcast(Intent(intent))
return true
}
fun saveImageToFile(file: File, image: ByteArray?): File {
val fos = FileOutputStream(file)
fos.write(image)
return file
}
fun writeByteArrayToFile(fileLocation: String, imageInBytes: ByteArray?) {
val file = File(fileLocation)
file.createNewFile()
val fileOutput = FileOutputStream(file)
fileOutput.write(imageInBytes)
}
private fun uriToBitmap(imageLocation: Uri, context: Context): Bitmap {
return MediaStore.Images.Media.getBitmap(context.contentResolver, imageLocation)
}
fun uriToByteArray(imageLocation: Uri, context: Context): ByteArray? {
val bitmap = uriToBitmap(imageLocation, context)
return bitmapToByteArray(bitmap)
}
private fun bitmapToByteArray(bitmap: Bitmap): ByteArray? {
val stream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
return stream.toByteArray()
}
}
| mit | 84717e8835c395214aedbd08008e0e15 | 33.676471 | 127 | 0.654792 | 4.678571 | false | false | false | false |
chrimaeon/app-rater | buildSrc/src/main/kotlin/com/cmgapps/gradle/configureKtlint.kt | 1 | 2326 | /*
* Copyright (c) 2020. Christian Grach <[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.cmgapps.gradle
import org.gradle.api.Project
import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.api.tasks.JavaExec
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.invoke
import org.gradle.kotlin.dsl.register
@Suppress("UnstableApiUsage")
fun Project.configureKtlint() {
val ktlint = configurations.create("ktlint")
tasks {
val inputFiles = fileTree("src") {
include("**/*.kt")
}
val outputDir = buildDir.resolve("reports")
register<JavaExec>("ktlintFormat") {
inputs.files(inputFiles)
outputs.dir(outputDir)
group = "Formatting"
description = "Fix Kotlin code style deviations."
mainClass.set("com.pinterest.ktlint.Main")
classpath = ktlint
args = listOf("-F", "src/**/*.kt")
}
val ktlintTask = register<JavaExec>("ktlint") {
inputs.files(inputFiles)
outputs.dir(outputDir)
group = "Verification"
description = "Check Kotlin code style."
mainClass.set("com.pinterest.ktlint.Main")
classpath = ktlint
args = listOf(
"src/**/*.kt",
"--reporter=plain",
"--reporter=html,output=$outputDir/ktlint.html"
)
}
named("check") {
dependsOn(ktlintTask)
}
}
dependencies {
val libs = project.extensions.getByType<VersionCatalogsExtension>().named("libs")
dependencies.add(ktlint.name, libs.findDependency("ktlint").orElseThrow())
}
}
| apache-2.0 | 9e031419ee746d4d4c4a44964cadaa33 | 30.863014 | 89 | 0.634566 | 4.516505 | false | false | false | false |
openstreetview/android | app/src/main/java/com/telenav/osv/recorder/metadata/MetadataSensorManager.kt | 1 | 8395 | package com.telenav.osv.recorder.metadata
import android.content.Context
import android.location.Location
import com.telenav.osv.data.collector.config.Config
import com.telenav.osv.data.collector.datatype.EventDataListener
import com.telenav.osv.data.collector.datatype.datatypes.BaseObject
import com.telenav.osv.data.collector.datatype.datatypes.ObdSpeedObject
import com.telenav.osv.data.collector.datatype.datatypes.PressureObject
import com.telenav.osv.data.collector.datatype.datatypes.ThreeAxesObject
import com.telenav.osv.data.collector.datatype.util.LibraryUtil
import com.telenav.osv.data.collector.manager.DataCollectorManager
import com.telenav.osv.item.KVFile
import com.telenav.osv.recorder.metadata.callback.*
import timber.log.Timber
/**
* The manager for the sensor across the app which are required to be logged by metadata.
*
* The class itself follows the Singleton pattern in order to maintain only one instance so all the data will be written in the order it is received.
*
* It uses [DataCollectorManager] as a dependency to get phone sensor data in the metadata file.
*
* Available lifecycle methods:
* * [start]
* * [stop]
*
* Available sensor logging methods (the sensors required by the metadata which are not existent in the data collector dependency):
* * [onPhotoVideoCallback]
* * [onObdCallback]
* * [onCameraSensorCallback]
* * [onDeviceLog]
* * [onGpsLog]
*/
class MetadataSensorManager private constructor() : EventDataListener, MetadataObdCallback, MetadataPhotoVideoCallback, MetadataCameraCallback, MetadataGpsCallback {
private val metadataWriter: MetadataWriter = MetadataWriter()
private val metadataLogger: MetadataLogger = MetadataLogger()
private var dataCollector: DataCollectorManager? = null
private var photoCachedData: PhotoCachedData = PhotoCachedData(null, null)
var listener: MetadataWrittingStatusCallback? = null
private object HOLDER {
val INSTANCE = MetadataSensorManager()
}
fun create(parentFolder: KVFile, context: Context) {
if (listener == null) {
Timber.e("Listener not set!")
return;
}
metadataWriter.createFile(parentFolder, listener!!, metadataLogger.headerWithBody())
if (dataCollector == null) {
val configBuilder = Config.Builder()
configBuilder.addSource(LibraryUtil.PHONE_SOURCE)
//heading
.addDataListener(this, LibraryUtil.HEADING)
.addSensorFrequency(LibraryUtil.HEADING, LibraryUtil.F_10HZ)
//pressure
.addDataListener(this, LibraryUtil.PRESSURE)
.addSensorFrequency(LibraryUtil.HEADING, LibraryUtil.F_10HZ)
//gravity
.addDataListener(this, LibraryUtil.GRAVITY)
.addSensorFrequency(LibraryUtil.GRAVITY, LibraryUtil.F_10HZ)
//linear accel
.addDataListener(this, LibraryUtil.LINEAR_ACCELERATION)
.addSensorFrequency(LibraryUtil.LINEAR_ACCELERATION, LibraryUtil.F_10HZ)
//rotation vector
.addDataListener(this, LibraryUtil.ROTATION_VECTOR_RAW)
.addSensorFrequency(LibraryUtil.ROTATION_VECTOR_RAW, LibraryUtil.F_10HZ)
dataCollector = DataCollectorManager(context, configBuilder.build())
Timber.d("start. Status: create data collector manager with specific settings")
}
}
/**
* Start method which will create the metadata file which and start the phone sensor collection by using internally the [MetadataWriter.createFile].
*/
fun start() {
//register for the desired phone sensors, and start the data collector library
Timber.d("start. Status: start data collector manager")
dataCollector?.startCollecting()
}
/**
* Stop method which will stop the data collector sensor gathering and signal internally the writter that the file is closed by using [MetadataWriter.finish].
*/
fun stop() {
dataCollector?.stopCollectingPhoneData()
Timber.d("stop. Status: DC stopped collecting. Append footer and close file.")
metadataWriter.finish(metadataLogger.footer())
}
override fun onPhotoVideoCallback(timestamp: Long, frameIndex: Int, videoIndex: Int, location: Location) {
if (location.latitude == 0.0 && location.longitude == 0.0) {
Timber.d("onPhotoVideoCallback. Status: error. Message: No gps found")
listener?.onMetadataLoggingError(Exception("Gps 0.0 found"))
return
}
Timber.d("onPhotoVideoCallback. Status: log photo data")
metadataWriter.appendInFile(metadataLogger.bodyPhotoVideo(timestamp, videoIndex, frameIndex, location, photoCachedData.compassData, photoCachedData.obdSpeedObject), true)
}
override fun onObdCallback(timeStamp: Long, speed: Int) {
Timber.d("onObdCallback. Status: log obd data. Timestamp: $timeStamp. Speed:$speed.")
metadataWriter.appendInFile(metadataLogger.bodyObd(timeStamp, speed))
}
override fun onCameraSensorCallback(timestamp: Long, focalLength: Float, horizontalFieldOfView: Double, verticalFieldOfView: Double, lensAperture: Float, cameraWidth: Int, cameraHeight: Int) {
Timber.d("onCameraSensorCallback. Status: log single exif data. Focal length: $focalLength")
metadataWriter.appendInFile(metadataLogger.bodyExif(timestamp, focalLength, cameraWidth, cameraHeight))
Timber.d("onCameraSensorCallback. Status: log camera data. Horizontal field of view: $horizontalFieldOfView. Vertical field of view: $verticalFieldOfView.")
metadataWriter.appendInFile(metadataLogger.bodyCamera(timestamp, horizontalFieldOfView, verticalFieldOfView, lensAperture))
}
fun onDeviceLog(timeStamp: Long, platform: String, osRawName: String, osVersion: String, deviceRawName: String, appVersion: String, appBuildNumber: String, isVideoCompression: Boolean) {
Timber.d("onDeviceLog. Status: log device data. Timestamp: $timeStamp. App Build number:$appBuildNumber. IsVideoCompression: $isVideoCompression")
metadataWriter.appendInFile(metadataLogger.bodyDevice(timeStamp, platform, osRawName, osVersion, deviceRawName, appVersion, appBuildNumber, if (isVideoCompression) COMPRESSION_VIDEO else COMPRESSION_PHOTO))
}
override fun onGpsLog(location: Location) {
metadataWriter.appendInFile(metadataLogger.bodyGps(location))
}
override fun onNewEvent(baseObject: BaseObject<*>?) {
if (baseObject!!.statusCode != LibraryUtil.PHONE_SENSOR_READ_SUCCESS) {
Timber.d("onNewEvent. Status: Failed status. Message: New event ignored.")
return
}
Timber.d(String.format("onNewEvent. Status: received sensor. type: %s", baseObject.getSensorType()))
when (baseObject.getSensorType()) {
LibraryUtil.ACCELEROMETER -> metadataWriter.appendInFile(metadataLogger.bodyAcceleration(baseObject as ThreeAxesObject))
LibraryUtil.GRAVITY -> metadataWriter.appendInFile(metadataLogger.bodyGravity(baseObject as ThreeAxesObject))
LibraryUtil.ROTATION_VECTOR_RAW -> metadataWriter.appendInFile(metadataLogger.bodyAttitude(baseObject as ThreeAxesObject))
LibraryUtil.LINEAR_ACCELERATION -> metadataWriter.appendInFile(metadataLogger.bodyAcceleration(baseObject as ThreeAxesObject))
LibraryUtil.PRESSURE -> {
Timber.d(String.format("onNewEvent. Status: pressure received sensor. "))
metadataWriter.appendInFile(metadataLogger.bodyPressure(baseObject as PressureObject))
}
LibraryUtil.HEADING -> {
val compassData = baseObject as ThreeAxesObject
photoCachedData.compassData = compassData
metadataWriter.appendInFile(metadataLogger.bodyCompass(compassData))
}
}
}
private data class PhotoCachedData(var compassData: ThreeAxesObject?, var obdSpeedObject: ObdSpeedObject?)
companion object {
val INSTANCE: MetadataSensorManager by lazy { HOLDER.INSTANCE }
private const val SIZE_ONE_VALUE = 1
private const val COMPRESSION_PHOTO = "photo"
private const val COMPRESSION_VIDEO = "video"
}
}
| lgpl-3.0 | fdfae9a9569070c127c1e46fd3815917 | 50.820988 | 214 | 0.712686 | 4.949882 | false | false | false | false |
uchuhimo/kotlin-playground | konf/src/main/kotlin/com/uchuhimo/konf/source/DefaultLoaders.kt | 1 | 1861 | package com.uchuhimo.konf.source
import com.uchuhimo.konf.Config
import com.uchuhimo.konf.source.base.FlatSource
import com.uchuhimo.konf.source.base.KVSource
import com.uchuhimo.konf.source.base.MapSource
import com.uchuhimo.konf.source.env.EnvProvider
import com.uchuhimo.konf.source.hocon.HoconProvider
import com.uchuhimo.konf.source.json.JsonProvider
import com.uchuhimo.konf.source.properties.PropertiesProvider
import com.uchuhimo.konf.source.toml.TomlProvider
import com.uchuhimo.konf.source.xml.XmlProvider
import com.uchuhimo.konf.source.yaml.YamlProvider
import java.io.File
class DefaultLoaders(val config: Config) {
@JvmField
val hocon = Loader(config, HoconProvider)
@JvmField
val json = Loader(config, JsonProvider)
@JvmField
val properties = Loader(config, PropertiesProvider)
@JvmField
val toml = Loader(config, TomlProvider)
@JvmField
val xml = Loader(config, XmlProvider)
@JvmField
val yaml = Loader(config, YamlProvider)
@JvmField
val map = MapLoader(config)
fun env(): Config = config.load(EnvProvider.fromEnv())
fun systemProperties(): Config = config.load(PropertiesProvider.fromSystem())
fun file(file: File): Config {
return when (file.extension) {
"conf" -> hocon.file(file)
"json" -> json.file(file)
"properties" -> properties.file(file)
"toml" -> toml.file(file)
"xml" -> xml.file(file)
"yml", "yaml" -> yaml.file(file)
else -> throw UnsupportedExtensionException(file)
}
}
}
class MapLoader(val config: Config) {
fun hierarchical(map: Map<String, Any>): Config = config.load(MapSource(map))
fun kv(map: Map<String, Any>): Config = config.load(KVSource(map))
fun flat(map: Map<String, String>): Config = config.load(FlatSource(map))
}
| apache-2.0 | fffdb45f86da67f16b39b7d812e7efba | 29.508197 | 81 | 0.697474 | 3.829218 | false | true | false | false |
panpf/sketch | sketch/src/androidTest/java/com/github/panpf/sketch/test/stateimage/ErrorStateImageTest.kt | 1 | 4761 | /*
* 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.stateimage
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.github.panpf.sketch.request.DisplayRequest
import com.github.panpf.sketch.request.UriInvalidException
import com.github.panpf.sketch.sketch
import com.github.panpf.sketch.stateimage.ColorStateImage
import com.github.panpf.sketch.stateimage.DrawableStateImage
import com.github.panpf.sketch.stateimage.ErrorStateImage
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ErrorStateImageTest {
@Test
fun testGetDrawable() {
val context = InstrumentationRegistry.getInstrumentation().context
val sketch = context.sketch
val request = DisplayRequest(context, "")
val colorDrawable = ColorDrawable(Color.BLUE)
val colorDrawable2 = ColorDrawable(Color.RED)
ErrorStateImage(DrawableStateImage(colorDrawable)).apply {
Assert.assertFalse(matcherList.isEmpty())
Assert.assertEquals(colorDrawable, getDrawable(sketch, request, null))
Assert.assertEquals(
colorDrawable,
getDrawable(sketch, request, UriInvalidException(""))
)
}
ErrorStateImage(DrawableStateImage(colorDrawable)) {
uriEmptyError(colorDrawable2)
}.apply {
Assert.assertFalse(matcherList.isEmpty())
Assert.assertEquals(colorDrawable, getDrawable(sketch, request, null))
Assert.assertEquals(
colorDrawable2,
getDrawable(sketch, request, UriInvalidException(""))
)
}
ErrorStateImage {
}.apply {
Assert.assertTrue(matcherList.isEmpty())
Assert.assertNull(getDrawable(sketch, request, null))
Assert.assertNull(
getDrawable(sketch, request, UriInvalidException(""))
)
}
}
@Test
fun testEqualsAndHashCode() {
val element1 = ErrorStateImage(ColorStateImage(Color.RED))
val element11 = ErrorStateImage(ColorStateImage(Color.RED))
val element2 = ErrorStateImage(ColorStateImage(Color.GREEN))
val element3 = ErrorStateImage(ColorStateImage(Color.BLUE))
Assert.assertNotSame(element1, element11)
Assert.assertNotSame(element1, element2)
Assert.assertNotSame(element1, element3)
Assert.assertNotSame(element2, element11)
Assert.assertNotSame(element2, element3)
Assert.assertEquals(element1, element1)
Assert.assertEquals(element1, element11)
Assert.assertNotEquals(element1, element2)
Assert.assertNotEquals(element1, element3)
Assert.assertNotEquals(element2, element11)
Assert.assertNotEquals(element2, element3)
Assert.assertNotEquals(element1, null)
Assert.assertNotEquals(element1, Any())
Assert.assertEquals(element1.hashCode(), element1.hashCode())
Assert.assertEquals(element1.hashCode(), element11.hashCode())
Assert.assertNotEquals(element1.hashCode(), element2.hashCode())
Assert.assertNotEquals(element1.hashCode(), element3.hashCode())
Assert.assertNotEquals(element2.hashCode(), element11.hashCode())
Assert.assertNotEquals(element2.hashCode(), element3.hashCode())
}
@Test
fun testToString() {
ErrorStateImage(ColorStateImage(Color.RED)).apply {
Assert.assertEquals(
"ErrorStateImage([DefaultMatcher(ColorStateImage(IntColor(${Color.RED})))])",
toString()
)
}
ErrorStateImage(ColorStateImage(Color.GREEN)) {
uriEmptyError(ColorStateImage(Color.YELLOW))
}.apply {
Assert.assertEquals(
"ErrorStateImage([UriEmptyMatcher(ColorStateImage(IntColor(${Color.YELLOW}))), DefaultMatcher(ColorStateImage(IntColor(${Color.GREEN})))])",
toString()
)
}
}
} | apache-2.0 | 5cb8e93bab32506a2b293371c2f6db12 | 38.355372 | 156 | 0.68599 | 4.954214 | false | true | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/users/StatusRetweetersLoader.kt | 1 | 3273 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.loader.users
import android.content.Context
import de.vanita5.microblog.library.MicroBlog
import de.vanita5.microblog.library.MicroBlogException
import de.vanita5.microblog.library.mastodon.Mastodon
import de.vanita5.microblog.library.twitter.model.Paging
import de.vanita5.twittnuker.annotation.AccountType
import de.vanita5.twittnuker.exception.APINotSupportedException
import de.vanita5.twittnuker.extension.model.api.mastodon.toParcelable
import de.vanita5.twittnuker.extension.model.api.toParcelable
import de.vanita5.twittnuker.extension.model.newMicroBlogInstance
import de.vanita5.twittnuker.model.AccountDetails
import de.vanita5.twittnuker.model.ParcelableUser
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.pagination.PaginatedArrayList
import de.vanita5.twittnuker.model.pagination.PaginatedList
class StatusRetweetersLoader(
context: Context,
accountKey: UserKey?,
private val statusId: String,
data: List<ParcelableUser>?,
fromUser: Boolean
) : AbsRequestUsersLoader(context, accountKey, data, fromUser) {
@Throws(MicroBlogException::class)
override fun getUsers(details: AccountDetails, paging: Paging): PaginatedList<ParcelableUser> {
when (details.type) {
AccountType.MASTODON -> {
val mastodon = details.newMicroBlogInstance(context, Mastodon::class.java)
val response = mastodon.getStatusFavouritedBy(statusId)
return PaginatedArrayList<ParcelableUser>(response.size).apply {
response.mapTo(this) { account ->
account.toParcelable(details)
}
}
}
AccountType.TWITTER -> {
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
val ids = microBlog.getRetweetersIDs(statusId, paging).iDs
val response = microBlog.lookupUsers(ids)
return PaginatedArrayList<ParcelableUser>(response.size).apply {
response.mapTo(this) { user ->
user.toParcelable(details, profileImageSize = profileImageSize)
}
}
}
else -> {
throw APINotSupportedException(details.type)
}
}
}
} | gpl-3.0 | 7c8aaaea9a3866217bbd243a515aae8e | 41.519481 | 99 | 0.69722 | 4.662393 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/LiveEventEmbed.kt | 1 | 4217 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* LiveEvent embed data.
*
* @param chatEmbedSource The chat's iFrame source URL.
* @param color The primary player color, which controls the color of the progress bar, buttons, and more.
* @param embedChat The embed code for RLE chat.
* @param embedProperties The height, width, and source URL properties used to generate the fixed HTML embed code.
* @param html The fixed HTML code to embed the live event's playlist on a website.
* @param logoInfo A collection of information about the logo in the corner of the embeddable player.
* @param responsiveHtml The responsive HTML code to embed the live event's playlist on a website.
* @param shouldAutoplay Whether the embedded RLE player should autoplay the RLE content.
* @param shouldDisplayEventSchedule Whether the embedded RLE player should display the event schedule.
* @param shouldDisplayFullscreenControls Whether the embedded RLE player should include the fullscreen controls.
* @param shouldDisplayLikeButton Whether the embedded RLE player should include the like button.
* @param shouldHideLiveLabel Whether the embedded RLE player should hide the live label.
* @param shouldHideViewerCount Whether the embedded RLE player should hide the viewer count.
* @param shouldLoop Whether the embedded RLE player should loop back to the first video once content is exhausted.
* @param shouldShowName Whether the embedded RLE player should display the author's name.
* @param shouldShowPlayBar Whether the embedded RLE player should include the play bar.
* @param shouldShowPlayList Whether the play list component appears in the embeddable player for this RLE.
* @param shouldShowPortrait Whether the embedded RLE player should display the author's portrait.
* @param shouldShowSchedule Whether the schedule component appears in the embeddable player for this RLE.
* @param shouldShowLatestVideoPlaceholder Whether the embedded RLE player should display the latest video placeholder.
* @param shouldShowVolumeControls Whether the embedded RLE player should include the volume controls.
* @param shouldShowTitle Whether the embedded RLE player should display the video title.
* @param shouldUseCustomColor Whether the embedded RLE player should use a custom color or the default Vimeo blue.
*/
@JsonClass(generateAdapter = true)
data class LiveEventEmbed(
@Json(name = "chat_embed_source")
val chatEmbedSource: String? = null,
@Json(name = "color")
val color: String? = null,
@Json(name = "embed_chat")
val embedChat: String? = null,
@Json(name = "embed_properties")
val embedProperties: LiveEventEmbedProperties? = null,
@Json(name = "html")
val html: String? = null,
@Json(name = "logos")
val logoInfo: LiveEventLogoInfo? = null,
@Json(name = "responsiveHtml")
val responsiveHtml: String? = null,
@Json(name = "autoplay")
val shouldAutoplay: Boolean? = null,
@Json(name = "event_schedule")
val shouldDisplayEventSchedule: Boolean? = null,
@Json(name = "fullscreen_button")
val shouldDisplayFullscreenControls: Boolean? = null,
@Json(name = "like_button")
val shouldDisplayLikeButton: Boolean? = null,
@Json(name = "hide_live_label")
val shouldHideLiveLabel: Boolean? = null,
@Json(name = "hide_viewer_count")
val shouldHideViewerCount: Boolean? = null,
@Json(name = "loop")
val shouldLoop: Boolean? = null,
@Json(name = "byline")
val shouldShowName: Boolean? = null,
@Json(name = "playbar")
val shouldShowPlayBar: Boolean? = null,
@Json(name = "playlist")
val shouldShowPlayList: Boolean? = null,
@Json(name = "portrait")
val shouldShowPortrait: Boolean? = null,
@Json(name = "schedule")
val shouldShowSchedule: Boolean? = null,
@Json(name = "show_latest_archived_clip")
val shouldShowLatestVideoPlaceholder: Boolean? = null,
@Json(name = "volume")
val shouldShowVolumeControls: Boolean? = null,
@Json(name = "title")
val shouldShowTitle: Boolean? = null,
@Json(name = "use_color")
val shouldUseCustomColor: Boolean? = null
)
| mit | 8e70782d644e9d3a060829dbe83dce06 | 39.548077 | 119 | 0.736543 | 4.311861 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/intentions/AddCurlyBracesIntentionTest.kt | 3 | 1619 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
class AddCurlyBracesIntentionTest : RsIntentionTestBase(AddCurlyBracesIntention::class) {
fun `test add curly braces simple`() = doAvailableTest(
"use std::m/*caret*/em;",
"use std::{mem/*caret*/};"
)
fun `test add curly brace super`() = doAvailableTest(
"use super/*caret*/::qux;",
"use super::{qux};"
)
fun `test add curly braces longer`() = doAvailableTest(
"use foo::bar::/*caret*/baz::qux;",
"use foo::bar::baz::{qux/*caret*/};"
)
fun `test add curly braces alias`() = doAvailableTest(
"use std::mem as mem/*caret*/ory;",
"use std::{mem as memory/*caret*/};"
)
fun `test add curly braces extra`() = doAvailableTest(
"#[macro_use] pub use /*comment*/ std::me/*caret*/m;",
"#[macro_use] pub use /*comment*/ std::{mem/*caret*/};"
)
fun `test works for root path 1`() = doAvailableTest(
"use ::foo/*caret*/;",
"use ::{foo/*caret*/};"
)
fun `test works for root path 2`() = doAvailableTest(
"use foo/*caret*/;",
"use ::{foo/*caret*/};"
)
fun `test not available for star imports`() = doUnavailableTest("""
use foo::*/*caret*/;
""")
fun `test without last path segment`() = doAvailableTest(
"use std::/*caret*/;",
"use std::{/*caret*/};"
)
fun `test not available if already has braces`() = doUnavailableTest("""
use foo::{bar/*caret*/};
""")
}
| mit | c0b7aed58d0905043b852494fe64fa95 | 27.403509 | 89 | 0.559605 | 4.098734 | false | true | false | false |
Senspark/ee-x | src/android/app_lovin/src/main/java/com/ee/internal/AppLovinRewardedAdListener.kt | 1 | 4145 | package com.ee.internal
import com.applovin.sdk.AppLovinAd
import com.applovin.sdk.AppLovinAdClickListener
import com.applovin.sdk.AppLovinAdDisplayListener
import com.applovin.sdk.AppLovinAdLoadListener
import com.applovin.sdk.AppLovinAdRewardListener
import com.applovin.sdk.AppLovinAdVideoPlaybackListener
import com.ee.ILogger
import com.ee.IMessageBridge
import com.ee.Thread
import com.ee.Utils
import kotlinx.serialization.Serializable
import java.util.concurrent.atomic.AtomicBoolean
internal class AppLovinRewardedAdListener(
private val _bridge: IMessageBridge,
private val _logger: ILogger)
: AppLovinAdLoadListener, AppLovinAdDisplayListener, AppLovinAdClickListener, AppLovinAdRewardListener, AppLovinAdVideoPlaybackListener {
@Serializable
@Suppress("unused")
private class ErrorResponse(
val code: Int,
val message: String
)
companion object {
private val kTag = AppLovinRewardedAdListener::class.java.name
private const val kPrefix = "AppLovinBridge"
private const val kOnRewardedAdLoaded = "${kPrefix}OnRewardedAdLoaded"
private const val kOnRewardedAdFailedToLoad = "${kPrefix}OnRewardedAdFailedToLoad"
private const val kOnRewardedAdClicked = "${kPrefix}OnRewardedAdClicked"
private const val kOnRewardedAdClosed = "${kPrefix}OnRewardedAdClosed"
}
private val _isLoaded = AtomicBoolean(false)
private var _rewarded = false
val isLoaded: Boolean
get() = _isLoaded.get()
override fun adReceived(ad: AppLovinAd) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::adReceived.name}")
_isLoaded.set(true)
_bridge.callCpp(kOnRewardedAdLoaded)
}
}
override fun failedToReceiveAd(errorCode: Int) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::failedToReceiveAd.name}: code $errorCode")
_bridge.callCpp(kOnRewardedAdFailedToLoad, ErrorResponse(errorCode, "").serialize())
}
}
override fun userDeclinedToViewAd(ad: AppLovinAd) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::userDeclinedToViewAd.name}")
}
}
override fun adDisplayed(ad: AppLovinAd) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::adDisplayed.name}")
_rewarded = false
}
}
override fun videoPlaybackBegan(ad: AppLovinAd) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::videoPlaybackBegan.name}")
}
}
override fun adClicked(ad: AppLovinAd) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::adClicked.name}")
_bridge.callCpp(kOnRewardedAdClicked)
}
}
override fun videoPlaybackEnded(ad: AppLovinAd, percentViewed: Double, fullyWatched: Boolean) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::videoPlaybackEnded.name}")
}
}
override fun userRewardVerified(ad: AppLovinAd, response: Map<String, String>) {
Thread.runOnMainThread {
_logger.info("$kTag: ${this::userRewardVerified.name}: $response")
_rewarded = true
}
}
override fun userRewardRejected(ad: AppLovinAd, response: Map<String, String>) {
Thread.runOnMainThread {
_logger.info("$kTag: ${this::userRewardRejected.name}: $response")
}
}
override fun userOverQuota(ad: AppLovinAd, response: Map<String, String>) {
Thread.runOnMainThread {
_logger.info("$kTag: ${this::userOverQuota.name}: $response")
}
}
override fun validationRequestFailed(ad: AppLovinAd, responseCode: Int) {
Thread.runOnMainThread {
_logger.info("$kTag: ${this::validationRequestFailed.name}: code = $responseCode")
}
}
override fun adHidden(ad: AppLovinAd) {
Thread.runOnMainThread {
_logger.info("$kTag: ${this::adHidden.name}")
_isLoaded.set(false)
_bridge.callCpp(kOnRewardedAdClosed, Utils.toString(_rewarded))
}
}
} | mit | 7c654b0d5d36e6d8c53171a634bcbd80 | 33.264463 | 141 | 0.664415 | 4.646861 | false | false | false | false |
noud02/Akatsuki | src/main/kotlin/moe/kyubey/akatsuki/commands/Unrestrict.kt | 1 | 4529 | /*
* Copyright (c) 2017-2019 Yui
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package moe.kyubey.akatsuki.commands
import me.aurieh.ares.exposed.async.asyncTransaction
import moe.kyubey.akatsuki.Akatsuki
import moe.kyubey.akatsuki.EventListener
import moe.kyubey.akatsuki.annotations.Argument
import moe.kyubey.akatsuki.annotations.Arguments
import moe.kyubey.akatsuki.annotations.Load
import moe.kyubey.akatsuki.annotations.Perm
import moe.kyubey.akatsuki.db.schema.Restrictions
import moe.kyubey.akatsuki.entities.Command
import moe.kyubey.akatsuki.entities.Context
import moe.kyubey.akatsuki.utils.I18n
import net.dv8tion.jda.core.Permission
import net.dv8tion.jda.core.entities.Member
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.deleteWhere
@Arguments(
Argument("command", "string"),
Argument("user", "user"),
Argument("reason", "string", true)
)
class UnrestrictGlobally : Command() {
override val desc = "Unrestrict usage of commands globally."
override val ownerOnly = true
override val guildOnly = true
override fun run(ctx: Context) {
val cmd = ctx.args["command"] as String
val mem = ctx.args["user"] as Member
if (cmd !in EventListener.cmdHandler.commands && cmd != "all") {
return ctx.send(
I18n.parse(
ctx.lang.getString("command_not_found"),
mapOf("username" to ctx.author.name)
)
)
}
asyncTransaction(Akatsuki.pool) {
Restrictions.deleteWhere {
Restrictions.global.eq(true) and Restrictions.userId.eq(mem.user.idLong) and Restrictions.command.eq(cmd)
}
ctx.send("Unrestricted global usage of command $cmd for user ${mem.user.name}#${mem.user.discriminator}!") // TODO translation
}.execute()
}
}
@Load
@Perm(Permission.MANAGE_SERVER)
@Arguments(
Argument("command", "string"),
Argument("user", "user", true)
)
class Unrestrict : Command() {
override val desc = "Unrestrict usage of commands."
override val guildOnly = true
init {
addSubcommand(UnrestrictGlobally(), "global")
}
override fun run(ctx: Context) {
val cmd = ctx.args["command"] as String
if (cmd !in EventListener.cmdHandler.commands && cmd != "all") {
return ctx.send(
I18n.parse(
ctx.lang.getString("command_not_found"),
mapOf("username" to ctx.author.name)
)
)
}
asyncTransaction(Akatsuki.pool) {
if ("user" in ctx.args) {
val mem = ctx.args["user"] as Member
Restrictions.deleteWhere {
Restrictions.guildId.eq(ctx.guild!!.idLong) and Restrictions.command.eq(cmd) and Restrictions.userId.eq(mem.user.idLong)
}
ctx.send("Unrestricted usage of command $cmd for user ${mem.user.name}#${mem.user.discriminator}!") // TODO translation
} else {
Restrictions.deleteWhere {
Restrictions.guildId.eq(ctx.guild!!.idLong) and Restrictions.command.eq(cmd) and Restrictions.everyone.eq(true)
}
ctx.send("Unrestricted usage of command $cmd!") // TODO translation
}
}.execute()
}
} | mit | 0d73195d67a6e1ba21ce8ae5fdc8168e | 36.438017 | 140 | 0.644734 | 4.342282 | false | false | false | false |
jorjoluiso/QuijoteLui | src/main/kotlin/com/quijotelui/service/ReporteFacturaServiceImpl.kt | 1 | 1602 | package com.quijotelui.service
import com.quijotelui.electronico.util.Fechas
import com.quijotelui.model.ReporteFactura
import com.quijotelui.repository.IReporteFacturaDao
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
@Service
class ReporteFacturaServiceImpl : IReporteFacturaService {
@Autowired
lateinit var reporteFacturaDao : IReporteFacturaDao
override fun findByFechas(fechaInicio: String, fechaFin: String): MutableList<ReporteFactura> {
val fechas = Fechas()
val fechaInDateTypeInicio = fechas.toDate(fechaInicio)
val fechaInDateTypeFin = fechas.toDate(fechaFin)
return reporteFacturaDao.findByFechas(fechaInDateTypeInicio, fechaInDateTypeFin)
}
/*
*
*El estado es:
* - Todos
* - NoAutorizados
* - Autorizados
*/
override fun findByFechasEstado(fechaInicio: String, fechaFin: String, estado: String): MutableList<ReporteFactura> {
val fechas = Fechas()
val fechaInDateTypeInicio = fechas.toDate(fechaInicio)
val fechaInDateTypeFin = fechas.toDate(fechaFin)
if (estado.equals("Autorizados")) {
return reporteFacturaDao.findByFechasAutorizado(fechaInDateTypeInicio, fechaInDateTypeFin)
}
else if (estado.equals("NoAutorizados")) {
return reporteFacturaDao.findByFechasNoAutorizado(fechaInDateTypeInicio, fechaInDateTypeFin)
}
else {
return reporteFacturaDao.findByFechas(fechaInDateTypeInicio, fechaInDateTypeFin)
}
}
} | gpl-3.0 | 8b27eee60e62666a36ef91edb0306c03 | 31.714286 | 121 | 0.724719 | 5.00625 | false | false | false | false |
kiruto/debug-bottle | components/src/main/kotlin/com/exyui/android/debugbottle/components/floating/Floating3DService.kt | 1 | 1336 | //package com.exyui.android.debugbottle.components.floating
//
//import android.content.Intent
//import android.os.Binder
//import android.os.IBinder
//import com.exyui.android.debugbottle.components.RunningFeatureMgr
//
///**
// * Created by yuriel on 9/1/16.
// *
// * 3D View floating window management service
// */
//@Suppress("DEPRECATION")
//@Deprecated(
// message = "Use __BubblesManagerService instead",
// replaceWith = ReplaceWith("__BubblesManagerService", "com.exyui.android.debugbottle.components.bubbles.services.__BubblesManagerService"),
// level = DeprecationLevel.WARNING
//)
//internal class Floating3DService : DTBaseFloatingService() {
//
// override val floatingViewMgr: DTDragFloatingViewMgr = Floating3DViewMgr
// private var binder: Binder? = null
//
// override fun onBind(intent: Intent?): IBinder? {
// return binder
// }
//
// override fun createView() {
// super.createView()
// RunningFeatureMgr.add(RunningFeatureMgr.VIEW_3D_WINDOW)
// }
//
// override fun onDestroy() {
// super.onDestroy()
// RunningFeatureMgr.remove(RunningFeatureMgr.VIEW_3D_WINDOW)
// }
//
// inner class FloatingBinder: Binder() {
// fun getService(): Floating3DService {
// return this@Floating3DService
// }
// }
//} | apache-2.0 | 0617f17d33ea8353291d35e9223ac599 | 30.093023 | 148 | 0.669162 | 3.895044 | false | false | false | false |
DemonWav/StatCraft | src/main/kotlin/com/demonwav/statcraft/commands/sc/SCXpGained.kt | 1 | 1952 | /*
* StatCraft Bukkit Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.commands.sc
import com.demonwav.statcraft.StatCraft
import com.demonwav.statcraft.commands.ResponseBuilder
import com.demonwav.statcraft.querydsl.QPlayers
import com.demonwav.statcraft.querydsl.QXpGained
import org.bukkit.command.CommandSender
import java.sql.Connection
class SCXpGained(plugin: StatCraft) : SCTemplate(plugin) {
init {
plugin.baseCommand.registerCommand("xpgained", this)
}
override fun hasPermission(sender: CommandSender, args: Array<out String>?) = sender.hasPermission("statcraft.user.xpgained")
override fun playerStatResponse(name: String, args: List<String>, connection: Connection): String {
val id = getId(name) ?: return ResponseBuilder.build(plugin) {
playerName { name }
statName { "Xp Gained" }
stats["Total"] = "0"
}
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val x = QXpGained.xpGained
val result = query.from(x).where(x.id.eq(id)).uniqueResult(x.amount.sum()) ?: 0
return ResponseBuilder.build(plugin) {
playerName { name }
statName { "Xp Gained" }
stats["Total"] = df.format(result)
}
}
override fun serverStatListResponse(num: Long, args: List<String>, connection: Connection): String {
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val x = QXpGained.xpGained
val p = QPlayers.players
val list = query
.from(x)
.innerJoin(p)
.on(x.id.eq(p.id))
.groupBy(p.name)
.orderBy(x.amount.sum().desc())
.limit(num)
.list(p.name, x.amount.sum())
return topListResponse("Xp Gained", list)
}
}
| mit | 4c9cfe88c45c81c371ed0f070fd31907 | 29.984127 | 129 | 0.642418 | 4.075157 | false | false | false | false |
bastman/kotlin-spring-jpa-examples | src/main/kotlin/com/example/demo/api/realestate/domain/jpa/services/JpaBrokerService.kt | 1 | 2307 | package com.example.demo.api.realestate.domain.jpa.services
import com.example.demo.api.common.EntityAlreadyExistException
import com.example.demo.api.common.EntityNotFoundException
import com.example.demo.api.realestate.domain.jpa.entities.Broker
import com.example.demo.api.realestate.domain.jpa.entities.QueryDslEntity.qBroker
import com.example.demo.api.realestate.domain.jpa.repositories.BrokerRepository
import com.example.demo.util.fp.pipe
import com.example.demo.util.optionals.toNullable
import com.querydsl.jpa.impl.JPAQuery
import org.springframework.stereotype.Component
import java.util.*
import javax.persistence.EntityManager
import javax.validation.Valid
@Component
class JpaBrokerService(
private val brokerRepository: BrokerRepository,
private val entityManager: EntityManager
) {
fun exists(brokerId: UUID): Boolean = brokerRepository.exists(brokerId)
fun findById(brokerId: UUID): Broker? =
brokerRepository
.getById(brokerId)
.toNullable()
fun getById(brokerId: UUID): Broker =
findById(brokerId) ?: throw EntityNotFoundException(
"ENTITY NOT FOUND! query: Broker.id=$brokerId"
)
fun requireExists(brokerId: UUID): UUID =
if (exists(brokerId)) {
brokerId
} else throw EntityNotFoundException(
"ENTITY NOT FOUND! query: Broker.id=$brokerId"
)
fun requireDoesNotExist(brokerId: UUID): UUID =
if (!exists(brokerId)) {
brokerId
} else throw EntityAlreadyExistException(
"ENTITY ALREADY EXIST! query: Broker.id=$brokerId"
)
fun insert(@Valid broker: Broker): Broker =
requireDoesNotExist(broker.id) pipe { brokerRepository.save(broker) }
fun update(@Valid broker: Broker): Broker =
requireExists(broker.id) pipe { brokerRepository.save(broker) }
fun findByIdList(brokerIdList: List<UUID>): List<Broker> {
val query = JPAQuery<Broker>(entityManager)
val resultSet = query.from(qBroker)
.where(
qBroker.id.`in`(brokerIdList)
)
.fetchResults()
return resultSet.results
}
} | mit | 55bf332b3078eff77b15a56b27845c05 | 35.634921 | 81 | 0.660598 | 4.708163 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/dashboard/mine/adapter/IssueListAdapter.kt | 1 | 2063 | package com.intfocus.template.dashboard.mine.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.View.INVISIBLE
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.intfocus.template.R
import com.intfocus.template.dashboard.mine.bean.IssueListDataBean
/**
* Created by liuruilin on 2017/6/12.
*/
class IssueListAdapter(val context: Context,
private var issueListDatas: List<IssueListDataBean>?,
var listener: IssueItemListener) : RecyclerView.Adapter<IssueListAdapter.IssueListHolder>() {
var inflater = LayoutInflater.from(context)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): IssueListHolder {
val contentView = inflater.inflate(R.layout.item_issue_list, parent, false)
return IssueListHolder(contentView)
}
override fun onBindViewHolder(holder: IssueListHolder, position: Int) {
holder.llIssueListItem.setOnClickListener { listener.itemClick(position) }
holder.tvIssueTitle.text = issueListDatas!![position].content
holder.tvIssueTime.text = issueListDatas!![position].time
if (issueListDatas!![position].status == 0) {
holder.ivIssuePoint.visibility = INVISIBLE
}
}
override fun getItemCount(): Int {
return if (issueListDatas == null) 0 else issueListDatas!!.size
}
class IssueListHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var llIssueListItem = itemView.findViewById<LinearLayout>(R.id.ll_issue_list_item)
var ivIssuePoint = itemView.findViewById<ImageView>(R.id.iv_issue_item_point)
var tvIssueTitle = itemView.findViewById<TextView>(R.id.tv_issue_item_title)
var tvIssueTime = itemView.findViewById<TextView>(R.id.tv_issue_item_time)
}
interface IssueItemListener {
fun itemClick(position: Int)
}
}
| gpl-3.0 | 5ad499405eddd61e2288fe48087ba663 | 37.924528 | 116 | 0.730005 | 4.389362 | false | false | false | false |
firebase/snippets-android | analytics/app/src/main/java/com/google/firebase/example/analytics/kotlin/MainActivity.kt | 1 | 12575 | package com.google.firebase.example.analytics.kotlin
import android.os.Bundle
import android.os.Parcelable
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.analytics.ktx.logEvent
import com.google.firebase.example.analytics.R
import com.google.firebase.ktx.Firebase
// importing libraries to support 3rd party ad_impression snippets
import com.ironsource.mediationsdk.impressionData.ImpressionDataListener
import com.ironsource.mediationsdk.impressionData.ImpressionData
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxAdRevenueListener
class MainActivity : AppCompatActivity(),
// importing libraries to support 3rd party ad_impression snippets
MaxAdRevenueListener, ImpressionDataListener {
// [START declare_analytics]
private lateinit var firebaseAnalytics: FirebaseAnalytics
// [END declare_analytics]
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// [START shared_app_measurement]
// Obtain the FirebaseAnalytics instance.
firebaseAnalytics = Firebase.analytics
// [END shared_app_measurement]
enhancedEcommerce()
setUserFavoriteFood("pizza")
recordImageView()
recordScreenView()
logCustomEvent()
}
fun enhancedEcommerce() {
// [START create_items]
val itemJeggings = Bundle().apply {
putString(FirebaseAnalytics.Param.ITEM_ID, "SKU_123")
putString(FirebaseAnalytics.Param.ITEM_NAME, "jeggings")
putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "pants")
putString(FirebaseAnalytics.Param.ITEM_VARIANT, "black")
putString(FirebaseAnalytics.Param.ITEM_BRAND, "Google")
putDouble(FirebaseAnalytics.Param.PRICE, 9.99)
}
val itemBoots = Bundle().apply {
putString(FirebaseAnalytics.Param.ITEM_ID, "SKU_456")
putString(FirebaseAnalytics.Param.ITEM_NAME, "boots")
putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "shoes")
putString(FirebaseAnalytics.Param.ITEM_VARIANT, "brown")
putString(FirebaseAnalytics.Param.ITEM_BRAND, "Google")
putDouble(FirebaseAnalytics.Param.PRICE, 24.99)
}
val itemSocks = Bundle().apply {
putString(FirebaseAnalytics.Param.ITEM_ID, "SKU_789")
putString(FirebaseAnalytics.Param.ITEM_NAME, "ankle_socks")
putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "socks")
putString(FirebaseAnalytics.Param.ITEM_VARIANT, "red")
putString(FirebaseAnalytics.Param.ITEM_BRAND, "Google")
putDouble(FirebaseAnalytics.Param.PRICE, 5.99)
}
// [END create_items]
// [START view_item_list]
val itemJeggingsWithIndex = Bundle(itemJeggings).apply {
putLong(FirebaseAnalytics.Param.INDEX, 1)
}
val itemBootsWithIndex = Bundle(itemBoots).apply {
putLong(FirebaseAnalytics.Param.INDEX, 2)
}
val itemSocksWithIndex = Bundle(itemSocks).apply {
putLong(FirebaseAnalytics.Param.INDEX, 3)
}
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM_LIST) {
param(FirebaseAnalytics.Param.ITEM_LIST_ID, "L001")
param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "Related products")
param(FirebaseAnalytics.Param.ITEMS,
arrayOf(itemJeggingsWithIndex, itemBootsWithIndex, itemSocksWithIndex))
}
// [END view_item_list]
// [START select_item]
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM) {
param(FirebaseAnalytics.Param.ITEM_LIST_ID, "L001")
param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "Related products")
param(FirebaseAnalytics.Param.ITEMS, arrayOf(itemJeggings))
}
// [END select_item]
// [START view_product_details]
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM) {
param(FirebaseAnalytics.Param.CURRENCY, "USD")
param(FirebaseAnalytics.Param.VALUE, 9.99)
param(FirebaseAnalytics.Param.ITEMS, arrayOf(itemJeggings))
}
// [END view_product_details]
// [START add_to_cart_wishlist]
val itemJeggingsWishlist = Bundle(itemJeggings).apply {
putLong(FirebaseAnalytics.Param.QUANTITY, 2)
}
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.ADD_TO_WISHLIST) {
param(FirebaseAnalytics.Param.CURRENCY, "USD")
param(FirebaseAnalytics.Param.VALUE, 2 * 9.99)
param(FirebaseAnalytics.Param.ITEMS, arrayOf(itemJeggingsWishlist))
}
// [END add_to_cart_wishlist]
// [START view_cart]
val itemJeggingsCart = Bundle(itemJeggings).apply {
putLong(FirebaseAnalytics.Param.QUANTITY, 2)
}
val itemBootsCart = Bundle(itemBoots).apply {
putLong(FirebaseAnalytics.Param.QUANTITY, 1)
}
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_CART) {
param(FirebaseAnalytics.Param.CURRENCY, "USD")
param(FirebaseAnalytics.Param.VALUE, 2 * 9.99 + 1 * 24.99)
param(FirebaseAnalytics.Param.ITEMS, arrayOf(itemJeggingsCart, itemBootsCart))
}
// [END view_cart]
// [START remove_from_cart]
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.REMOVE_FROM_CART) {
param(FirebaseAnalytics.Param.CURRENCY, "USD")
param(FirebaseAnalytics.Param.VALUE, 1 * 24.99)
param(FirebaseAnalytics.Param.ITEMS, arrayOf(itemBootsCart))
}
// [END remove_from_cart]
// [START start_checkout]
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.BEGIN_CHECKOUT) {
param(FirebaseAnalytics.Param.CURRENCY, "USD")
param(FirebaseAnalytics.Param.VALUE, 14.98)
param(FirebaseAnalytics.Param.COUPON, "SUMMER_FUN")
param(FirebaseAnalytics.Param.ITEMS, arrayOf(itemJeggingsCart))
}
// [END start_checkout]
// [START add_shipping]
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.ADD_SHIPPING_INFO) {
param(FirebaseAnalytics.Param.CURRENCY, "USD")
param(FirebaseAnalytics.Param.VALUE, 14.98)
param(FirebaseAnalytics.Param.COUPON, "SUMMER_FUN")
param(FirebaseAnalytics.Param.SHIPPING_TIER, "Ground")
param(FirebaseAnalytics.Param.ITEMS, arrayOf(itemJeggingsCart))
}
// [END add_shipping]
// [START add_payment]
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.ADD_PAYMENT_INFO) {
param(FirebaseAnalytics.Param.CURRENCY, "USD")
param(FirebaseAnalytics.Param.VALUE, 14.98)
param(FirebaseAnalytics.Param.COUPON, "SUMMER_FUN")
param(FirebaseAnalytics.Param.PAYMENT_TYPE, "Visa")
param(FirebaseAnalytics.Param.ITEMS, arrayOf(itemJeggingsCart))
}
// [END add_payment]
// [START log_purchase]
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.PURCHASE) {
param(FirebaseAnalytics.Param.TRANSACTION_ID, "T12345")
param(FirebaseAnalytics.Param.AFFILIATION, "Google Store")
param(FirebaseAnalytics.Param.CURRENCY, "USD")
param(FirebaseAnalytics.Param.VALUE, 14.98)
param(FirebaseAnalytics.Param.TAX, 2.58)
param(FirebaseAnalytics.Param.SHIPPING, 5.34)
param(FirebaseAnalytics.Param.COUPON, "SUMMER_FUN")
param(FirebaseAnalytics.Param.ITEMS, arrayOf(itemJeggingsCart))
}
// [END log_purchase]
// [START log_refund]
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.REFUND) {
param(FirebaseAnalytics.Param.TRANSACTION_ID, "T12345")
param(FirebaseAnalytics.Param.AFFILIATION, "Google Store")
param(FirebaseAnalytics.Param.CURRENCY, "USD")
param(FirebaseAnalytics.Param.VALUE, 9.99)
// (Optional) for partial refunds, define the item ID and quantity of refunded items
param(FirebaseAnalytics.Param.ITEM_ID, "SKU_123")
param(FirebaseAnalytics.Param.QUANTITY, 1)
param(FirebaseAnalytics.Param.ITEMS, arrayOf(itemJeggings))
}
// [END log_refund]
// [START apply_promo]
val promoParams = Bundle().apply {
putString(FirebaseAnalytics.Param.PROMOTION_ID, "SUMMER_FUN")
putString(FirebaseAnalytics.Param.PROMOTION_NAME, "Summer Sale")
putString(FirebaseAnalytics.Param.CREATIVE_NAME, "summer2020_promo.jpg")
putString(FirebaseAnalytics.Param.CREATIVE_SLOT, "featured_app_1")
putString(FirebaseAnalytics.Param.LOCATION_ID, "HERO_BANNER")
putParcelableArray(FirebaseAnalytics.Param.ITEMS, arrayOf<Parcelable>(itemJeggings))
}
// Promotion displayed
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_PROMOTION, promoParams)
// Promotion selected
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_PROMOTION, promoParams)
// [END apply_promo]
}
private fun setUserFavoriteFood(food: String) {
// [START user_property]
firebaseAnalytics.setUserProperty("favorite_food", food)
// [END user_property]
}
private fun recordImageView() {
val id = "imageId"
val name = "imageTitle"
// [START image_view_event]
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM) {
param(FirebaseAnalytics.Param.ITEM_ID, id)
param(FirebaseAnalytics.Param.ITEM_NAME, name)
param(FirebaseAnalytics.Param.CONTENT_TYPE, "image")
}
// [END image_view_event]
}
private fun recordScreenView() {
val screenName = "Home Page"
// [START set_current_screen]
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW) {
param(FirebaseAnalytics.Param.SCREEN_NAME, screenName)
param(FirebaseAnalytics.Param.SCREEN_CLASS, "MainActivity")
}
// [END set_current_screen]
}
private fun logCustomEvent() {
val name = "customImage"
val text = "I'd love to hear more about $name"
// [START custom_event]
firebaseAnalytics.logEvent("share_image") {
param("image_name", name)
param("full_text", text)
}
// [END custom_event]
}
// [START ad_impression_applovin]
override fun onAdRevenuePaid(impressionData: MaxAd?) {
impressionData?.let {
firebaseAnalytics = Firebase.analytics
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.AD_IMPRESSION) {
param(FirebaseAnalytics.Param.AD_PLATFORM, "appLovin")
param(FirebaseAnalytics.Param.AD_UNIT_NAME, impressionData.adUnitId)
param(FirebaseAnalytics.Param.AD_FORMAT, impressionData.format.displayName)
param(FirebaseAnalytics.Param.AD_SOURCE, impressionData.networkName)
param(FirebaseAnalytics.Param.VALUE, impressionData.revenue)
param(FirebaseAnalytics.Param.CURRENCY, "USD") // All Applovin revenue is sent in USD
}
}
}
// [END ad_impression_applovin]
// [START ad_impression_ironsource]
override fun onImpressionSuccess(impressionData: ImpressionData) {
// The onImpressionSuccess will be reported when the rewarded video and interstitial ad is
// opened.
// For banners, the impression is reported on load success. Log.d(TAG, "onImpressionSuccess" +
// impressionData);
firebaseAnalytics = Firebase.analytics
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.AD_IMPRESSION) {
param(FirebaseAnalytics.Param.AD_PLATFORM, "ironSource")
param(FirebaseAnalytics.Param.AD_SOURCE, impressionData.adNetwork)
param(FirebaseAnalytics.Param.AD_FORMAT, impressionData.adUnit)
param(FirebaseAnalytics.Param.AD_UNIT_NAME, impressionData.instanceName)
param(FirebaseAnalytics.Param.CURRENCY, "USD")
param(FirebaseAnalytics.Param.VALUE, impressionData.revenue)
}
}
// [END ad_impression_ironsource]
} | apache-2.0 | 189b8e2186162c4c0a2c2e7f7ae97a0d | 41.343434 | 102 | 0.660596 | 4.686918 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/user/Items.kt | 1 | 2681 | package com.habitrpg.android.habitica.models.user
import com.habitrpg.android.habitica.models.BaseObject
import com.habitrpg.shared.habitica.models.AvatarItems
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.RealmClass
import java.util.Date
@RealmClass(embedded = true)
open class Items : RealmObject, BaseObject, AvatarItems {
fun setItemTypes() {
hatchingPotions?.forEach { it.itemType = "hatchingPotions" }
eggs?.forEach { it.itemType = "eggs" }
food?.forEach { it.itemType = "food" }
quests?.forEach { it.itemType = "quests" }
special?.forEach { it.itemType = "special" }
}
var eggs: RealmList<OwnedItem>? = null
set(value) {
field = value
field?.forEach { it.itemType = "eggs" }
}
var food: RealmList<OwnedItem>? = null
set(value) {
field = value
field?.forEach { it.itemType = "food" }
}
var hatchingPotions: RealmList<OwnedItem>? = null
set(value) {
field = value
field?.forEach { it.itemType = "hatchingPotions" }
}
var quests: RealmList<OwnedItem>? = null
set(value) {
field = value
field?.forEach { it.itemType = "quests" }
}
var special: RealmList<OwnedItem>? = null
set(value) {
field = value
field?.forEach { it.itemType = "special" }
}
var pets: RealmList<OwnedPet>? = null
var mounts: RealmList<OwnedMount>? = null
override var currentMount: String? = null
override var currentPet: String? = null
var lastDropCount: Int = 0
var lastDropDate: Date? = null
// private QuestContent quest;
override var gear: Gear? = null
constructor(currentMount: String, currentPet: String, lastDropCount: Int, lastDropDate: Date) {
this.currentMount = currentMount
this.currentPet = currentPet
this.lastDropCount = lastDropCount
this.lastDropDate = lastDropDate
}
constructor()
val hasTransformationItems: Boolean
get() {
return special?.any { transformationItem ->
transformationItem.key == ("seafoam") && transformationItem.numberOwned > 0 ||
transformationItem.key == ("shinySeed") && transformationItem.numberOwned > 0 ||
transformationItem.key == ("snowball") && transformationItem.numberOwned > 0 ||
transformationItem.key == ("spookySparkles") && transformationItem.numberOwned > 0
} ?: false
}
}
| gpl-3.0 | 9cbf7e8425a4787105346def9a853289 | 34.22973 | 102 | 0.597538 | 4.670732 | false | false | false | false |
wix/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/options/AnimationOptions.kt | 1 | 5582 | package com.reactnativenavigation.options
import android.animation.Animator
import android.animation.AnimatorSet
import android.util.Property
import android.util.TypedValue.COMPLEX_UNIT_DIP
import android.util.TypedValue.COMPLEX_UNIT_FRACTION
import android.view.View
import android.view.View.*
import com.reactnativenavigation.options.params.Bool
import com.reactnativenavigation.options.params.NullBool
import com.reactnativenavigation.options.params.NullText
import com.reactnativenavigation.options.params.Text
import com.reactnativenavigation.options.parsers.BoolParser
import com.reactnativenavigation.options.parsers.TextParser
import com.reactnativenavigation.utils.CollectionUtils
import com.reactnativenavigation.utils.CollectionUtils.first
import org.json.JSONObject
import java.util.*
import kotlin.math.max
open class AnimationOptions @JvmOverloads constructor(json: JSONObject? = null) : LayoutAnimation {
@JvmField var id: Text = NullText()
@JvmField var enabled: Bool = NullBool()
@JvmField var waitForRender: Bool = NullBool()
override var sharedElements = SharedElements()
override var elementTransitions = ElementTransitions()
private var valueOptions = HashSet<ValueAnimationOptions>()
init {
parse(json)
}
private fun parse(json: JSONObject?) {
json ?: return
val iter = json.keys()
while (iter.hasNext()) {
when (val key = iter.next()) {
"id" -> id = TextParser.parse(json, key)
"enable", "enabled" -> enabled = BoolParser.parse(json, key)
"waitForRender" -> waitForRender = BoolParser.parse(json, key)
"sharedElementTransitions" -> sharedElements = SharedElements.parse(json)
"elementTransitions" -> elementTransitions = ElementTransitions.parse(json)
else -> valueOptions.add(ValueAnimationOptions.parse(json.optJSONObject(key), getAnimProp(key)))
}
}
}
fun mergeWith(other: AnimationOptions) {
if (other.id.hasValue()) id = other.id
if (other.enabled.hasValue()) enabled = other.enabled
if (other.waitForRender.hasValue()) waitForRender = other.waitForRender
if (other.valueOptions.isNotEmpty()) valueOptions = other.valueOptions
if (other.sharedElements.hasValue()) sharedElements = other.sharedElements
if (other.elementTransitions.hasValue()) elementTransitions = other.elementTransitions
}
fun mergeWithDefault(defaultOptions: AnimationOptions) {
if (!id.hasValue()) id = defaultOptions.id
if (!enabled.hasValue()) enabled = defaultOptions.enabled
if (!waitForRender.hasValue()) waitForRender = defaultOptions.waitForRender
if (valueOptions.isEmpty()) valueOptions = defaultOptions.valueOptions
if (!sharedElements.hasValue()) sharedElements = defaultOptions.sharedElements
if (!elementTransitions.hasValue()) elementTransitions = defaultOptions.elementTransitions
}
fun hasValue() = id.hasValue()
|| enabled.hasValue()
|| waitForRender.hasValue()
|| sharedElements.hasValue()
|| elementTransitions.hasValue()
|| valueOptions.isNotEmpty()
fun getAnimation(view: View) = getAnimation(view, AnimatorSet())
fun getAnimation(view: View, defaultAnimation: Animator): Animator {
if (!hasAnimation()) return defaultAnimation
return AnimatorSet().apply { playTogether(valueOptions.map { it.getAnimation(view) }) }
}
fun shouldWaitForRender() = Bool(waitForRender.isTrue or hasElementTransitions())
fun hasElementTransitions() = sharedElements.hasValue() or elementTransitions.hasValue()
val duration: Int
get() = CollectionUtils.reduce(valueOptions, 0, { item: ValueAnimationOptions, currentValue: Int -> max(item.duration[currentValue], currentValue) })
open fun hasAnimation(): Boolean = valueOptions.isNotEmpty()
fun isFadeAnimation(): Boolean = valueOptions.size == 1 && valueOptions.find(ValueAnimationOptions::isAlpha) != null
fun setValueDy(animation: Property<View?, Float?>?, fromDelta: Float, toDelta: Float) {
first(valueOptions, { o: ValueAnimationOptions -> o.equals(animation) }) { param: ValueAnimationOptions ->
param.setFromDelta(fromDelta)
param.setToDelta(toDelta)
}
}
companion object {
private fun getAnimProp(key: String): Triple<Property<View, Float>, Int, (View) -> Float> {
when (key) {
"x" -> return Triple(X, COMPLEX_UNIT_DIP, View::getX)
"y" -> return Triple(Y, COMPLEX_UNIT_DIP, View::getY)
"translationX" -> return Triple(TRANSLATION_X, COMPLEX_UNIT_DIP, View::getTranslationX)
"translationY" -> return Triple(TRANSLATION_Y, COMPLEX_UNIT_DIP, View::getTranslationY)
"alpha" -> return Triple(ALPHA, COMPLEX_UNIT_FRACTION, View::getAlpha)
"scaleX" -> return Triple(SCALE_X, COMPLEX_UNIT_FRACTION, View::getScaleX)
"scaleY" -> return Triple(SCALE_Y, COMPLEX_UNIT_FRACTION, View::getScaleY)
"rotationX" -> return Triple(ROTATION_X, COMPLEX_UNIT_FRACTION, View::getRotationX)
"rotationY" -> return Triple(ROTATION_Y, COMPLEX_UNIT_FRACTION, View::getRotationY)
"rotation" -> return Triple(ROTATION, COMPLEX_UNIT_FRACTION, View::getRotation)
}
throw IllegalArgumentException("This animation is not supported: $key")
}
}
} | mit | a1e8c38aa0b48fc131c0d2fe463ab393 | 46.717949 | 157 | 0.688463 | 4.8922 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/localized_name/data/RoadNameSuggestionsDao.kt | 1 | 4032 | package de.westnordost.streetcomplete.quests.localized_name.data
import android.database.sqlite.SQLiteOpenHelper
import java.util.ArrayList
import java.util.HashMap
import javax.inject.Inject
import de.westnordost.osmapi.map.data.LatLon
import de.westnordost.streetcomplete.quests.localized_name.data.RoadNamesTable.Columns.GEOMETRY
import de.westnordost.streetcomplete.quests.localized_name.data.RoadNamesTable.Columns.MAX_LATITUDE
import de.westnordost.streetcomplete.quests.localized_name.data.RoadNamesTable.Columns.MAX_LONGITUDE
import de.westnordost.streetcomplete.quests.localized_name.data.RoadNamesTable.Columns.MIN_LATITUDE
import de.westnordost.streetcomplete.quests.localized_name.data.RoadNamesTable.Columns.MIN_LONGITUDE
import de.westnordost.streetcomplete.quests.localized_name.data.RoadNamesTable.Columns.NAMES
import de.westnordost.streetcomplete.quests.localized_name.data.RoadNamesTable.Columns.WAY_ID
import de.westnordost.streetcomplete.quests.localized_name.data.RoadNamesTable.NAME
import de.westnordost.streetcomplete.util.Serializer
import de.westnordost.streetcomplete.util.SphericalEarthMath
import de.westnordost.streetcomplete.ktx.toObject
import de.westnordost.streetcomplete.ktx.transaction
// TODO only open in order to be able to mock it in tests
open class RoadNameSuggestionsDao @Inject constructor(
private val dbHelper: SQLiteOpenHelper,
private val serializer: Serializer
) {
private val insert = dbHelper.writableDatabase.compileStatement(
"INSERT OR REPLACE INTO $NAME " +
"($WAY_ID,$NAMES,$GEOMETRY,$MIN_LATITUDE,$MIN_LONGITUDE,$MAX_LATITUDE,$MAX_LONGITUDE) " +
"values (?,?,?,?,?,?,?);"
)
fun putRoad(wayId: Long, namesByLanguage: Map<String, String>, geometry: List<LatLon>) {
val bbox = SphericalEarthMath.enclosingBoundingBox(geometry)
dbHelper.writableDatabase.transaction {
insert.bindLong(1, wayId)
insert.bindBlob(2, serializer.toBytes(HashMap(namesByLanguage)))
insert.bindBlob(3, serializer.toBytes(ArrayList(geometry)))
insert.bindDouble(4, bbox.minLatitude)
insert.bindDouble(5, bbox.minLongitude)
insert.bindDouble(6, bbox.maxLatitude)
insert.bindDouble(7, bbox.maxLongitude)
insert.executeInsert()
insert.clearBindings()
}
}
/** returns something like [{"": "17th Street", "de": "17. Straße", "en": "17th Street" }, ...] */
fun getNames(points: List<LatLon>, maxDistance: Double): List<MutableMap<String, String>> {
// preselection via intersection check of bounding boxes
val query = Array(points.size) {
"$MIN_LATITUDE <= ? AND $MIN_LONGITUDE <= ? AND " +
"$MAX_LATITUDE >= ? AND $MAX_LONGITUDE >= ? "
}.joinToString(" OR ")
val args = arrayOfNulls<String>(points.size * 4)
for (i in points.indices) {
val point = points[i]
val bbox = SphericalEarthMath.enclosingBoundingBox(point, maxDistance)
val ai = i * 4
args[ai + 0] = "" + bbox.maxLatitude
args[ai + 1] = "" + bbox.maxLongitude
args[ai + 2] = "" + bbox.minLatitude
args[ai + 3] = "" + bbox.minLongitude
}
val cols = arrayOf(GEOMETRY, NAMES)
val result = mutableListOf<MutableMap<String, String>>()
dbHelper.readableDatabase.query(NAME, cols, query, args, null, null, null).use { cursor ->
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast) {
val geometry: ArrayList<LatLon> = serializer.toObject(cursor.getBlob(0))
if (SphericalEarthMath.isWithinDistance(maxDistance, points, geometry)) {
val map: HashMap<String,String> = serializer.toObject(cursor.getBlob(1))
result.add(map)
}
cursor.moveToNext()
}
}
}
return result
}
}
| gpl-3.0 | ecccbe93f1f4a31b6371084c5b84e772 | 43.296703 | 102 | 0.671794 | 4.405464 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/data/implementation/UserRepositoryImpl.kt | 1 | 19694 | package com.habitrpg.android.habitica.data.implementation
import com.habitrpg.android.habitica.data.ApiClient
import com.habitrpg.android.habitica.data.TaskRepository
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.data.local.UserLocalRepository
import com.habitrpg.android.habitica.extensions.filterMapEmpty
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.models.Achievement
import com.habitrpg.android.habitica.models.QuestAchievement
import com.habitrpg.android.habitica.models.Skill
import com.habitrpg.android.habitica.models.TeamPlan
import com.habitrpg.android.habitica.models.inventory.Customization
import com.habitrpg.android.habitica.models.responses.SkillResponse
import com.habitrpg.android.habitica.models.responses.UnlockResponse
import com.habitrpg.android.habitica.models.social.Group
import com.habitrpg.android.habitica.models.social.GroupMembership
import com.habitrpg.android.habitica.models.tasks.Task
import com.habitrpg.android.habitica.models.user.Stats
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.models.user.UserQuestStatus
import com.habitrpg.android.habitica.proxy.AnalyticsManager
import com.habitrpg.common.habitica.extensions.Optional
import com.habitrpg.shared.habitica.models.responses.TaskDirection
import com.habitrpg.shared.habitica.models.responses.VerifyUsernameResponse
import com.habitrpg.shared.habitica.models.tasks.Attribute
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.Maybe
import io.reactivex.rxjava3.functions.BiFunction
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext
import java.util.Date
import java.util.GregorianCalendar
import java.util.concurrent.TimeUnit
class UserRepositoryImpl(
localRepository: UserLocalRepository,
apiClient: ApiClient,
userID: String,
private val taskRepository: TaskRepository,
private val appConfigManager: AppConfigManager,
private val analyticsManager: AnalyticsManager
) : BaseRepositoryImpl<UserLocalRepository>(localRepository, apiClient, userID), UserRepository {
private var lastSync: Date? = null
override fun getUser(): Flow<User?> = getUser(userID)
override fun getUserFlowable(): Flowable<User> = localRepository.getUserFlowable(userID)
override fun getUser(userID: String): Flow<User?> = localRepository.getUser(userID)
private fun updateUser(userID: String, updateData: Map<String, Any>): Flowable<User> {
return Flowable.zip(
apiClient.updateUser(updateData),
localRepository.getUserFlowable(userID).firstElement().toFlowable()
) { newUser, user -> mergeUser(user, newUser) }
}
private fun updateUser(userID: String, key: String, value: Any): Flowable<User> {
val updateData = HashMap<String, Any>()
updateData[key] = value
return updateUser(userID, updateData)
}
override fun updateUser(updateData: Map<String, Any>): Flowable<User> {
return updateUser(userID, updateData)
}
override fun updateUser(key: String, value: Any): Flowable<User> {
return updateUser(userID, key, value)
}
@Suppress("ReturnCount")
override suspend fun retrieveUser(withTasks: Boolean, forced: Boolean, overrideExisting: Boolean): User? {
// Only retrieve again after 3 minutes or it's forced.
if (forced || this.lastSync == null || Date().time - (this.lastSync?.time ?: 0) > 180000) {
val user = apiClient.retrieveUser(withTasks) ?: return null
lastSync = Date()
localRepository.saveUser(user)
if (withTasks) {
val id = user.id
val tasksOrder = user.tasksOrder
val tasks = user.tasks
if (id != null && tasksOrder != null && tasks != null) {
taskRepository.saveTasks(id, tasksOrder, tasks)
}
}
val calendar = GregorianCalendar()
val timeZone = calendar.timeZone
val offset = -TimeUnit.MINUTES.convert(timeZone.getOffset(calendar.timeInMillis).toLong(), TimeUnit.MILLISECONDS)
/*if (offset.toInt() != user.preferences?.timezoneOffset ?: 0) {
return@flatMap updateUser(user.id ?: "", "preferences.timezoneOffset", offset.toString())
} else {
return@flatMap Flowable.just(user)
}*/
return user
} else {
return null
}
}
override suspend fun revive(): User? {
apiClient.revive()
return retrieveUser(false, true)
}
override fun resetTutorial(): Maybe<User> {
return localRepository.getTutorialSteps()
.firstElement()
.map<Map<String, Any>> { tutorialSteps ->
val updateData = HashMap<String, Any>()
for (step in tutorialSteps) {
updateData[step.flagPath] = false
}
updateData
}
.flatMap { updateData -> updateUser(updateData).firstElement() }
}
override suspend fun sleep(user: User): User {
val newValue = !(user.preferences?.sleep ?: false)
localRepository.modify(user) { it.preferences?.sleep = newValue }
if (apiClient.sleep() != true) {
localRepository.modify(user) { it.preferences?.sleep = !newValue }
}
return user
}
override fun getSkills(user: User): Flowable<out List<Skill>> =
localRepository.getSkills(user)
override fun getSpecialItems(user: User): Flowable<out List<Skill>> =
localRepository.getSpecialItems(user)
override fun useSkill(key: String, target: String?, taskId: String): Flowable<SkillResponse> {
return zipWithLiveUser(apiClient.useSkill(key, target ?: "", taskId)) { response, user ->
response.hpDiff = (response.user?.stats?.hp ?: 0.0) - (user.stats?.hp ?: 0.0)
response.expDiff =(response.user?.stats?.exp ?: 0.0) - (user.stats?.exp ?: 0.0)
response.goldDiff = (response.user?.stats?.gp ?: 0.0) - (user.stats?.gp ?: 0.0)
response.damage = (response.user?.party?.quest?.progress?.up ?: 0.0f) - (user.party?.quest?.progress?.up ?: 0.0f)
response.user?.let { mergeUser(user, it) }
response
}
}
override fun useSkill(key: String, target: String?): Flowable<SkillResponse> {
return zipWithLiveUser(apiClient.useSkill(key, target ?: "")) { response, user ->
response.hpDiff = (response.user?.stats?.hp ?: 0.0) - (user.stats?.hp ?: 0.0)
response.expDiff =(response.user?.stats?.exp ?: 0.0) - (user.stats?.exp ?: 0.0)
response.goldDiff = (response.user?.stats?.gp ?: 0.0) - (user.stats?.gp ?: 0.0)
response.damage = (response.user?.party?.quest?.progress?.up ?: 0.0f) - (user.party?.quest?.progress?.up ?: 0.0f)
response.user?.let { mergeUser(user, it) }
response
}
}
override suspend fun disableClasses(): User? = apiClient.disableClasses()
override suspend fun changeClass(selectedClass: String?): User? {
return apiClient.changeClass(selectedClass)
}
override fun unlockPath(customization: Customization): Flowable<UnlockResponse> {
return unlockPath(customization.path, customization.price ?: 0)
}
override fun unlockPath(path: String, price: Int): Flowable<UnlockResponse> {
return zipWithLiveUser(apiClient.unlockPath(path)) { unlockResponse, copiedUser ->
val user = localRepository.getUnmanagedCopy(copiedUser)
user.preferences = unlockResponse.preferences
user.purchased = unlockResponse.purchased
user.items = unlockResponse.items
user.balance = copiedUser.balance - (price / 4.0)
localRepository.saveUser(copiedUser, false)
unlockResponse
}
}
override suspend fun runCron() {
runCron(ArrayList())
}
override fun readNotification(id: String): Flowable<List<Any>> = apiClient.readNotification(id)
override fun getUserQuestStatus(): Flowable<UserQuestStatus> {
return localRepository.getUserQuestStatus(userID)
}
override suspend fun reroll(): User? {
return apiClient.reroll()
}
override fun readNotifications(notificationIds: Map<String, List<String>>): Flowable<List<Any>> =
apiClient.readNotifications(notificationIds)
override fun seeNotifications(notificationIds: Map<String, List<String>>): Flowable<List<Any>> =
apiClient.seeNotifications(notificationIds)
override fun changeCustomDayStart(dayStartTime: Int): Flowable<User> {
val updateObject = HashMap<String, Any>()
updateObject["dayStart"] = dayStartTime
return apiClient.changeCustomDayStart(updateObject)
}
override fun updateLanguage(languageCode: String): Flowable<User> {
return updateUser("preferences.language", languageCode)
.doOnNext { apiClient.setLanguageCode(languageCode) }
}
override suspend fun resetAccount(): User? {
apiClient.resetAccount()
return retrieveUser(withTasks = true, forced = true)
}
override fun deleteAccount(password: String): Flowable<Void> =
apiClient.deleteAccount(password)
override fun sendPasswordResetEmail(email: String): Flowable<Void> =
apiClient.sendPasswordResetEmail(email)
override fun updateLoginName(newLoginName: String, password: String?): Maybe<User> {
return (
if (password != null && password.isNotEmpty()) {
apiClient.updateLoginName(newLoginName.trim(), password.trim())
} else {
apiClient.updateUsername(newLoginName.trim())
}
).flatMapMaybe { localRepository.getUserFlowable(userID).firstElement() }
.doOnNext { user ->
localRepository.modify(user) { liveUser ->
liveUser.authentication?.localAuthentication?.username = newLoginName
liveUser.flags?.verifiedUsername = true
}
}
.firstElement()
}
override fun verifyUsername(username: String): Flowable<VerifyUsernameResponse> = apiClient.verifyUsername(username.trim())
override fun updateEmail(newEmail: String, password: String): Flowable<Void> =
apiClient.updateEmail(newEmail.trim(), password)
override fun updatePassword(
oldPassword: String,
newPassword: String,
newPasswordConfirmation: String
): Flowable<Void> =
apiClient.updatePassword(oldPassword.trim(), newPassword.trim(), newPasswordConfirmation.trim())
override fun allocatePoint(stat: Attribute): Flowable<Stats> {
getLiveUser().firstElement().subscribe(
{ liveUser ->
localRepository.executeTransaction {
when (stat) {
Attribute.STRENGTH -> liveUser.stats?.strength = liveUser.stats?.strength?.inc()
Attribute.INTELLIGENCE -> liveUser.stats?.intelligence = liveUser.stats?.intelligence?.inc()
Attribute.CONSTITUTION -> liveUser.stats?.constitution = liveUser.stats?.constitution?.inc()
Attribute.PERCEPTION -> liveUser.stats?.per = liveUser.stats?.per?.inc()
}
liveUser.stats?.points = liveUser.stats?.points?.dec()
}
},
ExceptionHandler.rx()
)
return zipWithLiveUser(apiClient.allocatePoint(stat.value)) { stats, user ->
localRepository.modify(user) { liveUser ->
liveUser.stats?.strength = stats.strength
liveUser.stats?.constitution = stats.constitution
liveUser.stats?.per = stats.per
liveUser.stats?.intelligence = stats.intelligence
liveUser.stats?.points = stats.points
liveUser.stats?.mp = stats.mp
}
stats
}
}
override fun bulkAllocatePoints(
strength: Int,
intelligence: Int,
constitution: Int,
perception: Int
): Flowable<Stats> =
zipWithLiveUser(apiClient.bulkAllocatePoints(strength, intelligence, constitution, perception)) { stats, user ->
localRepository.modify(user) { liveUser ->
liveUser.stats?.strength = stats.strength
liveUser.stats?.constitution = stats.constitution
liveUser.stats?.per = stats.per
liveUser.stats?.intelligence = stats.intelligence
liveUser.stats?.points = stats.points
liveUser.stats?.mp = stats.mp
}
stats
}
override suspend fun runCron(tasks: MutableList<Task>) {
withContext(Dispatchers.Main) {
var observable: Maybe<Any> = localRepository.getUserFlowable(userID).firstElement()
.filter { it.needsCron }
.map { user ->
localRepository.modify(user) { liveUser ->
liveUser.needsCron = false
liveUser.lastCron = Date()
}
user
}
if (tasks.isNotEmpty()) {
val scoringList = mutableListOf<Map<String, String>>()
for (task in tasks) {
val map = mutableMapOf<String, String>()
map["id"] = task.id ?: ""
map["direction"] = TaskDirection.UP.text
scoringList.add(map)
}
observable = observable.flatMap { taskRepository.bulkScoreTasks(scoringList).firstElement() }
}
observable.flatMap { apiClient.runCron().firstElement() }
// .flatMap {
// this.retrieveUser(withTasks = true, forced = true)
// }
.subscribe({ }, ExceptionHandler.rx())
}
}
override fun useCustomization(type: String, category: String?, identifier: String): Flowable<User> {
if (appConfigManager.enableLocalChanges()) {
localRepository.getUserFlowable(userID).firstElement().subscribe(
{ liveUser ->
localRepository.modify(liveUser) { user ->
when (type) {
"skin" -> user.preferences?.skin = identifier
"shirt" -> user.preferences?.shirt = identifier
"hair" -> {
when (category) {
"color" -> user.preferences?.hair?.color = identifier
"flower" -> user.preferences?.hair?.flower = identifier.toInt()
"mustache" -> user.preferences?.hair?.mustache = identifier.toInt()
"beard" -> user.preferences?.hair?.beard = identifier.toInt()
"bangs" -> user.preferences?.hair?.bangs = identifier.toInt()
"base" -> user.preferences?.hair?.base = identifier.toInt()
}
}
"background" -> user.preferences?.background = identifier
"chair" -> user.preferences?.chair = identifier
}
}
},
ExceptionHandler.rx()
)
}
var updatePath = "preferences.$type"
if (category != null) {
updatePath = "$updatePath.$category"
}
return updateUser(updatePath, identifier)
}
override fun retrieveAchievements(): Flowable<List<Achievement>> {
return apiClient.getMemberAchievements(userID).doOnNext {
localRepository.save(it)
}
}
override fun getAchievements(): Flow<List<Achievement>> {
return localRepository.getAchievements()
}
override fun getQuestAchievements(): Flow<List<QuestAchievement>> {
return localRepository.getQuestAchievements(userID)
}
override fun retrieveTeamPlans(): Flowable<List<TeamPlan>> {
return apiClient.getTeamPlans().doOnNext { teams ->
teams.forEach { it.userID = userID }
localRepository.save(teams)
}
}
override fun getTeamPlans(): Flow<List<TeamPlan>> {
return localRepository.getTeamPlans(userID)
}
override suspend fun retrieveTeamPlan(teamID: String): Group? {
val team = apiClient.getGroup(teamID) ?: return null
val tasks = apiClient.getTeamPlanTasks(teamID)
localRepository.save(team)
val id = team.id
val tasksOrder = team.tasksOrder
if (id.isNotBlank() && tasksOrder != null && tasks != null) {
taskRepository.saveTasks(id, tasksOrder, tasks)
}
val members = apiClient.getGroupMembers(teamID, true) ?: return team
localRepository.save(members.map { it.id?.let { member -> GroupMembership(member, id) } }.filterNotNull())
members.let { localRepository.save(members) }
return team
}
override fun getTeamPlan(teamID: String): Flowable<Group> {
return localRepository.getTeamPlan(teamID)
}
private fun getLiveUser(): Flowable<User> {
return localRepository.getUserFlowable(userID)
.map { Optional(localRepository.getLiveObject(it)) }
.filterMapEmpty()
}
private fun <T : Any> zipWithLiveUser(flowable: Flowable<T>, mergeFunc: BiFunction<T, User, T>): Flowable<T> {
return Flowable.zip(flowable, getLiveUser().firstElement().toFlowable(), mergeFunc)
}
private fun mergeUser(oldUser: User?, newUser: User): User {
if (oldUser == null || !oldUser.isValid) {
return oldUser ?: newUser
}
val copiedUser: User = if (oldUser.isManaged) {
localRepository.getUnmanagedCopy(oldUser)
} else {
oldUser
}
if (newUser.inbox != null) {
copiedUser.inbox = newUser.inbox
}
if (newUser.items != null) {
copiedUser.items = newUser.items
}
if (newUser.preferences != null) {
copiedUser.preferences = newUser.preferences
}
if (newUser.flags != null) {
copiedUser.flags = newUser.flags
}
if (newUser.stats != null) {
copiedUser.stats?.merge(newUser.stats)
}
if (newUser.profile != null) {
copiedUser.profile = newUser.profile
}
if (newUser.party != null) {
copiedUser.party = newUser.party
}
copiedUser.needsCron = newUser.needsCron
copiedUser.versionNumber = newUser.versionNumber
localRepository.saveUser(copiedUser, false)
return copiedUser
}
}
| gpl-3.0 | 2e4e45ee0c849165d370d44495be0d81 | 41.861915 | 127 | 0.605616 | 5.021418 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/data/local/implementation/RealmInventoryLocalRepository.kt | 1 | 16957 | package com.habitrpg.android.habitica.data.local.implementation
import com.habitrpg.android.habitica.data.local.InventoryLocalRepository
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.models.inventory.Egg
import com.habitrpg.android.habitica.models.inventory.Equipment
import com.habitrpg.android.habitica.models.inventory.Food
import com.habitrpg.android.habitica.models.inventory.HatchingPotion
import com.habitrpg.android.habitica.models.inventory.Item
import com.habitrpg.android.habitica.models.inventory.Mount
import com.habitrpg.android.habitica.models.inventory.Pet
import com.habitrpg.android.habitica.models.inventory.QuestContent
import com.habitrpg.android.habitica.models.inventory.SpecialItem
import com.habitrpg.android.habitica.models.shops.ShopItem
import com.habitrpg.android.habitica.models.user.Items
import com.habitrpg.android.habitica.models.user.OwnedItem
import com.habitrpg.android.habitica.models.user.OwnedMount
import com.habitrpg.android.habitica.models.user.OwnedPet
import com.habitrpg.android.habitica.models.user.User
import hu.akarnokd.rxjava3.bridge.RxJavaBridge
import io.reactivex.rxjava3.core.Flowable
import io.realm.Realm
import io.realm.RealmObject
import io.realm.Sort
import io.realm.kotlin.toFlow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class RealmInventoryLocalRepository(realm: Realm) : RealmContentLocalRepository(realm), InventoryLocalRepository {
override fun getQuestContent(keys: List<String>): Flow<List<QuestContent>> {
return realm.where(QuestContent::class.java)
.`in`("key", keys.toTypedArray())
.findAll()
.toFlow()
.filter { it.isLoaded }
}
override fun getQuestContent(key: String): Flow<QuestContent?> {
return realm.where(QuestContent::class.java).equalTo("key", key)
.findAll()
.toFlow()
.filter { content -> content.isLoaded && content.isValid && !content.isEmpty() }
.map { content -> content.first() }
}
override fun getEquipment(searchedKeys: List<String>): Flowable<out List<Equipment>> {
return RxJavaBridge.toV3Flowable(
realm.where(Equipment::class.java)
.`in`("key", searchedKeys.toTypedArray())
.findAll()
.asFlowable()
.filter { it.isLoaded }
)
}
override fun getArmoireRemainingCount(): Long {
return realm.where(Equipment::class.java)
.equalTo("klass", "armoire")
.beginGroup()
.equalTo("owned", false)
.or()
.isNull("owned")
.endGroup()
.count()
}
override fun getOwnedEquipment(type: String): Flowable<out List<Equipment>> {
return RxJavaBridge.toV3Flowable(
realm.where(Equipment::class.java)
.equalTo("type", type)
.equalTo("owned", true)
.findAll()
.asFlowable()
.filter { it.isLoaded }
)
}
override fun getOwnedEquipment(): Flowable<out List<Equipment>> {
return RxJavaBridge.toV3Flowable(
realm.where(Equipment::class.java)
.equalTo("owned", true)
.findAll()
.asFlowable()
.filter { it.isLoaded }
)
}
override fun getEquipmentType(type: String, set: String): Flowable<out List<Equipment>> {
return RxJavaBridge.toV3Flowable(
realm.where(Equipment::class.java)
.equalTo("type", type)
.equalTo("gearSet", set)
.findAll()
.asFlowable()
.filter { it.isLoaded }
)
}
override fun getOwnedItems(itemType: String, userID: String, includeZero: Boolean): Flow<List<OwnedItem>> {
return queryUser(userID).map {
val items = when (itemType) {
"eggs" -> it?.items?.eggs
"hatchingPotions" -> it?.items?.hatchingPotions
"food" -> it?.items?.food
"quests" -> it?.items?.quests
"special" -> it?.items?.special
else -> emptyList()
} ?: emptyList()
if (includeZero) {
items
} else {
items.filter { it.numberOwned > 0 }
}
}
}
override fun getItemsFlowable(itemClass: Class<out Item>, keys: Array<String>): Flow<List<Item>> {
return realm.where(itemClass).`in`("key", keys).findAll().toFlow()
.filter { it.isLoaded }
}
override fun getItemsFlowable(itemClass: Class<out Item>): Flowable<out List<Item>> {
return RxJavaBridge.toV3Flowable(
realm.where(itemClass).findAll().asFlowable()
.filter { it.isLoaded }
)
}
override fun getItems(itemClass: Class<out Item>): Flow<List<Item>> {
return realm.where(itemClass).findAll().toFlow()
.filter { it.isLoaded }
}
override fun getOwnedItems(userID: String, includeZero: Boolean): Flowable<Map<String, OwnedItem>> {
return queryUserFlowable(userID).map {
val items = HashMap<String, OwnedItem>()
it.items?.eggs?.forEach { items[it.key + "-" + it.itemType] = it }
it.items?.food?.forEach { items[it.key + "-" + it.itemType] = it }
it.items?.hatchingPotions?.forEach { items[it.key + "-" + it.itemType] = it }
it.items?.quests?.forEach { items[it.key + "-" + it.itemType] = it }
if (includeZero) {
items
} else {
items.filter { it.value.numberOwned > 0 }
}
}
}
override fun getEquipment(key: String): Flowable<Equipment> {
return RxJavaBridge.toV3Flowable(
realm.where(Equipment::class.java)
.equalTo("key", key)
.findAll()
.asFlowable()
.filter { realmObject -> realmObject.isLoaded && realmObject.isNotEmpty() }
.map { it.first() }
.cast(Equipment::class.java)
)
}
override fun getMounts(): Flow<List<Mount>> {
return realm.where(Mount::class.java)
.sort("type", Sort.ASCENDING, "animal", Sort.ASCENDING)
.findAll()
.toFlow()
.filter { it.isLoaded }
}
override fun getMounts(type: String?, group: String?, color: String?): Flow<List<Mount>> {
var query = realm.where(Mount::class.java)
.sort("type", Sort.ASCENDING, if (color == null) "color" else "animal", Sort.ASCENDING)
if (type != null) {
query = query.equalTo("animal", type)
}
if (group != null) {
query = query.equalTo("type", group)
}
if (color != null) {
query = query.equalTo("color", color)
}
return query.findAll()
.toFlow()
.filter { it.isLoaded }
}
override fun getOwnedMounts(userID: String): Flow<List<OwnedMount>> {
return queryUser(userID)
.map {
it?.items?.mounts?.filter {
it.owned == true
} ?: emptyList()
}
}
override fun getPets(): Flow<List<Pet>> {
return realm.where(Pet::class.java)
.sort("type", Sort.ASCENDING, "animal", Sort.ASCENDING)
.findAll()
.toFlow()
.filter { it.isLoaded }
}
override fun getPets(type: String?, group: String?, color: String?): Flow<List<Pet>> {
var query = realm.where(Pet::class.java)
.sort("type", Sort.ASCENDING, if (color == null) "color" else "animal", Sort.ASCENDING)
if (type != null) {
query = query.equalTo("animal", type)
}
if (group != null) {
query = query.equalTo("type", group)
}
if (color != null) {
query = query.equalTo("color", color)
}
return query.findAll()
.toFlow()
.filter { it.isLoaded }
}
override fun getOwnedPets(userID: String): Flow<List<OwnedPet>> {
return realm.where(User::class.java)
.equalTo("id", userID)
.findAll()
.toFlow()
.filter { it.isLoaded && it.isValid && !it.isEmpty() }
.map {
it.first()?.items?.pets?.filter {
it.trained > 0
} ?: emptyList()
}
}
override fun updateOwnedEquipment(user: User) {
}
override fun changeOwnedCount(type: String, key: String, userID: String, amountToAdd: Int) {
getOwnedItem(userID, type, key, true).firstElement().subscribe({ changeOwnedCount(it, amountToAdd) }, ExceptionHandler.rx())
}
override fun changeOwnedCount(item: OwnedItem, amountToAdd: Int?) {
val liveItem = getLiveObject(item) ?: return
amountToAdd?.let { amount ->
executeTransaction { liveItem.numberOwned = liveItem.numberOwned + amount }
}
}
override fun getOwnedItem(userID: String, type: String, key: String, includeZero: Boolean): Flowable<OwnedItem> {
return queryUserFlowable(userID).map {
var items = (
when (type) {
"eggs" -> it.items?.eggs
"hatchingPotions" -> it.items?.hatchingPotions
"food" -> it.items?.food
"quests" -> it.items?.quests
else -> emptyList()
} ?: emptyList()
)
items = items.filter { it.key == key }
if (includeZero) {
items
} else {
items.filter { it.numberOwned > 0 }
}
}
.filter { it.isNotEmpty() }
.map { it.first() }
}
override fun getItem(type: String, key: String): Flowable<Item> {
val itemClass: Class<out RealmObject> = when (type) {
"eggs" -> Egg::class.java
"hatchingPotions" -> HatchingPotion::class.java
"food" -> Food::class.java
"quests" -> QuestContent::class.java
"special" -> SpecialItem::class.java
else -> Egg::class.java
}
return RxJavaBridge.toV3Flowable(
realm.where(itemClass).equalTo("key", key)
.findAll()
.asFlowable()
.filter { realmObject -> realmObject.isLoaded && realmObject.isNotEmpty() }
.map { it.first() }
.cast(Item::class.java)
)
}
override fun decrementMysteryItemCount(user: User?) {
if (user == null) {
return
}
val liveUser = getLiveObject(user)
val ownedItems = liveUser?.items?.special
val item = ownedItems?.firstOrNull() { it.key == "inventory_present" }
executeTransaction {
if (item != null && item.isValid) {
item.numberOwned = item.numberOwned - 1
}
if (liveUser?.isValid == true) {
liveUser.purchased?.plan?.mysteryItemCount = (user.purchased?.plan?.mysteryItemCount ?: 0) - 1
}
}
}
override fun getInAppRewards(): Flowable<out List<ShopItem>> {
return RxJavaBridge.toV3Flowable(
realm.where(ShopItem::class.java)
.findAll()
.asFlowable()
.filter { it.isLoaded }
)
}
override fun saveInAppRewards(onlineItems: List<ShopItem>) {
val localItems = realm.where(ShopItem::class.java).findAll().createSnapshot()
executeTransaction {
for (localItem in localItems) {
if (!onlineItems.contains(localItem)) {
localItem.deleteFromRealm()
}
}
realm.insertOrUpdate(onlineItems)
}
}
override fun hatchPet(eggKey: String, potionKey: String, userID: String) {
val newPet = OwnedPet()
newPet.key = "$eggKey-$potionKey"
newPet.trained = 5
val user = realm.where(User::class.java).equalTo("id", userID).findFirst() ?: return
val egg = user.items?.eggs?.firstOrNull { it.key == eggKey } ?: return
val hatchingPotion = user.items?.hatchingPotions?.firstOrNull { it.key == potionKey } ?: return
executeTransaction {
egg.numberOwned -= 1
hatchingPotion.numberOwned -= 1
user.items?.pets?.add(newPet)
}
}
override fun getLiveObject(obj: OwnedItem): OwnedItem? {
if (isClosed) return null
if (!obj.isManaged) return obj
return realm.where(OwnedItem::class.java).equalTo("key", obj.key).equalTo("itemType", obj.itemType).findFirst()
}
override fun save(items: Items, userID: String) {
val user = realm.where(User::class.java).equalTo("id", userID).findFirst() ?: return
items.setItemTypes()
executeTransaction {
user.items = items
}
}
override fun unhatchPet(eggKey: String, potionKey: String, userID: String) {
val pet = realm.where(OwnedPet::class.java).equalTo("key", "$eggKey-$potionKey").findFirst()
val user = realm.where(User::class.java).equalTo("id", userID).findFirst() ?: return
val egg = user.items?.eggs?.firstOrNull { it.key == eggKey } ?: return
val hatchingPotion = user.items?.hatchingPotions?.firstOrNull { it.key == potionKey } ?: return
executeTransaction {
egg.numberOwned += 1
hatchingPotion.numberOwned += 1
user.items?.pets?.remove(pet)
}
}
override fun feedPet(foodKey: String, petKey: String, feedValue: Int, userID: String) {
val user = realm.where(User::class.java).equalTo("id", userID).findFirst() ?: return
val pet = user.items?.pets?.firstOrNull { it.key == petKey } ?: return
val food = user.items?.food?.firstOrNull { it.key == foodKey } ?: return
executeTransaction {
pet.trained = feedValue
food.numberOwned -= 1
if (feedValue < 0) {
val mount = OwnedMount()
mount.key = petKey
mount.owned = true
user.items?.mounts?.add(mount)
}
}
}
override fun getLatestMysteryItem(): Flowable<Equipment> {
return RxJavaBridge.toV3Flowable(
realm.where(Equipment::class.java)
.contains("key", "mystery_2")
.sort("mystery", Sort.DESCENDING)
.findAll()
.asFlowable()
.filter { it.isLoaded && it.size > 0 }
.map {
val format = SimpleDateFormat("yyyyMM", Locale.US)
it.first {
it.key?.contains(format.format(Date())) == true
}
}
)
}
override fun soldItem(userID: String, updatedUser: User): User {
val user = realm.where(User::class.java)
.equalTo("id", userID)
.findFirst() ?: return updatedUser
executeTransaction {
val items = updatedUser.items
if (items != null) {
user.items = items
}
val stats = updatedUser.stats
if (stats != null) {
user.stats = stats
}
}
return user
}
override fun getAvailableLimitedItems(): Flowable<List<Item>> {
return Flowable.combineLatest(
realm.where(Egg::class.java)
.lessThan("event.start", Date())
.greaterThan("event.end", Date())
.findAll().asFlowable(),
realm.where(Food::class.java)
.lessThan("event.start", Date())
.greaterThan("event.end", Date())
.findAll().asFlowable(),
realm.where(HatchingPotion::class.java)
.lessThan("event.start", Date())
.greaterThan("event.end", Date())
.findAll().asFlowable(),
realm.where(QuestContent::class.java)
.lessThan("event.start", Date())
.greaterThan("event.end", Date())
.findAll().asFlowable(),
{ eggs, food, potions, quests ->
val items = mutableListOf<Item>()
items.addAll(eggs)
items.addAll(food)
items.addAll(potions)
items.addAll(quests)
items
}
)
}
}
| gpl-3.0 | 33d5c786a49eb96e06739855813c7e45 | 36.766147 | 132 | 0.553577 | 4.569388 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/query/s9api/debugger/SaxonStackFrame.kt | 1 | 3148 | /*
* Copyright (C) 2020-2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.saxon.query.s9api.debugger
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XNamedValue
import com.intellij.xdebugger.frame.XStackFrame
import uk.co.reecedunn.intellij.plugin.processor.debug.frame.ComputeChildren
import uk.co.reecedunn.intellij.plugin.processor.debug.frame.VirtualFileStackFrame
import uk.co.reecedunn.intellij.plugin.processor.debug.frame.addChildren
import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.Processor
import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.expr.XPathContext
import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.trace.InstructionInfo
import uk.co.reecedunn.intellij.plugin.xpm.module.path.XpmModuleUri
import javax.xml.transform.SourceLocator
class SaxonStackFrame private constructor(
private val xpathContext: XPathContext?,
private val processor: Processor?
) : ComputeChildren {
override fun computeChildren(node: XCompositeNode, evaluator: XDebuggerEvaluator?) {
node.addChildren(computeStackVariables(), true)
}
private fun computeStackVariables(): Sequence<XNamedValue> {
val frame = xpathContext!!.getStackFrame()
val names = frame.getStackFrameMap().getVariableMap()
return frame.getStackFrameValues().asSequence().withIndex().mapNotNull { (index, value) ->
SaxonVariable(names[index], value, processor!!)
}
}
companion object {
fun create(
locator: SourceLocator,
xpathContext: XPathContext?,
processor: Processor?,
queryFile: VirtualFile
): XStackFrame {
val path = locator.systemId
val line = locator.lineNumber.let { if (it == -1) 1 else it } - 1
val column = locator.columnNumber.let { if (it == -1) 1 else it } - 1
val context = (locator as? InstructionInfo)?.getObjectName()?.toString()
val children = SaxonStackFrame(xpathContext, processor)
val file = when {
path.isNullOrEmpty() -> null
path.startsWith("file:/") -> LocalFileSystem.getInstance().findFileByPath(path.substring(6))
else -> XpmModuleUri(queryFile, path)
}
return VirtualFileStackFrame(file ?: queryFile, line, column, context, children, null)
}
}
}
| apache-2.0 | eaa20a58ad1b7b469c4b86c89627563b | 44.623188 | 108 | 0.716645 | 4.396648 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/host/exp/exponent/modules/api/components/webview/events/TopLoadingErrorEvent.kt | 2 | 781 | package abi42_0_0.host.exp.exponent.modules.api.components.webview.events
import abi42_0_0.com.facebook.react.bridge.WritableMap
import abi42_0_0.com.facebook.react.uimanager.events.Event
import abi42_0_0.com.facebook.react.uimanager.events.RCTEventEmitter
/**
* Event emitted when there is an error in loading.
*/
class TopLoadingErrorEvent(viewId: Int, private val mEventData: WritableMap) :
Event<TopLoadingErrorEvent>(viewId) {
companion object {
const val EVENT_NAME = "topLoadingError"
}
override fun getEventName(): String = EVENT_NAME
override fun canCoalesce(): Boolean = false
override fun getCoalescingKey(): Short = 0
override fun dispatch(rctEventEmitter: RCTEventEmitter) =
rctEventEmitter.receiveEvent(viewTag, eventName, mEventData)
}
| bsd-3-clause | 561487ab52f123257b1800deb856976c | 31.541667 | 78 | 0.774648 | 4.046632 | false | false | false | false |
alexstolzberg/kartleaderboard | app/src/main/java/com/mariokartleaderboard/SessionSettings.kt | 1 | 2566 | package com.mariokartleaderboard
import android.os.Parcel
import android.os.Parcelable
class SessionSettings(var raceType: RaceType = SessionSettings.RaceType.CC150,
var items: Items = SessionSettings.Items.NORMAL,
var comsLevel: ComsLevel = SessionSettings.ComsLevel.HARD,
var comVehicles: ComVehicles = SessionSettings.ComVehicles.ALL,
var raceCount: Int = 5) :Parcelable {
enum class RaceType(val raceType: String) {
CC50("50cc"),
CC100("100cc"),
CC150("150cc"),
CC200("200cc"),
MIRROR("Mirror")
}
enum class Items(val items: String) {
NORMAL("Normal Items"),
SHELLS_ONLY("Shells Only"),
BANANAS_ONLY("Bananas Only"),
MUSHROOMS_ONLY("Mushrooms Only"),
BOB_OMBS_ONLY("Bob-ombs Only"),
NO_ITEMS("No Items"),
NO_ITEMS_OR_COINS("No Items or Coins"),
FRANTIC("Frantic Items")
}
enum class ComsLevel(val comsLevel: String) {
EASY("Easy COM"),
NORMAL("Normal COM"),
HARD("Hard COM")
}
enum class ComVehicles(val comVehicles: String) {
ALL("All Vehicles"),
KARTS_ONLY("Karts Only"),
BIKES_ONLY("Bikes Only")
}
constructor(parcel: Parcel) : this(
parcel.readSerializable() as RaceType,
parcel.readSerializable() as Items,
parcel.readSerializable() as ComsLevel,
parcel.readSerializable() as ComVehicles,
parcel.readInt())
override fun toString(): String {
return """
Race Session Settings
-----------------------------------
Race Type: ${raceType.raceType}
Items: ${items.items}
Computer Level: ${comsLevel.comsLevel}
Computer Vehicles: ${comVehicles.comVehicles}
Race Count: $raceCount"""
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeSerializable(raceType)
parcel.writeSerializable(items)
parcel.writeSerializable(comsLevel)
parcel.writeSerializable(comVehicles)
parcel.writeInt(raceCount)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<SessionSettings> {
override fun createFromParcel(parcel: Parcel): SessionSettings {
return SessionSettings(parcel)
}
override fun newArray(size: Int): Array<SessionSettings?> {
return arrayOfNulls(size)
}
}
}
| apache-2.0 | 0dfe9aa5126add3dd1c607d8a922a13f | 30.292683 | 85 | 0.596648 | 4.509666 | false | false | false | false |
java-opengl-labs/ogl-samples | src/main/kotlin/ogl_samples/tests/gl430/gl-430-perf-monitor-amd.kt | 1 | 1655 | package ogl_samples.tests.gl430
import glm_.BYTES
import ogl_samples.framework.Test
import uno.buffer.floatBufferOf
import uno.buffer.shortBufferOf
import uno.caps.Caps.Profile
import uno.glf.glf
/**
* Created by elect on 17/04/17.
*/
fun main(args: Array<String>) {
gl_430_perf_monitor_amd().loop()
}
private class gl_430_perf_monitor_amd : Test("gl-430-perf-monitor-amd", Profile.CORE, 4, 3) {
val SHADER_SOURCE_TEXTURE = "gl-430/fbo-texture-2d"
val SHADER_SOURCE_SPLASH = "es-300/fbo-splash"
val TEXTURE = "kueken7_rgb_dxt1_unorm.dds"
val vertexCount = 4
val vertexSize = vertexCount * glf.pos2_tc2.stride
val vertexData = floatBufferOf(
-1f, -1f, 0f, 1f,
+1f, -1f, 1f, 1f,
+1f, +1f, 1f, 0f,
-1f, +1f, 0f, 0f)
val elementCount = 6
val elementSize = elementCount * Short.BYTES
val elementData = shortBufferOf(
0, 1, 2,
2, 3, 0)
object Buffer {
val VERTEX = 0
val ELEMENT = 1
val TRANSFORM = 2
val MAX = 3
}
object Texture {
val DIFFUSE = 0
val COLORBUFFER = 1
val RENDERBUFFER = 2
val MAX = 3
}
override fun begin(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun render(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun end(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
} | mit | 84aad5d2b282a0d37b624b1e3c777980 | 24.476923 | 107 | 0.612689 | 3.551502 | false | false | false | false |
nearbydelta/KoreanAnalyzer | komoran/src/test/kotlin/kr/bydelta/koala/test/tests.kt | 1 | 2738 | package kr.bydelta.koala.test
import kr.bydelta.koala.*
import kr.bydelta.koala.kmr.Dictionary
import kr.bydelta.koala.kmr.Tagger
import kr.bydelta.koala.kmr.fromSejongPOS
import kr.bydelta.koala.kmr.toSejongPOS
import kr.co.shineware.nlp.komoran.constant.DEFAULT_MODEL
import kr.co.shineware.nlp.komoran.core.Komoran
import org.spekframework.spek2.Spek
object KomoranTaggerTest : Spek(TaggerSpek(getTagger = { Tagger() },
tagSentByOrig = {
val komoran = Komoran(DEFAULT_MODEL.FULL)
val original = komoran.analyze(it)
val tag = StringBuffer()
var prev = 0
for (token in original.tokenList) {
if (token.beginIndex > prev) {
tag.append(" ")
}
tag.append("${token.morph}/${token.pos}")
prev = token.endIndex
}
"" to tag.toString()
}, tagParaByOrig = { emptyList() },
tagSentByKoala = { str, tagger ->
val tagged = tagger.tagSentence(str)
val tag = tagged.joinToString(" ") { w -> w.joinToString("") { "${it.surface}/${it.originalTag}" } }
str to tag
}, isSentenceSplitterImplemented = true))
object KomoranLightTaggerTest : Spek(TaggerSpek(getTagger = { Tagger(useLightTagger = true) },
tagSentByOrig = {
val komoran = Komoran(DEFAULT_MODEL.LIGHT)
val original = komoran.analyze(it)
val tag = StringBuffer()
var prev = 0
for (token in original.tokenList) {
if (token.beginIndex > prev) {
tag.append(" ")
}
tag.append("${token.morph}/${token.pos}")
prev = token.endIndex
}
"" to tag.toString()
}, tagParaByOrig = { emptyList() },
tagSentByKoala = { str, tagger ->
val tagged = tagger.tagSentence(str)
val tag = tagged.joinToString(" ") { w -> w.joinToString("") { "${it.surface}/${it.originalTag}" } }
str to tag
}, isSentenceSplitterImplemented = true))
object KomoranDictTest : Spek(DictSpek(dict = Dictionary, getTagger = { Tagger() }))
object KomoranTagConversionTest : Spek(TagConversionSpek(from = { it.toSejongPOS() },
to = { it.fromSejongPOS() },
getMapping = {
when (it) {
POS.NNM -> listOf(Conversion("NNB", toSejong = false))
POS.XPV -> listOf(Conversion("XR", toSejong = false))
POS.XSM, POS.XSO -> emptyList()
POS.NF, POS.NV -> listOf(Conversion("NA", toSejong = false))
else -> listOf(Conversion(it.toString()))
}
})) | gpl-3.0 | e47287d2172b0b53321a9031e3b2b850 | 37.041667 | 112 | 0.559167 | 4.205837 | false | true | false | false |
ligi/PassAndroid | android/src/main/java/org/ligi/passandroid/ui/MoveToNewTopicUI.kt | 1 | 2371 | package org.ligi.passandroid.ui
import android.app.Activity
import androidx.appcompat.app.AlertDialog
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import org.ligi.passandroid.R
import org.ligi.passandroid.functions.moveWithUndoSnackbar
import org.ligi.passandroid.model.PassStore
import org.ligi.passandroid.model.pass.Pass
internal class MoveToNewTopicUI(private val context: Activity, private val passStore: PassStore, private val pass: Pass) {
fun show() {
val dialog = AlertDialog.Builder(context)
.setTitle(context.getString(R.string.move_to_new_topic))
.setView(R.layout.dialog_move_to_new_topic)
.setPositiveButton(android.R.string.ok, null)
.setNegativeButton(android.R.string.cancel) { _, _ -> passStore.notifyChange() }
.setOnCancelListener { passStore.notifyChange() }
.show()
val move: (topic: String) -> Any = { topic ->
moveWithUndoSnackbar(passStore.classifier, pass, topic, context)
dialog.dismiss()
}
val newTopicEditText = dialog.findViewById<EditText>(R.id.new_topic_edit)
val suggestionButtonContainer = dialog.findViewById<ViewGroup>(R.id.topic_suggestions_button_container)
if (newTopicEditText != null) {
// we need to do this here so the dialog does not get dismissed
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
if (newTopicEditText.text.toString().isEmpty()) {
newTopicEditText.error = context.getString(R.string.cannot_be_empty)
newTopicEditText.requestFocus()
} else {
move(newTopicEditText.text.toString())
}
}
}
val oldTopic = passStore.classifier.getTopic(pass, "")
val suggestionTopicStringIds = intArrayOf(R.string.topic_trash, R.string.topic_archive, R.string.topic_new)
suggestionTopicStringIds.map { context.getString(it) }.forEach { topic ->
if (topic != oldTopic) {
val button = Button(context)
button.text = topic
suggestionButtonContainer?.addView(button)
button.setOnClickListener { move(topic) }
}
}
}
}
| gpl-3.0 | 9ac02b310a617e4f138f50a7f833b42b | 39.87931 | 122 | 0.639814 | 4.559615 | false | false | false | false |
android/architecture-components-samples | GithubBrowserSample/app/src/test/java/com/android/example/github/ui/search/SearchViewModelTest.kt | 1 | 4326 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.github.ui.search
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.android.example.github.repository.RepoRepository
import com.android.example.github.util.mock
import com.android.example.github.vo.Repo
import com.android.example.github.vo.Resource
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.mockito.Mockito.never
import org.mockito.Mockito.reset
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyNoMoreInteractions
@RunWith(JUnit4::class)
class SearchViewModelTest {
@Rule
@JvmField
val instantExecutor = InstantTaskExecutorRule()
private val repository = mock(RepoRepository::class.java)
private lateinit var viewModel: SearchViewModel
@Before
fun init() {
// need to init after instant executor rule is established.
viewModel = SearchViewModel(repository)
}
@Test
fun empty() {
val result = mock<Observer<Resource<List<Repo>>>>()
viewModel.results.observeForever(result)
viewModel.loadNextPage()
verifyNoMoreInteractions(repository)
}
@Test
fun basic() {
val result = mock<Observer<Resource<List<Repo>>>>()
viewModel.results.observeForever(result)
viewModel.setQuery("foo")
verify(repository).search("foo")
verify(repository, never()).searchNextPage("foo")
}
@Test
fun noObserverNoQuery() {
`when`(repository.searchNextPage("foo")).thenReturn(mock())
viewModel.setQuery("foo")
verify(repository, never()).search("foo")
// next page is user interaction and even if loading state is not observed, we query
// would be better to avoid that if main search query is not observed
viewModel.loadNextPage()
verify(repository).searchNextPage("foo")
}
@Test
fun swap() {
val nextPage = MutableLiveData<Resource<Boolean>>()
`when`(repository.searchNextPage("foo")).thenReturn(nextPage)
val result = mock<Observer<Resource<List<Repo>>>>()
viewModel.results.observeForever(result)
verifyNoMoreInteractions(repository)
viewModel.setQuery("foo")
verify(repository).search("foo")
viewModel.loadNextPage()
viewModel.loadMoreStatus.observeForever(mock())
verify(repository).searchNextPage("foo")
assertThat(nextPage.hasActiveObservers(), `is`(true))
viewModel.setQuery("bar")
assertThat(nextPage.hasActiveObservers(), `is`(false))
verify(repository).search("bar")
verify(repository, never()).searchNextPage("bar")
}
@Test
fun refresh() {
viewModel.refresh()
verifyNoMoreInteractions(repository)
viewModel.setQuery("foo")
viewModel.refresh()
verifyNoMoreInteractions(repository)
viewModel.results.observeForever(mock())
verify(repository).search("foo")
reset(repository)
viewModel.refresh()
verify(repository).search("foo")
}
@Test
fun resetSameQuery() {
viewModel.results.observeForever(mock())
viewModel.setQuery("foo")
verify(repository).search("foo")
reset(repository)
viewModel.setQuery("FOO")
verifyNoMoreInteractions(repository)
viewModel.setQuery("bar")
verify(repository).search("bar")
}
}
| apache-2.0 | 9d112a510604eaef8bbcc715e42254b2 | 32.534884 | 92 | 0.696486 | 4.636656 | false | true | false | false |
mdaniel/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/contributors/helpers/CallableMetadataProvider.kt | 1 | 10808 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.completion.contributors.helpers
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.KtStarProjectionTypeArgument
import org.jetbrains.kotlin.analysis.api.components.buildClassType
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithTypeParameters
import org.jetbrains.kotlin.analysis.api.types.KtSubstitutor
import org.jetbrains.kotlin.analysis.api.types.KtType
import org.jetbrains.kotlin.analysis.api.types.KtTypeParameterType
import org.jetbrains.kotlin.idea.completion.weighers.WeighingContext
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
internal object CallableMetadataProvider {
class CallableMetadata(
val kind: CallableKind,
/**
* The index of the matched receiver. This number makes completion prefer candidates that are available from the innermost receiver
* when all other things are equal. Explicit receiver is pushed to the end because if explicit receiver does not match, the entry
* would not have showed up in the first place.
*
* For example, consider the code below
*
* ```
* class Foo { // receiver 2
* fun String.f1() { // receiver 1
* fun Int.f2() { // receiver 0
* length // receiver index = 1
* listOf("").size // receiver index = 3 (explicit receiver is added to the end)
* "".f1() // receiver index = 3 (explicit receiver is honored over implicit (dispatch) receiver)
* }
* }
* }
* ```
*/
val receiverIndex: Int?
) {
companion object {
val local = CallableMetadata(CallableKind.Local, null)
val globalOrStatic = CallableMetadata(CallableKind.GlobalOrStatic, null)
}
}
sealed class CallableKind(private val index: Int) : Comparable<CallableKind> {
object Local : CallableKind(0) // local non_extension
object ThisClassMember : CallableKind(1)
object BaseClassMember : CallableKind(2)
object ThisTypeExtension : CallableKind(3)
object BaseTypeExtension : CallableKind(4)
object GlobalOrStatic : CallableKind(5) // global non_extension
object TypeParameterExtension : CallableKind(6)
class ReceiverCastRequired(val fullyQualifiedCastType: String) : CallableKind(7)
override fun compareTo(other: CallableKind): Int = this.index - other.index
}
fun KtAnalysisSession.getCallableMetadata(
context: WeighingContext,
symbol: KtSymbol,
substitutor: KtSubstitutor
): CallableMetadata? {
if (symbol !is KtCallableSymbol) return null
if (symbol is KtSyntheticJavaPropertySymbol) {
return getCallableMetadata(context, symbol.javaGetterSymbol, substitutor)
}
val overriddenSymbols = symbol.getDirectlyOverriddenSymbols()
if (overriddenSymbols.isNotEmpty()) {
val weights = overriddenSymbols
.mapNotNull { callableWeightByReceiver(it, context, substitutor, returnCastRequiredOnReceiverMismatch = false) }
.takeUnless { it.isEmpty() }
?: symbol.getAllOverriddenSymbols().map { callableWeightBasic(context, it, substitutor) }
return weights.minByOrNull { it.kind }
}
return callableWeightBasic(context, symbol, substitutor)
}
private fun KtAnalysisSession.callableWeightBasic(
context: WeighingContext,
symbol: KtCallableSymbol,
substitutor: KtSubstitutor
): CallableMetadata {
callableWeightByReceiver(symbol, context, substitutor, returnCastRequiredOnReceiverMismatch = true)?.let { return it }
return when (symbol.getContainingSymbol()) {
null, is KtPackageSymbol, is KtClassifierSymbol -> CallableMetadata.globalOrStatic
else -> CallableMetadata.local
}
}
private fun KtAnalysisSession.callableWeightByReceiver(
symbol: KtCallableSymbol,
context: WeighingContext,
substitutor: KtSubstitutor,
returnCastRequiredOnReceiverMismatch: Boolean
): CallableMetadata? {
val actualExplicitReceiverType = context.explicitReceiver?.let {
getReferencedClassTypeInCallableReferenceExpression(it) ?: it.getKtType()
}
val actualImplicitReceiverTypes = context.implicitReceiver.map { it.type }
val expectedExtensionReceiverType = symbol.receiverType?.let { substitutor.substitute(it) }
val weightBasedOnExtensionReceiver = expectedExtensionReceiverType?.let { receiverType ->
// If a symbol expects an extension receiver, then either
// * the call site explicitly specifies the extension receiver , or
// * the call site specifies no receiver.
// In other words, in this case, an explicit receiver can never be a dispatch receiver.
callableWeightByReceiver(symbol,
actualExplicitReceiverType?.let { listOf(it) } ?: actualImplicitReceiverTypes,
receiverType,
returnCastRequiredOnReceiverMismatch
)
}
if (returnCastRequiredOnReceiverMismatch && weightBasedOnExtensionReceiver?.kind is CallableKind.ReceiverCastRequired) return weightBasedOnExtensionReceiver
// In Fir, a local function takes its containing function's dispatch receiver as its dispatch receiver. But we don't consider a
// local function as a class member. Hence, here we return null so that it's handled by other logic.
if (symbol.callableIdIfNonLocal == null) return null
val expectedDispatchReceiverType = (symbol as? KtCallableSymbol)?.getDispatchReceiverType()
val weightBasedOnDispatchReceiver = expectedDispatchReceiverType?.let { receiverType ->
callableWeightByReceiver(
symbol,
actualImplicitReceiverTypes + listOfNotNull(actualExplicitReceiverType),
receiverType,
returnCastRequiredOnReceiverMismatch
)
}
if (returnCastRequiredOnReceiverMismatch && weightBasedOnDispatchReceiver?.kind is CallableKind.ReceiverCastRequired) return weightBasedOnDispatchReceiver
return weightBasedOnExtensionReceiver ?: weightBasedOnDispatchReceiver
}
/**
* Return the type from the referenced class if this explicit receiver is a receiver in a callable reference expression. For example,
* in the following code, `String` is such a receiver. And this method should return the `String` type in this case.
* ```
* val l = String::length
* ```
*/
private fun KtAnalysisSession.getReferencedClassTypeInCallableReferenceExpression(explicitReceiver: KtExpression): KtType? {
val callableReferenceExpression = explicitReceiver.getParentOfType<KtCallableReferenceExpression>(strict = true) ?: return null
if (callableReferenceExpression.lhs != explicitReceiver) return null
val symbol = when (explicitReceiver) {
is KtDotQualifiedExpression -> explicitReceiver.selectorExpression?.mainReference?.resolveToSymbol()
is KtNameReferenceExpression -> explicitReceiver.mainReference.resolveToSymbol()
else -> return null
}
if (symbol !is KtClassLikeSymbol) return null
return buildClassType(symbol) {
if (symbol is KtSymbolWithTypeParameters) {
repeat(symbol.typeParameters.size) {
argument(KtStarProjectionTypeArgument(token))
}
}
}
}
private fun KtAnalysisSession.callableWeightByReceiver(
symbol: KtCallableSymbol,
actualReceiverTypes: List<KtType>,
expectedReceiverType: KtType,
returnCastRequiredOnReceiverTypeMismatch: Boolean
): CallableMetadata? {
if (expectedReceiverType is KtFunctionType) return null
var bestMatchIndex: Int? = null
var bestMatchWeightKind: CallableKind? = null
for ((i, actualReceiverType) in actualReceiverTypes.withIndex()) {
val weightKind = callableWeightKindByReceiverType(symbol, actualReceiverType, expectedReceiverType)
if (weightKind != null) {
if (bestMatchWeightKind == null || weightKind < bestMatchWeightKind) {
bestMatchWeightKind = weightKind
bestMatchIndex = i
}
}
}
// TODO: FE1.0 has logic that uses `null` for receiverIndex if the symbol matches every actual receiver in order to "prevent members
// of `Any` to show up on top". But that seems hacky and can cause collateral damage if the implicit receivers happen to implement
// some common interface. So that logic is left out here for now. We can add it back in future if needed.
if (bestMatchWeightKind == null) {
return if (returnCastRequiredOnReceiverTypeMismatch)
CallableMetadata(CallableKind.ReceiverCastRequired(expectedReceiverType.render()), null)
else null
}
return CallableMetadata(bestMatchWeightKind, bestMatchIndex)
}
private fun KtAnalysisSession.callableWeightKindByReceiverType(
symbol: KtCallableSymbol,
actualReceiverType: KtType,
expectedReceiverType: KtType,
): CallableKind? = when {
actualReceiverType isEqualTo expectedReceiverType -> when {
isExtensionCallOnTypeParameterReceiver(symbol) -> CallableKind.TypeParameterExtension
symbol.isExtension -> CallableKind.ThisTypeExtension
else -> CallableKind.ThisClassMember
}
actualReceiverType isSubTypeOf expectedReceiverType -> when {
symbol.isExtension -> CallableKind.BaseTypeExtension
else -> CallableKind.BaseClassMember
}
else -> null
}
private fun KtAnalysisSession.isExtensionCallOnTypeParameterReceiver(symbol: KtCallableSymbol): Boolean {
val originalSymbol = symbol.originalOverriddenSymbol
val receiverParameterType = originalSymbol?.receiverType as? KtTypeParameterType ?: return false
val parameterTypeOwner = receiverParameterType.symbol.getContainingSymbol() ?: return false
return parameterTypeOwner == originalSymbol
}
} | apache-2.0 | 3d4cac2735f8b0b7fa21dce1afe6e7d3 | 49.041667 | 164 | 0.686899 | 5.801396 | false | false | false | false |
mdaniel/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/ui/tree/BookmarksTreeStructure.kt | 8 | 1416 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.bookmark.ui.tree
import com.intellij.ide.bookmark.ui.BookmarksView
import com.intellij.ide.projectView.impl.CompoundTreeStructureProvider
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.ide.util.treeView.AbstractTreeStructure
import com.intellij.ide.util.treeView.NodeDescriptor
class BookmarksTreeStructure(val panel: BookmarksView) : AbstractTreeStructure() {
private val root = RootNode(panel)
override fun commit() = Unit
override fun hasSomethingToCommit() = false
override fun createDescriptor(element: Any, parent: NodeDescriptor<*>?) = element as NodeDescriptor<*>
override fun getRootElement(): Any = root
override fun getParentElement(element: Any): Any? = element.asAbstractTreeNode?.parent
override fun getChildElements(element: Any): Array<Any> {
val node = element as? AbstractTreeNode<*>
if (panel.isPopup && node !is RootNode && node !is GroupNode) return emptyArray()
val children = node?.children?.ifEmpty { null } ?: return emptyArray()
val parent = node.parentFolderNode ?: return children.toTypedArray()
val provider = CompoundTreeStructureProvider.get(panel.project) ?: return children.toTypedArray()
return provider.modify(node, children, parent.settings).toTypedArray()
}
}
| apache-2.0 | 6a1a9a5241c0ed85636693b3a75134fb | 49.571429 | 120 | 0.775424 | 4.438871 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinBlockIntoSingleStatementHandler.kt | 1 | 3088 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.joinLines
import com.intellij.codeInsight.editorActions.JoinLinesHandlerDelegate
import com.intellij.codeInsight.editorActions.JoinLinesHandlerDelegate.CANNOT_JOIN
import com.intellij.openapi.editor.Document
import com.intellij.psi.PsiFile
import com.intellij.psi.util.elementType
import org.jetbrains.kotlin.idea.base.util.reformatted
import org.jetbrains.kotlin.idea.inspections.UseExpressionBodyInspection
import org.jetbrains.kotlin.idea.intentions.MergeIfsIntention
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class JoinBlockIntoSingleStatementHandler : JoinLinesHandlerDelegate {
override fun tryJoinLines(document: Document, file: PsiFile, start: Int, end: Int): Int {
if (file !is KtFile) return CANNOT_JOIN
if (start == 0) return CANNOT_JOIN
val c = document.charsSequence[start]
val index = if (c == '\n') start - 1 else start
val brace = file.findElementAt(index) ?: return CANNOT_JOIN
if (brace.elementType != KtTokens.LBRACE) return CANNOT_JOIN
val block = brace.parent as? KtBlockExpression ?: return CANNOT_JOIN
val statement = block.statements.singleOrNull() ?: return CANNOT_JOIN
val parent = block.parent
val useExpressionBodyInspection = UseExpressionBodyInspection(convertEmptyToUnit = false)
val oneLineReturnFunction = (parent as? KtDeclarationWithBody)?.takeIf { useExpressionBodyInspection.isActiveFor(it) }
if (parent !is KtContainerNode && parent !is KtWhenEntry && oneLineReturnFunction == null) return CANNOT_JOIN
if (block.node.getChildren(KtTokens.COMMENTS).isNotEmpty()) return CANNOT_JOIN // otherwise we will loose comments
// handle nested if's
val pparent = parent.parent
if (pparent is KtIfExpression) {
if (block == pparent.then && statement is KtIfExpression && statement.`else` == null) {
// if outer if has else-branch and inner does not have it, do not remove braces otherwise else-branch will belong to different if!
if (pparent.`else` != null) return CANNOT_JOIN
return MergeIfsIntention.applyTo(pparent)
}
if (block == pparent.`else`) {
val ifParent = pparent.parent
if (!(ifParent is KtBlockExpression || ifParent is KtDeclaration || KtPsiUtil.isAssignment(ifParent))) {
return CANNOT_JOIN
}
}
}
val resultExpression = if (oneLineReturnFunction != null) {
useExpressionBodyInspection.simplify(oneLineReturnFunction, false)
oneLineReturnFunction.bodyExpression ?: return CANNOT_JOIN
} else {
block.replace(statement)
}
return resultExpression.reformatted(true).startOffset
}
}
| apache-2.0 | b2f8362f40ab5392894882bbd283c652 | 46.507692 | 158 | 0.700453 | 4.893819 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MakeUpperBoundNonNullableFix.kt | 1 | 12246 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.util.IntentionName
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.util.containers.addIfNotNull
import org.jetbrains.kotlin.backend.jvm.ir.psiElement
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.descriptors.isOverridable
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.getTypeParameters
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtTypeParameter
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.NotNullTypeParameter
import org.jetbrains.kotlin.types.isNullable
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.types.typeUtil.supertypes
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
/**
* A quick fix that make a type parameter non-nullable by either adding `Any` as an upper bound or by changing an existing
* explicitly nullable upper bound with its non-nullable subtype.
*
* Since Kotlin 1.6.20, the compiler generates warnings if Kotlin code uses nullable generic types when calling Java code
* with `@NotNull` annotations (these warnings are going to become errors in future releases, see
* https://youtrack.jetbrains.com/issue/KT-36770 for details). Adding a non-nullable upper bound to a type parameter
* changes the function or classifier interface, but this can fix a lot of warnings and errors, so one may view it
* as a "default" fix for this kind of errors.
*
* @param typeParameter the type parameter to update
* @param kind the required modification of the upper bound
*/
open class MakeUpperBoundNonNullableFix(
typeParameter: KtTypeParameter,
private val kind: Kind
) : KotlinQuickFixAction<KtTypeParameter>(typeParameter) {
/**
* The set of actions that can be performed
*/
sealed class Kind {
abstract val renderedUpperBound: String
@IntentionName
abstract fun getText(parameter: KtTypeParameter): String
/**
* Add `Any` as an upper bound
*/
object AddAnyAsUpperBound : Kind() {
override val renderedUpperBound = StandardNames.FqNames.any.render()
override fun getText(parameter: KtTypeParameter): String = KotlinBundle.message(
"fix.make.upperbound.not.nullable.any.text",
parameter.name ?: ""
)
}
/**
* Replace an existing upper bound with another upper bound
* @param replacement the type of the new upper bound
*/
class ReplaceExistingUpperBound(val replacement: KotlinType) : Kind() {
override val renderedUpperBound = IdeDescriptorRenderers.SOURCE_CODE.renderType(replacement)
override fun getText(parameter: KtTypeParameter): String = KotlinBundle.message(
"fix.make.upperbound.not.nullable.remove.nullability.text",
parameter.name ?: "",
renderedUpperBound
)
}
}
override fun getText(): String = element?.let { kind.getText(it) } ?: ""
override fun getFamilyName() = KotlinBundle.message("fix.make.upperbound.not.nullable.family")
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean {
val element = this.element ?: return false
return element.name != null &&
when (kind) {
Kind.AddAnyAsUpperBound -> element.extendsBound == null
is Kind.ReplaceExistingUpperBound -> element.extendsBound != null
}
}
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val typeParameter = element ?: return
val typeReference = KtPsiFactory(project).createType(kind.renderedUpperBound)
val insertedTypeReference = typeParameter.setExtendsBound(typeReference) ?: return
ShortenReferences.DEFAULT.process(insertedTypeReference)
}
companion object : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
return when (diagnostic.factory) {
ErrorsJvm.NULLABLE_TYPE_PARAMETER_AGAINST_NOT_NULL_TYPE_PARAMETER -> {
val info = ErrorsJvm.NULLABLE_TYPE_PARAMETER_AGAINST_NOT_NULL_TYPE_PARAMETER.cast(diagnostic)
listOfNotNull(createActionForTypeParameter(info.a))
}
ErrorsJvm.WRONG_TYPE_PARAMETER_NULLABILITY_FOR_JAVA_OVERRIDE -> {
val info = ErrorsJvm.WRONG_TYPE_PARAMETER_NULLABILITY_FOR_JAVA_OVERRIDE.cast(diagnostic)
listOfNotNull(createActionForTypeParameter(info.a))
}
Errors.TYPE_MISMATCH -> {
val info = Errors.TYPE_MISMATCH.cast(diagnostic)
createActionsForTypeMismatch(actual = info.b, expected = info.a)
}
Errors.TYPE_MISMATCH_WARNING -> {
val info = Errors.TYPE_MISMATCH_WARNING.cast(diagnostic)
createActionsForTypeMismatch(actual = info.b, expected = info.a)
}
ErrorsJvm.WRONG_NULLABILITY_FOR_JAVA_OVERRIDE -> {
val info = ErrorsJvm.WRONG_NULLABILITY_FOR_JAVA_OVERRIDE.cast(diagnostic)
createActionsForOverride(actual = info.a, expected = info.b)
}
Errors.NOTHING_TO_OVERRIDE -> {
val info = Errors.NOTHING_TO_OVERRIDE.cast(diagnostic)
createActionsForOverrideNothing(actual = info.a)
}
else -> emptyList()
}
}
private fun extractPotentiallyFixableTypesForExpectedType(actual: KotlinType, expected: KotlinType): Set<KotlinType> {
fun KotlinType.isNonNullable() = !this.isNullable() || this is NotNullTypeParameter
val result = mutableSetOf<KotlinType>()
if (actual.isTypeParameter() && actual.isNullable() && expected.isNonNullable()) {
result.add(actual)
}
for ((actualProjection, expectedProjection) in actual.arguments.zip(expected.arguments)) {
if (!actualProjection.isStarProjection && !expectedProjection.isStarProjection) {
result.addAll(extractPotentiallyFixableTypesForExpectedType(actualProjection.type, expectedProjection.type))
}
}
return result
}
private fun createActionsForOverride(actual: CallableMemberDescriptor, expected: CallableMemberDescriptor): List<IntentionAction> {
val result = mutableListOf<IntentionAction>()
for ((actualParameter, expectedParameter) in actual.valueParameters.zip(expected.valueParameters)) {
val actualType = actualParameter?.type ?: continue
val expectedType = expectedParameter?.type ?: continue
extractPotentiallyFixableTypesForExpectedType(actualType, expectedType).forEach {
result.addAll(createActionsForType(it))
}
}
return result
}
// Generate actions for NOTHING_TO_OVERRIDE error. The function searches for compatible override candidates
// in parent classes and tries to find an upper bound that makes the nullability of the actual function
// arguments match the candidate's arguments.
private fun createActionsForOverrideNothing(actual: CallableMemberDescriptor): List<IntentionAction> {
val functionName = actual.name
val containingClass = actual.containingDeclaration.safeAs<ClassDescriptor>() ?: return emptyList()
return containingClass.defaultType.supertypes()
.asSequence()
.flatMap { supertype -> supertype.memberScope.getContributedFunctions(functionName, NoLookupLocation.FROM_IDE) }
.filter { it.kind.isReal && it.isOverridable }
.flatMap { candidate -> createActionsForOverride(actual, candidate) }
.toList()
}
private fun createActionsForTypeMismatch(actual: KotlinType, expected: KotlinType): List<IntentionAction> {
val result = mutableListOf<IntentionAction>()
val fixableTypes = extractPotentiallyFixableTypesForExpectedType(actual, expected)
for (type in fixableTypes) {
result.addAll(createActionsForType(type, highPriority = true))
}
return result
}
private fun createActionsForType(type: KotlinType, highPriority: Boolean = false): List<IntentionAction> {
val result = mutableListOf<IntentionAction>()
for (typeParameterDescriptor in type.getTypeParameters()) {
result.addIfNotNull(createActionForTypeParameter(typeParameterDescriptor, highPriority))
}
return result
}
private fun createActionForTypeParameter(
typeParameterDescriptor: TypeParameterDescriptor,
highPriority: Boolean = false,
): IntentionAction? {
fun makeAction(typeParameter: KtTypeParameter, kind: Kind): IntentionAction {
return if (highPriority)
HighPriorityMakeUpperBoundNonNullableFix(typeParameter, kind)
else
MakeUpperBoundNonNullableFix(typeParameter, kind)
}
val psiElement = typeParameterDescriptor.psiElement?.safeAs<KtTypeParameter>() ?: return null
val existingUpperBound = psiElement.extendsBound
if (existingUpperBound != null) {
val context = existingUpperBound.analyze(BodyResolveMode.PARTIAL)
val upperBoundType = context[BindingContext.TYPE, existingUpperBound] ?: return null
if (upperBoundType.isMarkedNullable) {
return makeAction(psiElement, Kind.ReplaceExistingUpperBound(upperBoundType.makeNotNullable()))
}
} else {
return makeAction(psiElement, Kind.AddAnyAsUpperBound)
}
return null
}
}
}
/**
* A higher priority version of the parent fix for handling type mismatch errors.
* The type mismatch error (`T & Any` expected, `T` found) may usually be resolved
* by either replacing the `T` type with a definitely non-nullable type `T & Any`, or
* by adding a non-nullable upper bound constraint to the type parameter `T`.
* The latter fix is more general and does not depend on the language version settings
* of the module, so it should be proposed first.
*/
class HighPriorityMakeUpperBoundNonNullableFix(
typeParameter: KtTypeParameter,
kind: Kind
) : MakeUpperBoundNonNullableFix(typeParameter, kind),
HighPriorityAction
| apache-2.0 | 6a27c97199f5e97112bf0cf9cf851055 | 47.403162 | 158 | 0.686265 | 5.335948 | false | false | false | false |
FlexSeries/FlexLib | src/main/kotlin/me/st28/flexseries/flexlib/util/GenericDataContainer.kt | 1 | 1303 | /**
* Copyright 2016 Stealth2800 <http://stealthyone.com/>
* Copyright 2016 Contributors <https://github.com/FlexSeries>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.st28.flexseries.flexlib.util
import java.util.*
open class GenericDataContainer {
protected val data: MutableMap<String, Any?> = HashMap()
fun isSet(name: String): Boolean = data.containsKey(name)
operator fun <T> get(name: String, defaultValue: (() -> T)? = null) : T? {
return data[name] as T ?: defaultValue?.invoke() ?: null
}
fun <T> getOrPut(name: String, defaultValue: () -> T) : T {
return data.getOrPut(name, defaultValue) as T
}
fun set(name: String, value: Any?) = data.put(name, value)
fun remove(name: String): Any? = data.remove(name)
}
| apache-2.0 | ddb758c74f2a965d6c0ce76689c7b3da | 32.410256 | 78 | 0.691481 | 3.877976 | false | false | false | false |
GunoH/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookIntervalPointersEvent.kt | 2 | 2111 | package org.jetbrains.plugins.notebooks.visualization
/**
* passed to [NotebookIntervalPointerFactory.ChangeListener] in next cases:
* * Underlying document is changed. (in such case cellLinesEvent != null)
* * Someone explicitly swapped two pointers or invalidated them by calling [NotebookIntervalPointerFactory.modifyPointers]
* * one of upper changes was reverted or redone. See corresponding [EventSource]
*
* Changes represented as list of trivial changes. [Change]
* Intervals which was just moved are not mentioned in changes. For example, when inserting code before them.
*/
data class NotebookIntervalPointersEvent(val changes: List<Change>,
val cellLinesEvent: NotebookCellLinesEvent?,
val source: EventSource) {
enum class EventSource {
ACTION, UNDO_ACTION, REDO_ACTION
}
data class PointerSnapshot(val pointer: NotebookIntervalPointer, val interval: NotebookCellLines.Interval)
/**
* any change contains enough information to be inverted. It simplifies undo/redo actions.
*/
sealed interface Change
data class OnInserted(val subsequentPointers: List<PointerSnapshot>) : Change {
val ordinals = subsequentPointers.first().interval.ordinal..subsequentPointers.last().interval.ordinal
}
/* snapshots contains intervals before removal */
data class OnRemoved(val subsequentPointers: List<PointerSnapshot>) : Change {
val ordinals = subsequentPointers.first().interval.ordinal..subsequentPointers.last().interval.ordinal
}
data class OnEdited(val pointer: NotebookIntervalPointer,
val intervalBefore: NotebookCellLines.Interval,
val intervalAfter: NotebookCellLines.Interval) : Change {
val ordinal: Int
get() = intervalAfter.ordinal
}
/* snapshots contains intervals after swap */
data class OnSwapped(val first: PointerSnapshot, val second: PointerSnapshot) : Change {
val firstOrdinal: Int
get() = first.interval.ordinal
val secondOrdinal: Int
get() = second.interval.ordinal
}
} | apache-2.0 | f0e0a12b1b7ef6aa899c573c5922cd66 | 40.411765 | 123 | 0.720985 | 4.978774 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/decompiler/stubBuilder/TypeParams/TypeParams.kt | 15 | 1287 | package test
import java.io.Serializable
class TypeParams<in T1 : Any, out T2, T3 : (Int) -> Int, T4, T5 : Any?, T6 : T5, T7> where T1 : Cloneable?, T1 : Serializable, T2 : String, T7 : T6 {
fun useParams(p1: T1, p2: (T2) -> Unit, p3: T3, p4: T4, P5: T5) {
}
fun useParamsInOtherOrder(p1: T3, p2: T3, p3: T1, p4: T5, P5: T1) {
}
fun useParamsInTypeArg(p1: List<T1>, p2: Map<T4?, T5?>, p3: (T4).(T2, T3) -> T1) {
}
fun <G1, G2, G3> withOwnParams(p1: G1, p2: G2, p3: G3, p4: T1, p5: (T2) -> Unit) {
}
fun <G1 : Any?, G2 : G1, G3, G4> withOwnParamsAndTypeConstraints(p1: G1, p2: G2, p3: G3, p4: T1, p5: (T2) -> Unit) where G4 : G1, G3 : String, G3 : Serializable? {
}
fun <T1, T2, T3> withOwnParamsClashing(p1: T1, p2: T2, p3: T3, p4: T4, p5: T5) {
}
fun <T1> T1.withOwnParamExtension(p: T1) {
}
val <G1> G1.withOwnParam: G1
get() = throw IllegalStateException()
val <G1: Int?> G1.withOwnBoundedParam: G1
get() = throw IllegalStateException()
val <G1: T4> G1.withOwnBoundedParamByOther: G1
get() = throw IllegalStateException()
val useSomeParam: T2
get() = throw IllegalStateException()
public inline fun <reified G, reified T> f(g: G, body: (G)-> T): T = body(g)
} | apache-2.0 | 28b5ce7ff586c3b44e19e21bc3eea231 | 28.272727 | 167 | 0.582751 | 2.414634 | false | false | false | false |
kondroid00/SampleProject_Android | app/src/main/java/com/kondroid/sampleproject/activity/ChatActivity.kt | 1 | 4329 | package com.kondroid.sampleproject.activity
import android.content.Context
import android.databinding.DataBindingUtil
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.inputmethod.InputMethodManager
import com.kondroid.sampleproject.R
import com.kondroid.sampleproject.auth.AccountManager
import com.kondroid.sampleproject.databinding.ActivityChatBinding
import com.kondroid.sampleproject.dto.websocket.WebSocketActionDto
import com.kondroid.sampleproject.dto.websocket.WebSocketErrorDto
import com.kondroid.sampleproject.dto.websocket.WebSocketMessageDto
import com.kondroid.sampleproject.helper.makeWeak
import com.kondroid.sampleproject.logic.WebSocketLogic
import com.kondroid.sampleproject.view.adapter.ChatListAdapter
import com.kondroid.sampleproject.viewmodel.ChatViewModel
import kotlinx.android.synthetic.main.activity_chat.*
import org.java_websocket.framing.CloseFrame
class ChatActivity : BaseActivity(), WebSocketLogic.Delegate {
private lateinit var recyclerView: RecyclerView
private lateinit var chatListAdapter: ChatListAdapter
private lateinit var vm: ChatViewModel
private val webSocketLogic = WebSocketLogic(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var binding = DataBindingUtil.setContentView<ActivityChatBinding>(this, R.layout.activity_chat)
vm = ChatViewModel(this)
binding.vm = vm
vm.initVM()
val roomId = intent.getStringExtra("roomId")
val roomName = intent.getStringExtra("roomName")
setTitle(roomName)
webSocketLogic.delegate = makeWeak(this)
webSocketLogic.connect(roomId)
val weakSelf = makeWeak(this)
vm.onTapSend = {
weakSelf.get()?.sendMessage()
}
setUpRecyclerView()
setUpCallback()
}
override fun onStop() {
super.onStop()
vm.release()
}
override fun onDestroy() {
super.onDestroy()
webSocketLogic.disconnect()
}
private fun setUpRecyclerView() {
recyclerView = chatRecyclerView
recyclerView.setHasFixedSize(true)
val layoutManager = LinearLayoutManager(this)
recyclerView.layoutManager = layoutManager
chatListAdapter = ChatListAdapter(this)
recyclerView.adapter = chatListAdapter
}
private fun setUpCallback() {
val weakSelf = makeWeak(this)
vm.onTapSend = { weakSelf.get()?.sendMessage() }
}
private fun sendMessage() {
webSocketLogic.sendMessage(vm.inputText.get())
vm.clearInput()
val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
manager.hideSoftInputFromWindow(currentFocus.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
//-------------------------------------------------------------------------------------------
// WebSocketLogic Delegate
//-------------------------------------------------------------------------------------------
override fun onOpen() {
AccountManager.user?.let {
webSocketLogic.sendJoin(it)
}
}
override fun onClose(code: Int, reason: String?, remote: Boolean) {
when (code) {
CloseFrame.NEVER_CONNECTED -> {
val weakSelf = makeWeak(this)
showAlert(getString(R.string.alert_socket_error_connect_failed), handler1 = {
weakSelf.get()?.finish()
})
}
CloseFrame.ABNORMAL_CLOSE, CloseFrame.GOING_AWAY -> {
showAlert(getString(R.string.alert_socket_error_connecting_failed))
}
}
}
override fun onReceiveJoined(data: WebSocketActionDto) {
chatListAdapter.clientNo = webSocketLogic.clientNo
}
override fun onReceiveRemoved(data: WebSocketActionDto) {
}
override fun onReceiveMessage(data: WebSocketMessageDto) {
vm.addMessage(data)
chatListAdapter.setMessages(vm.messages)
recyclerView.scrollToPosition(chatListAdapter.itemCount - 1)
}
override fun onReceiveError(data: WebSocketErrorDto) {
}
}
| mit | aeea46d32af1ccccd2c4a15c8fa5dcfd | 32.55814 | 103 | 0.672904 | 5.117021 | false | false | false | false |
ktorio/ktor | ktor-network/ktor-network-tls/jvm/src/io/ktor/network/tls/TLSConfigBuilder.kt | 1 | 4276 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.network.tls
import kotlinx.coroutines.*
import java.security.*
import java.security.cert.*
import java.security.cert.Certificate
import javax.net.ssl.*
/**
* [TLSConfig] builder.
*/
public actual class TLSConfigBuilder {
/**
* List of client certificate chains with private keys.
*/
public val certificates: MutableList<CertificateAndKey> = mutableListOf()
/**
* [SecureRandom] to use in encryption.
*/
public var random: SecureRandom? = null
/**
* Custom [X509TrustManager] to verify server authority.
*
* Use system by default.
*/
public var trustManager: TrustManager? = null
set(value) {
value?.let {
check(it is X509TrustManager) {
"Failed to set [trustManager]: $value. Only [X509TrustManager] supported."
}
}
field = value
}
/**
* List of allowed [CipherSuite]s.
*/
public var cipherSuites: List<CipherSuite> = CIOCipherSuites.SupportedSuites
/**
* Custom server name for TLS server name extension.
* See also: https://en.wikipedia.org/wiki/Server_Name_Indication
*/
public actual var serverName: String? = null
/**
* Create [TLSConfig].
*/
public actual fun build(): TLSConfig = TLSConfig(
random ?: SecureRandom(),
certificates,
trustManager as? X509TrustManager ?: findTrustManager(),
cipherSuites,
serverName
)
}
/**
* Append config from [other] builder.
*/
public actual fun TLSConfigBuilder.takeFrom(other: TLSConfigBuilder) {
certificates += other.certificates
random = other.random
cipherSuites = other.cipherSuites
serverName = other.serverName
trustManager = other.trustManager
}
/**
* Add client certificate chain to use.
*/
public fun TLSConfigBuilder.addCertificateChain(chain: Array<X509Certificate>, key: PrivateKey) {
certificates += CertificateAndKey(chain, key)
}
/**
* Add client certificates from [store] by using the certificate with specific [alias]
* or all certificates, if [alias] is null.
*/
@JvmName("addKeyStoreNullablePassword")
public fun TLSConfigBuilder.addKeyStore(store: KeyStore, password: CharArray?, alias: String? = null) {
val keyManagerAlgorithm = KeyManagerFactory.getDefaultAlgorithm()!!
val keyManagerFactory = KeyManagerFactory.getInstance(keyManagerAlgorithm)!!
keyManagerFactory.init(store, password)
val managers = keyManagerFactory.keyManagers.filterIsInstance<X509KeyManager>()
val aliases = alias?.let { listOf(it) } ?: store.aliases()!!.toList()
loop@ for (certAlias in aliases) {
val chain: Array<Certificate>? = store.getCertificateChain(certAlias)
checkNotNull(chain) { "Fail to get the certificate chain for this alias: $certAlias" }
val allX509 = chain.all { it is X509Certificate }
check(allX509) { "Fail to add key store $store. Only X509 certificate format supported." }
for (manager in managers) {
val key = manager.getPrivateKey(certAlias) ?: continue
val map = chain.map { it as X509Certificate }
addCertificateChain(map.toTypedArray(), key)
continue@loop
}
throw NoPrivateKeyException(certAlias, store)
}
}
/**
* Throws if failed to find [PrivateKey] for any alias in [KeyStore].
*/
@OptIn(ExperimentalCoroutinesApi::class)
public class NoPrivateKeyException(
private val alias: String,
private val store: KeyStore
) : IllegalStateException("Failed to find private key for alias $alias. Please check your key store: $store"),
CopyableThrowable<NoPrivateKeyException> {
override fun createCopy(): NoPrivateKeyException? = NoPrivateKeyException(alias, store).also {
it.initCause(this)
}
}
private fun findTrustManager(): X509TrustManager {
val factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())!!
factory.init(null as KeyStore?)
val manager = factory.trustManagers!!
return manager.filterIsInstance<X509TrustManager>().first()
}
| apache-2.0 | c9fb1b8535b6f408a792851a6f1396e9 | 30.211679 | 118 | 0.680543 | 4.592911 | false | true | false | false |
armcha/Ribble | app/src/main/kotlin/io/armcha/ribble/presentation/widget/AnimatedImageView.kt | 1 | 704 | package io.armcha.ribble.presentation.widget
import android.content.Context
import android.support.v7.widget.AppCompatImageView
import android.util.AttributeSet
/**
* Created by Chatikyan on 16.02.2017.
*/
class AnimatedImageView(context: Context, attrs: AttributeSet? = null)
: AppCompatImageView(context, attrs), AnimatedView {
fun setAnimatedImage(newImage: Int, startDelay: Long = 0L) {
changeImage(newImage, startDelay)
}
private fun changeImage(newImage: Int, startDelay: Long) {
if (tag == newImage)
return
animate(view = this, startDelay = startDelay) {
setImageResource(newImage)
tag = newImage
}
}
} | apache-2.0 | edd3870fd28c8e3bcbd25b8a380ef964 | 26.115385 | 70 | 0.678977 | 4.4 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/util/MemberReference.kt | 1 | 5108 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.util
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiField
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiMethod
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.containers.stream
import org.jetbrains.annotations.Contract
import java.io.Serializable
import java.util.stream.Stream
/**
* Represents a reference to a class member (a method or a field). It may
* resolve to multiple members if [matchAll] is set or if the member is
* not full qualified.
*/
data class MemberReference(
val name: String,
val descriptor: String? = null,
val owner: String? = null,
val matchAll: Boolean = false
) : Serializable {
@get:Contract(pure = true)
val qualified
get() = this.owner != null
@get:Contract(pure = true)
val withoutOwner
get() = if (this.owner == null) this else MemberReference(this.name, this.descriptor, null, this.matchAll)
@Contract(pure = true)
fun matchOwner(psiClass: PsiClass): Boolean {
return this.owner == null || this.owner == psiClass.fullQualifiedName
}
@Contract(pure = true)
fun match(method: PsiMethod, qualifier: PsiClass): Boolean {
return this.name == method.internalName && matchOwner(qualifier)
&& (this.descriptor == null || this.descriptor == method.descriptor)
}
@Contract(pure = true)
fun match(field: PsiField, qualifier: PsiClass): Boolean {
return this.name == field.name && matchOwner(qualifier)
&& (this.descriptor == null || this.descriptor == field.descriptor)
}
fun resolve(project: Project, scope: GlobalSearchScope = GlobalSearchScope.allScope(project)): Pair<PsiClass, PsiMember>? {
return resolve(project, scope, ::Pair)
}
fun resolveMember(project: Project, scope: GlobalSearchScope = GlobalSearchScope.allScope(project)): PsiMember? {
return resolve(project, scope) { _, member -> member }
}
@Contract(pure = true)
private inline fun <R> resolve(project: Project, scope: GlobalSearchScope, ret: (PsiClass, PsiMember) -> R): R? {
if (this.owner == null) {
throw IllegalStateException("Cannot resolve unqualified member reference (owner == null)")
}
val psiClass = findQualifiedClass(project, this.owner, scope) ?: return null
val member: PsiMember? = if (descriptor != null && descriptor.startsWith('(')) {
// Method, we assume there is only one (since this member descriptor is full qualified)
psiClass.findMethods(this, checkBases = true).findAny().orElse(null)
} else {
// Field
psiClass.findField(this, checkBases = true)
}
return member?.let { ret(psiClass, member) }
}
}
// Class
@Contract(pure = true)
fun PsiClass.findMethods(member: MemberReference, checkBases: Boolean = false): Stream<PsiMethod> {
if (!member.matchOwner(this)) {
return Stream.empty()
}
val result = findMethodsByInternalName(member.name, checkBases)
return if (member.descriptor != null) {
result.stream().filter { it.descriptor == member.descriptor }
} else {
result.stream()
}
}
@Contract(pure = true)
fun PsiClass.findField(member: MemberReference, checkBases: Boolean = false): PsiField? {
if (!member.matchOwner(this)) {
return null
}
val field = findFieldByName(member.name, checkBases) ?: return null
if (member.descriptor != null && member.descriptor != field.descriptor) {
return null
}
return field
}
// Method
@get:Contract(pure = true)
val PsiMethod.memberReference
get() = MemberReference(internalName, descriptor)
@get:Contract(pure = true)
val PsiMethod.qualifiedMemberReference
get() = MemberReference(internalName, descriptor, containingClass!!.fullQualifiedName)
@Contract(pure = true)
fun PsiMethod.getQualifiedMemberReference(owner: PsiClass): MemberReference {
return MemberReference(internalName, descriptor, owner.fullQualifiedName)
}
fun PsiMethod?.isSameReference(reference: PsiMethod?): Boolean =
this != null && (this === reference || qualifiedMemberReference == reference?.qualifiedMemberReference)
// Field
@get:Contract(pure = true)
val PsiField.simpleMemberReference
get() = MemberReference(name)
@get:Contract(pure = true)
val PsiField.memberReference
get() = MemberReference(name, descriptor)
@get:Contract(pure = true)
val PsiField.simpleQualifiedMemberReference
get() = MemberReference(name, null, containingClass!!.fullQualifiedName)
@get:Contract(pure = true)
val PsiField.qualifiedMemberReference
get() = MemberReference(name, descriptor, containingClass!!.fullQualifiedName)
@Contract(pure = true)
fun PsiField.getQualifiedMemberReference(owner: PsiClass): MemberReference {
return MemberReference(name, descriptor, owner.fullQualifiedName)
}
| mit | e62efdd32ba440f54a6df78439b56bbf | 30.925 | 127 | 0.695576 | 4.362084 | false | false | false | false |
rellermeyer/99tsp | kotlin/greedy/TravelingSalesman.kt | 1 | 3298 | import java.io.File
import java.util.*
import java.util.regex.Pattern
/**
* TravelingSalesman
*
* @author Ian Caffey
* @since 1.0
*/
//regex for node line
val LINE_PATTERN: Pattern = Pattern.compile("\\s+")
fun main(args: Array<String>) {
//Read all node lines from file, parse into Triple<Int, Int, Int>, and solve
File(args[0] + ".tsp").readLines().filterNotNull().
/*primitive filtering of non-node lines*/
filter { it.indexOf(":") == -1 && it != "NODE_COORD_SECTION" && it != "EOF" }.
map(String::trim).map(::parse).apply(::solve)
}
/**
* Solves the Traveling Salesman problem given a collection of nodes which represent a graph.
*
* @param nodes the graph of node triples(first -> id, second -> x, third -> y)
*/
fun solve(nodes: List<Triple<Int, Int, Int>>) {
var distance = 0
val unvisited = ArrayList<Triple<Int, Int, Int>>(nodes)
val path = ArrayList<Triple<Int, Int, Int>>()
val start = nodes[(Math.random() * nodes.size).toInt()] //begin path at random node
path.add(start)
unvisited.remove(start) //prune start to manually create path from last node to start
while (unvisited.isNotEmpty()) {
val (nearestDistance, nearest) = nearest(path.last(), unvisited)
distance += nearestDistance
path.add(nearest)
unvisited.remove(nearest)
}
println("Distance: " + (distance + distance(start, path.last())))
path.forEach { println(it.first) }
println(-1)
}
/**
* Calculates the nearest nodes within a collection of nodes.
*
* @param start the start node triple(second -> x, third -> y)
* @param neighbors the neighbor node tripls
* @return a {@code Pair} consisting of the distance and the nearest node triple
* @see distance
*/
fun nearest(start: Triple<Int, Int, Int>, neighbors: Iterable<Triple<Int, Int, Int>>): Pair<Int, Triple<Int, Int, Int>> {
var nearest: Triple<Int, Int, Int> = Triple(0, 0, 0)
var nearestDistance = Int.MAX_VALUE
neighbors.forEach {
val distance = distance(start, it)
if (distance < nearestDistance) {
nearest = it
nearestDistance = distance
}
}
return Pair(nearestDistance, nearest)
}
/**
* Calculates the Euclidean distance between two node triples.
*
* @param source the source node triple(second -> x, third -> y)
* @param destination the destination node triple(second -> x, third -> y)
* @return the euclidean distance rounded using {@code nint((int) x + 0.5)}
*/
fun distance(source: Triple<Int, Int, Int>, destination: Triple<Int, Int, Int>): Int {
return (Math.sqrt(Math.pow((source.second - destination.second).toDouble(), 2.0) +
Math.pow((source.third - destination.third).toDouble(), 2.0)) + 0.5).toInt()
}
/**
* Parses a trimmed space-delimited line of 3 numbers into a new {@code Triple<Int, Int, Int>}.
*
* @param line the input number string
* @return a new {@code Triple<Int, Int, Int>}
*/
fun parse(line: String): Triple<Int, Int, Int> {
val parts = line.split(LINE_PATTERN)
if (parts.size != 3)
throw IllegalStateException("Malformed line. Expected 3 space-delimited numbers. Actual: " + parts)
return Triple(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), Integer.parseInt(parts[2]))
} | bsd-3-clause | 25d5b10a92b750f7084238aaea3164c1 | 36.067416 | 121 | 0.65282 | 3.64823 | false | false | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/dalatlaptop/ux/fragments/DrawerFragment.kt | 1 | 13714 | package com.tungnui.dalatlaptop.ux.fragments
import android.os.Bundle
import android.os.SystemClock
import android.support.design.widget.NavigationView
import android.support.v4.app.Fragment
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.Toolbar
import android.util.Log
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.tungnui.dalatlaptop.CONST
import com.tungnui.dalatlaptop.MyApplication
import com.tungnui.dalatlaptop.R
import com.tungnui.dalatlaptop.SettingsMy
import com.tungnui.dalatlaptop.ux.adapters.DrawerRecyclerAdapter
import com.tungnui.dalatlaptop.api.CategoryService
import com.tungnui.dalatlaptop.api.ServiceGenerator
import com.tungnui.dalatlaptop.models.Category
import com.tungnui.dalatlaptop.utils.loadImg
import com.tungnui.dalatlaptop.ux.MainActivity
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_drawer.*
class DrawerFragment : Fragment(), NavigationView.OnNavigationItemSelectedListener {
private var mCompositeDisposable: CompositeDisposable
val categoryService: CategoryService
init {
mCompositeDisposable = CompositeDisposable()
categoryService = ServiceGenerator.createService(CategoryService::class.java)
}
private var drawerLoading = false
private lateinit var drawerListener: FragmentDrawerListener
private lateinit var mDrawerToggle: ActionBarDrawerToggle
private lateinit var mDrawerLayout: DrawerLayout
private lateinit var drawerMenuRecyclerAdapter: DrawerRecyclerAdapter
private lateinit var drawerSubmenuRecyclerAdapter: DrawerRecyclerAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_drawer, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
nav_view.setNavigationItemSelectedListener(this)
drawer_menu_retry_btn.setOnClickListener {
if (!drawerLoading)
getDrawerItems()
}
prepareDrawerRecycler()
drawer_menu_back_btn.setOnClickListener(object : View.OnClickListener {
private var mLastClickTime: Long = 0
override fun onClick(v: View) {
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000)
return
mLastClickTime = SystemClock.elapsedRealtime()
animateMenuHide()
}
})
drawer_submenu_back_btn.setOnClickListener(object : View.OnClickListener {
private var mLastClickTime: Long = 0
override fun onClick(v: View) {
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000)
return
mLastClickTime = SystemClock.elapsedRealtime()
animateSubMenuHide()
}
})
val headerView = nav_view.getHeaderView(0)
headerView.setOnClickListener { _ ->
drawerListener?.onAccountSelected()
toggleDrawerMenu()
}
invalidateHeader()
}
private fun prepareDrawerRecycler() {
drawerMenuRecyclerAdapter = DrawerRecyclerAdapter { category ->
if (category.display != "subcategories") {
drawerListener?.onDrawerItemCategorySelected(category)
toggleDrawerMenu()
} else
animateSubMenuShow(category)
}
drawer_menu_recycler.layoutManager = LinearLayoutManager(context)
drawer_menu_recycler.setHasFixedSize(true)
drawer_menu_recycler.adapter = drawerMenuRecyclerAdapter
drawerSubmenuRecyclerAdapter = DrawerRecyclerAdapter { category ->
drawerListener?.onDrawerItemCategorySelected(category)
toggleDrawerMenu()
}
drawer_submenu_recycler.layoutManager = LinearLayoutManager(context)
drawer_submenu_recycler.itemAnimator = DefaultItemAnimator()
drawer_submenu_recycler.setHasFixedSize(true)
drawer_submenu_recycler.adapter = drawerSubmenuRecyclerAdapter
}
fun setUp(drawerLayout: DrawerLayout, toolbar: Toolbar, eventsListener: FragmentDrawerListener) {
mDrawerLayout = drawerLayout
this.drawerListener = eventsListener
mDrawerToggle = object : ActionBarDrawerToggle(activity, drawerLayout, toolbar, R.string.content_description_open_navigation_drawer, R.string.content_description_close_navigation_drawer) {
override fun onDrawerOpened(drawerView: View?) {
super.onDrawerOpened(drawerView)
activity.invalidateOptionsMenu()
}
override fun onDrawerClosed(drawerView: View?) {
super.onDrawerClosed(drawerView)
activity.invalidateOptionsMenu()
}
override fun onDrawerSlide(drawerView: View?, slideOffset: Float) {
super.onDrawerSlide(drawerView, slideOffset)
// toolbar.setAlpha(1 - slideOffset / 2);
}
}
toolbar.setOnClickListener { toggleDrawerMenu() }
mDrawerLayout.addDrawerListener(mDrawerToggle)
mDrawerLayout.post { mDrawerToggle.syncState() }
}
fun toggleDrawerMenu() {
if (mDrawerLayout.isDrawerVisible(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START)
} else {
mDrawerLayout.openDrawer(GravityCompat.START)
}
}
fun closeDrawerMenu() {
mDrawerLayout.closeDrawer(GravityCompat.START)
}
fun onBackHide(): Boolean {
mDrawerLayout.let {
if (it.isDrawerVisible(GravityCompat.START)) {
if (drawer_submenu_layout.visibility == View.VISIBLE) {
animateSubMenuHide()
} else
it.closeDrawer(GravityCompat.START)
return true
}
}
return false
}
fun invalidateHeader() {
val headerView = nav_view.getHeaderView(0)
val txtUserName = headerView.findViewById<TextView>(R.id.navigation_drawer_list_header_text)
val avatarImage = headerView.findViewById<ImageView>(R.id.navigation_drawer_header_avatar)
val user = SettingsMy.getActiveUser()
if (user != null) {
txtUserName.text = user.username
if (user.avatarUrl == null) {
avatarImage.setImageResource(R.drawable.user)
} else {
avatarImage.loadImg(user.avatarUrl)
}
}else{
txtUserName.text = "Xin chào, Khách!"
avatarImage.setImageResource(R.drawable.user)
}
}
private fun getDrawerItems() {
}
private fun animateSubMenuHide() {
val slideAwayDisappear = AnimationUtils.loadAnimation(activity, R.anim.slide_away_disappear)
val slideAwayAppear = AnimationUtils.loadAnimation(activity, R.anim.slide_away_appear)
slideAwayDisappear.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
drawer_menu_layout.visibility = View.VISIBLE
drawer_menu_layout.startAnimation(slideAwayAppear)
}
override fun onAnimationEnd(animation: Animation) {
drawer_submenu_layout.visibility = View.GONE
}
override fun onAnimationRepeat(animation: Animation) {}
})
drawer_submenu_layout.startAnimation(slideAwayDisappear)
}
private fun animateMenuHide() {
val slideAwayDisappear = AnimationUtils.loadAnimation(activity, R.anim.slide_away_disappear)
val slideAwayAppear = AnimationUtils.loadAnimation(activity, R.anim.slide_away_appear)
slideAwayDisappear.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
nav_view.visibility = View.VISIBLE
nav_view.startAnimation(slideAwayAppear)
}
override fun onAnimationEnd(animation: Animation) {
drawer_menu_layout.visibility = View.GONE
}
override fun onAnimationRepeat(animation: Animation) {}
})
drawer_menu_layout.startAnimation(slideAwayDisappear)
}
private fun animateMenuShow() {
val slideInDisappear = AnimationUtils.loadAnimation(activity, R.anim.slide_in_disappear)
val slideInAppear = AnimationUtils.loadAnimation(activity, R.anim.slide_in_appear)
slideInDisappear.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
drawer_menu_layout.visibility = View.VISIBLE
drawer_menu_layout.startAnimation(slideInAppear)
}
override fun onAnimationEnd(animation: Animation) {
nav_view.visibility = View.GONE
}
override fun onAnimationRepeat(animation: Animation) {}
})
nav_view.startAnimation(slideInDisappear)
drawerLoading = true
if (drawerMenuRecyclerAdapter.itemCount == 0)
drawer_menu_progress.visibility = View.VISIBLE
var disposable = categoryService.getCategory()
.subscribeOn((Schedulers.io()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ items ->
drawer_menu_progress.visibility = View.GONE
drawer_menu_retry_btn.visibility = View.GONE
drawerMenuRecyclerAdapter.changeDrawerItems(items)
drawerLoading = false
},
{ _ ->
drawerLoading = false
drawer_menu_progress.visibility = View.GONE
drawer_menu_retry_btn.visibility = View.VISIBLE
})
mCompositeDisposable.add(disposable)
}
private fun animateSubMenuShow(category: Category) {
val slideInDisappear = AnimationUtils.loadAnimation(activity, R.anim.slide_in_disappear)
val slideInAppear = AnimationUtils.loadAnimation(activity, R.anim.slide_in_appear)
slideInDisappear.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation) {
drawer_submenu_layout.visibility = View.VISIBLE
drawer_submenu_layout.startAnimation(slideInAppear)
}
override fun onAnimationEnd(animation: Animation) {
drawer_menu_layout.visibility = View.GONE
}
override fun onAnimationRepeat(animation: Animation) {}
})
drawer_menu_layout.startAnimation(slideInDisappear)
drawer_submenu_back_btn.text = category.name
if (drawerSubmenuRecyclerAdapter.itemCount == 0)
drawer_submenu_progress.visibility = View.VISIBLE
var disposable = categoryService.getChildrenCategory(category.id!!)
.subscribeOn((Schedulers.io()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ items ->
drawer_submenu_progress.visibility = View.GONE
drawer_submenu_retry_btn.visibility = View.GONE
drawerSubmenuRecyclerAdapter.changeDrawerItems(items)
drawerLoading = false
},
{ _ ->
drawer_submenu_progress.visibility = View.GONE
drawer_submenu_retry_btn.visibility = View.VISIBLE
})
mCompositeDisposable.add(disposable)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.nav_home -> {
drawerListener.onDrawerHomeSelected()
toggleDrawerMenu()
}
R.id.nav_category -> animateMenuShow()
R.id.nav_cart -> {
drawerListener.onDrawerCartSelected()
toggleDrawerMenu()
}
R.id.nav_order -> {
drawerListener.onDrawerOrderSelected()
toggleDrawerMenu()
}
}
return true;
}
override fun onPause() {
if (drawerLoading) {
drawer_menu_progress.visibility = View.GONE
drawer_menu_retry_btn.visibility = View.VISIBLE
drawerLoading = false
}
super.onPause()
}
override fun onDestroy() {
mDrawerLayout?.removeDrawerListener(mDrawerToggle)
super.onDestroy()
}
interface FragmentDrawerListener {
fun onDrawerItemCategorySelected(category: Category)
fun onAccountSelected()
fun onDrawerCartSelected()
fun onDrawerOrderSelected()
fun onDrawerHomeSelected()
fun onDrawerSettingSelected()
}
}
| mit | 86e114eb931d9cc80756a904ca26f3cc | 38.065527 | 196 | 0.650598 | 5.567194 | false | false | false | false |
DreierF/MyTargets | shared/src/main/java/de/dreier/mytargets/shared/models/db/SightMark.kt | 1 | 1456 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.shared.models.db
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.ForeignKey.CASCADE
import androidx.room.Index
import androidx.room.PrimaryKey
import android.os.Parcelable
import de.dreier.mytargets.shared.models.Dimension
import de.dreier.mytargets.shared.models.Dimension.Unit.METER
import de.dreier.mytargets.shared.models.IIdSettable
import kotlinx.android.parcel.Parcelize
@Parcelize
@Entity(
foreignKeys = [
ForeignKey(
entity = Bow::class,
parentColumns = ["id"],
childColumns = ["bowId"],
onDelete = CASCADE
)
],
indices = [
Index(value = ["bowId"])
]
)
data class SightMark(
@PrimaryKey(autoGenerate = true)
override var id: Long = 0,
var bowId: Long? = null,
var distance: Dimension = Dimension(18f, METER),
var value: String? = ""
) : IIdSettable, Parcelable
| gpl-2.0 | 0dae44338c6df1922f50e04c6f3cf1ac | 29.333333 | 68 | 0.708791 | 4.112994 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/forge/inspections/sideonly/SidedProxyAnnotator.kt | 1 | 2980 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.forge.inspections.sideonly
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.forge.ForgeModuleType
import com.demonwav.mcdev.platform.forge.util.ForgeConstants
import com.google.common.base.Strings
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiAnnotationMemberValue
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiField
import com.intellij.psi.PsiReferenceExpression
import com.intellij.psi.impl.JavaConstantExpressionEvaluator
import com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl
import com.intellij.psi.search.GlobalSearchScope
class SidedProxyAnnotator : Annotator {
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
if (element !is PsiField) {
return
}
val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return
val instance = MinecraftFacet.getInstance(module) ?: return
if (!instance.isOfType(ForgeModuleType)) {
return
}
check(element)
}
companion object {
fun check(field: PsiField) {
val modifierList = field.modifierList ?: return
val annotation = modifierList.findAnnotation(ForgeConstants.SIDED_PROXY_ANNOTATION) ?: return
val clientSide = annotation.findAttributeValue("clientSide")
val serverSide = annotation.findAttributeValue("serverSide")
if (clientSide != null && !Strings.isNullOrEmpty(clientSide.text)) {
annotateClass(clientSide, Side.CLIENT)
}
if (serverSide != null && !Strings.isNullOrEmpty(serverSide.text)) {
annotateClass(serverSide, Side.SERVER)
}
}
private fun annotateClass(value: PsiAnnotationMemberValue, side: Side) {
val text: String?
if (value is PsiLiteralExpressionImpl) {
text = value.innerText
if (text == null) {
return
}
} else if (value is PsiReferenceExpression) {
val resolve = value.resolve() as? PsiField ?: return
text = JavaConstantExpressionEvaluator.computeConstantExpression(
resolve.initializer,
null,
false
) as? String ?: return
} else {
return
}
val psiClass =
JavaPsiFacade.getInstance(value.project).findClass(text, GlobalSearchScope.allScope(value.project))
?: return
psiClass.putUserData(Side.KEY, side)
}
}
}
| mit | 46f07c6b38c56a2db8dfeb664ad649f3 | 32.111111 | 115 | 0.647651 | 5.120275 | false | false | false | false |
noboru-i/SlideViewer | app/src/main/java/hm/orz/chaos114/android/slideviewer/widget/SlideListRowView.kt | 1 | 1243 | package hm.orz.chaos114.android.slideviewer.widget
import android.content.Context
import android.databinding.DataBindingUtil
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.RelativeLayout
import com.bumptech.glide.Glide
import hm.orz.chaos114.android.slideviewer.R
import hm.orz.chaos114.android.slideviewer.databinding.ViewSlideListRowBinding
import hm.orz.chaos114.android.slideviewer.infra.model.Slide
import hm.orz.chaos114.android.slideviewer.infra.model.TalkMetaData
class SlideListRowView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
private val binding: ViewSlideListRowBinding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.view_slide_list_row, this, true)
fun bind(slides: List<Slide>?, talkMetaData: TalkMetaData?) {
slides?.let {
Glide.with(context).load(it[0].preview).into(binding.slideListRowImage)
}
talkMetaData?.let {
binding.slideListRowTitle.text = it.title
binding.slideListRowUser.text = context.getString(R.string.slide_list_author, it.user)
}
}
}
| mit | 062d75fc5329c8f215d305ff256cee99 | 36.666667 | 146 | 0.752212 | 4.062092 | false | false | false | false |
BreakOutEvent/breakout-backend | src/main/java/backend/model/posting/PostingServiceImpl.kt | 1 | 6185 | package backend.model.posting
import backend.controller.exceptions.BadRequestException
import backend.exceptions.DomainException
import backend.model.location.Location
import backend.model.location.LocationService
import backend.model.media.Media
import backend.model.media.MediaService
import backend.model.misc.Coord
import backend.model.user.Participant
import backend.model.user.User
import backend.model.user.UserAccount
import backend.services.NotificationService
import org.springframework.data.domain.PageRequest
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDateTime
@Service
class PostingServiceImpl(private val repository: PostingRepository,
private val notificationService: NotificationService,
private val locationService: LocationService,
private val mediaService: MediaService) : PostingService {
override fun removeComment(posting: Posting, commentId: Long) {
posting.removeComment(commentId)
this.save(posting)
}
// TODO: This should return Posting (will break API)
override fun addComment(posting: Posting, from: UserAccount, at: LocalDateTime, withText: String): Comment {
val comment = posting.addComment(from, at, withText)
this.save(posting)
val users = posting.team!!.members.map { it.account }.filter { it.id != from.id && !it.isBlocking(from) }
notificationService.notifyNewComment(comment, posting, users)
return comment
}
// TODO: This should return Posting (will break API)
override fun like(posting: Posting, account: UserAccount, timeCreated: LocalDateTime): Like {
val like = posting.like(timeCreated, account)
this.save(posting)
val users = posting.team!!.members.map { it.account }.filter { it.id != account.id && !it.isBlocking(account) }
notificationService.notifyNewLike(like, posting, users)
return like // TODO: Transactional?
}
override fun unlike(by: UserAccount, from: Posting) {
from.unlike(by)
this.save(from)
}
override fun save(posting: Posting): Posting = repository.save(posting)!!
override fun findAll(page: Int, size: Int): List<Posting> = repository.findAllByOrderByIdDesc(PageRequest(page, size))
override fun findByEventIds(events: List<Long>, page: Int, size: Int): List<Posting> {
return repository.findByTeamEventIdInOrderByIdDesc(events, PageRequest(page, size))
}
override fun findReported(): List<Posting> = repository.findReported()
@Transactional
override fun savePostingWithLocationAndMedia(text: String?,
postingLocation: Coord?,
user: UserAccount,
media: Media?,
date: LocalDateTime): Posting {
var location: Location? = null
if (postingLocation != null) {
val uploader = user.getRole(Participant::class) ?: throw DomainException("user is no participant and can therefor not upload location")
location = locationService.create(postingLocation, uploader, date, true)
}
var savedMedia: Media? = null
if (media != null) {
savedMedia = mediaService.save(media)
}
return repository.save(Posting(text, date, location, user, savedMedia))
}
@Transactional
override fun adminSavePostingWithLocationAndMedia(text: String?,
postingLocation: Coord?,
user: UserAccount,
media: Media?,
date: LocalDateTime): Posting {
var location: Location? = null
if (postingLocation != null) {
val uploader = user.getRole(Participant::class) ?: throw DomainException("user is no participant and can therefor not upload location")
location = locationService.adminCreate(postingLocation, uploader, date, true)
}
var savedMedia: Media? = null
if (media != null) {
savedMedia = mediaService.save(media)
}
return repository.save(Posting(text, date, location, user, savedMedia))
}
override fun createPosting(user: User,
text: String?,
media: Media?,
locationCoord: Coord?,
clientDate: LocalDateTime): Posting {
//check if any of the optional posting types is available
if (media == null && (text == null || text.trim() == "") && locationCoord == null)
throw BadRequestException("empty postings not allowed")
return this.savePostingWithLocationAndMedia(text, locationCoord, user.account, media, clientDate)
}
override fun adminCreatePosting(user: User,
text: String?,
media: Media?,
locationCoord: Coord?,
clientDate: LocalDateTime): Posting {
//check if any of the optional posting types is available
if (media == null && (text == null || text.trim() == "") && locationCoord == null)
throw BadRequestException("empty postings not allowed")
return this.adminSavePostingWithLocationAndMedia(text, locationCoord, user.account, media, clientDate)
}
override fun getByID(id: Long): Posting? = repository.findById(id)
override fun findByHashtag(hashtag: String, page: Int, size: Int): List<Posting> = repository.findByHashtag(hashtag, PageRequest(page, size))
@Transactional
override fun delete(posting: Posting) {
repository.delete(posting)
}
override fun findAllByChallenge(challengeId: Long): List<Posting> {
return repository.findAllByChallengeId(challengeId)
}
}
| agpl-3.0 | e04cbb9dc3054c1803e3ae153e5a0e53 | 40.790541 | 147 | 0.622797 | 5.167084 | false | false | false | false |
google/intellij-community | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/codeInsight/ReferenceVariantsHelper.kt | 2 | 25225 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeInsight
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.incremental.KotlinLookupLocation
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.load.kotlin.toSourceElement
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.calls.smartcasts.SmartCastManager
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.descriptorUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.scopes.*
import org.jetbrains.kotlin.resolve.scopes.receivers.ClassQualifier
import org.jetbrains.kotlin.resolve.scopes.utils.collectAllFromMeAndParent
import org.jetbrains.kotlin.resolve.scopes.utils.collectDescriptorsFiltered
import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.synthetic.JavaSyntheticScopes
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeConstructor
import org.jetbrains.kotlin.types.expressions.DoubleColonLHS
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.util.suppressedByNotPropertyList
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.util.*
@OptIn(FrontendInternals::class)
class ReferenceVariantsHelper(
private val bindingContext: BindingContext,
private val resolutionFacade: ResolutionFacade,
private val moduleDescriptor: ModuleDescriptor,
private val visibilityFilter: (DeclarationDescriptor) -> Boolean,
private val notProperties: Set<FqNameUnsafe> = setOf()
) {
fun getReferenceVariants(
expression: KtSimpleNameExpression,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
filterOutJavaGettersAndSetters: Boolean = true,
filterOutShadowed: Boolean = true,
excludeNonInitializedVariable: Boolean = true,
useReceiverType: KotlinType? = null
): Collection<DeclarationDescriptor> = getReferenceVariants(
expression, CallTypeAndReceiver.detect(expression),
kindFilter, nameFilter, filterOutJavaGettersAndSetters, filterOutShadowed, excludeNonInitializedVariable, useReceiverType
)
fun getReferenceVariants(
contextElement: PsiElement,
callTypeAndReceiver: CallTypeAndReceiver<*, *>,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
filterOutJavaGettersAndSetters: Boolean = true,
filterOutShadowed: Boolean = true,
excludeNonInitializedVariable: Boolean = true,
useReceiverType: KotlinType? = null
): Collection<DeclarationDescriptor> {
var variants: Collection<DeclarationDescriptor> =
getReferenceVariantsNoVisibilityFilter(contextElement, kindFilter, nameFilter, callTypeAndReceiver, useReceiverType)
.filter { !resolutionFacade.frontendService<DeprecationResolver>().isHiddenInResolution(it) && visibilityFilter(it) }
if (filterOutShadowed) {
ShadowedDeclarationsFilter.create(bindingContext, resolutionFacade, contextElement, callTypeAndReceiver)?.let {
variants = it.filter(variants)
}
}
if (filterOutJavaGettersAndSetters && kindFilter.kindMask.and(DescriptorKindFilter.FUNCTIONS_MASK) != 0) {
variants = filterOutJavaGettersAndSetters(variants)
}
if (excludeNonInitializedVariable && kindFilter.kindMask.and(DescriptorKindFilter.VARIABLES_MASK) != 0) {
variants = excludeNonInitializedVariable(variants, contextElement)
}
return variants
}
fun <TDescriptor : DeclarationDescriptor> filterOutJavaGettersAndSetters(variants: Collection<TDescriptor>): Collection<TDescriptor> {
val accessorMethodsToRemove = HashSet<FunctionDescriptor>()
val filteredVariants = variants.filter { it !is SyntheticJavaPropertyDescriptor || !it.suppressedByNotPropertyList(notProperties) }
for (variant in filteredVariants) {
if (variant is SyntheticJavaPropertyDescriptor) {
accessorMethodsToRemove.add(variant.getMethod.original)
val setter = variant.setMethod
if (setter != null && setter.returnType?.isUnit() == true) { // we do not filter out non-Unit setters
accessorMethodsToRemove.add(setter.original)
}
}
}
return filteredVariants.filter { it !is FunctionDescriptor || it.original !in accessorMethodsToRemove }
}
// filters out variable inside its initializer
fun excludeNonInitializedVariable(
variants: Collection<DeclarationDescriptor>,
contextElement: PsiElement
): Collection<DeclarationDescriptor> {
for (element in contextElement.parentsWithSelf) {
val parent = element.parent
if (parent is KtVariableDeclaration && element == parent.initializer) {
return variants.filter { it.findPsi() != parent }
} else if (element is KtParameter) {
// Filter out parameters initialized after the current parameter. For example
// ```
// fun test(a: Int = <caret>, b: Int) {}
// ```
// `b` should not show up in completion.
return variants.filter {
val candidatePsi = it.findPsi()
if (candidatePsi is KtParameter && candidatePsi.parent == parent) {
return@filter candidatePsi.startOffset < element.startOffset
}
true
}
}
if (element is KtDeclaration) break // we can use variable inside lambda or anonymous object located in its initializer
}
return variants
}
private fun getReferenceVariantsNoVisibilityFilter(
contextElement: PsiElement,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
callTypeAndReceiver: CallTypeAndReceiver<*, *>,
useReceiverType: KotlinType?
): Collection<DeclarationDescriptor> {
val callType = callTypeAndReceiver.callType
@Suppress("NAME_SHADOWING")
val kindFilter = kindFilter.intersect(callType.descriptorKindFilter)
val receiverExpression: KtExpression?
when (callTypeAndReceiver) {
is CallTypeAndReceiver.IMPORT_DIRECTIVE -> {
return getVariantsForImportOrPackageDirective(callTypeAndReceiver.receiver, kindFilter, nameFilter)
}
is CallTypeAndReceiver.PACKAGE_DIRECTIVE -> {
return getVariantsForImportOrPackageDirective(callTypeAndReceiver.receiver, kindFilter, nameFilter)
}
is CallTypeAndReceiver.TYPE -> {
return getVariantsForUserType(callTypeAndReceiver.receiver, contextElement, kindFilter, nameFilter)
}
is CallTypeAndReceiver.ANNOTATION -> {
return getVariantsForUserType(callTypeAndReceiver.receiver, contextElement, kindFilter, nameFilter)
}
is CallTypeAndReceiver.CALLABLE_REFERENCE -> {
return getVariantsForCallableReference(callTypeAndReceiver, contextElement, useReceiverType, kindFilter, nameFilter)
}
is CallTypeAndReceiver.DEFAULT -> receiverExpression = null
is CallTypeAndReceiver.DOT -> receiverExpression = callTypeAndReceiver.receiver
is CallTypeAndReceiver.SUPER_MEMBERS -> receiverExpression = callTypeAndReceiver.receiver
is CallTypeAndReceiver.SAFE -> receiverExpression = callTypeAndReceiver.receiver
is CallTypeAndReceiver.INFIX -> receiverExpression = callTypeAndReceiver.receiver
is CallTypeAndReceiver.OPERATOR -> return emptyList()
is CallTypeAndReceiver.UNKNOWN -> return emptyList()
else -> throw RuntimeException() //TODO: see KT-9394
}
val resolutionScope = contextElement.getResolutionScope(bindingContext, resolutionFacade)
val dataFlowInfo = bindingContext.getDataFlowInfoBefore(contextElement)
val containingDeclaration = resolutionScope.ownerDescriptor
val smartCastManager = resolutionFacade.frontendService<SmartCastManager>()
val languageVersionSettings = resolutionFacade.frontendService<LanguageVersionSettings>()
val implicitReceiverTypes = resolutionScope.getImplicitReceiversWithInstance(
languageVersionSettings.supportsFeature(LanguageFeature.DslMarkersSupport)
).flatMap {
smartCastManager.getSmartCastVariantsWithLessSpecificExcluded(
it.value,
bindingContext,
containingDeclaration,
dataFlowInfo,
languageVersionSettings,
resolutionFacade.frontendService()
)
}.toSet()
val descriptors = LinkedHashSet<DeclarationDescriptor>()
val filterWithoutExtensions = kindFilter exclude DescriptorKindExclude.Extensions
if (receiverExpression != null) {
val qualifier = bindingContext[BindingContext.QUALIFIER, receiverExpression]
if (qualifier != null) {
descriptors.addAll(qualifier.staticScope.collectStaticMembers(resolutionFacade, filterWithoutExtensions, nameFilter))
}
val explicitReceiverTypes = if (useReceiverType != null) {
listOf(useReceiverType)
} else {
callTypeAndReceiver.receiverTypes(
bindingContext,
contextElement,
moduleDescriptor,
resolutionFacade,
stableSmartCastsOnly = false
)!!
}
descriptors.processAll(implicitReceiverTypes, explicitReceiverTypes, resolutionScope, callType, kindFilter, nameFilter)
} else {
assert(useReceiverType == null) { "'useReceiverType' parameter is not supported for implicit receiver" }
descriptors.processAll(implicitReceiverTypes, implicitReceiverTypes, resolutionScope, callType, kindFilter, nameFilter)
// add non-instance members
descriptors.addAll(
resolutionScope.collectDescriptorsFiltered(
filterWithoutExtensions,
nameFilter,
changeNamesForAliased = true
)
)
descriptors.addAll(resolutionScope.collectAllFromMeAndParent { scope ->
scope.collectSyntheticStaticMembersAndConstructors(resolutionFacade, kindFilter, nameFilter)
})
}
if (callType == CallType.SUPER_MEMBERS) { // we need to unwrap fake overrides in case of "super." because ShadowedDeclarationsFilter does not work correctly
return descriptors.flatMapTo(LinkedHashSet<DeclarationDescriptor>()) {
if (it is CallableMemberDescriptor && it.kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE)
it.overriddenDescriptors
else
listOf(it)
}
}
return descriptors
}
private fun getVariantsForUserType(
receiverExpression: KtExpression?,
contextElement: PsiElement,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): Collection<DeclarationDescriptor> {
if (receiverExpression != null) {
val qualifier = bindingContext[BindingContext.QUALIFIER, receiverExpression] ?: return emptyList()
return qualifier.staticScope.collectStaticMembers(resolutionFacade, kindFilter, nameFilter)
} else {
val scope = contextElement.getResolutionScope(bindingContext, resolutionFacade)
return scope.collectDescriptorsFiltered(kindFilter, nameFilter, changeNamesForAliased = true)
}
}
private fun getVariantsForCallableReference(
callTypeAndReceiver: CallTypeAndReceiver.CALLABLE_REFERENCE,
contextElement: PsiElement,
useReceiverType: KotlinType?,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): Collection<DeclarationDescriptor> {
val descriptors = LinkedHashSet<DeclarationDescriptor>()
val resolutionScope = contextElement.getResolutionScope(bindingContext, resolutionFacade)
val receiver = callTypeAndReceiver.receiver
if (receiver != null) {
val isStatic = bindingContext[BindingContext.DOUBLE_COLON_LHS, receiver] is DoubleColonLHS.Type
val explicitReceiverTypes = if (useReceiverType != null) {
listOf(useReceiverType)
} else {
callTypeAndReceiver.receiverTypes(
bindingContext,
contextElement,
moduleDescriptor,
resolutionFacade,
stableSmartCastsOnly = false
)!!
}
val constructorFilter = { descriptor: ClassDescriptor -> if (isStatic) true else descriptor.isInner }
descriptors.addNonExtensionMembers(explicitReceiverTypes, kindFilter, nameFilter, constructorFilter)
descriptors.addScopeAndSyntheticExtensions(
resolutionScope,
explicitReceiverTypes,
CallType.CALLABLE_REFERENCE,
kindFilter,
nameFilter
)
if (isStatic) {
explicitReceiverTypes
.mapNotNull { (it.constructor.declarationDescriptor as? ClassDescriptor)?.staticScope }
.flatMapTo(descriptors) { it.collectStaticMembers(resolutionFacade, kindFilter, nameFilter) }
}
} else {
val constructorFilter: (ClassDescriptor) -> Boolean = { !it.isInner }
resolutionScope.ownerDescriptor.parentsWithSelf.firstIsInstanceOrNull<ClassDescriptor>()?.let { classDescriptor ->
// process instance members, class constructors and companion object
listOfNotNull(classDescriptor, classDescriptor.companionObjectDescriptor).forEach {
descriptors.addNonExtensionMembers(
it.unsubstitutedMemberScope,
it.typeConstructor,
kindFilter,
nameFilter,
constructorFilter
)
}
}
// process non-instance members and class constructors
descriptors.addNonExtensionCallablesAndConstructors(
resolutionScope,
kindFilter,
nameFilter,
constructorFilter = constructorFilter,
classesOnly = false
)
}
return descriptors
}
private fun getVariantsForImportOrPackageDirective(
receiverExpression: KtExpression?,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): Collection<DeclarationDescriptor> {
if (receiverExpression != null) {
val qualifier = bindingContext[BindingContext.QUALIFIER, receiverExpression] ?: return emptyList()
val staticDescriptors = qualifier.staticScope.collectStaticMembers(resolutionFacade, kindFilter, nameFilter)
val objectDescriptor =
(qualifier as? ClassQualifier)?.descriptor?.takeIf { it.kind == ClassKind.OBJECT } ?: return staticDescriptors
return staticDescriptors + objectDescriptor.defaultType.memberScope.getDescriptorsFiltered(kindFilter, nameFilter)
} else {
val rootPackage = resolutionFacade.moduleDescriptor.getPackage(FqName.ROOT)
return rootPackage.memberScope.getDescriptorsFiltered(kindFilter, nameFilter)
}
}
private fun MutableSet<DeclarationDescriptor>.processAll(
implicitReceiverTypes: Collection<KotlinType>,
receiverTypes: Collection<KotlinType>,
resolutionScope: LexicalScope,
callType: CallType<*>,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
) {
addNonExtensionMembers(receiverTypes, kindFilter, nameFilter, constructorFilter = { it.isInner })
addMemberExtensions(implicitReceiverTypes, receiverTypes, callType, kindFilter, nameFilter)
addScopeAndSyntheticExtensions(resolutionScope, receiverTypes, callType, kindFilter, nameFilter)
}
private fun MutableSet<DeclarationDescriptor>.addMemberExtensions(
dispatchReceiverTypes: Collection<KotlinType>,
extensionReceiverTypes: Collection<KotlinType>,
callType: CallType<*>,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
) {
val memberFilter = kindFilter exclude DescriptorKindExclude.NonExtensions
for (dispatchReceiverType in dispatchReceiverTypes) {
for (member in dispatchReceiverType.memberScope.getDescriptorsFiltered(memberFilter, nameFilter)) {
addAll((member as CallableDescriptor).substituteExtensionIfCallable(extensionReceiverTypes, callType))
}
}
}
private fun MutableSet<DeclarationDescriptor>.addNonExtensionMembers(
receiverTypes: Collection<KotlinType>,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
constructorFilter: (ClassDescriptor) -> Boolean
) {
for (receiverType in receiverTypes) {
addNonExtensionMembers(receiverType.memberScope, receiverType.constructor, kindFilter, nameFilter, constructorFilter)
receiverType.constructor.declarationDescriptor.safeAs<ClassDescriptor>()?.companionObjectDescriptor?.let {
addNonExtensionMembers(it.unsubstitutedMemberScope, it.typeConstructor, kindFilter, nameFilter, constructorFilter)
}
}
}
private fun MutableSet<DeclarationDescriptor>.addNonExtensionMembers(
memberScope: MemberScope,
typeConstructor: TypeConstructor,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
constructorFilter: (ClassDescriptor) -> Boolean
) {
addNonExtensionCallablesAndConstructors(
memberScope.memberScopeAsImportingScope(),
kindFilter, nameFilter, constructorFilter,
false
)
typeConstructor.supertypes.forEach {
addNonExtensionCallablesAndConstructors(
it.memberScope.memberScopeAsImportingScope(),
kindFilter, nameFilter, constructorFilter,
true
)
}
}
private fun MutableSet<DeclarationDescriptor>.addNonExtensionCallablesAndConstructors(
scope: HierarchicalScope,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
constructorFilter: (ClassDescriptor) -> Boolean,
classesOnly: Boolean
) {
var filterToUse =
DescriptorKindFilter(kindFilter.kindMask and DescriptorKindFilter.CALLABLES.kindMask).exclude(DescriptorKindExclude.Extensions)
// should process classes if we need constructors
if (filterToUse.acceptsKinds(DescriptorKindFilter.FUNCTIONS_MASK)) {
filterToUse = filterToUse.withKinds(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS_MASK)
}
for (descriptor in scope.collectDescriptorsFiltered(filterToUse, nameFilter, changeNamesForAliased = true)) {
if (descriptor is ClassDescriptor) {
if (descriptor.modality == Modality.ABSTRACT || descriptor.modality == Modality.SEALED) continue
if (!constructorFilter(descriptor)) continue
descriptor.constructors.filterTo(this) { kindFilter.accepts(it) }
} else if (!classesOnly && kindFilter.accepts(descriptor)) {
this.add(descriptor)
}
}
}
private fun MutableSet<DeclarationDescriptor>.addScopeAndSyntheticExtensions(
scope: LexicalScope,
receiverTypes: Collection<KotlinType>,
callType: CallType<*>,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
) {
if (kindFilter.excludes.contains(DescriptorKindExclude.Extensions)) return
if (receiverTypes.isEmpty()) return
fun process(extensionOrSyntheticMember: CallableDescriptor) {
if (kindFilter.accepts(extensionOrSyntheticMember) && nameFilter(extensionOrSyntheticMember.name)) {
if (extensionOrSyntheticMember.isExtension) {
addAll(extensionOrSyntheticMember.substituteExtensionIfCallable(receiverTypes, callType))
} else {
add(extensionOrSyntheticMember)
}
}
}
for (descriptor in scope.collectDescriptorsFiltered(
kindFilter exclude DescriptorKindExclude.NonExtensions,
nameFilter,
changeNamesForAliased = true
)) {
// todo: sometimes resolution scope here is LazyJavaClassMemberScope. see ea.jetbrains.com/browser/ea_problems/72572
process(descriptor as CallableDescriptor)
}
val syntheticScopes = resolutionFacade.getFrontendService(SyntheticScopes::class.java).forceEnableSamAdapters()
if (kindFilter.acceptsKinds(DescriptorKindFilter.VARIABLES_MASK)) {
val lookupLocation = (scope.ownerDescriptor.toSourceElement.getPsi() as? KtElement)?.let { KotlinLookupLocation(it) }
?: NoLookupLocation.FROM_IDE
for (extension in syntheticScopes.collectSyntheticExtensionProperties(receiverTypes, lookupLocation)) {
process(extension)
}
}
if (kindFilter.acceptsKinds(DescriptorKindFilter.FUNCTIONS_MASK)) {
for (syntheticMember in syntheticScopes.collectSyntheticMemberFunctions(receiverTypes)) {
process(syntheticMember)
}
}
}
}
private fun MemberScope.collectStaticMembers(
resolutionFacade: ResolutionFacade,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): Collection<DeclarationDescriptor> {
return getDescriptorsFiltered(kindFilter, nameFilter) + collectSyntheticStaticMembersAndConstructors(
resolutionFacade,
kindFilter,
nameFilter
)
}
@OptIn(FrontendInternals::class)
fun ResolutionScope.collectSyntheticStaticMembersAndConstructors(
resolutionFacade: ResolutionFacade,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): List<FunctionDescriptor> {
val syntheticScopes = resolutionFacade.getFrontendService(SyntheticScopes::class.java)
val functionDescriptors = getContributedDescriptors(DescriptorKindFilter.FUNCTIONS)
val classifierDescriptors = getContributedDescriptors(DescriptorKindFilter.CLASSIFIERS)
return (syntheticScopes.forceEnableSamAdapters().collectSyntheticStaticFunctions(functionDescriptors) +
syntheticScopes.collectSyntheticConstructors(classifierDescriptors))
.filter { kindFilter.accepts(it) && nameFilter(it.name) }
}
// New Inference disables scope with synthetic SAM-adapters because it uses conversions for resolution
// However, sometimes we need to pretend that we have those synthetic members, for example:
// - to show both option (with SAM-conversion signature, and without) in completion
// - for various intentions and checks (see RedundantSamConstructorInspection, ConflictingExtensionPropertyIntention and other)
// TODO(dsavvinov): review clients, rewrite them to not rely on synthetic adapetrs
fun SyntheticScopes.forceEnableSamAdapters(): SyntheticScopes {
return if (this !is JavaSyntheticScopes)
this
else
object : SyntheticScopes {
override val scopes: Collection<SyntheticScope> = [email protected]
}
}
| apache-2.0 | 665e6f2e302e002af83fd95f451c38e9 | 45.886617 | 164 | 0.68892 | 6.342721 | false | false | false | false |
spacecowboy/Feeder | app/src/main/java/com/nononsenseapps/feeder/ui/compose/components/BottomAppBar.kt | 1 | 5382 | package com.nononsenseapps.feeder.ui.compose.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.BottomAppBarDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Surface
import androidx.compose.material3.contentColorFor
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.nononsenseapps.feeder.ui.compose.bottomBarHeight
import com.nononsenseapps.feeder.ui.compose.theme.FeederTheme
/**
* Material Design bottom app bar. Forked from library because the library version does not take
* navigation bar padding into account properly - nor does it allow the FAB to be animated
* according to the guidelines.
*
* A bottom app bar displays navigation and key actions at the bottom of mobile screens.
*/
@Composable
fun PaddedBottomAppBar(
actions: @Composable RowScope.() -> Unit,
modifier: Modifier = Modifier,
floatingActionButton: @Composable (() -> Unit)? = null,
containerColor: Color = BottomAppBarDefaults.containerColor,
contentColor: Color = contentColorFor(containerColor),
tonalElevation: Dp = BottomAppBarDefaults.ContainerElevation,
contentPadding: PaddingValues = BottomAppBarDefaults.ContentPadding,
) = BottomAppBar(
modifier = modifier,
containerColor = containerColor,
contentColor = contentColor,
tonalElevation = tonalElevation,
contentPadding = contentPadding
) {
actions()
if (floatingActionButton != null) {
Spacer(Modifier.weight(1f, true))
Box(
Modifier
.fillMaxHeight()
.padding(
top = FABVerticalPadding,
end = FABHorizontalPadding
),
contentAlignment = Alignment.TopStart
) {
floatingActionButton()
}
}
}
@Preview
@Composable
fun PreviewPaddedBottomBar() {
FeederTheme {
PaddedBottomAppBar(
actions = {
IconButton(onClick = {}) {
Icon(
Icons.Default.PlayArrow,
contentDescription = null
)
}
IconButton(onClick = {}) {
Icon(
Icons.Default.Pause,
contentDescription = null
)
}
IconButton(onClick = {}) {
Icon(
Icons.Default.Stop,
contentDescription = null
)
}
}
)
}
}
// Padding minus IconButton's min touch target expansion
private val BottomAppBarHorizontalPadding = 16.dp - 12.dp
// Padding minus IconButton's min touch target expansion
private val BottomAppBarVerticalPadding = 16.dp - 12.dp
// Padding minus content padding
private val FABHorizontalPadding = 16.dp - BottomAppBarHorizontalPadding
private val FABVerticalPadding = 12.dp - BottomAppBarVerticalPadding
@Composable
private fun BottomAppBar(
modifier: Modifier = Modifier,
containerColor: Color = BottomAppBarDefaults.containerColor,
contentColor: Color = contentColorFor(containerColor),
tonalElevation: Dp = BottomAppBarDefaults.ContainerElevation,
contentPadding: PaddingValues = BottomAppBarDefaults.ContentPadding,
content: @Composable RowScope.() -> Unit
) {
Surface(
color = containerColor,
contentColor = contentColor,
tonalElevation = tonalElevation,
shape = RectangleShape,
modifier = modifier
) {
Box(
modifier = Modifier.windowInsetsPadding(
WindowInsets.navigationBars.only(WindowInsetsSides.Bottom)
)
) {
Row(
Modifier
.fillMaxWidth()
.height(bottomBarHeight)
.padding(contentPadding),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically,
content = content
)
}
}
}
| gpl-3.0 | d1813311ff44ecd395f68832bafb387f | 35.120805 | 96 | 0.684132 | 5.392786 | false | false | false | false |
SixRQ/KAXB | src/main/kotlin/com/sixrq/kaxb/parsers/Tag.kt | 1 | 3517 | /*
* Copyright 2017 SixRQ Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sixrq.kaxb.parsers
import org.w3c.dom.Node
open class Tag(val xmlns: String) {
var name: String = ""
var elementName = ""
var type: String = ""
var minOccurs: String = ""
var maxOccurs: String = ""
var value: String = ""
var processContents: String = ""
var base: String = ""
var schemaLocation: String = ""
var imports: MutableList<String> = mutableListOf()
var includes: MutableList<String> = mutableListOf()
val children: MutableList<Tag> = mutableListOf()
open fun processAttributes(item: Node?) {
if (item!!.attributes.getNamedItem("name") != null) {
name = extractClassName(item.attributes.getNamedItem("name").nodeValue)
elementName = item.attributes.getNamedItem("name").nodeValue
}
if (item.attributes.getNamedItem("type") != null) {
type = extractClassName(item.attributes.getNamedItem("type").nodeValue)
} else if (item.attributes.getNamedItem("base") != null) {
type = extractClassName(item.attributes.getNamedItem("base").nodeValue)
}
if (item.attributes.getNamedItem("minOccurs") != null) {
minOccurs = item.attributes.getNamedItem("minOccurs").nodeValue
}
if (item.attributes.getNamedItem("maxOccurs") != null) {
maxOccurs = item.attributes.getNamedItem("maxOccurs").nodeValue
}
if (item.attributes.getNamedItem("value") != null) {
value = item.attributes.getNamedItem("value").nodeValue
}
if (item.attributes.getNamedItem("processContents") != null) {
processContents = item.attributes.getNamedItem("processContents").nodeValue
}
if (item.attributes.getNamedItem("base") != null) {
base = item.attributes.getNamedItem("base").nodeValue
}
if (item.attributes.getNamedItem("schemaLocation") != null) {
schemaLocation = item.attributes.getNamedItem("schemaLocation").nodeValue
}
}
fun getPropertyName() = name.replaceFirst(name[0], name[0].toLowerCase())
fun extractClassName(name: String): String {
val className = StringBuilder()
name.split('_').forEach {
className.append(it.capitalize())
}
return className.toString()
}
open fun processText(item: Node) {}
open fun extractType() : String {
when (type.toLowerCase()) {
"xsd:string" -> return "String"
"xsd:token" -> return "String"
"xsd:decimal" -> return "BigDecimal"
"xsd:double" -> return "Double"
"xsd:hexbinary" -> return "ByteArray"
"xsd:boolean" -> return "Boolean"
"xsd:any" -> return "Any"
else -> return extractClassName(type)
}
}
override fun toString(): String{
return "$children"
}
}
| apache-2.0 | eb29c81118895e4a450f06f315033d44 | 36.414894 | 87 | 0.62269 | 4.485969 | false | false | false | false |
zdary/intellij-community | platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/GroupNode.kt | 12 | 1151 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.analysis.problemsView.toolWindow
import com.intellij.analysis.problemsView.Problem
import com.intellij.ide.projectView.PresentationData
import com.intellij.openapi.project.Project
import com.intellij.ui.SimpleTextAttributes.REGULAR_ATTRIBUTES
import com.intellij.ui.tree.LeafState
internal class GroupNode(val parent: FileNode, val group: String, val problems: Collection<Problem>) : Node(parent) {
override fun getLeafState() = LeafState.NEVER
override fun getName() = group
override fun update(project: Project, presentation: PresentationData) = presentation.addText(name, REGULAR_ATTRIBUTES)
override fun getChildren() = problems.map { ProblemNode(this, parent.file, it) }
override fun hashCode() = group.hashCode()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (this.javaClass != other?.javaClass) return false
val that = other as? GroupNode ?: return false
return that.parent == parent && that.group == group
}
}
| apache-2.0 | 3f2c3f8bfd149b25117438a99ccdfe8f | 40.107143 | 140 | 0.762815 | 4.231618 | false | false | false | false |
googlecodelabs/android-performance | benchmarking/app/src/main/java/com/example/macrobenchmark_codelab/ui/home/FilterScreen.kt | 1 | 9513 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.macrobenchmark_codelab.ui.home
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ContentAlpha
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Slider
import androidx.compose.material.SliderDefaults
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Done
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.example.macrobenchmark_codelab.R
import com.example.macrobenchmark_codelab.model.Filter
import com.example.macrobenchmark_codelab.model.SnackRepo
import com.example.macrobenchmark_codelab.ui.components.FilterChip
import com.example.macrobenchmark_codelab.ui.components.JetsnackScaffold
import com.example.macrobenchmark_codelab.ui.theme.JetsnackTheme
import com.google.accompanist.flowlayout.FlowMainAxisAlignment
import com.google.accompanist.flowlayout.FlowRow
@OptIn(ExperimentalAnimationApi::class)
@Composable
fun FilterScreen(
onDismiss: () -> Unit
) {
var sortState by remember { mutableStateOf(SnackRepo.getSortDefault()) }
var maxCalories by remember { mutableStateOf(0f) }
val defaultFilter = SnackRepo.getSortDefault()
Dialog(onDismissRequest = onDismiss) {
val priceFilters = remember { SnackRepo.getPriceFilters() }
val categoryFilters = remember { SnackRepo.getCategoryFilters() }
val lifeStyleFilters = remember { SnackRepo.getLifeStyleFilters() }
JetsnackScaffold(
topBar = {
TopAppBar(
navigationIcon = {
IconButton(onClick = onDismiss) {
Icon(
imageVector = Icons.Filled.Close,
contentDescription = stringResource(id = R.string.close)
)
}
},
title = {
Text(
text = stringResource(id = R.string.label_filters),
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
style = MaterialTheme.typography.h6
)
},
actions = {
var resetEnabled = sortState != defaultFilter
IconButton(
onClick = { /* TODO: Open search */ },
enabled = resetEnabled
) {
val alpha = if (resetEnabled) {
ContentAlpha.high
} else {
ContentAlpha.disabled
}
CompositionLocalProvider(LocalContentAlpha provides alpha) {
Text(
text = stringResource(id = R.string.reset),
style = MaterialTheme.typography.body2
)
}
}
},
backgroundColor = JetsnackTheme.colors.uiBackground
)
}
) {
Column(
Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(horizontal = 24.dp, vertical = 16.dp),
) {
SortFiltersSection(
sortState = sortState,
onFilterChange = { filter ->
sortState = filter.name
}
)
FilterChipSection(
title = stringResource(id = R.string.price),
filters = priceFilters
)
FilterChipSection(
title = stringResource(id = R.string.category),
filters = categoryFilters
)
MaxCalories(
sliderPosition = maxCalories,
onValueChanged = { newValue ->
maxCalories = newValue
}
)
FilterChipSection(
title = stringResource(id = R.string.lifestyle),
filters = lifeStyleFilters
)
}
}
}
}
@Composable
fun FilterChipSection(title: String, filters: List<Filter>) {
FilterTitle(text = title)
FlowRow(
mainAxisAlignment = FlowMainAxisAlignment.Center,
modifier = Modifier
.fillMaxWidth()
.padding(top = 12.dp, bottom = 16.dp)
.padding(horizontal = 4.dp)
) {
filters.forEach { filter ->
FilterChip(
filter = filter,
modifier = Modifier.padding(end = 4.dp, bottom = 8.dp)
)
}
}
}
@Composable
fun SortFiltersSection(sortState: String, onFilterChange: (Filter) -> Unit) {
FilterTitle(text = stringResource(id = R.string.sort))
Column(Modifier.padding(bottom = 24.dp)) {
SortFilters(
sortState = sortState,
onChanged = onFilterChange
)
}
}
@Composable
fun SortFilters(
sortFilters: List<Filter> = SnackRepo.getSortFilters(),
sortState: String,
onChanged: (Filter) -> Unit
) {
sortFilters.forEach { filter ->
SortOption(
text = filter.name,
icon = filter.icon,
selected = sortState == filter.name,
onClickOption = {
onChanged(filter)
}
)
}
}
@Composable
fun MaxCalories(sliderPosition: Float, onValueChanged: (Float) -> Unit) {
FlowRow {
FilterTitle(text = stringResource(id = R.string.max_calories))
Text(
text = stringResource(id = R.string.per_serving),
style = MaterialTheme.typography.body2,
color = JetsnackTheme.colors.brand,
modifier = Modifier.padding(top = 5.dp, start = 10.dp)
)
}
Slider(
value = sliderPosition,
onValueChange = { newValue ->
onValueChanged(newValue)
},
valueRange = 0f..300f,
steps = 5,
modifier = Modifier
.fillMaxWidth(),
colors = SliderDefaults.colors(
thumbColor = JetsnackTheme.colors.brand,
activeTrackColor = JetsnackTheme.colors.brand
)
)
}
@Composable
fun FilterTitle(text: String) {
Text(
text = text,
style = MaterialTheme.typography.h6,
color = JetsnackTheme.colors.brand,
modifier = Modifier.padding(bottom = 8.dp)
)
}
@Composable
fun SortOption(
text: String,
icon: ImageVector?,
onClickOption: () -> Unit,
selected: Boolean
) {
Row(
modifier = Modifier
.padding(top = 14.dp)
.selectable(selected) { onClickOption() }
) {
if (icon != null) {
Icon(imageVector = icon, contentDescription = null)
}
Text(
text = text,
style = MaterialTheme.typography.subtitle1,
modifier = Modifier
.padding(start = 10.dp)
.weight(1f)
)
if (selected) {
Icon(
imageVector = Icons.Filled.Done,
contentDescription = null,
tint = JetsnackTheme.colors.brand
)
}
}
}
@Preview("filter screen")
@Composable
fun FilterScreenPreview() {
FilterScreen(onDismiss = {})
}
| apache-2.0 | 529d2160debde9537a9e10618952766b | 33.718978 | 88 | 0.583412 | 5.201203 | false | false | false | false |
cartland/android-UniversalMusicPlayer | common/src/main/java/com/example/android/uamp/common/MediaSessionConnection.kt | 1 | 7258 | /*
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.common
import android.content.ComponentName
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.ResultReceiver
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import androidx.lifecycle.MutableLiveData
import androidx.media.MediaBrowserServiceCompat
import com.example.android.uamp.common.MediaSessionConnection.MediaBrowserConnectionCallback
import com.example.android.uamp.media.NETWORK_FAILURE
/**
* Class that manages a connection to a [MediaBrowserServiceCompat] instance.
*
* Typically it's best to construct/inject dependencies either using DI or, as UAMP does,
* using [InjectorUtils] in the app module. There are a few difficulties for that here:
* - [MediaBrowserCompat] is a final class, so mocking it directly is difficult.
* - A [MediaBrowserConnectionCallback] is a parameter into the construction of
* a [MediaBrowserCompat], and provides callbacks to this class.
* - [MediaBrowserCompat.ConnectionCallback.onConnected] is the best place to construct
* a [MediaControllerCompat] that will be used to control the [MediaSessionCompat].
*
* Because of these reasons, rather than constructing additional classes, this is treated as
* a black box (which is why there's very little logic here).
*
* This is also why the parameters to construct a [MediaSessionConnection] are simple
* parameters, rather than private properties. They're only required to build the
* [MediaBrowserConnectionCallback] and [MediaBrowserCompat] objects.
*/
class MediaSessionConnection(context: Context, serviceComponent: ComponentName) {
val isConnected = MutableLiveData<Boolean>()
.apply { postValue(false) }
val networkFailure = MutableLiveData<Boolean>()
.apply { postValue(false) }
val rootMediaId: String get() = mediaBrowser.root
val playbackState = MutableLiveData<PlaybackStateCompat>()
.apply { postValue(EMPTY_PLAYBACK_STATE) }
val nowPlaying = MutableLiveData<MediaMetadataCompat>()
.apply { postValue(NOTHING_PLAYING) }
val transportControls: MediaControllerCompat.TransportControls
get() = mediaController.transportControls
private val mediaBrowserConnectionCallback = MediaBrowserConnectionCallback(context)
private val mediaBrowser = MediaBrowserCompat(
context,
serviceComponent,
mediaBrowserConnectionCallback, null
).apply { connect() }
private lateinit var mediaController: MediaControllerCompat
fun subscribe(parentId: String, callback: MediaBrowserCompat.SubscriptionCallback) {
mediaBrowser.subscribe(parentId, callback)
}
fun unsubscribe(parentId: String, callback: MediaBrowserCompat.SubscriptionCallback) {
mediaBrowser.unsubscribe(parentId, callback)
}
fun sendCommand(command: String, parameters: Bundle?) =
sendCommand(command, parameters) { _, _ -> }
fun sendCommand(
command: String,
parameters: Bundle?,
resultCallback: ((Int, Bundle?) -> Unit)
) = if (mediaBrowser.isConnected) {
mediaController.sendCommand(command, parameters, object : ResultReceiver(Handler()) {
override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
resultCallback(resultCode, resultData)
}
})
true
} else {
false
}
private inner class MediaBrowserConnectionCallback(private val context: Context) :
MediaBrowserCompat.ConnectionCallback() {
/**
* Invoked after [MediaBrowserCompat.connect] when the request has successfully
* completed.
*/
override fun onConnected() {
// Get a MediaController for the MediaSession.
mediaController = MediaControllerCompat(context, mediaBrowser.sessionToken).apply {
registerCallback(MediaControllerCallback())
}
isConnected.postValue(true)
}
/**
* Invoked when the client is disconnected from the media browser.
*/
override fun onConnectionSuspended() {
isConnected.postValue(false)
}
/**
* Invoked when the connection to the media browser failed.
*/
override fun onConnectionFailed() {
isConnected.postValue(false)
}
}
private inner class MediaControllerCallback : MediaControllerCompat.Callback() {
override fun onPlaybackStateChanged(state: PlaybackStateCompat?) {
playbackState.postValue(state ?: EMPTY_PLAYBACK_STATE)
}
override fun onMetadataChanged(metadata: MediaMetadataCompat?) {
nowPlaying.postValue(metadata ?: NOTHING_PLAYING)
}
override fun onQueueChanged(queue: MutableList<MediaSessionCompat.QueueItem>?) {
}
override fun onSessionEvent(event: String?, extras: Bundle?) {
super.onSessionEvent(event, extras)
when (event) {
NETWORK_FAILURE -> networkFailure.postValue(true)
}
}
/**
* Normally if a [MediaBrowserServiceCompat] drops its connection the callback comes via
* [MediaControllerCompat.Callback] (here). But since other connection status events
* are sent to [MediaBrowserCompat.ConnectionCallback], we catch the disconnect here and
* send it on to the other callback.
*/
override fun onSessionDestroyed() {
mediaBrowserConnectionCallback.onConnectionSuspended()
}
}
companion object {
// For Singleton instantiation.
@Volatile
private var instance: MediaSessionConnection? = null
fun getInstance(context: Context, serviceComponent: ComponentName) =
instance ?: synchronized(this) {
instance ?: MediaSessionConnection(context, serviceComponent)
.also { instance = it }
}
}
}
@Suppress("PropertyName")
val EMPTY_PLAYBACK_STATE: PlaybackStateCompat = PlaybackStateCompat.Builder()
.setState(PlaybackStateCompat.STATE_NONE, 0, 0f)
.build()
@Suppress("PropertyName")
val NOTHING_PLAYING: MediaMetadataCompat = MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, "")
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, 0)
.build()
| apache-2.0 | b36f9be746d9cdb460ecd601114370d2 | 38.021505 | 96 | 0.702535 | 5.290087 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.