repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
dinosaurwithakatana/freight
freight-processor/src/main/kotlin/io/dwak/freight/processor/binding/AbstractBindingClass.kt
1
5556
package io.dwak.freight.processor.binding import com.squareup.javapoet.* import io.dwak.freight.processor.extension.getTypeMirror import io.dwak.freight.processor.model.Binding import io.dwak.freight.processor.model.FieldBinding import java.io.IOException import javax.annotation.processing.Filer import javax.annotation.processing.Messager import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.Element import javax.lang.model.util.Elements import javax.lang.model.util.Types import javax.tools.Diagnostic abstract class AbstractBindingClass(val classPackage: String, val className: String, val targetClass: String, val processingEnvironment: ProcessingEnvironment) { val targetClassName = ClassName.get(classPackage, targetClass) val generatedClassName = ClassName.get(classPackage, className) val integer = TypeName.INT val float = TypeName.FLOAT val character = TypeName.CHAR val byte = TypeName.BYTE val short = TypeName.SHORT val boolean = TypeName.BOOLEAN val booleanObject = ClassName.get("java.lang", "Boolean") val integerObject = ClassName.get("java.lang", "Integer") val floatObject = ClassName.get("java.lang", "Float") val iBinder = ClassName.get("android.os", "IBinder") val bundle = ClassName.get("android.os", "Bundle") val charsequence = ClassName.get("java.lang", "CharSequence") val string = ClassName.get("java.lang", "String") val parcelable = ClassName.get("android.os", "Parcelable") val arrayList = ClassName.get("java.util", "ArrayList") val parcelableTypeMirror = processingEnvironment .getTypeMirror("${parcelable.packageName()}.${parcelable.simpleName()}") val serializableTypeMirror = processingEnvironment.getTypeMirror("java.io.Serializable") val integerArrayList = ParameterizedTypeName.get(arrayList, TypeName.INT.box()) val stringArrayList = ParameterizedTypeName.get(arrayList, string) val parcelableArrayList = ParameterizedTypeName.get(arrayList, parcelable) val charSequenceArrayList = ParameterizedTypeName.get(arrayList, charsequence) private val messager: Messager by lazy { processingEnvironment.messager } protected val elementUtils: Elements by lazy { processingEnvironment.elementUtils } protected val typeUtils: Types by lazy { processingEnvironment.typeUtils } protected val bindings = hashMapOf<String, Binding>() abstract fun createAndAddBinding(element: Element) abstract fun generate(): TypeSpec @Throws(IOException::class) fun writeToFiler(filer: Filer) { JavaFile.builder(classPackage, generate()).build().writeTo(filer) } @Suppress("unused") fun note(note: String) { messager.printMessage(Diagnostic.Kind.NOTE, note) } @Suppress("unused") fun error(message: String) { messager.printMessage(Diagnostic.Kind.ERROR, message) } @Suppress("unused") inline fun error(condition: Boolean, message: () -> String) { if (condition) error(message.invoke()) } protected fun handleType(it: FieldBinding, f: (String) -> String) : Pair<Boolean, String> { val bundleStatement: String = "" when { TypeName.get(it.type) == string -> return Pair(true, f("String")) TypeName.get(it.type) == charsequence -> return Pair(true, f("CharSequence")) TypeName.get(it.type) == integer -> return Pair(true, f("Int")) TypeName.get(it.type) == integerObject -> return Pair(true, f("Int")) TypeName.get(it.type) == float -> return Pair(true, f("Float")) TypeName.get(it.type) == floatObject -> return Pair(true, f("Float")) TypeName.get(it.type) == character -> return Pair(true, f("Char")) TypeName.get(it.type) == bundle -> return Pair(true, f("Bundle")) TypeName.get(it.type) == iBinder -> return Pair(true, f("Binder")) TypeName.get(it.type) == byte -> return Pair(true, f("Byte")) TypeName.get(it.type) == short -> return Pair(true, f("Short")) TypeName.get(it.type) == boolean -> return Pair(true, f("Boolean")) TypeName.get(it.type) == booleanObject -> return Pair(true, f("Boolean")) TypeName.get(it.type) == ArrayTypeName.of(float) -> return Pair(true, f("FloatArray")) TypeName.get(it.type) == ArrayTypeName.of(character) -> return Pair(true, f("CharArray")) TypeName.get(it.type) == ArrayTypeName.of(byte) -> return Pair(true, f("ByteArray")) TypeName.get(it.type) == ArrayTypeName.of(charsequence) -> return Pair(true, f("CharSequenceArray")) TypeName.get(it.type) == integerArrayList -> return Pair(true, f("IntegerArrayList")) TypeName.get(it.type) == stringArrayList -> return Pair(true, f("StringArrayList")) TypeName.get(it.type) == charSequenceArrayList -> return Pair(true, f("CharSequenceArrayList")) typeUtils.isAssignable(it.type, parcelableTypeMirror) -> return Pair(true, f("Parcelable")) typeUtils.isAssignable(it.type, serializableTypeMirror) -> return Pair(false, f("Serializable")) else -> return Pair(false, bundleStatement) } } }
apache-2.0
5067b33b13a8f3b89d679548900841e0
47.321739
100
0.651548
4.491512
false
false
false
false
kirimin/mitsumine
app/src/main/java/me/kirimin/mitsumine/bookmarklist/BookmarkPopupWindowBuilder.kt
1
1443
package me.kirimin.mitsumine.bookmarklist import android.content.Context import android.graphics.drawable.ColorDrawable import android.util.TypedValue import android.view.LayoutInflater import android.view.WindowManager import android.widget.ArrayAdapter import android.widget.ListView import android.widget.PopupWindow import me.kirimin.mitsumine.R object BookmarkPopupWindowBuilder { public val INDEX_SHARE: Int = 0 public val INDEX_BROWSER: Int = 1 public val INDEX_SEARCH: Int = 2 fun build(context: Context): PopupWindow { val popupWindow = PopupWindow(context) popupWindow.contentView = LayoutInflater.from(context).inflate(R.layout.popup_list, null) val list = popupWindow.contentView.findViewById(R.id.popupWindowListView) as ListView list.adapter = ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, listOf("共有", "ブラウザで見る", "ユーザーを検索")) val width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 160f, context.resources.displayMetrics) popupWindow.height = WindowManager.LayoutParams.WRAP_CONTENT popupWindow.width = width.toInt() popupWindow.isOutsideTouchable = true popupWindow.isFocusable = true popupWindow.isTouchable = true popupWindow.setBackgroundDrawable(ColorDrawable(context.resources.getColor(android.R.color.transparent))) return popupWindow } }
apache-2.0
32012cdd83d07d6b408f002481d103bb
41.787879
125
0.761162
4.451104
false
false
false
false
aosp-mirror/platform_frameworks_support
room/compiler/src/main/kotlin/androidx/room/solver/binderprovider/FlowableQueryResultBinderProvider.kt
1
2685
/* * 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 androidx.room.solver.binderprovider import androidx.room.ext.RoomRxJava2TypeNames import androidx.room.ext.RxJava2TypeNames import androidx.room.processor.Context import androidx.room.processor.ProcessorErrors import androidx.room.solver.ObservableQueryResultBinderProvider import androidx.room.solver.query.result.FlowableQueryResultBinder import androidx.room.solver.query.result.QueryResultAdapter import androidx.room.solver.query.result.QueryResultBinder import javax.lang.model.type.DeclaredType import javax.lang.model.type.TypeMirror class FlowableQueryResultBinderProvider(context: Context) : ObservableQueryResultBinderProvider(context) { private val flowableTypeMirror: TypeMirror? by lazy { context.processingEnv.elementUtils .getTypeElement(RxJava2TypeNames.FLOWABLE.toString())?.asType() } private val hasRxJava2Artifact by lazy { context.processingEnv.elementUtils .getTypeElement(RoomRxJava2TypeNames.RX_ROOM.toString()) != null } override fun extractTypeArg(declared: DeclaredType): TypeMirror = declared.typeArguments.first() override fun create(typeArg: TypeMirror, resultAdapter: QueryResultAdapter?, tableNames: Set<String>): QueryResultBinder { return FlowableQueryResultBinder( typeArg = typeArg, queryTableNames = tableNames, adapter = resultAdapter) } override fun matches(declared: DeclaredType): Boolean = declared.typeArguments.size == 1 && isRxJava2Publisher(declared) private fun isRxJava2Publisher(declared: DeclaredType): Boolean { if (flowableTypeMirror == null) { return false } val erasure = context.processingEnv.typeUtils.erasure(declared) val match = context.processingEnv.typeUtils.isAssignable(flowableTypeMirror, erasure) if (match && !hasRxJava2Artifact) { context.logger.e(ProcessorErrors.MISSING_ROOM_RXJAVA2_ARTIFACT) } return match } }
apache-2.0
f635d31164992728410f993df9bed1b3
39.69697
100
0.730726
4.84657
false
false
false
false
MaTriXy/gradle-play-publisher-1
play/plugin/src/test/kotlin/com/github/triplet/gradle/play/tasks/InstallInternalSharingArtifactIntegrationTest.kt
1
4733
package com.github.triplet.gradle.play.tasks import com.github.triplet.gradle.androidpublisher.FakePlayPublisher import com.github.triplet.gradle.androidpublisher.UploadInternalSharingArtifactResponse import com.github.triplet.gradle.androidpublisher.newUploadInternalSharingArtifactResponse import com.github.triplet.gradle.play.helpers.IntegrationTestBase import com.google.common.truth.Truth.assertThat import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.Test import java.io.File class InstallInternalSharingArtifactIntegrationTest : IntegrationTestBase() { override val factoryInstallerStatement = "com.github.triplet.gradle.play.tasks." + "InstallInternalSharingArtifactIntegrationTest.installFactories()" @Test fun `Build depends on uploading apk artifact by default`() { val result = execute("", "installReleasePrivateArtifact") assertThat(result.task(":uploadReleasePrivateApk")).isNotNull() assertThat(result.task(":uploadReleasePrivateApk")!!.outcome).isEqualTo(TaskOutcome.SUCCESS) } @Test fun `Build depends on uploading bundle artifact when specified`() { // language=gradle val config = """ play.defaultToAppBundles = true """ val result = execute(config, "installReleasePrivateArtifact") assertThat(result.task(":uploadReleasePrivateBundle")).isNotNull() assertThat(result.task(":uploadReleasePrivateBundle")!!.outcome).isEqualTo(TaskOutcome.SUCCESS) } @Test fun `Task is not cacheable`() { val result1 = execute("", "installReleasePrivateArtifact") val result2 = execute("", "installReleasePrivateArtifact") assertThat(result1.task(":installReleasePrivateArtifact")).isNotNull() assertThat(result1.task(":installReleasePrivateArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS) assertThat(result2.task(":installReleasePrivateArtifact")).isNotNull() assertThat(result2.task(":installReleasePrivateArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS) } @Test fun `Task launches view intent with artifact URL`() { val result = execute("", "installReleasePrivateArtifact") assertThat(result.task(":installReleasePrivateArtifact")).isNotNull() assertThat(result.task(":installReleasePrivateArtifact")!!.outcome).isEqualTo(TaskOutcome.SUCCESS) assertThat(result.output) .contains("am start -a \"android.intent.action.VIEW\" -d myDownloadUrl") } @Test fun `Task fails when shell connection fails`() { // language=gradle val config = """ System.setProperty("FAIL", "true") """ val result = executeExpectingFailure(config, "installReleasePrivateArtifact") assertThat(result.task(":installReleasePrivateArtifact")).isNotNull() assertThat(result.task(":installReleasePrivateArtifact")!!.outcome).isEqualTo(TaskOutcome.FAILED) assertThat(result.output).contains("Failed to install") } companion object { @JvmStatic fun installFactories() { val publisher = object : FakePlayPublisher() { override fun uploadInternalSharingApk( apkFile: File ): UploadInternalSharingArtifactResponse { println("uploadInternalSharingApk($apkFile)") return newUploadInternalSharingArtifactResponse( "{\"downloadUrl\": \"myDownloadUrl\"}", "") } override fun uploadInternalSharingBundle( bundleFile: File ): UploadInternalSharingArtifactResponse { println("uploadInternalSharingBundle($bundleFile)") return newUploadInternalSharingArtifactResponse( "{\"downloadUrl\": \"myDownloadUrl\"}", "") } } val shell = object : InstallInternalSharingArtifact.AdbShell { fun install() { val context = this InstallInternalSharingArtifact.AdbShell.setFactory( object : InstallInternalSharingArtifact.AdbShell.Factory { override fun create(adbExecutable: File, timeOutInMs: Int) = context }) } override fun executeShellCommand(command: String): Boolean { println("executeShellCommand($command)") return System.getProperty("FAIL") == null } } publisher.install() shell.install() } } }
mit
e75ae631126a8a4c1c4fff7598ec2f6c
41.63964
107
0.644834
5.771951
false
true
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/action/item/MousePointerSingleAction.kt
1
3868
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.legacy.action.item import android.app.AlertDialog import android.os.Parcel import android.os.Parcelable import android.view.View import android.widget.CheckBox import com.squareup.moshi.JsonReader import com.squareup.moshi.JsonWriter import jp.hazuki.yuzubrowser.legacy.R import jp.hazuki.yuzubrowser.legacy.action.SingleAction import jp.hazuki.yuzubrowser.legacy.action.view.ActionActivity import jp.hazuki.yuzubrowser.ui.app.StartActivityInfo import java.io.IOException class MousePointerSingleAction : SingleAction, Parcelable { var isBackFinish = true private set @Throws(IOException::class) constructor(id: Int, reader: JsonReader?) : super(id) { if (reader != null) { if (reader.peek() != JsonReader.Token.BEGIN_OBJECT) return reader.beginObject() while (reader.hasNext()) { if (reader.peek() != JsonReader.Token.NAME) return when (reader.nextName()) { FIELD_NAME_BACK_FINISH -> { if (reader.peek() == JsonReader.Token.NULL) { reader.skipValue() } else { isBackFinish = reader.nextBoolean() } } else -> reader.skipValue() } } reader.endObject() } } @Throws(IOException::class) override fun writeIdAndData(writer: JsonWriter) { writer.value(id) writer.beginObject() writer.name(FIELD_NAME_BACK_FINISH) writer.value(isBackFinish) writer.endObject() } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(id) dest.writeInt(if (isBackFinish) 1 else 0) } private constructor(source: Parcel) : super(source.readInt()) { isBackFinish = source.readInt() == 1 } override fun showSubPreference(context: ActionActivity): StartActivityInfo? { val view = View.inflate(context, R.layout.action_checkbox, null) val checkBox = view.findViewById(R.id.checkBox) as CheckBox checkBox.setText(R.string.action_mousepointer_backfinish) checkBox.isChecked = isBackFinish AlertDialog.Builder(context) .setTitle(R.string.action_settings) .setView(view) .setPositiveButton(android.R.string.ok) { _, _ -> isBackFinish = checkBox.isChecked } .setNegativeButton(android.R.string.cancel, null) .show() return null } companion object { private const val TAG = "MousePointerSingleAction" private const val FIELD_NAME_BACK_FINISH = "0" @JvmField val CREATOR: Parcelable.Creator<MousePointerSingleAction> = object : Parcelable.Creator<MousePointerSingleAction> { override fun createFromParcel(source: Parcel): MousePointerSingleAction { return MousePointerSingleAction(source) } override fun newArray(size: Int): Array<MousePointerSingleAction?> { return arrayOfNulls(size) } } } }
apache-2.0
704201db276b0c70becc26717deaaea7
33.535714
123
0.633402
4.582938
false
false
false
false
seventhroot/elysium
bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/servlet/api/v1/GitHubProfileAPIServlet.kt
1
5851
package com.rpkit.players.bukkit.servlet.api.v1 import com.google.gson.Gson import com.rpkit.core.web.RPKServlet import com.rpkit.players.bukkit.RPKPlayersBukkit import com.rpkit.players.bukkit.profile.RPKGitHubProfileImpl import com.rpkit.players.bukkit.profile.RPKGitHubProfileProvider import com.rpkit.players.bukkit.profile.RPKProfileProvider import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import javax.servlet.http.HttpServletResponse.* class GitHubProfileAPIServlet(private val plugin: RPKPlayersBukkit): RPKServlet() { override val url = "/api/v1/githubprofile/*" override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) { val gson = Gson() if (req.pathInfo == null) { resp.contentType = "application/json" resp.status = SC_NOT_FOUND resp.writer.write( gson.toJson( mapOf( Pair("message", "Not found.") ) ) ) return } val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class) val profile = profileProvider.getProfile(req.pathInfo.drop(1)) if (profile == null) { resp.contentType = "application/json" resp.status = SC_NOT_FOUND resp.writer.write( gson.toJson( mapOf( Pair("message", "Not found.") ) ) ) return } val githubProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKGitHubProfileProvider::class) val githubProfiles = githubProfileProvider.getGitHubProfiles(profile) resp.contentType = "application/json" resp.status = SC_OK resp.writer.write( gson.toJson( githubProfiles.map { githubProfile -> mapOf( Pair("id", githubProfile.id), Pair("profile_id", githubProfile.profile.id), Pair("name", githubProfile.name) ) } ) ) } override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) { val gson = Gson() if (req.pathInfo == null) { resp.contentType = "application/json" resp.status = SC_NOT_FOUND resp.writer.write( gson.toJson( mapOf( Pair("message", "Not found.") ) ) ) return } val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class) val profile = profileProvider.getProfile(req.pathInfo.drop(1)) if (profile == null) { resp.contentType = "application/json" resp.status = SC_NOT_FOUND resp.writer.write( gson.toJson( mapOf( Pair("message", "Not found.") ) ) ) return } val activeProfile = profileProvider.getActiveProfile(req) if (activeProfile == null) { resp.contentType = "application/json" resp.status = SC_FORBIDDEN resp.writer.write( gson.toJson( mapOf( Pair("message", "Not authenticated.") ) ) ) return } if (activeProfile != profile) { resp.contentType = "application/json" resp.status = SC_FORBIDDEN resp.writer.write( gson.toJson( mapOf( Pair("message", "You do not have permission.") ) ) ) return } val name = req.getParameter("name") if (name == null) { resp.contentType = "application/json" resp.status = SC_BAD_REQUEST resp.writer.write( gson.toJson( mapOf( Pair("message", "Missing name parameter.") ) ) ) return } val oauthToken = req.getParameter("oauth_token") if (oauthToken == null) { resp.contentType = "application/json" resp.status = SC_BAD_REQUEST resp.writer.write( gson.toJson( mapOf( Pair("message", "Missing oauth token parameter.") ) ) ) return } val githubProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKGitHubProfileProvider::class) val githubProfile = RPKGitHubProfileImpl( profile = profile, name = name, oauthToken = oauthToken ) githubProfileProvider.addGitHubProfile(githubProfile) resp.contentType = "application/json" resp.status = SC_OK resp.writer.write( gson.toJson( mapOf( Pair("message", "GitHub profile added successfully.") ) ) ) } }
apache-2.0
89b3aad36295eaba83e8fb503520fef8
35.575
114
0.47086
5.686103
false
false
false
false
crummy/spacetrader
src/main/kotlin/com/malcolmcrum/spacetrader/controllers/MarketController.kt
1
4607
package com.malcolmcrum.spacetrader.controllers import com.malcolmcrum.spacetrader.model.* import com.malcolmcrum.spacetrader.nouns.random import kotlin.math.roundToInt val MAX_SKILL = 10 // TODO: move elsewhere class MarketController(private val market: Market, private val system: SolarSystem, private val difficulty: Difficulty) { fun updateAmounts() { when { market.countdown > getInitialCountdown(difficulty) -> market.countdown = getInitialCountdown(difficulty) market.countdown <= 0 -> TradeItem.values().forEach { resetQuantity(it) } else -> TradeItem.values().forEach { increaseQuantity(it) } } } fun updatePrices() { TradeItem.values().filter { !isNotSold(it) } .forEach { var price = standardPrice(it, system.size, system.tech, system.politics, system.specialResource) if (it.doublePriceStatus == system.status) { price *= 2 } price = price + (0..it.priceVariance).random() - (0..it.priceVariance).random() market.basePrices[it] = Math.max(0, price) } } private fun isNotSold(item: TradeItem): Boolean { return when { item == TradeItem.NARCOTICS && !system.politics.drugsOk -> true item == TradeItem.FIREARMS && !system.politics.firearmsOk -> true system.tech < item.techRequiredForProduction -> true else -> false } } private fun resetQuantity(item: TradeItem) { market.amounts[item] = standardQuantity(item) } private fun standardQuantity(item: TradeItem): Int { if (isNotSold(item)) { return 0 } var quantity = 9 + (0..5).random() - Math.abs(item.techOptimalProduction.ordinal - system.tech.ordinal) * (1 + system.size.ordinal) if (item == TradeItem.NARCOTICS || item == TradeItem.ROBOTS) { quantity = (quantity * (5 - difficulty.ordinal) / (6 - difficulty.ordinal)) + 1 } if (system.specialResource == item.cheapResource) { quantity *= 4/3 } if (system.specialResource == item.expensiveResource) { quantity = (quantity * 3) shr 2 } if (system.status == item.doublePriceStatus) { quantity /= 5 } quantity = quantity - (0..10).random() + (0..10).random() return Math.max(quantity, 0) } private fun getInitialCountdown(difficulty: Difficulty) = difficulty.ordinal + 3 private fun increaseQuantity(item: TradeItem) { val increment = when { isNotSold(item) -> 0 else -> Math.max(0, market.amounts[item]!! + (0..5).random() - (0..5).random()) } val previousValue = market.amounts[item]!! market.amounts[item] = previousValue + increment } fun getBuyPrice(item: TradeItem, tradeSkill: Int, policeRecord: PoliceRecord): Int { if (isNotSold(item)) { return 0 } val basePrice = market.basePrices[item]!! var buyPrice = (basePrice * policeRecord.marketPriceModifier()).roundToInt() buyPrice = (buyPrice * (103 + (MAX_SKILL - tradeSkill)) / 100) return if (buyPrice <= basePrice) { basePrice + 1 } else { buyPrice } } fun getSellPrice(item: TradeItem, policeRecord: PoliceRecord): Int { val basePrice = market.basePrices[item]!! return (basePrice * policeRecord.marketPriceModifier()).roundToInt() } private fun standardPrice(item: TradeItem, size: SystemSize, tech: TechLevel, politics: Politics, specialResource: SpecialResource?): Int { var price = item.minTradePrice + (tech.ordinal * item.priceIncreasePerTechLevel) if (politics.desiredTradeItem == item) { price *= 4/3 } price = (price * (100 - (2 * politics.strengthTraders))) / 100 price = (price * (100 - size.ordinal)) / 100 if (specialResource == item.cheapResource) { price *= 3 / 4 } if (specialResource == item.expensiveResource) { price *= 4 / 3 } return Math.max(0, price) } fun getAmount(item: TradeItem): Int { return market.amounts[item]!! } fun remove(item: TradeItem, amount: Int) { market.amounts[item] = market.amounts[item]!!.minus(amount) } fun add(item: TradeItem, amount: Int) { market.amounts[item] = market.amounts[item]!!.plus(amount) } }
gpl-2.0
ebf9fe4411e9cdefc471e2e3496561ea
31.914286
143
0.591925
3.978411
false
false
false
false
Yorxxx/played-next-kotlin
app/src/commonTest/java/com/piticlistudio/playednext/common/TestDataFactory.kt
1
1977
package com.piticlistudio.playednext.common import java.util.* /** * Factory class that makes instances of data models with random field values. * The aim of this class is to help setting up test fixtures. */ object TestDataFactory { private val sRandom = Random() // fun randomUuid(): String { // return UUID.randomUUID().toString() // } // // fun makePokemon(id: String): Pokemon { // return Pokemon(id, randomUuid() + id, makeSprites(), makeStatisticList(3)) // } // // fun makePokemonNamesList(count: Int): List<String> { // val pokemonList = ArrayList<String>() // for (i in 0..count - 1) { // pokemonList.add(makePokemon(i.toString()).name) // } // return pokemonList // } // // fun makePokemonNameList(pokemonList: List<NamedResource>): List<String> { // val names = ArrayList<String>() // for (pokemon in pokemonList) { // names.add(pokemon.name) // } // return names // } // // fun makeStatistic(): Statistic { // val statistic = Statistic() // statistic.baseStat = sRandom.nextInt() // statistic.stat = makeNamedResource(randomUuid()) // return statistic // } // // fun makeStatisticList(count: Int): List<Statistic> { // val statisticList = ArrayList<Statistic>() // for (i in 0..count - 1) { // statisticList.add(makeStatistic()) // } // return statisticList // } // // fun makeSprites(): Sprites { // val sprites = Sprites() // sprites.frontDefault = randomUuid() // return sprites // } // // fun makeNamedResource(unique: String): NamedResource { // return NamedResource(randomUuid() + unique, randomUuid()) // } // // fun makeNamedResourceList(count: Int): List<NamedResource> { // val namedResourceList = (0..count - 1).map { makeNamedResource(it.toString()) } // return namedResourceList // } }
mit
474f5ca70d05511188c9d395b6edf096
28.969697
89
0.596358
3.730189
false
false
false
false
herolynx/bouncer
src/main/kotlin/com/herolynx/bouncer/db/sql/BasicRepository.kt
1
1131
package com.herolynx.bouncer.db.sql import com.herolynx.bouncer.db.ReadRepository import com.herolynx.bouncer.db.WriteRepository import com.querydsl.jpa.impl.JPAQuery import org.funktionale.option.Option import org.funktionale.option.toOption import org.funktionale.tries.Try import javax.persistence.EntityManager internal class BasicWriteRepository(private val em:EntityManager) : WriteRepository, BasicReadRepository(em) { override fun <T> save(entity: T): Try<T> = Try { em.merge<T>(entity) } override fun <T, Id> delete(clazz: Class<T>, id: Id): Try<Option<T>> = Try { val entity = em.find(clazz, id).toOption() entity.map { e -> em.remove(e) em.flush() } entity } } internal open class BasicReadRepository : ReadRepository { private val em: EntityManager constructor(em: EntityManager) { this.em = em } override fun <T, Id> find(clazz: Class<T>, id: Id): Try<Option<T>> = Try { em.find(clazz, id).toOption() } override fun <T> query(query: (JPAQuery<Any>) -> T): Try<T> = Try { query(JPAQuery<Any>(em)) } }
mit
224159d04427df118c6ef7aa6014295f
27.3
110
0.667551
3.469325
false
false
false
false
savoirfairelinux/ring-client-android
ring-android/app/src/main/java/cx/ring/fragments/ConversationFragment.kt
1
51716
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Author: Adrien Béraud <[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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package cx.ring.fragments import android.Manifest import android.animation.LayoutTransition import android.animation.ValueAnimator import android.annotation.SuppressLint import android.app.Activity import android.app.ActivityOptions import android.content.* import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.content.pm.PackageManager import android.graphics.Typeface import android.hardware.Camera import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.os.IBinder import android.provider.MediaStore import android.text.Editable import android.text.TextUtils import android.text.TextWatcher import android.util.Log import android.view.* import android.view.inputmethod.EditorInfo import android.widget.* import androidx.annotation.ColorInt import androidx.appcompat.view.menu.MenuBuilder import androidx.appcompat.view.menu.MenuPopupHelper import androidx.appcompat.widget.PopupMenu import androidx.appcompat.widget.Toolbar import androidx.core.view.* import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.appbar.AppBarLayout import com.google.android.material.snackbar.Snackbar import cx.ring.R import cx.ring.adapters.ConversationAdapter import cx.ring.application.JamiApplication import cx.ring.client.CallActivity import cx.ring.client.ContactDetailsActivity import cx.ring.client.ConversationActivity import cx.ring.client.HomeActivity import cx.ring.databinding.FragConversationBinding import cx.ring.interfaces.Colorable import cx.ring.mvp.BaseSupportFragment import cx.ring.service.DRingService import cx.ring.service.LocationSharingService import cx.ring.services.NotificationServiceImpl import cx.ring.services.SharedPreferencesServiceImpl.Companion.getConversationPreferences import cx.ring.utils.ActionHelper import cx.ring.utils.AndroidFileUtils import cx.ring.utils.ContentUriHandler import cx.ring.utils.ConversationPath import cx.ring.utils.DeviceUtils.isTablet import cx.ring.utils.MediaButtonsHelper.MediaButtonsHelperCallback import cx.ring.views.AvatarDrawable import cx.ring.views.AvatarFactory import dagger.hilt.android.AndroidEntryPoint import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.disposables.CompositeDisposable import net.jami.conversation.ConversationPresenter import net.jami.conversation.ConversationView import net.jami.daemon.JamiService import net.jami.model.* import net.jami.model.Account.ComposingStatus import net.jami.services.NotificationService import net.jami.smartlist.ConversationItemViewModel import java.io.File import java.util.* @AndroidEntryPoint class ConversationFragment : BaseSupportFragment<ConversationPresenter, ConversationView>(), MediaButtonsHelperCallback, ConversationView, OnSharedPreferenceChangeListener { private var locationServiceConnection: ServiceConnection? = null private var binding: FragConversationBinding? = null private var mAudioCallBtn: MenuItem? = null private var mVideoCallBtn: MenuItem? = null private var currentBottomView: View? = null private var mAdapter: ConversationAdapter? = null private var marginPx = 0 private var marginPxTotal = 0 private val animation = ValueAnimator() private var mPreferences: SharedPreferences? = null private var mCurrentPhoto: File? = null private var mCurrentFileAbsolutePath: String? = null private val mCompositeDisposable = CompositeDisposable() private var mSelectedPosition = 0 private var mIsBubble = false private var mConversationAvatar: AvatarDrawable? = null private val mParticipantAvatars: MutableMap<String, AvatarDrawable> = HashMap() private val mSmallParticipantAvatars: MutableMap<String, AvatarDrawable> = HashMap() private var mapWidth = 0 private var mapHeight = 0 private var mLastRead: String? = null private var loading = true private var animating = 0 fun getConversationAvatar(uri: String): AvatarDrawable? { return mParticipantAvatars[uri] } fun getSmallConversationAvatar(uri: String): AvatarDrawable? { synchronized(mSmallParticipantAvatars) { return mSmallParticipantAvatars[uri] } } override fun refreshView(conversation: List<Interaction>) { if (binding != null) binding!!.pbLoading.visibility = View.GONE mAdapter?.let { adapter -> adapter.updateDataset(conversation) loading = false } requireActivity().invalidateOptionsMenu() } override fun scrollToEnd() { mAdapter?.let { adapter -> if (adapter.itemCount > 0) binding!!.histList.scrollToPosition(adapter.itemCount - 1) } } private fun updateListPadding() { val binding = binding ?: return val bottomView = currentBottomView ?: return val bottomViewHeight = bottomView.height if (bottomViewHeight != 0) { val padding = bottomViewHeight + marginPxTotal binding.histList.updatePadding(bottom = padding) val params = binding.mapCard.layoutParams as RelativeLayout.LayoutParams params.bottomMargin = padding binding.mapCard.layoutParams = params } } override fun displayErrorToast(error: Error) { val errorString: String = when (error) { Error.NO_INPUT -> getString(R.string.call_error_no_camera_no_microphone) Error.INVALID_FILE -> getString(R.string.invalid_file) Error.NOT_ABLE_TO_WRITE_FILE -> getString(R.string.not_able_to_write_file) Error.NO_SPACE_LEFT -> getString(R.string.no_space_left_on_device) else -> getString(R.string.generic_error) } Toast.makeText(requireContext(), errorString, Toast.LENGTH_LONG).show() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { val res = resources marginPx = res.getDimensionPixelSize(R.dimen.conversation_message_input_margin) mapWidth = res.getDimensionPixelSize(R.dimen.location_sharing_minmap_width) mapHeight = res.getDimensionPixelSize(R.dimen.location_sharing_minmap_height) marginPxTotal = marginPx return FragConversationBinding.inflate(inflater, container, false).let { binding -> [email protected] = binding binding.presenter = this@ConversationFragment animation.duration = 150 animation.addUpdateListener { valueAnimator: ValueAnimator -> binding.histList.updatePadding(bottom = valueAnimator.animatedValue as Int) } val layout: View = binding.conversationLayout // remove action bar height for tablet layout if (isTablet(layout.context)) { layout.updatePadding(top = 0) } if (Build.VERSION.SDK_INT >= 30) { ViewCompat.setWindowInsetsAnimationCallback( layout, object : WindowInsetsAnimationCompat.Callback(DISPATCH_MODE_STOP) { override fun onPrepare(animation: WindowInsetsAnimationCompat) { animating++ } override fun onProgress( insets: WindowInsetsCompat, runningAnimations: List<WindowInsetsAnimationCompat> ): WindowInsetsCompat { layout.updatePadding(bottom = insets.systemWindowInsetBottom) return insets } override fun onEnd(animation: WindowInsetsAnimationCompat) { animating-- } }) } ViewCompat.setOnApplyWindowInsetsListener(layout) { _, insets: WindowInsetsCompat -> if (animating == 0) layout.updatePadding(bottom = insets.systemWindowInsetBottom) WindowInsetsCompat.CONSUMED } binding.ongoingcallPane.visibility = View.GONE ViewCompat.setOnReceiveContentListener(binding.msgInputTxt, SUPPORTED_MIME_TYPES) { _, contentInfo -> for (i in 0 until contentInfo.clip.itemCount) { val item: ClipData.Item = contentInfo.clip.getItemAt(i) if (item.uri == null && item.text != null) { binding.msgInputTxt.setText(item.text) } else { startFileSend(AndroidFileUtils.getCacheFile(requireContext(), item.uri) .flatMapCompletable { sendFile(it) }) } } null } binding.msgInputTxt.setOnEditorActionListener { _, actionId: Int, _ -> actionSendMsgText(actionId) } binding.msgInputTxt.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus: Boolean -> if (hasFocus) { (childFragmentManager.findFragmentById(R.id.mapLayout) as LocationSharingFragment?)?.hideControls() } } binding.msgInputTxt.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {} override fun afterTextChanged(s: Editable) { val message = s.toString() val hasMessage = !TextUtils.isEmpty(message) presenter.onComposingChanged(hasMessage) if (hasMessage) { binding.msgSend.visibility = View.VISIBLE binding.emojiSend.visibility = View.GONE } else { binding.msgSend.visibility = View.GONE binding.emojiSend.visibility = View.VISIBLE } mPreferences?.let { preferences -> if (hasMessage) preferences.edit().putString(KEY_PREFERENCE_PENDING_MESSAGE, message).apply() else preferences.edit().remove(KEY_PREFERENCE_PENDING_MESSAGE).apply() } } }) setHasOptionsMenu(true) binding.root } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding?.let { binding -> mPreferences?.let { preferences -> val pendingMessage = preferences.getString(KEY_PREFERENCE_PENDING_MESSAGE, null) if (pendingMessage != null && pendingMessage.isNotEmpty()) { binding.msgInputTxt.setText(pendingMessage) binding.msgSend.visibility = View.VISIBLE binding.emojiSend.visibility = View.GONE } } binding.msgInputTxt.addOnLayoutChangeListener { _, _, _, _, _, oldLeft, oldTop, oldRight, oldBottom -> if (oldBottom == 0 && oldTop == 0) { updateListPadding() } else { if (animation.isStarted) animation.cancel() animation.setIntValues( binding.histList.paddingBottom, (currentBottomView?.height ?: 0) + marginPxTotal ) animation.start() } } binding.histList.addOnScrollListener(object : RecyclerView.OnScrollListener() { // The minimum amount of items to have below current scroll position // before loading more. val visibleThreshold = 3 override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {} override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { val layoutManager = recyclerView.layoutManager as LinearLayoutManager? if (!loading && layoutManager!!.findFirstVisibleItemPosition() < visibleThreshold) { loading = true presenter.loadMore() } } }) val animator = binding.histList.itemAnimator as DefaultItemAnimator? animator?.supportsChangeAnimations = false binding.histList.adapter = mAdapter val toolbarLayout: AppBarLayout? = activity?.findViewById(R.id.toolbar_layout) toolbarLayout?.isLifted = true } } override fun setConversationColor(@ColorInt color: Int) { val activity = activity as Colorable? activity?.setColor(color) mAdapter?.setPrimaryColor(color) } override fun setConversationSymbol(symbol: CharSequence) { binding?.emojiSend?.text = symbol } override fun onDestroyView() { mPreferences?.unregisterOnSharedPreferenceChangeListener(this) animation.removeAllUpdateListeners() binding?.histList?.adapter = null mCompositeDisposable.clear() locationServiceConnection?.let { try { requireContext().unbindService(it) } catch (e: Exception) { Log.w(TAG, "Error unbinding service: " + e.message) } } mAdapter = null super.onDestroyView() binding = null } override fun onContextItemSelected(item: MenuItem): Boolean { return if (mAdapter!!.onContextItemSelected(item)) true else super.onContextItemSelected(item) } fun updateAdapterItem() { if (mSelectedPosition != -1) { mAdapter!!.notifyItemChanged(mSelectedPosition) mSelectedPosition = -1 } } fun sendMessageText() { val message = binding!!.msgInputTxt.text.toString() clearMsgEdit() presenter.sendTextMessage(message) } fun sendEmoji() { presenter.sendTextMessage(binding!!.emojiSend.text.toString()) } @SuppressLint("RestrictedApi") fun expandMenu(v: View) { val context = requireContext() val popup = PopupMenu(context, v) popup.inflate(R.menu.conversation_share_actions) popup.setOnMenuItemClickListener { item: MenuItem -> when (item.itemId) { R.id.conv_send_audio -> sendAudioMessage() R.id.conv_send_video -> sendVideoMessage() R.id.conv_send_file -> presenter.selectFile() R.id.conv_share_location -> shareLocation() R.id.chat_plugins -> presenter.showPluginListHandlers() } false } popup.menu.findItem(R.id.chat_plugins).isVisible = JamiService.getPluginsEnabled() && !JamiService.getChatHandlers().isEmpty() val menuHelper = MenuPopupHelper(context, (popup.menu as MenuBuilder), v) menuHelper.setForceShowIcon(true) menuHelper.show() } override fun showPluginListHandlers(accountId: String, contactId: String) { Log.w(TAG, "show Plugin Chat Handlers List") val fragment = PluginHandlersListFragment.newInstance(accountId, contactId) childFragmentManager.beginTransaction() .add(R.id.pluginListHandlers, fragment, PluginHandlersListFragment.TAG) .commit() binding?.let { binding -> val params = binding.mapCard.layoutParams as RelativeLayout.LayoutParams if (params.width != ViewGroup.LayoutParams.MATCH_PARENT) { params.width = ViewGroup.LayoutParams.MATCH_PARENT params.height = ViewGroup.LayoutParams.MATCH_PARENT binding.mapCard.layoutParams = params } binding.mapCard.visibility = View.VISIBLE } } fun hidePluginListHandlers() { if (binding!!.mapCard.visibility != View.GONE) { binding!!.mapCard.visibility = View.GONE val fragmentManager = childFragmentManager val fragment = fragmentManager.findFragmentById(R.id.pluginListHandlers) if (fragment != null) { fragmentManager.beginTransaction() .remove(fragment) .commit() } } val params = binding!!.mapCard.layoutParams as RelativeLayout.LayoutParams if (params.width != mapWidth) { params.width = mapWidth params.height = mapHeight binding!!.mapCard.layoutParams = params } } private fun shareLocation() { presenter.shareLocation() } fun closeLocationSharing(isSharing: Boolean) { val params = binding!!.mapCard.layoutParams as RelativeLayout.LayoutParams if (params.width != mapWidth) { params.width = mapWidth params.height = mapHeight binding!!.mapCard.layoutParams = params } if (!isSharing) hideMap() } fun openLocationSharing() { binding!!.conversationLayout.layoutTransition.enableTransitionType(LayoutTransition.CHANGING) val params = binding!!.mapCard.layoutParams as RelativeLayout.LayoutParams if (params.width != ViewGroup.LayoutParams.MATCH_PARENT) { params.width = ViewGroup.LayoutParams.MATCH_PARENT params.height = ViewGroup.LayoutParams.MATCH_PARENT binding!!.mapCard.layoutParams = params } } override fun startShareLocation(accountId: String, conversationId: String) { showMap(accountId, conversationId, true) } /** * Used to update with the past adapter position when a long click was registered */ fun updatePosition(position: Int) { mSelectedPosition = position } override fun showMap(accountId: String, contactId: String, open: Boolean) { if (binding!!.mapCard.visibility == View.GONE) { Log.w(TAG, "showMap $accountId $contactId") val fragmentManager = childFragmentManager val fragment = LocationSharingFragment.newInstance(accountId, contactId, open) fragmentManager.beginTransaction() .add(R.id.mapLayout, fragment, "map") .commit() binding!!.mapCard.visibility = View.VISIBLE } if (open) { val fragment = childFragmentManager.findFragmentById(R.id.mapLayout) if (fragment != null) { (fragment as LocationSharingFragment).showControls() } } } override fun hideMap() { if (binding!!.mapCard.visibility != View.GONE) { binding!!.mapCard.visibility = View.GONE val fragmentManager = childFragmentManager val fragment = fragmentManager.findFragmentById(R.id.mapLayout) if (fragment != null) { fragmentManager.beginTransaction() .remove(fragment) .commit() } } } private fun sendAudioMessage() { if (!presenter.deviceRuntimeService.hasAudioPermission()) { requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), REQUEST_CODE_CAPTURE_AUDIO) } else { try { val ctx = requireContext() val intent = Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION) mCurrentPhoto = AndroidFileUtils.createAudioFile(ctx) startActivityForResult(intent, REQUEST_CODE_CAPTURE_AUDIO) } catch (ex: Exception) { Log.e(TAG, "sendAudioMessage: error", ex) Toast.makeText(activity, "Can't find audio recorder app", Toast.LENGTH_SHORT).show() } } } private fun sendVideoMessage() { if (!presenter.deviceRuntimeService.hasVideoPermission()) { requestPermissions(arrayOf(Manifest.permission.CAMERA), REQUEST_CODE_CAPTURE_VIDEO) } else { try { val context = requireContext() val intent = Intent(MediaStore.ACTION_VIDEO_CAPTURE).apply { putExtra("android.intent.extras.CAMERA_FACING", Camera.CameraInfo.CAMERA_FACING_FRONT) putExtra("android.intent.extras.LENS_FACING_FRONT", 1) putExtra("android.intent.extra.USE_FRONT_CAMERA", true) putExtra(MediaStore.EXTRA_OUTPUT, ContentUriHandler.getUriForFile(context, ContentUriHandler.AUTHORITY_FILES, AndroidFileUtils.createVideoFile(context).apply { mCurrentPhoto = this })) } startActivityForResult(intent, REQUEST_CODE_CAPTURE_VIDEO) } catch (ex: Exception) { Log.e(TAG, "sendVideoMessage: error", ex) Toast.makeText(activity, "Can't find video recorder app", Toast.LENGTH_SHORT).show() } } } fun takePicture() { if (!presenter.deviceRuntimeService.hasVideoPermission()) { requestPermissions(arrayOf(Manifest.permission.CAMERA), REQUEST_CODE_TAKE_PICTURE) return } val c = context ?: return try { val photoFile = AndroidFileUtils.createImageFile(c) Log.i(TAG, "takePicture: trying to save to $photoFile") val photoURI = ContentUriHandler.getUriForFile(c, ContentUriHandler.AUTHORITY_FILES, photoFile) val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, photoURI) .putExtra("android.intent.extras.CAMERA_FACING", 1) .putExtra("android.intent.extras.LENS_FACING_FRONT", 1) .putExtra("android.intent.extra.USE_FRONT_CAMERA", true) mCurrentPhoto = photoFile startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PICTURE) } catch (e: Exception) { Toast.makeText(c, "Error taking picture: " + e.localizedMessage, Toast.LENGTH_SHORT) .show() } } override fun askWriteExternalStoragePermission() { requestPermissions( arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), JamiApplication.PERMISSIONS_REQUEST ) } override fun openFilePicker() { val intent = Intent(Intent.ACTION_GET_CONTENT) intent.addCategory(Intent.CATEGORY_OPENABLE) intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) intent.type = "*/*" startActivityForResult(intent, REQUEST_CODE_FILE_PICKER) } private fun sendFile(file: File): Completable { return Completable.fromAction { presenter.sendFile(file) } } private fun startFileSend(op: Completable) { setLoading(true) op.observeOn(AndroidSchedulers.mainThread()) .doFinally { setLoading(false) } .subscribe({}) { e -> Log.e(TAG, "startFileSend: not able to create cache file", e) displayErrorToast(Error.INVALID_FILE) } } override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) { Log.w(TAG, "onActivityResult: $requestCode $resultCode $resultData") if (requestCode == REQUEST_CODE_FILE_PICKER) { if (resultCode == Activity.RESULT_OK && resultData != null) { val clipData = resultData.clipData if (clipData != null) { // checking multiple selection or not for (i in 0 until clipData.itemCount) { val uri = clipData.getItemAt(i).uri startFileSend(AndroidFileUtils.getCacheFile(requireContext(), uri) .observeOn(AndroidSchedulers.mainThread()) .flatMapCompletable { file: File -> sendFile(file) }) } } else { resultData.data?.let { uri -> startFileSend(AndroidFileUtils.getCacheFile(requireContext(), uri) .observeOn(AndroidSchedulers.mainThread()) .flatMapCompletable { file: File -> sendFile(file) }) } } } } else if (requestCode == REQUEST_CODE_TAKE_PICTURE || requestCode == REQUEST_CODE_CAPTURE_AUDIO || requestCode == REQUEST_CODE_CAPTURE_VIDEO) { if (resultCode != Activity.RESULT_OK) { mCurrentPhoto = null return } val currentPhoto = mCurrentPhoto var file: Single<File>? = null if (currentPhoto == null || !currentPhoto.exists() || currentPhoto.length() == 0L) { resultData?.data?.let { uri -> file = AndroidFileUtils.getCacheFile(requireContext(), uri) } } else { file = Single.just(currentPhoto) } mCurrentPhoto = null val sendingFile = file if (sendingFile != null) startFileSend(sendingFile.flatMapCompletable { f -> sendFile(f) }) else Toast.makeText(activity, "Can't find picture", Toast.LENGTH_SHORT).show() } else if (requestCode == REQUEST_CODE_SAVE_FILE) { val uri = resultData?.data if (resultCode == Activity.RESULT_OK && uri != null) { writeToFile(uri) } } } private fun writeToFile(data: Uri) { val path = mCurrentFileAbsolutePath ?: return val cr = context?.contentResolver ?: return mCompositeDisposable.add(AndroidFileUtils.copyFileToUri(cr, File(path), data) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ Toast.makeText(context, R.string.file_saved_successfully, Toast.LENGTH_SHORT).show() }) { Toast.makeText(context, R.string.generic_error, Toast.LENGTH_SHORT).show() }) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { var i = 0 val n = permissions.size while (i < n) { val granted = grantResults[i] == PackageManager.PERMISSION_GRANTED when (permissions[i]) { Manifest.permission.CAMERA -> { presenter.cameraPermissionChanged(granted) if (granted) { if (requestCode == REQUEST_CODE_CAPTURE_VIDEO) { sendVideoMessage() } else if (requestCode == REQUEST_CODE_TAKE_PICTURE) { takePicture() } } return } Manifest.permission.RECORD_AUDIO -> { if (granted) { if (requestCode == REQUEST_CODE_CAPTURE_AUDIO) { sendAudioMessage() } } return } else -> { } } i++ } } override fun addElement(element: Interaction) { if (mLastRead != null && mLastRead == element.messageId) element.read() if (mAdapter!!.add(element)) scrollToEnd() loading = false } override fun updateElement(element: Interaction) { mAdapter!!.update(element) } override fun removeElement(element: Interaction) { mAdapter!!.remove(element) } override fun setComposingStatus(composingStatus: ComposingStatus) { mAdapter!!.setComposingStatus(composingStatus) if (composingStatus == ComposingStatus.Active) scrollToEnd() } override fun setLastDisplayed(interaction: Interaction) { mAdapter!!.setLastDisplayed(interaction) } override fun acceptFile(accountId: String, conversationUri: net.jami.model.Uri, transfer: DataTransfer) { if (transfer.messageId == null && transfer.fileId == null) return val cacheDir = requireContext().cacheDir val spaceLeft = AndroidFileUtils.getSpaceLeft(cacheDir.toString()) if (spaceLeft == -1L || transfer.totalSize > spaceLeft) { presenter.noSpaceLeft() return } requireActivity().startService(Intent(DRingService.ACTION_FILE_ACCEPT, ConversationPath.toUri(accountId, conversationUri), requireContext(), DRingService::class.java) .putExtra(DRingService.KEY_MESSAGE_ID, transfer.messageId) .putExtra(DRingService.KEY_TRANSFER_ID, transfer.fileId) ) } override fun refuseFile(accountId: String, conversationUri: net.jami.model.Uri, transfer: DataTransfer) { if (transfer.messageId == null && transfer.fileId == null) return requireActivity().startService(Intent(DRingService.ACTION_FILE_CANCEL, ConversationPath.toUri(accountId, conversationUri), requireContext(), DRingService::class.java) .putExtra(DRingService.KEY_MESSAGE_ID, transfer.messageId) .putExtra(DRingService.KEY_TRANSFER_ID, transfer.fileId) ) } override fun shareFile(path: File, displayName: String) { val c = context ?: return var fileUri: Uri? = null try { fileUri = ContentUriHandler.getUriForFile(c, ContentUriHandler.AUTHORITY_FILES, path, displayName) } catch (e: IllegalArgumentException) { Log.e("File Selector", "The selected file can't be shared: " + path.name) } if (fileUri != null) { val sendIntent = Intent() sendIntent.action = Intent.ACTION_SEND sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) val type = c.contentResolver.getType(fileUri.buildUpon().appendPath(displayName).build()) sendIntent.setDataAndType(fileUri, type) sendIntent.putExtra(Intent.EXTRA_STREAM, fileUri) startActivity(Intent.createChooser(sendIntent, null)) } } override fun openFile(path: File, displayName: String) { val c = context ?: return var fileUri: Uri? = null try { fileUri = ContentUriHandler.getUriForFile(c, ContentUriHandler.AUTHORITY_FILES, path, displayName) } catch (e: IllegalArgumentException) { Log.e(TAG, "The selected file can't be shared: " + path.name) } if (fileUri != null) { val sendIntent = Intent() sendIntent.action = Intent.ACTION_VIEW sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) val type = c.contentResolver.getType(fileUri.buildUpon().appendPath(displayName).build()) sendIntent.setDataAndType(fileUri, type) sendIntent.putExtra(Intent.EXTRA_STREAM, fileUri) //startActivity(Intent.createChooser(sendIntent, null)); try { startActivity(sendIntent) } catch (e: ActivityNotFoundException) { Snackbar.make(requireView(), R.string.conversation_open_file_error, Snackbar.LENGTH_LONG) .show() Log.e("File Loader", "File of unknown type, could not open: " + path.name) } } } fun actionSendMsgText(actionId: Int): Boolean { when (actionId) { EditorInfo.IME_ACTION_SEND -> { sendMessageText() return true } } return false } fun onClick() { presenter.clickOnGoingPane() } override fun onStart() { super.onStart() presenter.resume(mIsBubble) } override fun onStop() { super.onStop() presenter.pause() } override fun onDestroy() { mCompositeDisposable.dispose() super.onDestroy() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { if (!isVisible) { return } inflater.inflate(R.menu.conversation_actions, menu) mAudioCallBtn = menu.findItem(R.id.conv_action_audiocall) mVideoCallBtn = menu.findItem(R.id.conv_action_videocall) } fun openContact() { presenter.openContact() } override fun onOptionsItemSelected(item: MenuItem): Boolean { val itemId = item.itemId if (itemId == android.R.id.home) { startActivity(Intent(activity, HomeActivity::class.java)) return true } else if (itemId == R.id.conv_action_audiocall) { presenter.goToCall(false) return true } else if (itemId == R.id.conv_action_videocall) { presenter.goToCall(true) return true } else if (itemId == R.id.conv_contact_details) { presenter.openContact() return true } return super.onOptionsItemSelected(item) } override fun initPresenter(presenter: ConversationPresenter) { val path = ConversationPath.fromBundle(arguments) mIsBubble = requireArguments().getBoolean(NotificationServiceImpl.EXTRA_BUBBLE) Log.w(TAG, "initPresenter $path") if (path == null) return val uri = path.conversationUri mAdapter = ConversationAdapter(this, presenter) presenter.init(uri, path.accountId) try { mPreferences = getConversationPreferences(requireContext(), path.accountId, uri).also { preferences -> preferences.registerOnSharedPreferenceChangeListener(this) presenter.setConversationColor(preferences.getInt(KEY_PREFERENCE_CONVERSATION_COLOR, resources.getColor(R.color.color_primary_light))) presenter.setConversationSymbol(preferences.getString(KEY_PREFERENCE_CONVERSATION_SYMBOL, resources.getText(R.string.conversation_default_emoji).toString())!!) mLastRead = preferences.getString(KEY_PREFERENCE_CONVERSATION_LAST_READ, null) } } catch (e: Exception) { Log.e(TAG, "Can't load conversation preferences") } var connection = locationServiceConnection if (connection == null) { connection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName, service: IBinder) { Log.w(TAG, "onServiceConnected") val binder = service as LocationSharingService.LocalBinder val locationService = binder.service //val path = ConversationPath(presenter.path) if (locationService.isSharing(path)) { showMap(path.accountId, uri.uri, false) } /*try { requireContext().unbindService(locationServiceConnection!!) } catch (e: Exception) { Log.w(TAG, "Error unbinding service", e) }*/ } override fun onServiceDisconnected(name: ComponentName) { Log.w(TAG, "onServiceDisconnected") locationServiceConnection = null } } locationServiceConnection = connection Log.w(TAG, "bindService") requireContext().bindService(Intent(requireContext(), LocationSharingService::class.java), connection, 0) } } override fun onSharedPreferenceChanged(prefs: SharedPreferences, key: String) { when (key) { KEY_PREFERENCE_CONVERSATION_COLOR -> presenter.setConversationColor( prefs.getInt(KEY_PREFERENCE_CONVERSATION_COLOR, resources.getColor(R.color.color_primary_light))) KEY_PREFERENCE_CONVERSATION_SYMBOL -> presenter.setConversationSymbol( prefs.getString(KEY_PREFERENCE_CONVERSATION_SYMBOL, resources.getText(R.string.conversation_default_emoji).toString())!!) } } override fun updateContact(contact: ContactViewModel) { val contactKey = contact.contact.primaryNumber val a = mSmallParticipantAvatars[contactKey] if (a != null) { a.update(contact) mParticipantAvatars[contactKey]!!.update(contact) mAdapter?.setPhoto() } else { mCompositeDisposable.add(AvatarFactory.getAvatar(requireContext(), contact, true) .observeOn(AndroidSchedulers.mainThread()) .subscribe { avatar -> mParticipantAvatars[contactKey] = avatar as AvatarDrawable mSmallParticipantAvatars[contactKey] = AvatarDrawable.Builder() .withContact(contact) .withCircleCrop(true) .withPresence(false) .build(requireContext()) mAdapter?.setPhoto() }) } } override fun displayContact(conversation: Conversation, contacts: List<ContactViewModel>) { val avatar = AvatarFactory.getAvatar(requireContext(), conversation, contacts, true).blockingGet() mConversationAvatar = avatar mParticipantAvatars[conversation.uri.rawRingId] = AvatarDrawable(avatar) setupActionbar(conversation, contacts) /*mCompositeDisposable.add(AvatarFactory.getAvatar(requireContext(), conversation, true) .observeOn(AndroidSchedulers.mainThread()) .subscribe { d -> mConversationAvatar = d as AvatarDrawable mParticipantAvatars[conversation.uri.rawRingId] = AvatarDrawable(d) setupActionbar(conversation) })*/ } override fun displayOnGoingCallPane(display: Boolean) { binding!!.ongoingcallPane.visibility = if (display) View.VISIBLE else View.GONE } override fun displayNumberSpinner(conversation: Conversation, number: net.jami.model.Uri) { binding!!.numberSelector.visibility = View.VISIBLE //binding.numberSelector.setAdapter(new NumberAdapter(getActivity(), conversation.getContact(), false)); binding!!.numberSelector.setSelection(getIndex(binding!!.numberSelector, number)) } override fun hideNumberSpinner() { binding!!.numberSelector.visibility = View.GONE } override fun clearMsgEdit() { binding!!.msgInputTxt.setText("") } override fun goToHome() { if (activity is ConversationActivity) { requireActivity().finish() } } override fun goToAddContact(contact: Contact) { startActivityForResult(ActionHelper.getAddNumberIntentForContact(contact), REQ_ADD_CONTACT) } override fun goToContactActivity(accountId: String, uri: net.jami.model.Uri) { val toolbar: Toolbar = requireActivity().findViewById(R.id.main_toolbar) val logo = toolbar.findViewById<ImageView>(R.id.contact_image) startActivity(Intent(Intent.ACTION_VIEW, ConversationPath.toUri(accountId, uri)) .setClass(requireContext().applicationContext, ContactDetailsActivity::class.java), ActivityOptions.makeSceneTransitionAnimation(activity, logo, "conversationIcon") .toBundle()) } override fun goToCallActivity(conferenceId: String, withCamera: Boolean) { startActivity(Intent(Intent.ACTION_VIEW) .setClass(requireContext().applicationContext, CallActivity::class.java) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .putExtra(NotificationService.KEY_CALL_ID, conferenceId) ) } override fun goToCallActivityWithResult(accountId: String, conversationUri: net.jami.model.Uri, contactUri: net.jami.model.Uri, withCamera: Boolean) { val intent = Intent(Intent.ACTION_CALL) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .setClass(requireContext(), CallActivity::class.java) .putExtras(ConversationPath.toBundle(accountId, conversationUri)) .putExtra(Intent.EXTRA_PHONE_NUMBER, contactUri.uri) .putExtra(CallFragment.KEY_HAS_VIDEO, withCamera) startActivity(intent) } private fun setupActionbar(conversation: Conversation, contacts: List<ContactViewModel>) { if (!isVisible) { return } val activity: Activity = requireActivity() val displayName = ConversationItemViewModel.getTitle(conversation, contacts) val identity = ConversationItemViewModel.getUriTitle(conversation.uri, contacts) val toolbar: Toolbar = activity.findViewById(R.id.main_toolbar) val title = toolbar.findViewById<TextView>(R.id.contact_title) val subtitle = toolbar.findViewById<TextView>(R.id.contact_subtitle) val logo = toolbar.findViewById<ImageView>(R.id.contact_image) logo.setImageDrawable(mConversationAvatar) logo.visibility = View.VISIBLE title.text = displayName title.textSize = 15f title.setTypeface(null, Typeface.NORMAL) if (identity != displayName) { subtitle.text = identity subtitle.visibility = View.VISIBLE } else { subtitle.text = "" subtitle.visibility = View.GONE } } fun blockContactRequest() { presenter.onBlockIncomingContactRequest() } fun refuseContactRequest() { presenter.onRefuseIncomingContactRequest() } fun acceptContactRequest() { presenter.onAcceptIncomingContactRequest() } fun addContact() { presenter.onAddContact() } override fun onPrepareOptionsMenu(menu: Menu) { super.onPrepareOptionsMenu(menu) val visible = binding!!.cvMessageInput.visibility == View.VISIBLE mAudioCallBtn?.isVisible = visible mVideoCallBtn?.isVisible = visible } override fun switchToUnknownView(name: String) { binding?.apply { cvMessageInput.visibility = View.GONE unknownContactPrompt.visibility = View.VISIBLE trustRequestPrompt.visibility = View.GONE tvTrustRequestMessage.text = getString(R.string.message_contact_not_trusted, name) trustRequestMessageLayout.visibility = View.VISIBLE currentBottomView = unknownContactPrompt } requireActivity().invalidateOptionsMenu() updateListPadding() } override fun switchToIncomingTrustRequestView(name: String) { binding?.apply { cvMessageInput.visibility = View.GONE unknownContactPrompt.visibility = View.GONE trustRequestPrompt.visibility = View.VISIBLE tvTrustRequestMessage.text = getString(R.string.message_contact_not_trusted_yet, name) trustRequestMessageLayout.visibility = View.VISIBLE currentBottomView = trustRequestPrompt } requireActivity().invalidateOptionsMenu() updateListPadding() } override fun switchToConversationView() { binding?.apply { cvMessageInput.visibility = View.VISIBLE unknownContactPrompt.visibility = View.GONE trustRequestPrompt.visibility = View.GONE trustRequestMessageLayout.visibility = View.GONE currentBottomView = cvMessageInput } requireActivity().invalidateOptionsMenu() updateListPadding() } override fun switchToSyncingView() { binding?.apply { cvMessageInput.visibility = View.GONE unknownContactPrompt.visibility = View.GONE trustRequestPrompt.visibility = View.GONE trustRequestMessageLayout.visibility = View.VISIBLE tvTrustRequestMessage.text = getText(R.string.conversation_syncing) } currentBottomView = null requireActivity().invalidateOptionsMenu() updateListPadding() } override fun switchToEndedView() { binding?.apply { cvMessageInput.visibility = View.GONE unknownContactPrompt.visibility = View.GONE trustRequestPrompt.visibility = View.GONE trustRequestMessageLayout.visibility = View.VISIBLE tvTrustRequestMessage.text = "Conversation ended" } currentBottomView = null requireActivity().invalidateOptionsMenu() updateListPadding() } override fun positiveMediaButtonClicked() { presenter.clickOnGoingPane() } override fun negativeMediaButtonClicked() { presenter.clickOnGoingPane() } override fun toggleMediaButtonClicked() { presenter.clickOnGoingPane() } private fun setLoading(isLoading: Boolean) { val binding = binding ?: return if (isLoading) { binding.btnTakePicture.visibility = View.GONE binding.pbDataTransfer.visibility = View.VISIBLE } else { binding.btnTakePicture.visibility = View.VISIBLE binding.pbDataTransfer.visibility = View.GONE } } fun handleShareIntent(intent: Intent) { Log.w(TAG, "handleShareIntent $intent") val action = intent.action if (Intent.ACTION_SEND == action || Intent.ACTION_SEND_MULTIPLE == action) { val type = intent.type if (type == null) { Log.w(TAG, "Can't share with no type") return } if (type.startsWith("text/plain")) { binding!!.msgInputTxt.setText(intent.getStringExtra(Intent.EXTRA_TEXT)) } else { val intentUri = intent.data if (intentUri != null) startFileSend(AndroidFileUtils.getCacheFile(requireContext(), intentUri).flatMapCompletable { file -> sendFile(file) }) intent.clipData?.let { clipData -> for (i in 0 until clipData.itemCount) { val uri = clipData.getItemAt(i).uri if (uri != intentUri) startFileSend(AndroidFileUtils.getCacheFile(requireContext(), uri).flatMapCompletable { file -> sendFile(file) }) } } } } else if (Intent.ACTION_VIEW == action) { val path = ConversationPath.fromIntent(intent) if (path != null && intent.getBooleanExtra(EXTRA_SHOW_MAP, false)) { shareLocation() } } } /** * Creates an intent using Android Storage Access Framework * This intent is then received by applications that can handle it like * Downloads or Google drive * @param file DataTransfer of the file that is going to be stored * @param currentFileAbsolutePath absolute path of the file we want to save */ override fun startSaveFile(file: DataTransfer, currentFileAbsolutePath: String) { //Get the current file absolute path and store it mCurrentFileAbsolutePath = currentFileAbsolutePath try { //Use Android Storage File Access to download the file val downloadFileIntent = Intent(Intent.ACTION_CREATE_DOCUMENT) downloadFileIntent.type = AndroidFileUtils.getMimeTypeFromExtension(file.extension) downloadFileIntent.addCategory(Intent.CATEGORY_OPENABLE) downloadFileIntent.putExtra(Intent.EXTRA_TITLE, file.displayName) startActivityForResult(downloadFileIntent, REQUEST_CODE_SAVE_FILE) } catch (e: Exception) { Log.i(TAG, "No app detected for saving files.") val directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) if (!directory.exists()) { directory.mkdirs() } writeToFile(Uri.fromFile(File(directory, file.displayName))) } } override fun displayNetworkErrorPanel() { binding?.apply { errorMsgPane.visibility = View.VISIBLE errorMsgPane.setOnClickListener(null) errorMsgPane.setText(R.string.error_no_network) } } override fun displayAccountOfflineErrorPanel() { binding?.apply { errorMsgPane.visibility = View.VISIBLE errorMsgPane.setOnClickListener(null) errorMsgPane.setText(R.string.error_account_offline) for (idx in 0 until btnContainer.childCount) { btnContainer.getChildAt(idx).isEnabled = false } } } override fun setSettings(readIndicator: Boolean, linkPreviews: Boolean) { mAdapter?.apply { setReadIndicatorStatus(readIndicator) showLinkPreviews = linkPreviews } } override fun updateLastRead(last: String) { Log.w(TAG, "Updated last read $mLastRead") mLastRead = last mPreferences?.edit()?.putString(KEY_PREFERENCE_CONVERSATION_LAST_READ, last)?.apply() } override fun hideErrorPanel() { binding?.errorMsgPane?.visibility = View.GONE } companion object { private val TAG = ConversationFragment::class.java.simpleName const val REQ_ADD_CONTACT = 42 const val KEY_PREFERENCE_PENDING_MESSAGE = "pendingMessage" const val KEY_PREFERENCE_CONVERSATION_COLOR = "color" const val KEY_PREFERENCE_CONVERSATION_LAST_READ = "lastRead" const val KEY_PREFERENCE_CONVERSATION_SYMBOL = "symbol" const val EXTRA_SHOW_MAP = "showMap" private const val REQUEST_CODE_FILE_PICKER = 1000 private const val REQUEST_PERMISSION_CAMERA = 1001 private const val REQUEST_CODE_TAKE_PICTURE = 1002 private const val REQUEST_CODE_SAVE_FILE = 1003 private const val REQUEST_CODE_CAPTURE_AUDIO = 1004 private const val REQUEST_CODE_CAPTURE_VIDEO = 1005 private fun getIndex(spinner: Spinner, myString: net.jami.model.Uri): Int { var i = 0 val n = spinner.count while (i < n) { if ((spinner.getItemAtPosition(i) as Phone).number == myString) { return i } i++ } return 0 } private val SUPPORTED_MIME_TYPES = arrayOf("image/png", "image/jpg", "image/gif", "image/webp") } }
gpl-3.0
c2d22ff940d7b45c232d986798b1d090
41.494659
179
0.624074
5.092064
false
false
false
false
ibinti/intellij-community
java/java-impl/src/com/intellij/codeInsight/hints/JavaInlayParameterHintsProvider.kt
2
4209
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.hints import com.intellij.codeInsight.completion.CompletionMemory import com.intellij.codeInsight.hints.HintInfo.MethodInfo import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiCallExpression import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod class JavaInlayParameterHintsProvider : InlayParameterHintsProvider { companion object { fun getInstance() = InlayParameterHintsExtension.forLanguage(JavaLanguage.INSTANCE) as JavaInlayParameterHintsProvider } override fun getHintInfo(element: PsiElement): MethodInfo? { if (element is PsiCallExpression) { val resolvedElement = CompletionMemory.getChosenMethod(element) ?: element.resolveMethodGenerics ().element if (resolvedElement is PsiMethod) { return getMethodInfo(resolvedElement) } } return null } override fun getParameterHints(element: PsiElement): List<InlayInfo> { if (element is PsiCallExpression) { return JavaInlayHintsProvider.hints(element).toList() } return emptyList() } override fun canShowHintsWhenDisabled(): Boolean { return true } fun getMethodInfo(method: PsiMethod): MethodInfo? { val containingClass = method.containingClass ?: return null val fullMethodName = StringUtil.getQualifiedName(containingClass.qualifiedName, method.name) val paramNames: List<String> = method.parameterList.parameters.map { it.name ?: "" } return MethodInfo(fullMethodName, paramNames) } override fun getDefaultBlackList() = defaultBlackList private val defaultBlackList = setOf( "(begin*, end*)", "(start*, end*)", "(first*, last*)", "(first*, second*)", "(from*, to*)", "(min*, max*)", "(key, value)", "(format, arg*)", "(message)", "(message, error)", "*Exception", "*.set*(*)", "*.add(*)", "*.set(*,*)", "*.get(*)", "*.create(*)", "*.getProperty(*)", "*.setProperty(*,*)", "*.print(*)", "*.println(*)", "*.append(*)", "*.charAt(*)", "*.indexOf(*)", "*.contains(*)", "*.startsWith(*)", "*.endsWith(*)", "*.equals(*)", "*.equal(*)", "*.compareTo(*)", "*.compare(*,*)", "java.lang.Math.*", "org.slf4j.Logger.*", "*.singleton(*)", "*.singletonList(*)", "*.Set.of", "*.ImmutableList.of", "*.ImmutableMultiset.of", "*.ImmutableSortedMultiset.of", "*.ImmutableSortedSet.of", "*.Arrays.asList" ) val isDoNotShowIfMethodNameContainsParameterName = Option("java.method.name.contains.parameter.name", "Do not show if method name contains parameter name", true) val isShowForParamsWithSameType = Option("java.multiple.params.same.type", "Show for non-literals in case of multiple params with the same type", false) val isDoNotShowForBuilderLikeMethods = Option("java.build.like.method", "Do not show for builder-like methods", true) override fun getSupportedOptions(): List<Option> { return listOf( isDoNotShowIfMethodNameContainsParameterName, isShowForParamsWithSameType, isDoNotShowForBuilderLikeMethods ) } }
apache-2.0
be5302998c8122e1c45b99431938ea27
31.384615
122
0.617011
5.010714
false
false
false
false
savoirfairelinux/ring-client-android
ring-android/libjamiclient/src/main/kotlin/net/jami/model/Interaction.kt
1
7477
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Author: Rayan Osseiran <[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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package net.jami.model import com.google.gson.JsonObject import com.google.gson.JsonParser import com.j256.ormlite.field.DatabaseField import com.j256.ormlite.table.DatabaseTable import io.reactivex.rxjava3.core.Maybe @DatabaseTable(tableName = Interaction.TABLE_NAME) open class Interaction { var account: String? = null var isIncoming = false var contact: Contact? = null @DatabaseField(generatedId = true, columnName = COLUMN_ID, index = true) var id = 0 @DatabaseField(columnName = COLUMN_AUTHOR, index = true) var author: String? = null @DatabaseField(columnName = COLUMN_CONVERSATION, foreignColumnName = ConversationHistory.COLUMN_CONVERSATION_ID, foreign = true) var conversation: ConversationHistory? = null @DatabaseField(columnName = COLUMN_TIMESTAMP, index = true) var timestamp: Long = 0 @DatabaseField(columnName = COLUMN_BODY) var body: String? = null @DatabaseField(columnName = COLUMN_TYPE) var mType: String? = null @DatabaseField(columnName = COLUMN_STATUS) var mStatus = InteractionStatus.UNKNOWN.toString() @DatabaseField(columnName = COLUMN_DAEMON_ID) var daemonId: Long? = null @DatabaseField(columnName = COLUMN_IS_READ) var mIsRead = 0 @DatabaseField(columnName = COLUMN_EXTRA_FLAG) var mExtraFlag = JsonObject().toString() var isNotified = false // Swarm var conversationId: String? = null private set var messageId: String? = null private set var parentId: String? = null private set /* Needed by ORMLite */ constructor() constructor(accountId: String) { account = accountId type = InteractionType.INVALID } constructor(conversation: Conversation, type: InteractionType) { this.conversation = conversation account = conversation.accountId mType = type.toString() } constructor( id: String, author: String?, conversation: ConversationHistory?, timestamp: String, body: String?, type: String?, status: String, daemonId: String?, isRead: String, extraFlag: String ) { this.id = id.toInt() this.author = author this.conversation = conversation this.timestamp = timestamp.toLong() this.body = body mType = type mStatus = status try { this.daemonId = daemonId?.toLong() } catch (e: NumberFormatException) { this.daemonId = 0L } mIsRead = isRead.toInt() mExtraFlag = extraFlag } fun read() { mIsRead = 1 } var type: InteractionType get() = if (mType != null) InteractionType.fromString(mType!!) else InteractionType.INVALID set(type) { mType = type.toString() } var status: InteractionStatus get() = InteractionStatus.fromString(mStatus) set(status) { if (status == InteractionStatus.DISPLAYED) mIsRead = 1 mStatus = status.toString() } val extraFlag: JsonObject get() = toJson(mExtraFlag) fun toJson(value: String?): JsonObject { return JsonParser.parseString(value).asJsonObject } fun fromJson(json: JsonObject): String { return json.toString() } open val daemonIdString: String? get() = daemonId?.toString() val isRead: Boolean get() = mIsRead == 1 val isSwarm: Boolean get() = messageId != null && messageId!!.isNotEmpty() fun setSwarmInfo(conversationId: String) { this.conversationId = conversationId messageId = null parentId = null } fun setSwarmInfo(conversationId: String, messageId: String, parent: String?) { this.conversationId = conversationId this.messageId = messageId parentId = parent } var preview: Any? = null enum class InteractionStatus { UNKNOWN, SENDING, SUCCESS, DISPLAYED, INVALID, FAILURE, TRANSFER_CREATED, TRANSFER_ACCEPTED, TRANSFER_CANCELED, TRANSFER_ERROR, TRANSFER_UNJOINABLE_PEER, TRANSFER_ONGOING, TRANSFER_AWAITING_PEER, TRANSFER_AWAITING_HOST, TRANSFER_TIMEOUT_EXPIRED, TRANSFER_FINISHED, FILE_AVAILABLE; val isError: Boolean get() = this == TRANSFER_ERROR || this == TRANSFER_UNJOINABLE_PEER || this == TRANSFER_CANCELED || this == TRANSFER_TIMEOUT_EXPIRED || this == FAILURE val isOver: Boolean get() = isError || this == TRANSFER_FINISHED companion object { fun fromString(str: String): InteractionStatus { for (s in values()) { if (s.name == str) { return s } } return INVALID } fun fromIntTextMessage(n: Int): InteractionStatus { return try { values()[n] } catch (e: ArrayIndexOutOfBoundsException) { INVALID } } fun fromIntFile(n: Int): InteractionStatus { return when (n) { 0 -> INVALID 1 -> TRANSFER_CREATED 2, 9 -> TRANSFER_ERROR 3 -> TRANSFER_AWAITING_PEER 4 -> TRANSFER_AWAITING_HOST 5 -> TRANSFER_ONGOING 6 -> TRANSFER_FINISHED 7, 8, 10 -> TRANSFER_UNJOINABLE_PEER 11 -> TRANSFER_TIMEOUT_EXPIRED else -> UNKNOWN } } } } enum class InteractionType { INVALID, TEXT, CALL, CONTACT, DATA_TRANSFER; companion object { fun fromString(str: String) = try { valueOf(str) } catch (e: Exception) { INVALID } } } companion object { const val TABLE_NAME = "interactions" const val COLUMN_ID = "id" const val COLUMN_AUTHOR = "author" const val COLUMN_CONVERSATION = "conversation" const val COLUMN_TIMESTAMP = "timestamp" const val COLUMN_BODY = "body" const val COLUMN_TYPE = "type" const val COLUMN_STATUS = "status" const val COLUMN_DAEMON_ID = "daemon_id" const val COLUMN_IS_READ = "is_read" const val COLUMN_EXTRA_FLAG = "extra_data" fun compare(a: Interaction?, b: Interaction?): Int { if (a == null) return if (b == null) 0 else -1 return if (b == null) 1 else java.lang.Long.compare(a.timestamp, b.timestamp) } } }
gpl-3.0
7813fec55e9e65307d6f103b6234629e
31.094421
288
0.605323
4.496091
false
false
false
false
aleksanderwozniak/WhatsThatFlag
app/src/main/java/me/wozappz/whatsthatflag/screens/game/GameActivity.kt
1
10181
package me.wozappz.whatsthatflag.screens.game import android.graphics.PorterDuff import android.net.Uri import android.os.Bundle import android.support.customtabs.CustomTabsIntent import android.support.v4.content.ContextCompat import android.support.v4.content.res.ResourcesCompat import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.view.View import android.view.WindowManager import android.widget.TextView import com.squareup.picasso.Callback import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.activity_game.* import me.wozappz.whatsthatflag.R import me.wozappz.whatsthatflag.app.App import me.wozappz.whatsthatflag.di.game.GameScreenModule import me.wozappz.whatsthatflag.screens.menu.CONTINENT import me.wozappz.whatsthatflag.utils.checkInternetConnection import me.wozappz.whatsthatflag.utils.loadUrl import org.jetbrains.anko.alert import org.jetbrains.anko.appcompat.v7.Appcompat import org.jetbrains.anko.find import org.jetbrains.anko.toast import javax.inject.Inject class GameActivity : AppCompatActivity(), GameScreenContract.View { @Inject override lateinit var presenter: GameScreenContract.Presenter private var isAnswerTimerInitialized = false private val animationManager by lazy { AnswerAnimationManager(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_game) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) val selectedContinent = intent.getSerializableExtra("SELECTED_CONTINENT") as CONTINENT val lowercaseContinent = selectedContinent.toString().toLowerCase() val continentStringId = convertToRes(lowercaseContinent) val continentResId = resources.getIdentifier(continentStringId, "string", packageName) val continentText = getString(continentResId) mCategoryTextView.text = getString(R.string.category_text, continentText) (application as App).daggerComponent .plus(GameScreenModule(this)) .injectTo(this) presenter.start() setupListeners() ShowcaseManager(this).showTutorial() } fun setupAnswerTimer() { val timeForAnswer = resources.getInteger(R.integer.answer_time) animationManager.createAnswerTimer(timeForAnswer) } private fun convertToRes(continentName: String): String { return "radio_text_$continentName" } override fun onResume() { super.onResume() if (animationManager.answerTimerExists() && isAnswerTimerInitialized) { presenter.redownloadImg(true) // prevents cheating resetAnswerButtonsColor() } else { isAnswerTimerInitialized = true } } override fun onStop() { Picasso.with(this).cancelRequest(mFlagImg) super.onStop() animationManager.stopAnswerTimer() animationManager.stopAnimationTimer() } override fun onBackPressed() { presenter.backButtonClicked() } fun onWTFclick(view: View) { presenter.btnWTFclicked() } private fun setupListeners() { mBtnA.setOnClickListener { presenter.answerBtnClicked(mBtnA.text.toString()) } mBtnB.setOnClickListener { presenter.answerBtnClicked(mBtnB.text.toString()) } mBtnC.setOnClickListener { presenter.answerBtnClicked(mBtnC.text.toString()) } mBtnD.setOnClickListener { presenter.answerBtnClicked(mBtnD.text.toString()) } } override fun loadImg(currentUrl: String, offline: Boolean, callback: Callback) { mFlagImg.loadUrl(currentUrl, offline, callback) } override fun renameButtons(btnNames: List<String>) { mBtnA.text = btnNames[0] mBtnB.text = btnNames[1] mBtnC.text = btnNames[2] mBtnD.text = btnNames[3] } override fun showScore(score: Int) { mScoreTextView.text = getString(R.string.score_text, score) } override fun showRemainingQuestions(amount: Int) { mQuestionsTextView.text = getString(R.string.questions_text, amount) } override fun showProgressBar() { mProgressBar.visibility = View.VISIBLE mFlagImg.visibility = View.INVISIBLE } override fun hideProgressBar() { mProgressBar.visibility = View.INVISIBLE mFlagImg.visibility = View.VISIBLE } override fun displayFlagInfoInBrowser(url: String) { val customTabsIntent = CustomTabsIntent.Builder().build() customTabsIntent.launchUrl(this, Uri.parse(url)) } override fun displayMessageErrorLoadNextFlag() { toast(getString(R.string.toast_game_error_load_next_flag)) } override fun displayMessageReloadImg() { toast(getString(R.string.toast_game_reload_img)) } override fun displayMessageFlagSkipped(flagName: String) { toast(getString(R.string.toast_game_flag_skipped, flagName)) } override fun showSummaryDialog(score: Int, totalFlagAmount: Int) { val percent: Int = (score * 100) / totalFlagAmount val summaryDialog = alert (Appcompat) { title = getString(R.string.alert_game_summary_title) message = getString(R.string.alert_game_summary_message, score, totalFlagAmount, percent) positiveButton(getString(R.string.alert_game_summary_btn_pos), { finish() overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right) }) }.build() summaryDialog.setCancelable(false) summaryDialog.setCanceledOnTouchOutside(false) summaryDialog.show() val typeface = ResourcesCompat.getFont(this, R.font.lato) val summaryTitle = summaryDialog.find<TextView>(android.support.v7.appcompat.R.id.alertTitle) summaryTitle.typeface = typeface val summaryMessage = summaryDialog.find<TextView>(android.R.id.message) summaryMessage.typeface = typeface val summaryContinueBtn = summaryDialog.getButton(AlertDialog.BUTTON_POSITIVE) summaryContinueBtn.typeface = typeface } override fun animateCorrectAnswer(btnName: String, staticAnimation: Boolean) { animationManager.animateCorrectAnswer(btnName, staticAnimation) } override fun animateWrongAnswer(btnSelectedName: String, btnCorrectName: String) { animationManager.animateWrongAnswer(btnSelectedName, btnCorrectName) } private fun resetAnswerButtonsColor() { val colorGray = ContextCompat.getColor(this, R.color.bluishGray) mBtnA.background.setColorFilter(colorGray, PorterDuff.Mode.SRC) mBtnB.background.setColorFilter(colorGray, PorterDuff.Mode.SRC) mBtnC.background.setColorFilter(colorGray, PorterDuff.Mode.SRC) mBtnD.background.setColorFilter(colorGray, PorterDuff.Mode.SRC) } override fun setButtonsClickability(enabled: Boolean) { mBtnA.isEnabled = enabled mBtnB.isEnabled = enabled mBtnC.isEnabled = enabled mBtnD.isEnabled = enabled mWTFbtn.isEnabled = enabled } override fun isConnectedToInternet(): Boolean { return checkInternetConnection(applicationContext) } override fun showNoConnectionAlert() { val internetErrorAlert = alert (Appcompat) { title = getString(R.string.alert_start_internet_error_title) message = getString(R.string.alert_game_internet_error_msg, getString(R.string.alert_game_internet_error_btn_pos)) positiveButton(getString(R.string.alert_game_internet_error_btn_pos), { }) negativeButton(getString(R.string.alert_game_internet_error_btn_neg), { finishAffinity() }) }.build() internetErrorAlert.setCancelable(false) internetErrorAlert.setCanceledOnTouchOutside(false) internetErrorAlert.show() val typeface = ResourcesCompat.getFont(this, R.font.lato) val netErrorTitle = internetErrorAlert.find<TextView>(android.support.v7.appcompat.R.id.alertTitle) netErrorTitle.typeface = typeface val netErrorMessage = internetErrorAlert.find<TextView>(android.R.id.message) netErrorMessage.typeface = typeface val netErrorPosBtn = internetErrorAlert.getButton(AlertDialog.BUTTON_POSITIVE) netErrorPosBtn.typeface = typeface val netErrorNegBtn = internetErrorAlert.getButton(AlertDialog.BUTTON_NEGATIVE) netErrorNegBtn.typeface = typeface } override fun showBackToMenuDialog() { val backDialog = alert (Appcompat) { title = getString(R.string.alert_game_back_title) message = getString(R.string.alert_game_back_message) positiveButton(getString(R.string.alert_game_back_btn_pos), { super.onBackPressed() overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right) animationManager.stopAnswerTimer() animationManager.stopAnimationTimer() }) negativeButton(getString(R.string.alert_game_back_btn_neg), { }) }.build() backDialog.setCancelable(false) backDialog.setCanceledOnTouchOutside(false) backDialog.show() val typeface = ResourcesCompat.getFont(this, R.font.lato) val backTitle = backDialog.find<TextView>(android.support.v7.appcompat.R.id.alertTitle) backTitle.typeface = typeface val backMessage = backDialog.find<TextView>(android.R.id.message) backMessage.typeface = typeface val backPosBtn = backDialog.getButton(AlertDialog.BUTTON_POSITIVE) backPosBtn.typeface = typeface val backNegBtn = backDialog.getButton(AlertDialog.BUTTON_NEGATIVE) backNegBtn.typeface = typeface } override fun startAnswerTimer() { animationManager.startAnswerTimer() } override fun stopAnswerTimer() { animationManager.stopAnswerTimer() } fun updateAnswerTimerProgressBar(progress: Int) { mTimerProgressBar.progress = progress } }
apache-2.0
a50ec9f962285f9eed1cdd59dbb35531
34.848592
126
0.706414
4.336031
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-notifications-bukkit/src/main/kotlin/com/rpkit/notifications/bukkit/messages/NotificationsMessages.kt
1
3859
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.notifications.bukkit.messages import com.rpkit.core.bukkit.message.BukkitMessages import com.rpkit.core.message.ParameterizedMessage import com.rpkit.core.message.to import com.rpkit.notifications.bukkit.RPKNotificationsBukkit import com.rpkit.notifications.bukkit.notification.RPKNotification import java.time.ZoneId import java.time.format.DateTimeFormatter class NotificationsMessages(plugin: RPKNotificationsBukkit): BukkitMessages(plugin) { class NotificationListItemMessage(private val message: ParameterizedMessage) { fun withParameters( notification: RPKNotification ) = message.withParameters( "id" to notification.id?.value.toString(), "recipient" to notification.recipient.name.value, "title" to notification.title, "content" to notification.content, "time" to DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") .withZone(ZoneId.systemDefault()) .format(notification.time), "read" to notification.read.toString() ) } class NotificationViewValidMessage(private val messages: List<ParameterizedMessage>) { fun withParameters( notification: RPKNotification ) = messages.map { it.withParameters( "id" to notification.id?.value.toString(), "recipient" to notification.recipient.name.value, "title" to notification.title, "content" to notification.content, "time" to DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") .withZone(ZoneId.systemDefault()) .format(notification.time), "read" to notification.read.toString() ) } } val notificationUsage = get("notification-usage") val notificationDismissUsage = get("notification-dismiss-usage") val notificationDismissInvalidNotificationIdNotANumber = get("notification-dismiss-invalid-notification-id-not-a-number") val notificationDismissInvalidRecipient = get("notification-dismiss-invalid-recipient") val notificationDismissInvalidNotification = get("notification-dismiss-invalid-notification") val notificationDismissValid = get("notification-dismiss-valid") val notificationViewInvalidRecipient = get("notification-view-invalid-recipient") val notificationViewInvalidNotification = get("notification-view-invalid-notification") val notificationViewValid = getParameterizedList("notification-view-valid") .let(::NotificationViewValidMessage) val notificationListTitle = get("notification-list-title") val notificationListItem = getParameterized("notification-list-item") .let(::NotificationListItemMessage) val notificationListItemHover = get("notification-list-item-hover") val notFromConsole = get("not-from-console") val noProfileSelf = get("no-profile-self") val noNotificationService = get("no-notification-service") val noPermissionNotificationDismiss = get("no-permission-notification-dismiss") val noPermissionNotificationList = get("no-permission-notification-list") val noPermissionNotificationView = get("no-permission-notification-view") }
apache-2.0
271df0166312080e3b770ba27dffed3c
46.073171
125
0.717803
4.752463
false
false
false
false
commons-app/apps-android-commons
app/src/test/kotlin/fr/free/nrw/commons/explore/depictions/DepictsClientTest.kt
5
6219
package fr.free.nrw.commons.explore.depictions import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import depictSearchItem import entity import fr.free.nrw.commons.mwapi.Binding import fr.free.nrw.commons.mwapi.Result import fr.free.nrw.commons.mwapi.SparqlResponse import fr.free.nrw.commons.upload.depicts.DepictsInterface import fr.free.nrw.commons.upload.structure.depictions.DepictedItem import fr.free.nrw.commons.wikidata.model.DepictSearchResponse import io.reactivex.Single import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.MockitoAnnotations import org.wikipedia.wikidata.* import java.lang.reflect.Method class DepictsClientTest { @Mock private lateinit var depictsInterface: DepictsInterface private lateinit var depictsClient: DepictsClient @Before fun setUp() { MockitoAnnotations.initMocks(this) depictsClient = DepictsClient(depictsInterface) } @Test fun searchForDepictions() { val depictSearchResponse = mock<DepictSearchResponse>() whenever(depictsInterface.searchForDepicts("query", "1", "en", "en", "0")) .thenReturn(Single.just(depictSearchResponse)) whenever(depictSearchResponse.search).thenReturn(listOf(depictSearchItem("1"),depictSearchItem("2"))) val entities = mock<Entities>() whenever(depictsInterface.getEntities("1|2")).thenReturn(Single.just(entities)) whenever(entities.entities()).thenReturn(emptyMap()) depictsClient.searchForDepictions("query", 1, 0) .test() .assertValue(emptyList()) } @Test fun getEntities() { val entities = mock<Entities>() whenever(depictsInterface.getEntities("ids")).thenReturn(Single.just(entities)) depictsClient.getEntities("ids").test().assertValue(entities) } @Test fun `Test toDepictions when description is empty`() { val sparqlResponse = mock<SparqlResponse>() val result = mock<Result>() whenever(sparqlResponse.results).thenReturn(result) val binding1 = mock<Binding>() val binding2 = mock<Binding>() whenever(result.bindings).thenReturn(listOf(binding1, binding2)) whenever(binding1.id).thenReturn("1") whenever(binding2.id).thenReturn("2") val entities = mock<Entities>() val entity = mock<Entities.Entity>() val statementPartial = mock<Statement_partial>() whenever(depictsInterface.getEntities("1|2")).thenReturn(Single.just(entities)) whenever(entities.entities()).thenReturn(mapOf("en" to entity)) whenever(entity.statements).thenReturn(mapOf("P31" to listOf(statementPartial))) whenever(statementPartial.mainSnak).thenReturn( Snak_partial("test", "P31", DataValue.EntityId( WikiBaseEntityValue("wikibase-entityid", "Q10", 10L) ) ) ) whenever(depictsInterface.getEntities("Q10")).thenReturn(Single.just(entities)) whenever(entity.id()).thenReturn("Q10") depictsClient.toDepictions(Single.just(sparqlResponse)) .test() .assertValue(listOf( DepictedItem("", "", null, listOf("Q10"), emptyList(), false, "Q10") )) } @Test fun `Test toDepictions when description is not empty`() { val sparqlResponse = mock<SparqlResponse>() val result = mock<Result>() whenever(sparqlResponse.results).thenReturn(result) val binding1 = mock<Binding>() val binding2 = mock<Binding>() whenever(result.bindings).thenReturn(listOf(binding1, binding2)) whenever(binding1.id).thenReturn("1") whenever(binding2.id).thenReturn("2") val entities = mock<Entities>() val entity = mock<Entities.Entity>() whenever(depictsInterface.getEntities("1|2")).thenReturn(Single.just(entities)) whenever(entities.entities()).thenReturn(mapOf("en" to entity)) whenever(entity.descriptions()).thenReturn(mapOf("en" to Entities.Label("en", "Test description") )) whenever(entity.id()).thenReturn("Q10") depictsClient.toDepictions(Single.just(sparqlResponse)) .test() .assertValue(listOf( DepictedItem("", "", null, listOf("Q10"), emptyList(), false, "Q10") )) } @Test fun `Test mapToDepictItem when description is not empty`() { val method: Method = DepictsClient::class.java.getDeclaredMethod( "mapToDepictItem", Entities.Entity::class.java ) method.isAccessible = true method.invoke(depictsClient, entity(descriptions = mapOf("en" to "Test"))) } @Test fun `Test mapToDepictItem when description is empty and P31 doesn't exists`() { val method: Method = DepictsClient::class.java.getDeclaredMethod( "mapToDepictItem", Entities.Entity::class.java ) method.isAccessible = true method.invoke(depictsClient, entity()) } @Test fun `Test mapToDepictItem when description is empty and P31 exists`() { val entities = mock<Entities>() val entity = mock<Entities.Entity>() val statementPartial = mock<Statement_partial>() whenever(entity.statements).thenReturn(mapOf("P31" to listOf(statementPartial))) whenever(statementPartial.mainSnak).thenReturn( Snak_partial("test", "P31", DataValue.EntityId( WikiBaseEntityValue("wikibase-entityid", "Q10", 10L) ) ) ) whenever(depictsInterface.getEntities("Q10")).thenReturn(Single.just(entities)) whenever(entities.entities()) .thenReturn(mapOf("test" to entity)) whenever(entity.id()).thenReturn("Q10") val method: Method = DepictsClient::class.java.getDeclaredMethod( "mapToDepictItem", Entities.Entity::class.java ) method.isAccessible = true method.invoke(depictsClient, entity) } }
apache-2.0
73493ca21d1d7edf5994749e6e94a8e8
38.360759
109
0.647532
4.513062
false
true
false
false
coil-kt/coil
coil-base/src/androidTest/java/coil/map/ResourceIntMapperTest.kt
1
1010
package coil.map import android.content.ContentResolver.SCHEME_ANDROID_RESOURCE import android.content.Context import androidx.core.net.toUri import androidx.test.core.app.ApplicationProvider import coil.base.test.R import coil.request.Options import kotlin.test.assertEquals import kotlin.test.assertNull import org.junit.Before import org.junit.Test class ResourceIntMapperTest { private lateinit var context: Context private lateinit var mapper: ResourceIntMapper @Before fun before() { context = ApplicationProvider.getApplicationContext() mapper = ResourceIntMapper() } @Test fun resourceInt() { val resId = R.drawable.normal val expected = "$SCHEME_ANDROID_RESOURCE://${context.packageName}/$resId".toUri() val actual = mapper.map(resId, Options(context)) assertEquals(expected, actual) } @Test fun invalidResourceInt() { val resId = 0 assertNull(mapper.map(resId, Options(context))) } }
apache-2.0
dde9d1bddb6462dc95bad5b04bb14a7b
24.25
89
0.714851
4.41048
false
true
false
false
android/user-interface-samples
Haptics/app/src/main/java/com/example/android/haptics/samples/ui/expand/ExpandRoute.kt
1
13726
/* * Copyright (C) 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.android.haptics.samples.ui.expand import android.content.Context import android.os.Build import android.os.VibrationEffect import android.os.Vibrator import androidx.annotation.RequiresApi import androidx.compose.animation.core.FiniteAnimationSpec import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.Transition import androidx.compose.animation.core.animateDp import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.tween import androidx.compose.animation.core.updateTransition import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.TouchApp import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.example.android.haptics.samples.R import com.example.android.haptics.samples.ui.components.Screen import com.example.android.haptics.samples.ui.modifiers.noRippleClickable import com.example.android.haptics.samples.ui.theme.HapticSamplerTheme import com.example.android.haptics.samples.ui.theme.secondaryText /** * The two possible states states of the expand shape. */ private enum class ExpandShapeState { Collapsed, Expanded } private const val DEFAULT_ANIMATE_TO_EXPANDED_DURATION_MS = 650 private const val DEFAULT_ANIMATE_TO_COLLAPSED_DURATION_MS = 500 // Add a tick after the animation between states has occurred and the controls/indicators appear. private const val ANIMATION_COMPLETE_TICK_DELAY_MS = 30 // We animate size and thickness of the shape. As it gets larger we make the circular shape // thinner. private val EXPAND_SHAPE_COLLAPSED_SIZE = 64.dp private val EXPAND_SHAPE_COLLAPSED_THICKNESS = EXPAND_SHAPE_COLLAPSED_SIZE / 2 private val EXPAND_SHAPE_EXPANDED_SIZE = EXPAND_SHAPE_COLLAPSED_SIZE * 5 private val EXPAND_SHAPE_EXPANDED_THICKNESS = EXPAND_SHAPE_COLLAPSED_SIZE / 4 // Representation of the primitive composition to be played by the vibrator when the indicator is // expanding. private val VIBRATION_DATA_FOR_EXPANDING = PrimitiveComposition( arrayOf( PrimitiveEffect(VibrationEffect.Composition.PRIMITIVE_SLOW_RISE, 0.3f), PrimitiveEffect(VibrationEffect.Composition.PRIMITIVE_QUICK_FALL, 0.3f), PrimitiveEffect(VibrationEffect.Composition.PRIMITIVE_TICK, 0.6f, ANIMATION_COMPLETE_TICK_DELAY_MS) ) ) // Representation of the primitive composition to be played by the vibrator when the indicator is // collapsing. private val VIBRATION_DATA_FOR_COLLAPSING = PrimitiveComposition( arrayOf( PrimitiveEffect(VibrationEffect.Composition.PRIMITIVE_SLOW_RISE), PrimitiveEffect(VibrationEffect.Composition.PRIMITIVE_TICK, 1f, ANIMATION_COMPLETE_TICK_DELAY_MS) ) ) @Composable fun ExpandRoute(viewModel: ExpandViewModel) { ExpandExampleScreen(messageToUser = viewModel.messageToUser) } @Composable fun ExpandExampleScreen(messageToUser: String) { val vibrator = LocalContext.current.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator var currentState by remember { mutableStateOf(ExpandShapeState.Collapsed) } val animateToExpandedDuration = remember { VIBRATION_DATA_FOR_EXPANDING.getDuration( vibrator, DEFAULT_ANIMATE_TO_EXPANDED_DURATION_MS ) } val animateToCollapsedDuration = remember { VIBRATION_DATA_FOR_COLLAPSING.getDuration( vibrator, DEFAULT_ANIMATE_TO_COLLAPSED_DURATION_MS ) } var transitionData = updateTransitionData( expandShapeState = currentState, animateToExpandedDuration = animateToExpandedDuration, animateToCollapsedDuration = animateToCollapsedDuration ) Screen( pageTitle = stringResource(R.string.expand_screen_title), messageToUser = messageToUser ) { Box(Modifier.fillMaxSize()) { Box( Modifier .align(Alignment.Center) .noRippleClickable { currentState = if (currentState == ExpandShapeState.Collapsed) ExpandShapeState.Expanded else ExpandShapeState.Collapsed vibrate(vibrator, transitioningToState = currentState) }, ) { Box( Modifier .fillMaxWidth() .height(EXPAND_SHAPE_EXPANDED_SIZE) .align(Alignment.Center) .offset(y = -(EXPAND_SHAPE_COLLAPSED_SIZE)) ) { // Draw a box containing either a circle when collapsed or the donut shape // when expanding or expanded. Box( modifier = Modifier .size(transitionData.size) .clip( if (transitionData.isCollapsed) CircleShape else ExpandShape(transitionData.thickness) ) .align(Alignment.Center) .background(MaterialTheme.colors.primaryVariant) ) // Draw indicators if there is no ongoing transition and collapsed. if (transitionData.isCollapsed) { Text( stringResource(R.string.expand_screen_tap_to_expand), Modifier .align(Alignment.Center) .offset(y = -(EXPAND_SHAPE_COLLAPSED_SIZE)) ) Icon( Icons.Outlined.TouchApp, contentDescription = null, tint = MaterialTheme.colors.secondaryText, modifier = Modifier.align( Alignment.Center ) ) } // Draw indicators if there is no ongoing transition and expanded. if (transitionData.isExpanded) { Text( stringResource(R.string.expand_screen_tap_to_minimize), Modifier .align(Alignment.Center) .offset(y = -((EXPAND_SHAPE_COLLAPSED_SIZE.value / 2).dp)) ) Box( modifier = Modifier .size(16.dp) .clip(CircleShape) .background(MaterialTheme.colors.secondary) .align(Alignment.Center) ) } } } } } } /** * Hold the transition values for expanding between states. */ private data class TransitionData( val size: Dp, val thickness: Float, val isCollapsed: Boolean, // Transition is complete and now collapsed. val isExpanded: Boolean, // Transition is complete and now expanded. ) /** * Create a transition and return it's animation values for animating between expanding and * collapsing. */ @Composable private fun updateTransitionData( expandShapeState: ExpandShapeState, animateToExpandedDuration: Int, animateToCollapsedDuration: Int ): TransitionData { val transition = updateTransition(expandShapeState, label = "Transition between ExpandShapeState.Collapsed and Expanded.") // For the expanding and collapsing animation, we use a donut-like shape making it larger and // and less thick. val size by transition.animateDp( transitionSpec = getTransitionSpec(animateToExpandedDuration, animateToCollapsedDuration), label = "Transition size between ExpandShapeState.Collapsed and Expanded." ) { state -> when (state) { ExpandShapeState.Collapsed -> EXPAND_SHAPE_COLLAPSED_SIZE ExpandShapeState.Expanded -> EXPAND_SHAPE_EXPANDED_SIZE } } val thickness by transition.animateFloat( transitionSpec = getTransitionSpec(animateToExpandedDuration, animateToCollapsedDuration), label = "Transition thickness between ExpandShapeState.Collapsed and Expanded." ) { state -> with(LocalDensity.current) { when (state) { ExpandShapeState.Collapsed -> { EXPAND_SHAPE_COLLAPSED_THICKNESS.toPx() } ExpandShapeState.Expanded -> { EXPAND_SHAPE_EXPANDED_THICKNESS.toPx() } } } } val isAtTargetState = transition.currentState === transition.targetState return TransitionData( size = size, thickness = thickness, isCollapsed = isAtTargetState && transition.currentState == ExpandShapeState.Collapsed, isExpanded = isAtTargetState && transition.currentState == ExpandShapeState.Expanded ) } @Composable private fun <T> getTransitionSpec( animateToExpandedDuration: Int, animateToCollapsedDuration: Int, ): @Composable() (Transition.Segment<ExpandShapeState>.() -> FiniteAnimationSpec<T>) = { when { ExpandShapeState.Collapsed isTransitioningTo ExpandShapeState.Expanded -> tween(durationMillis = animateToExpandedDuration, easing = LinearEasing) else -> tween(durationMillis = animateToCollapsedDuration, easing = LinearEasing) } } /** * Play vibration effect based on what state the shape is transitioning to. */ private fun vibrate(vibrator: Vibrator, transitioningToState: ExpandShapeState) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { return } var vibrationEffect: VibrationEffect = if (transitioningToState === ExpandShapeState.Expanded) { VIBRATION_DATA_FOR_EXPANDING.buildVibrationEffect() } else { VIBRATION_DATA_FOR_COLLAPSING.buildVibrationEffect() } vibrator.vibrate(vibrationEffect) } /** * Representation of an array of primitives that can be played in a sequence. */ private class PrimitiveComposition( val compositionOfPrimitives: Array<PrimitiveEffect> ) { @RequiresApi(Build.VERSION_CODES.R) fun allPrimitivesSupported(vibrator: Vibrator): Boolean { return compositionOfPrimitives.all { primitiveEffect -> vibrator.areAllPrimitivesSupported(primitiveEffect.effectId) } } @RequiresApi(Build.VERSION_CODES.R) fun buildVibrationEffect(): VibrationEffect { val vibrationEffect = VibrationEffect.startComposition() for (primitive in compositionOfPrimitives) { vibrationEffect.addPrimitive(primitive.effectId, primitive.scale, primitive.delay) } return vibrationEffect.compose() } /** * If able, return the duration of the primitive composition. * * @param vibrator Vibrator service. * @param defaultIfUnsupportedPrimitives Value returned when either the current device does * not support checking duration or not all primitives are supported. */ fun getDuration(vibrator: Vibrator, defaultIfUnsupportedPrimitives: Int = 0): Int { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S || !allPrimitivesSupported(vibrator)) return defaultIfUnsupportedPrimitives var compositionDuration = 0 for (primitive in compositionOfPrimitives) { val duration = vibrator.getPrimitiveDurations(primitive.effectId)[0] compositionDuration += duration } return compositionDuration } } /** * Representation of a primitive to be played in a composition. */ private data class PrimitiveEffect( val effectId: Int, val scale: Float = 1f, val delay: Int = 0, ) @Preview(showBackground = true) @Composable fun ExpandExampleScreenPreview() { HapticSamplerTheme { ExpandExampleScreen( messageToUser = "A message to display to user." ) } }
apache-2.0
3d9c5743c61d8bcd71ff9085ee771f1f
38.901163
178
0.666764
4.905647
false
false
false
false
chillcoding-at-the-beach/my-cute-heart
MyCuteHeart/app/src/main/java/com/chillcoding/ilove/view/dialog/QuoteDialog.kt
1
1789
package com.chillcoding.ilove.view.dialog import android.app.AlertDialog import android.app.Dialog import android.app.DialogFragment import android.os.Bundle import android.view.LayoutInflater import com.chillcoding.ilove.MainActivity import com.chillcoding.ilove.R import com.chillcoding.ilove.extension.showAlertOnLove import com.chillcoding.ilove.view.activity.PurchaseActivity import kotlinx.android.synthetic.main.dialog_quote.view.* import org.jetbrains.anko.share import org.jetbrains.anko.startActivity import java.util.* class QuoteDialog : DialogFragment() { private val mLoveQuoteArray: Array<String> by lazy { resources.getStringArray(R.array.text_love) } private val mRandom = Random() override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = AlertDialog.Builder(activity) val activity = (activity as MainActivity) var nbQuotes = mLoveQuoteArray.size if (!activity.isPremium) nbQuotes = 8 val dialogQuoteView = (LayoutInflater.from(activity)).inflate(R.layout.dialog_quote, null) dialogQuoteView.dialogQuote.text = mLoveQuoteArray[mRandom.nextInt(nbQuotes)] builder.setView(dialogQuoteView) .setPositiveButton(R.string.action_love, { _, _ -> activity.showAlertOnLove() }) .setNegativeButton(android.R.string.cancel, null) if (activity.isPremium || activity.isUnlimitedQuotes) builder.setNeutralButton(R.string.action_share, { _, _ -> share("${dialogQuoteView.dialogQuote.text} \n${getString(R.string.text_from)} ${getString(R.string.url_app)}", "I Love") }) else builder.setNeutralButton(R.string.action_more, { _, _ -> startActivity<PurchaseActivity>() }) return builder.create() } }
gpl-3.0
57b8748cf9c2bc6707693614fde97b77
44.897436
193
0.727222
4.011211
false
false
false
false
CPRTeam/CCIP-Android
app/src/main/java/app/opass/ccip/ui/auth/AuthActivity.kt
1
8110
package app.opass.ccip.ui.auth import android.app.Activity import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import android.provider.MediaStore import android.widget.Button import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isGone import androidx.fragment.app.Fragment import androidx.viewpager2.widget.ViewPager2 import androidx.viewpager2.widget.ViewPager2.SCROLL_STATE_IDLE import app.opass.ccip.R import app.opass.ccip.extension.hideIme import app.opass.ccip.extension.showIme import app.opass.ccip.ui.MainActivity import app.opass.ccip.ui.event.EventActivity import com.google.android.material.snackbar.Snackbar import com.google.zxing.* import com.google.zxing.common.HybridBinarizer import com.google.zxing.integration.android.IntentIntegrator import kotlinx.android.synthetic.main.activity_auth.* import java.io.IOException private const val REQUEST_SCAN_FROM_GALLERY = 1 class AuthActivity : AppCompatActivity() { private lateinit var adapter: AuthViewPagerAdapter private lateinit var nextButton: Button private lateinit var prevButton: Button enum class AuthMethod { SCAN_FROM_CAMERA, SCAN_FROM_GALLERY, ENTER_TOKEN } abstract class PageFragment : Fragment() { open fun onSelected() {} open fun onNextButtonClicked() {} open fun getNextButtonText(): Int? = null open fun getPreviousButtonText(): Int? = null abstract fun shouldShowNextButton(): Boolean open fun shouldShowPreviousButton() = true // Returns true if the event is handled. open fun onBackPressed() = false } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_auth) nextButton = findViewById(R.id.next) prevButton = findViewById(R.id.previous) val fragmentList = intent?.extras?.getString(EXTRA_EVENT_ID)?.let { mutableListOf<PageFragment>( EventCheckFragment.newInstance( it ) ) } ?: mutableListOf<PageFragment>(MethodSelectionFragment()) adapter = AuthViewPagerAdapter(this, fragmentList) view_pager.isUserInputEnabled = false view_pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageScrollStateChanged(state: Int) { if (state == SCROLL_STATE_IDLE && adapter.fragments.lastIndex >= view_pager.currentItem) { onPageSelected() } } }) view_pager.adapter = adapter nextButton.setOnClickListener { if (adapter.fragments.lastIndex >= view_pager.currentItem) { adapter.fragments[view_pager.currentItem].onNextButtonClicked() } } prevButton.setOnClickListener { onBackPressed() } onPageSelected() } override fun onBackPressed() { val item = adapter.fragments[view_pager.currentItem] if (!item.onBackPressed() && !popFragment()) { super.onBackPressed() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data) result?.contents?.let { processToken(it) } if (requestCode == REQUEST_SCAN_FROM_GALLERY && resultCode == Activity.RESULT_OK) { data?.let(::processGalleryIntent) } } private fun onPageSelected() { adapter.fragments[view_pager.currentItem].onSelected() updateButtonState() } private fun processGalleryIntent(intent: Intent) { val bitmap: Bitmap try { bitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, intent.data) } catch (e: IOException) { e.printStackTrace() return } val width = bitmap.width val height = bitmap.height val pixels = IntArray(width * height) bitmap.getPixels(pixels, 0, width, 0, 0, width, height) val source = RGBLuminanceSource(width, height, pixels) val binaryBitmap = BinaryBitmap(HybridBinarizer(source)) val reader = MultiFormatReader() try { val result = reader.decode(binaryBitmap) result?.text?.let { processToken(it) } } catch (e: NotFoundException) { Snackbar.make(content, R.string.no_qr_code_found, Snackbar.LENGTH_SHORT).show() } catch (e: ChecksumException) { e.printStackTrace() } catch (e: FormatException) { e.printStackTrace() } } private fun addAndAdvance(fragment: PageFragment) { adapter.fragments.add(fragment) adapter.notifyDataSetChanged() view_pager.currentItem++ } private fun popFragment(): Boolean { if (adapter.fragments.size <= 1) return false view_pager.currentItem-- adapter.fragments.removeAt(adapter.fragments.lastIndex) adapter.notifyDataSetChanged() return true } fun updateButtonState() { adapter.fragments[view_pager.currentItem].run { nextButton.isGone = !shouldShowNextButton() prevButton.isGone = !shouldShowPreviousButton() if (shouldShowNextButton()) nextButton.text = getNextButtonText()?.let(this@AuthActivity::getString) if (shouldShowPreviousButton()) prevButton.text = getPreviousButtonText()?.let(this@AuthActivity::getString) } } fun onAuthMethodSelected(method: AuthMethod) { when (method) { AuthMethod.SCAN_FROM_CAMERA -> { IntentIntegrator(this).run { setDesiredBarcodeFormats(IntentIntegrator.QR_CODE) setPrompt(getString(R.string.scan_ticket_qrcode)) setCameraId(0) setBeepEnabled(false) setBarcodeImageEnabled(false) captureActivity = CaptureActivity::class.java initiateScan() } } AuthMethod.SCAN_FROM_GALLERY -> { val intent = Intent().apply { type = "image/*" action = Intent.ACTION_GET_CONTENT } startActivityForResult( Intent.createChooser(intent, getString(R.string.select_picture)), REQUEST_SCAN_FROM_GALLERY ) } AuthMethod.ENTER_TOKEN -> addAndAdvance(TokenEntryFragment()) } } fun processToken(token: String, disableRetry: Boolean = false) { addAndAdvance(TokenCheckFragment.newInstance(token, disableRetry)) } fun onAuthFinished() { val isStartedByUrl = intent?.extras?.getString(EXTRA_EVENT_ID) != null if (isStartedByUrl) startActivity(Intent(this, MainActivity::class.java)) finish() } fun onEventChecked(isSuccess: Boolean) { if (isSuccess) { intent!!.extras!!.getString(EXTRA_TOKEN)?.let { processToken(it, disableRetry = true) } ?: onAuthFinished() } else { startActivity(Intent(this, EventActivity::class.java)) finish() } } fun switchEvent() { startActivity(Intent(this, EventActivity::class.java)) finish() } fun hideKeyboard() = content.hideIme() fun showKeyboard() = content.showIme() companion object { private const val EXTRA_TOKEN = "EXTRA_TOKEN" private const val EXTRA_EVENT_ID = "EXTRA_EVENT_ID" fun createIntent(context: Context, eventId: String, token: String?) = Intent(context, AuthActivity::class.java).apply { putExtra(EXTRA_EVENT_ID, eventId) token?.let { putExtra(EXTRA_TOKEN, it) } } } }
gpl-3.0
dbafe6e16e8693c5498e30ca94bd2be6
34.726872
120
0.630949
4.86211
false
false
false
false
JustinMullin/drifter-kotlin
src/main/kotlin/xyz/jmullin/drifter/rendering/shader/Shaders.kt
1
942
package xyz.jmullin.drifter.rendering.shader import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.glutils.ShaderProgram /** * Convenience object for shader switching. Use switch in the context of a Layer2D to update * the current shader for that layer/batch and handle the context switching and flushing automatically. */ object Shaders { init { ShaderProgram.pedantic = false } val default = shader("default", "default") fun switch(s: ShaderSet, batch: SpriteBatch) { batch.flush() batch.shader = s.program batch.flush() s.update() } } /** * Convenience constructor for a shader. Provides a no-op block intended for placing side-effecting * uniform delegate creators. */ fun shader(fragShader: String, vertShader: String = "default", init: ShaderSet.() -> Unit = {}): ShaderSet { return ShaderSet(fragShader, vertShader).apply(init) }
mit
e3c4abe52dcc92342b5b055247930a79
28.4375
108
0.704883
4.131579
false
false
false
false
owntracks/android
project/app/src/main/java/org/owntracks/android/App.kt
1
8221
package org.owntracks.android import android.annotation.SuppressLint import android.app.Application import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.os.Build import android.os.StrictMode import androidx.appcompat.app.AppCompatDelegate import androidx.core.app.NotificationManagerCompat import androidx.databinding.DataBindingUtil import androidx.lifecycle.MutableLiveData import androidx.work.Configuration import androidx.work.WorkerFactory import dagger.hilt.EntryPoints import dagger.hilt.android.HiltAndroidApp import org.bouncycastle.jce.provider.BouncyCastleProvider import org.conscrypt.Conscrypt import org.owntracks.android.di.CustomBindingComponentBuilder import org.owntracks.android.di.CustomBindingEntryPoint import org.owntracks.android.geocoding.GeocoderProvider import org.owntracks.android.logging.TimberInMemoryLogTree import org.owntracks.android.services.MessageProcessor import org.owntracks.android.services.worker.Scheduler import org.owntracks.android.support.Preferences import org.owntracks.android.support.RunThingsOnOtherThreads import org.owntracks.android.support.SimpleIdlingResource import org.owntracks.android.ui.AppShortcuts import timber.log.Timber import java.security.Security import javax.inject.Inject import javax.inject.Provider @HiltAndroidApp class App : Application(), Configuration.Provider { @Inject lateinit var preferences: Preferences @Inject lateinit var runThingsOnOtherThreads: RunThingsOnOtherThreads @Inject lateinit var messageProcessor: MessageProcessor @Inject lateinit var workerFactory: WorkerFactory @Inject lateinit var scheduler: Scheduler @Inject lateinit var bindingComponentProvider: Provider<CustomBindingComponentBuilder> @Inject lateinit var appShortcuts: AppShortcuts val workManagerFailedToInitialize = MutableLiveData(false) @SuppressLint("RestrictedApi") override fun onCreate() { // Make sure we use Conscrypt for advanced TLS features on all devices. // X509ExtendedTrustManager not available pre-24, fall back to device. https://github.com/google/conscrypt/issues/603 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Security.insertProviderAt( Conscrypt.newProviderBuilder().provideTrustManager(true).build(), 1 ) } else { Security.insertProviderAt( Conscrypt.newProviderBuilder().provideTrustManager(false).build(), 1 ) } // Bring in a real version of BC and don't use the device version. Security.removeProvider("BC") Security.addProvider(BouncyCastleProvider()) super.onCreate() val dataBindingComponent = bindingComponentProvider.get().build() val dataBindingEntryPoint = EntryPoints.get( dataBindingComponent, CustomBindingEntryPoint::class.java ) DataBindingUtil.setDefaultComponent(dataBindingEntryPoint) scheduler.cancelAllTasks() Timber.plant(TimberInMemoryLogTree(BuildConfig.DEBUG)) if (BuildConfig.DEBUG) { Timber.e("StrictMode enabled in DEBUG build") StrictMode.setThreadPolicy( StrictMode.ThreadPolicy.Builder() .detectNetwork() .penaltyFlashScreen() .penaltyDialog() .build() ) StrictMode.setVmPolicy( StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .detectFileUriExposure() .penaltyLog() .build() ) } preferences.checkFirstStart() // Running this on a background thread will deadlock FirebaseJobDispatcher. // Initialize will call Scheduler to connect off the main thread anyway. runThingsOnOtherThreads.postOnMainHandlerDelayed({ messageProcessor.initialize() }, 510) when (preferences.theme) { Preferences.NIGHT_MODE_AUTO -> AppCompatDelegate.setDefaultNightMode(Preferences.SYSTEM_NIGHT_AUTO_MODE) Preferences.NIGHT_MODE_ENABLE -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) Preferences.NIGHT_MODE_DISABLE -> AppCompatDelegate.setDefaultNightMode( AppCompatDelegate.MODE_NIGHT_NO ) } if (preferences.experimentalFeatures.contains(Preferences.EXPERIMENTAL_FEATURE_ENABLE_APP_SHORTCUTS)) { appShortcuts.enableLogViewerShortcut(this) } else { appShortcuts.disableLogViewerShortcut(this) } // Notifications can be sent from multiple places, so let's make sure we've got the channels in place createNotificationChannels() } private fun createNotificationChannels() { val notificationManager = NotificationManagerCompat.from(this) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Importance min will show normal priority notification for foreground service. See https://developer.android.com/reference/android/app/NotificationManager#IMPORTANCE_MIN // User has to actively configure this in the notification channel settings. val ongoingNotificationChannelName = if (getString(R.string.notificationChannelOngoing).trim() .isNotEmpty() ) getString(R.string.notificationChannelOngoing) else "Ongoing" NotificationChannel( NOTIFICATION_CHANNEL_ONGOING, ongoingNotificationChannelName, NotificationManager.IMPORTANCE_LOW ).apply { lockscreenVisibility = Notification.VISIBILITY_PUBLIC description = getString(R.string.notificationChannelOngoingDescription) enableLights(false) enableVibration(false) setShowBadge(false) setSound(null, null) }.run { notificationManager.createNotificationChannel(this) } val eventsNotificationChannelName = if (getString(R.string.events).trim() .isNotEmpty() ) getString(R.string.events) else "Events" NotificationChannel( NOTIFICATION_CHANNEL_EVENTS, eventsNotificationChannelName, NotificationManager.IMPORTANCE_HIGH ).apply { lockscreenVisibility = Notification.VISIBILITY_PUBLIC description = getString(R.string.notificationChannelEventsDescription) enableLights(false) enableVibration(false) setShowBadge(true) setSound(null, null) }.run { notificationManager.createNotificationChannel(this) } val errorNotificationChannelName = if (getString(R.string.notificationChannelErrors).trim() .isNotEmpty() ) getString(R.string.notificationChannelErrors) else "Errors" NotificationChannel( GeocoderProvider.ERROR_NOTIFICATION_CHANNEL_ID, errorNotificationChannelName, NotificationManager.IMPORTANCE_LOW ).apply { lockscreenVisibility = Notification.VISIBILITY_PRIVATE }.run { notificationManager.createNotificationChannel(this) } } } val permissionIdlingResource: SimpleIdlingResource = SimpleIdlingResource("location", true) companion object { const val NOTIFICATION_CHANNEL_ONGOING = "O" const val NOTIFICATION_CHANNEL_EVENTS = "E" } @SuppressLint("RestrictedApi") override fun getWorkManagerConfiguration(): Configuration = Configuration.Builder() .setWorkerFactory(workerFactory) .setInitializationExceptionHandler { throwable -> Timber.e(throwable, "Exception thrown when initializing WorkManager") workManagerFailedToInitialize.postValue(true) } .build() }
epl-1.0
eb308bcd53b457387a190e28408e5e67
40.105
183
0.680452
5.581127
false
false
false
false
LorittaBot/Loritta
pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/CoinFlipBetMatchmakingResults.kt
1
608
package net.perfectdreams.loritta.cinnamon.pudding.tables import net.perfectdreams.exposedpowerutils.sql.javatime.timestampWithTimeZone import org.jetbrains.exposed.dao.id.LongIdTable object CoinFlipBetMatchmakingResults : LongIdTable() { val winner = reference("winner", Profiles).index() val loser = reference("loser", Profiles).index() val quantity = long("quantity").index() val quantityAfterTax = long("quantity_after_tax") val tax = long("tax").nullable() val taxPercentage = double("tax_percentage").nullable() val timestamp = timestampWithTimeZone("timestamp").index() }
agpl-3.0
b07851fe6154a2f24804760a98b3a4ac
42.5
77
0.754934
4.28169
false
false
false
false
Haldir65/AndroidRepo
app/src/main/java/com/me/harris/androidanimations/_36_fun_kt/Money.kt
1
3323
package com.me.harris.androidanimations._36_fun_kt import java.math.BigDecimal /** * Created by Harris on 2017/5/23. */ data class Money(var amount: Int, val currency: String) { operator fun plus(popcon: Money) = popcon.amount } data class DecMoney(var amount: BigDecimal, val currency: String) fun sendPayment(m: Money, message: String? = "default message"): Unit { println("sending ouy money ${m.amount} currency is${m.currency}") } fun main(args: Array<String>) { // Top Level entry Point val tickets = Money(100, "$") val popcon = tickets.copy(500, "EUR") if (tickets !== popcon) { println("stuff not equal") } val costs = tickets + popcon val train : DecMoney = DecMoney(100.bd, "$") val users: List<User> = ArrayList<User>(3) // 1. high order function findEmails(users,{each -> each.endsWith(".com")}) //just like lambda // 2. findEmails(users,{it.endsWith(".com")}) //one parameter like in groovy //3. findEmails(users){ it.endsWith(".com") } // Like stream val dotUser = users.filter { it.id ==10L }.sortedBy { it.id }.map { Pair(it.id,it.name)}.first() val (id,_) = users.filter { it.id ==10L }.sortedBy { it.id }.map { Pair(it.id,it.name)}.first() print(id) // sendPayment(tickets,"good luck") // // sendPayment(popcon) // default parameter // // val popMoney = DecMoney(BigDecimal(100),"$") // // 7.percentof(popMoney)// 7 Percent of popMoney // // 7 percentof popMoney // any extension function with on parameter can add in fix // // // val bd2 = 100.bd // val decM :DecMoney = popMoney.copy(bd2,"$") // // print(decM.amount) } fun sum(x: Int, y: Int) = x + y fun convertToDollars(m: Money,o:Money) :Money{ o.amount = (m.amount * 7.5).toInt() return o } //use nullable fun printMoneyAmount(m: Money?) { // print(m?.amount) print(m?.amount) } //high order function, a function that takes function or return a function data class User(val id: Long,val name:String) fun findEmails(user: List<User>, prdicate: (String) -> (Boolean)) :List<User> { TODO("Later!") // filtering users } fun bindHolder(payloads: List<Any>, pair: Pair<String,Int>) { // the way to iterate a list payloads.forEach { when (it) { is Payloads.Favorite -> print("is Favorite") is Payloads.Retweet -> { print("is Retweet") pair.apply { var text = first text = it.toString() } } } } } fun convertVerboseRealMoney(m: DecMoney): DecMoney { when (m.currency) { "$" -> return m "EUR" -> return DecMoney(m.amount * BigDecimal(1.10),"$") else -> TODO() } } // a much more simple expression fun convertRealMoney(m: DecMoney) =when (m.currency) { "$" -> m "EUR" -> DecMoney(m.amount * BigDecimal(1.10),"$") else -> TODO() } // extension Function fun BigDecimal.percent(percentage:Int) = this.multiply(BigDecimal(percentage)).divide(BigDecimal(1000)) infix fun Int.percentof(money: DecMoney) = money.amount.multiply(BigDecimal(this)).divide(BigDecimal(100)) private val Int.bd: BigDecimal get() { return BigDecimal(this) //return the instance }
apache-2.0
39c4a4d6bba69b5d9138012fa30a7a08
21.459459
106
0.606681
3.401228
false
false
false
false
christophpickl/gadsu
src/main/kotlin/gadsu/persistence/V6_1__xprop_update.kt
1
3603
package gadsu.persistence import at.cpickl.gadsu.service.LOG import com.google.common.annotations.VisibleForTesting import org.flywaydb.core.api.migration.jdbc.JdbcMigration import java.sql.Connection import java.util.LinkedList // https://flywaydb.org/documentation/migration/java class V6_1__xprop_update : JdbcMigration { companion object { @VisibleForTesting val hungryDigestParts = listOf( "DigestionSlow", "DigestionFast", "Blockage", "Diarrhea", "UndigestedParts", "StoolHard", "StoolSoft", "WindBelly", "Farts") private val hungryDigest_prefixHungry = hungryDigestParts.map { "Hungry_$it" } } private val log = LOG(javaClass) override fun migrate(connection: Connection) { log.info("migrate") migrateTastesIntoExistingHungryAndDelete(connection) migrateHungryPartlyIntoNewDigestion(connection) } private fun migrateTastesIntoExistingHungryAndDelete(connection: Connection) { val xprops = selectXProps(connection) xprops.filter { it.key == "Taste" }.forEach { xprop -> val tasteVals = xprop.values.map { it.replace("Taste_", "Hungry_Taste") } val hungry = xprops.firstOrNull { it.idClient == xprop.idClient && it.key == "Hungry" } if (hungry == null) { connection.prepareStatement("INSERT INTO xprops (id_client, key, val) VALUES ('${xprop.idClient}', 'Hungry', '${tasteVals.joinToString(",")}')").apply { executeUpdate();close() } } else { val mergedVals = hungry.values.plus(tasteVals) connection.prepareStatement("UPDATE xprops SET val = '${mergedVals.joinToString(",")}' WHERE id_client = '${xprop.idClient}' AND key = 'Hungry'").apply { executeUpdate();close() } } } connection.prepareStatement("DELETE FROM xprops WHERE key = 'Taste'").apply { executeUpdate(); close() } } private fun migrateHungryPartlyIntoNewDigestion(connection: Connection) { val xprops = selectXProps(connection) xprops.filter { it.key == "Hungry" }.forEach { xprop -> val intersect = xprop.values.intersect(hungryDigest_prefixHungry) if (intersect.isNotEmpty()) { val digestionValues = intersect.map { it.replace("Hungry_", "Digestion_") } connection.prepareStatement("INSERT INTO xprops (id_client, key, val) VALUES " + "('${xprop.idClient}', 'Digestion', '${digestionValues.joinToString(",")}')").apply { executeUpdate();close() } val hungryCleaned = xprop.values.minus(hungryDigest_prefixHungry) connection.prepareStatement("UPDATE xprops SET val = '${hungryCleaned.joinToString(",")}' WHERE id_client = '${xprop.idClient}' AND key = 'Hungry'").apply { executeUpdate();close() } } } } private fun selectXProps(connection: Connection): LinkedList<XPropDbo> { val statement = connection.prepareStatement("SELECT * FROM xprops") val result = LinkedList<XPropDbo>() try { val rs = statement.executeQuery() while (rs.next()) { // we already got a note here, but it will be always null, as no valid V6 entry was created yet result.add(XPropDbo(rs.getString("id_client"), rs.getString("key"), rs.getString("val").split(","))) } } finally { statement.close() } return result } } private data class XPropDbo(val idClient: String, val key: String, val values: List<String>)
apache-2.0
f0514006d48cf88d17aaf135c8a38d36
44.607595
199
0.635859
4.085034
false
false
false
false
daring2/fms
zabbix/core/src/main/kotlin/com/gitlab/daring/fms/zabbix/model/Item.kt
1
667
package com.gitlab.daring.fms.zabbix.model import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonInclude @JsonInclude(JsonInclude.Include.NON_NULL) data class Item( val key: String, val delay: Int = 60, val key_orig: String? = null, @Volatile var lastlogsize: Long = 0, @Volatile var mtime: Long = 0, @JsonIgnore val charset: String = "UTF-8", @JsonIgnore val host: String = "" ) { fun applyValue(v: ItemValue): Item { v.lastlogsize?.let { lastlogsize = it } v.mtime?.let { mtime = it } return this } }
apache-2.0
e877d7ed8c08b66befbdc01c890cfda3
23.740741
51
0.604198
3.811429
false
false
false
false
charbgr/CliffHanger
cliffhanger/api-tmdb/src/main/kotlin/com/github/charbgr/cliffhanger/api_tmdb/TmdbAPI.kt
1
1604
package com.github.charbgr.cliffhanger.api_tmdb import com.github.charbgr.cliffhanger.api_tmdb.dao.MovieDAO import com.github.charbgr.cliffhanger.api_tmdb.dao.SearchDAO import io.reactivex.Scheduler import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import okhttp3.logging.HttpLoggingInterceptor.Level.BODY import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.moshi.MoshiConverterFactory class TmdbAPI(scheduler: Scheduler) { val retrofit: Retrofit by lazy { val okHttpClient: OkHttpClient = OkHttpClient .Builder() .addInterceptor(apiKeyInterceptor()) .addInterceptor(HttpLoggingInterceptor().apply { level = BODY }) .build() Retrofit.Builder() .baseUrl(Routes.BASE_BACKEND_URL) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(scheduler)) .addConverterFactory(MoshiConverterFactory.create()) .build() } val movieDAO: MovieDAO by lazy { retrofit.create(MovieDAO::class.java) } val searchDAO: SearchDAO by lazy { retrofit.create(SearchDAO::class.java) } private fun apiKeyInterceptor(): Interceptor = Interceptor { val request = it.request() val requestBuilder = request.newBuilder() val urlHttpBuilder = request.url().newBuilder() urlHttpBuilder.addQueryParameter("api_key", BuildConfig.TMDB_API_KEY) val newRequest = requestBuilder.url(urlHttpBuilder.build()).build() it.proceed(newRequest) } }
mit
f5b66f6c7c1acb3625dda93b55130419
29.846154
88
0.745636
4.51831
false
false
false
false
marcellourbani/InEvents
internationsevents/src/main/java/com/marcellourbani/internationsevents/data/Event.kt
1
6025
package com.marcellourbani.internationsevents.data data class EventResponse ( val total: Long, val limit: Long, val offset: Long, val _links: InLinkWrapper, val _embedded: EventResponseEmbedded ) data class EventResponseEmbedded ( val self: List<Event> ) data class Event ( val guestlistId: Long, val id: Long, val type: Type, val title: String, val surtitle: String, val description: String, val stickerTitle: String, val imageUrl: String, val startDateTime: String, val startsOn: String, val startsOnUtc: String, val endsOn: String, val endsOnUtc: String, val attendeeCount: Long, val nationalityCount: Long, val isNewcomerOnly: Boolean, val activityGroupId: Long? = null, val activityGroupCategoryId: Long? = null, val videoConferenceType: String?=null, val isPublished: Boolean, val externalUrl: String, val invitationType: String? = null, val userGalleryId: Long, val promotionGalleryId: Long, val activityContactPhone: Any? = null, val attendingContactsIds: List<String>, val totalAttendingContacts: Long, val meetingPoint: String? = null, val format: String, val isActivityHostedByConsul: Boolean? = null, val ticketShopIframeCode: Any? = null, val localcommunityId: Long, val _links: EventLinks, val _embedded: EventEmbedded ) data class EventEmbedded ( val permissions: Permissions, val guestlist: Guestlist, val venue: Venue, val hosts: Hosts, val latestInvitationSender: AttendingContactElement? = null, val userGallery: Gallery, val promotionGallery: Gallery, val localcommunity: Localcommunity, val attendingContact: AttendingContactElement? = null, val rsvp: Rsvp? = null, ) data class Rsvp ( val guestlistId: Long, val inviteeId: Long, val id: Long, val status: String, val isNewcomer: Boolean, val _links: InLinkWrapper, val _embedded: AttendingContactEmbedded ) data class AttendingContactElement ( val countryOfOriginCode: Country, val countryOfResidencyCode: Country, val isPremium: Boolean, val id: Long, val imagePath: String, val localcommunityName: String, val roles: List<String>, val role: String, val origin: Origin, val residency: Origin, val gender: Gender, val firstName: String, val lastName: String, val membership: Long, val isActive: Boolean, val localcommunityId: Long, val workplacePosition: String? = null, val workplaceCompany: String? = null, val motto: String? = null, val languages: List<String>, val interests: List<String>, val registeredOn: String, val expatType: String?=null, val _links: AttendingContactLinks, val _embedded: AttendingContactEmbedded ) data class AttendingContactEmbedded ( val permissions: Permissions ) enum class Gender { f, m } data class AttendingContactLinks ( val self: InLink, val localcommunity: InLink ) data class Guestlist ( val id: Long, val attendeeCount: Long, val guestlistStatistics: GuestlistStatistics, val guestlistRestrictions: GuestlistRestrictions, val isOpen: Boolean, val pricing: Pricing? = null, val activityPricing: List<ActivityPricing>? = null, val closedOn: Any? = null, val ticketingEd25519PublicKeyId: Long? = null, val _links: GuestlistLinks, val _embedded: GuestlistEmbedded ) data class ActivityPricing ( val name: String, val price: BasicMemberFee ) data class BasicMemberFee ( val text: String, val amount: String, val currencyName: String, val currencySymbol: String ) data class GuestlistEmbedded ( val permissions: Permissions, val ticketingEd25519PublicKey: TicketingEd25519PublicKey? = null ) data class TicketingEd25519PublicKey ( val id: Long, val publicKey: String, val createdOn: String, val _links: InLinkWrapper ) data class GuestlistRestrictions ( val attendanceLimit: Long? = null, val waitingListEnabled: Boolean, val newcomerOnly: Boolean, val expatsOnly: Boolean, val albatrossOnly: Boolean, val womenOnly: Boolean ) data class GuestlistStatistics ( val albatrossAttendeesCount: Long, val premiumAttendeesWithAffirmativeRsvpCount: Long, val basicAttendeesCount: Long, val basicAttendeesWithAffirmativeRsvpCount: Long, val otherAttendeesCount: Long, val attendeesWithoutAffirmativeRsvpCount: Long, val totalAttendeesCount: Long ) data class GuestlistLinks ( val self: InLink, val acceptedRsvps: InLink, val ticketingEd25519PublicKey: InLink? = null ) data class Pricing ( val benefits: String, val premiumMemberFee: BasicMemberFee, val basicMemberFee: BasicMemberFee, val nonMemberFee: BasicMemberFee ) data class Hosts ( val total: Long, val limit: Any? = null, val offset: Any? = null, val _embedded: HostsEmbedded ) data class HostsEmbedded ( val self: List<AttendingContactElement> ) data class Gallery ( val id: Long, val entityType: Type, val entityId: Long, val galleryType: GalleryType, val title: String, val photoCount: Long, val _links: PromotionGalleryLinks, val _embedded: AttendingContactEmbedded ) enum class Type { activity, event } enum class GalleryType { promotion, user } data class PromotionGalleryLinks ( val self: InLink, val photos: InLink, val privileges: InLink ) data class Venue ( val localcommunityId: Any? = null, val id: Any? = null, val name: String, val address: String? = null, val website: String? = null, val city: String?=null, val coordinates: Coordinates ) data class EventLinks ( val self: InLink, val guestlist: InLink, val latestInvitationSender: InLink? = null, val userGallery: InLink, val promotionGallery: InLink, val localcommunity: InLink, val attendingContact: InLink? = null )
gpl-3.0
724c92b186150f8aa2097b4b0c9065bb
23.692623
68
0.702407
3.825397
false
false
false
false
chenxyu/android-banner
bannerlibrary/src/main/java/com/chenxyu/bannerlibrary/BannerView.kt
1
23642
package com.chenxyu.bannerlibrary import android.content.Context import android.graphics.Outline import android.graphics.Rect import android.os.Build import android.os.Handler import android.os.Looper import android.os.Message import android.util.AttributeSet import android.view.View import android.view.ViewGroup import android.view.ViewOutlineProvider import android.widget.LinearLayout import android.widget.RelativeLayout import androidx.annotation.DrawableRes import androidx.annotation.RequiresApi import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearSmoothScroller import androidx.recyclerview.widget.RecyclerView import androidx.viewpager2.widget.MarginPageTransformer import androidx.viewpager2.widget.ViewPager2 import com.chenxyu.bannerlibrary.extend.az import com.chenxyu.bannerlibrary.extend.dpToPx import com.chenxyu.bannerlibrary.indicator.CircleIndicator import com.chenxyu.bannerlibrary.indicator.DrawableIndicator import com.chenxyu.bannerlibrary.indicator.Indicator import com.chenxyu.bannerlibrary.listener.OnItemClickListener import com.chenxyu.bannerlibrary.listener.OnItemLongClickListener import com.chenxyu.bannerlibrary.transformer.DepthPageTransformer import com.chenxyu.bannerlibrary.transformer.RotationPageTransformer import com.chenxyu.bannerlibrary.transformer.ScalePageTransformer import com.chenxyu.bannerlibrary.transformer.ZoomOutPageTransformer import java.lang.ref.WeakReference /** * @Author: ChenXingYu * @CreateDate: 2020/3/2 0:38 * @Description: BannerView基于ViewPager2(支持动画) * @Version: 1.0 */ class BannerView : RelativeLayout { companion object { private const val WHAT_NEXT_PAGE = 1 const val HORIZONTAL = ViewPager2.ORIENTATION_HORIZONTAL const val VERTICAL = ViewPager2.ORIENTATION_VERTICAL } private var mViewPager2: ViewPager2? = null private var mAdapter: Adapter<*, *>? = null /** *当前页面数据长度 */ private var mDataSize: Int = -1 /** * 指示器 */ private var mIndicator: Indicator? = null /** * 指示器是否循环 */ private var isLoopForIndicator: Boolean = true /** * 指示器外边距 */ private var mIndicatorMargin: Int? = null /** * 指示器位置 */ private var mIndicatorGravity: Int? = null /** * 默认Indicator */ @DrawableRes private var mIndicatorNormal: Int? = null /** * 选中Indicator */ @DrawableRes private var mIndicatorSelected: Int? = null /** * 预加载页面限制(默认2) */ private var mOffscreenPageLimit = 2 /** * 观察Fragment或Activity生命周期控制Banner开始和暂停 */ private var mLifecycleOwner: LifecycleOwner? = null /** * 是否触摸 */ private var isTouch = false /** * 页面切换延迟时间 */ private var mDelayMillis: Long = 5000 /** * 滑动持续时间 */ private var mDuration: Int? = null /** * 自动循环轮播(true:默认自动-循环轮播 false:不自动-循环轮播 null:不循环) */ private var isAutoPlay: Boolean? = true /** * Handler控制轮播 */ private var mHandler: Handler? = BannerHandler(this) /** * 观察Activity或Fragment生命周期 */ private val mLifecycleEventObserver = LifecycleEventObserver { _, event -> when (event) { Lifecycle.Event.ON_RESUME -> { if (isAutoPlay != null && isAutoPlay == true) { mHandler?.sendEmptyMessageDelayed(WHAT_NEXT_PAGE, mDelayMillis) } } Lifecycle.Event.ON_PAUSE -> mHandler?.removeMessages(WHAT_NEXT_PAGE) Lifecycle.Event.ON_DESTROY -> { release() } else -> { } } } constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { val attributes = context.obtainStyledAttributes(attrs, R.styleable.BannerView) attributes.let { if (it.hasValue(R.styleable.BannerView_orientation)) { mViewPager2?.orientation = it.getInteger(R.styleable.BannerView_orientation, HORIZONTAL) } if (it.hasValue(R.styleable.BannerView_indicatorNormal)) { mIndicatorNormal = it.getResourceId(R.styleable.BannerView_indicatorNormal, -1) } if (it.hasValue(R.styleable.BannerView_indicatorSelected)) { mIndicatorSelected = it.getResourceId(R.styleable.BannerView_indicatorSelected, -1) } if (it.hasValue(R.styleable.BannerView_indicatorMargin)) { mIndicatorMargin = it.getDimension(R.styleable.BannerView_indicatorMargin, -1F).toInt() } if (it.hasValue(R.styleable.BannerView_indicatorGravity)) { mIndicatorGravity = it.getInteger(R.styleable.BannerView_indicatorGravity, -1) } if (it.hasValue(R.styleable.BannerView_autoPlay)) { isAutoPlay = it.getBoolean(R.styleable.BannerView_autoPlay, true) } if (it.hasValue(R.styleable.BannerView_offscreenPageLimit)) { mOffscreenPageLimit = it.getInteger(R.styleable.BannerView_offscreenPageLimit, mOffscreenPageLimit) } if (it.hasValue(R.styleable.BannerView_delayMillis)) { mDelayMillis = it.getInteger(R.styleable.BannerView_delayMillis, 5000).toLong() } if (it.hasValue(R.styleable.BannerView_duration)) { mDuration = it.getInteger(R.styleable.BannerView_duration, 0) } } attributes.recycle() mViewPager2 = ViewPager2(context) mViewPager2?.id = R.id.view_pager_id val layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT ) addView(mViewPager2, 0, layoutParams) } /** * 释放资源 */ fun release() { mHandler?.removeMessages(WHAT_NEXT_PAGE) mHandler = null mAdapter = null mViewPager2 = null mIndicatorNormal = null mIndicatorSelected = null mIndicatorMargin = 0 mDataSize = -1 mOffscreenPageLimit = 0 mLifecycleOwner = null mDelayMillis = 0 mDuration = null isTouch = false mIndicator = null mLifecycleOwner?.lifecycle?.removeObserver(mLifecycleEventObserver) mLifecycleOwner = null } /** * 创建Banner */ fun build() { if (mAdapter == null) throw NullPointerException("Please set up adapter") mAdapter?.getRealData()?.size?.let { if (it < 1) throw RuntimeException("No less than 1 pieces of data") } // 替换LayoutManager mDuration?.let { replaceLayoutManager() } mViewPager2?.let { it.offscreenPageLimit = mOffscreenPageLimit it.adapter = mAdapter it.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageScrollStateChanged(state: Int) { super.onPageScrollStateChanged(state) when (state) { // 闲置 ViewPager2.SCROLL_STATE_IDLE -> { isTouch = false if (isAutoPlay != null) { if (it.currentItem == 0) { it.setCurrentItem(mDataSize - 2, false) } if (it.currentItem == mDataSize - 1) { it.setCurrentItem(1, false) } } } // 拖拽中 ViewPager2.SCROLL_STATE_DRAGGING -> { isTouch = true } // 惯性滑动中 ViewPager2.SCROLL_STATE_SETTLING -> { isTouch = false } } } }) // 设置指示器 if (mIndicator != null || mIndicatorNormal != null || mIndicatorSelected != null || mIndicatorMargin != null || mIndicatorGravity != null) { if (mIndicator == null) { mIndicator = DrawableIndicator(true, mIndicatorNormal, mIndicatorSelected, mIndicatorMargin, mIndicatorGravity) } mIndicator!!.initialize(this, mAdapter!!.getRealItemCount(), mViewPager2!!.orientation, isLoopForIndicator) mIndicator!!.registerOnPageChangeCallback(mViewPager2) } else { mIndicator?.unregisterOnPageChangeCallback(mViewPager2) mIndicator = null } if (isAutoPlay != null) { // 默认设置第一页 it.setCurrentItem(1, false) if (mLifecycleOwner != null) { mLifecycleOwner?.lifecycle?.addObserver(mLifecycleEventObserver) } else { mHandler?.sendEmptyMessageDelayed(WHAT_NEXT_PAGE, mDelayMillis) } } else { mHandler?.removeMessages(WHAT_NEXT_PAGE) } } } /** * 观察Activity或Fragment生命周期控制Banner开始和暂停 * @param lifecycleOwner Fragment or Activity */ fun setLifecycle(lifecycleOwner: LifecycleOwner): BannerView { mLifecycleOwner = lifecycleOwner return this } /** * 设置适配器 * @param adapter 自定义适配器[Adapter] * @param orientation 滑动方向 默认[HORIZONTAL] [VERTICAL] */ fun setAdapter(adapter: Adapter<*, *>, orientation: Int = HORIZONTAL): BannerView { mAdapter = adapter.apply { autoPlay(isAutoPlay) mDataSize = itemCount } mViewPager2?.orientation = orientation return this } /** * 设置指示器 * @param indicator 自定义指示器需继承此类[Indicator] */ fun setIndicator(indicator: Indicator): BannerView { mIndicator = indicator return this } /** * 自动循环轮播 * @param autoPlay true:默认自动-循环轮播 false:不自动-循环轮播 null:不循环 */ fun setAutoPlay(autoPlay: Boolean?): BannerView { isAutoPlay = autoPlay mAdapter?.autoPlay(isAutoPlay) isLoopForIndicator = autoPlay != null return this } /** * 预加载页面限制(默认2) */ fun setOffscreenPageLimit(@ViewPager2.OffscreenPageLimit limit: Int): BannerView { mOffscreenPageLimit = limit return this } /** * 页面切换延迟时间 * @param delayMillis 延迟时间(毫秒) */ fun setDelayMillis(delayMillis: Long): BannerView { mDelayMillis = delayMillis return this } /** * 滑动持续时间 * @param duration 持续时间(毫秒) */ fun setDuration(duration: Int): BannerView { mDuration = duration return this } /** * 设置页面间距 * @param margin 间距(DP) */ fun setPageMargin(margin: Int): BannerView { mViewPager2?.setPageTransformer(MarginPageTransformer(margin.dpToPx(context))) return this } /** * Banner圆角(DP) * @param radius 半径范围 */ @RequiresApi(Build.VERSION_CODES.LOLLIPOP) fun setRoundRect(radius: Float): BannerView { outlineProvider = object : ViewOutlineProvider() { override fun getOutline(view: View?, outline: Outline?) { outline?.setRoundRect(left, top, right, bottom, radius.dpToPx(context)) } } clipToOutline = radius > 0F return this } /** * 一屏多页,在[setAdapter]之后设置 * @param margin 间距(DP) */ fun setMultiPage(margin: Int): BannerView { clipChildren = false mViewPager2?.clipChildren = false val params = mViewPager2?.layoutParams?.az<MarginLayoutParams>() if (mViewPager2?.orientation == HORIZONTAL) { params?.leftMargin = margin.dpToPx(context) * 2 params?.rightMargin = params?.leftMargin } else { params?.topMargin = margin.dpToPx(context) * 2 params?.bottomMargin = params?.topMargin } return this } /** * 缩放动画,在[setAdapter]之后设置 */ fun setScalePageTransformer(): BannerView { mViewPager2?.let { setPageTransformer(ScalePageTransformer(it.orientation)) } return this } /** * 官方示例缩放动画,在[setAdapter]之后设置 */ fun setZoomOutPageTransformer(): BannerView { mViewPager2?.let { setPageTransformer(ZoomOutPageTransformer(it.orientation)) } return this } /** * 官方示例旋转动画,在[setAdapter]之后设置 */ fun setRotationPageTransformer(): BannerView { mViewPager2?.let { setPageTransformer(RotationPageTransformer(it.orientation)) } return this } /** * 官方示例深度动画,在[setAdapter]之后设置 */ fun setDepthPageTransformer(): BannerView { mViewPager2?.let { setPageTransformer(DepthPageTransformer(it.orientation)) } return this } /** * 设置动画[ZoomOutPageTransformer] [RotationPageTransformer] * [DepthPageTransformer] [ScalePageTransformer] */ fun setPageTransformer(transformer: ViewPager2.PageTransformer): BannerView { mViewPager2?.setPageTransformer(transformer) return this } /** * 开始循环 */ fun start() { if (mDataSize > 0) { mHandler?.sendEmptyMessageDelayed(WHAT_NEXT_PAGE, mDelayMillis) } } /** * 暂停循环 */ fun pause() { if (mDataSize > 0) { mHandler?.removeMessages(WHAT_NEXT_PAGE) } } /** * 替换LayoutManager */ private fun replaceLayoutManager() { mViewPager2?.let { val layoutManagerImpl = LayoutManagerImpl(context, it.orientation) layoutManagerImpl.mDuration = mDuration layoutManagerImpl.mOffscreenPageLimit = mOffscreenPageLimit layoutManagerImpl.mDataSize = mDataSize val mRecyclerView = it.getChildAt(0)?.az<RecyclerView>() mRecyclerView?.layoutManager = layoutManagerImpl val mLayoutManager = it::class.java.getDeclaredField("mLayoutManager") mLayoutManager.isAccessible = true mLayoutManager.set(it, layoutManagerImpl) val field = it::class.java.getDeclaredField("mPageTransformerAdapter") field.isAccessible = true val mPageTransformerAdapter = field.get(it) val mLayoutManager2 = mPageTransformerAdapter::class.java.getDeclaredField("mLayoutManager") mLayoutManager2.isAccessible = true mLayoutManager2.set(mPageTransformerAdapter, layoutManagerImpl) val field2 = it::class.java.getDeclaredField("mScrollEventAdapter") field2.isAccessible = true val mScrollEventAdapter = field2.get(it) val mLayoutManager3 = mScrollEventAdapter::class.java.getDeclaredField("mLayoutManager") mLayoutManager3.isAccessible = true mLayoutManager3.set(mScrollEventAdapter, layoutManagerImpl) } } class BannerHandler(view: BannerView) : Handler(Looper.getMainLooper()) { private val weakReference = WeakReference(view) override fun handleMessage(msg: Message) { val bannerView = weakReference.get() when (msg.what) { WHAT_NEXT_PAGE -> { if (bannerView?.isTouch != null && !bannerView.isTouch) { bannerView.mViewPager2?.let { it.currentItem = it.currentItem + 1 } } bannerView?.mDelayMillis?.let { sendEmptyMessageDelayed(WHAT_NEXT_PAGE, it) } } } } } /** * 自定义Adapter需要继承此类,使用getReal开头的方法获取真实的数据 * @param VH ViewHolder * @param T 数据类型 */ abstract class Adapter<VH : RecyclerView.ViewHolder, T>( private val mData: MutableList<T?> ) : RecyclerView.Adapter<VH>() { private val transformData = mutableListOf<T?>() var onItemClickListener: OnItemClickListener? = null var onItemLongClickListener: OnItemLongClickListener? = null /** * 自动循环轮播(true:默认自动-循环轮播 false:不自动-循环轮播 null:不循环) */ private var autoPlay: Boolean? = false init { transformData.addAll(mData) if (transformData.size < 1) throw RuntimeException("Minimum size 1") } /** * 是否循环轮播 */ fun autoPlay(autoPlay: Boolean?) { this.autoPlay = autoPlay when { autoPlay != null && transformData.size == mData.size -> { // 循环轮播前后增加一页 transformData.add(0, transformData[transformData.size - 1]) transformData.add(transformData.size, transformData[1]) } autoPlay == null -> { transformData.clear() transformData.addAll(mData) } } } /** * 处理过的ItemCount */ override fun getItemCount(): Int = transformData.size /** * 处理过的Data */ fun getData(): MutableList<T?> { return transformData } /** * 真实的ItemCount */ fun getRealItemCount(): Int = mData.size /** * 真实的Data */ fun getRealData(): MutableList<T?> { return mData } /** * 真实的Position * @param position [onBindViewHolder]里面的position */ fun getRealPosition(position: Int): Int { return if (autoPlay != null) { when (position) { 0 -> mData.size - 1 transformData.size - 1 -> 0 else -> position - 1 } } else { position } } /** * 真实的Item * @param position [onBindViewHolder] [OnItemClickListener] [OnItemLongClickListener]里面的position */ fun getRealItem(position: Int): T? { return when (position) { 0 -> mData[mData.size - 1] transformData.size - 1 -> mData[0] else -> mData[position - 1] } } /** * 根布局强制MATCH_PARENT */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH { val bannerViewHolder = onCreateVH(parent, viewType) bannerViewHolder.itemView.rootView?.apply { val lp = RecyclerView.LayoutParams( RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.MATCH_PARENT ) layoutParams = lp } return bannerViewHolder } /** * @param parent 绑定到适配器位置后,新视图将被添加到其中的ViewGroup * @param viewType 视图类型 */ abstract fun onCreateVH(parent: ViewGroup, viewType: Int): VH /** * ClickListener获取的都是真实position */ override fun onBindViewHolder(holder: VH, position: Int) { holder.itemView.setOnClickListener { onItemClickListener?.onItemClick(it, getRealPosition(position)) } holder.itemView.setOnLongClickListener { onItemLongClickListener?.onItemLongClick(it, getRealPosition(position)) return@setOnLongClickListener true } onBindViewHolder(holder, position, transformData[position]) } /** * @param holder ViewHolder * @param position 当前Item位置 * @param item 当前Item数据 */ abstract fun onBindViewHolder(holder: VH, position: Int, item: T?) } /** * 多布局使用或[RecyclerView.ViewHolder] */ abstract class ViewHolder<in T>(itemView: View) : RecyclerView.ViewHolder(itemView) { abstract fun initView(item: T?, position: Int? = null, context: Context? = null) } private class LayoutManagerImpl(context: Context, orientation: Int, reverseLayout: Boolean = false) : LinearLayoutManager( context, orientation, reverseLayout ) { /** * 滑动持续时间 */ var mDuration: Int? = null /** * 预加载页面限制(默认2) */ var mOffscreenPageLimit = 2 /** *当前页面数据长度 */ var mDataSize: Int = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT override fun smoothScrollToPosition( recyclerView: RecyclerView?, state: RecyclerView.State?, position: Int ) { val linearSmoothScroller = object : LinearSmoothScroller(recyclerView!!.context) { override fun calculateTimeForDeceleration(dx: Int): Int { return mDuration ?: super.calculateTimeForDeceleration(dx) } } linearSmoothScroller.targetPosition = position startSmoothScroll(linearSmoothScroller) } override fun calculateExtraLayoutSpace(state: RecyclerView.State, extraLayoutSpace: IntArray) { val pageLimit: Int = mOffscreenPageLimit if (pageLimit == ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT) { // Only do custom prefetching of offscreen pages if requested super.calculateExtraLayoutSpace(state, extraLayoutSpace) return } val offscreenSpace: Int = mDataSize * pageLimit extraLayoutSpace[0] = offscreenSpace extraLayoutSpace[1] = offscreenSpace } override fun requestChildRectangleOnScreen(parent: RecyclerView, child: View, rect: Rect, immediate: Boolean, focusedChildVisible: Boolean): Boolean { return false // users should use setCurrentItem instead } } }
mit
9b7b33e21183d7c049ad669c6aa4f820
31.274678
126
0.576995
4.897959
false
false
false
false
rovkinmax/RxRetainFragment
app/src/androidTest/java/com/github/rovkinmax/rxretainexample/ComposeBindTest.kt
1
4795
package com.github.rovkinmax.rxretainexample import android.app.FragmentManager import android.content.Context import android.content.Intent import android.support.test.InstrumentationRegistry import android.support.test.filters.SdkSuppress import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import android.support.test.uiautomator.UiDevice import com.github.rovkinmax.rxretain.RetainFactory import com.github.rovkinmax.rxretainexample.test.TestableActivity import com.github.rovkinmax.rxretainexample.test.bindToThread import com.github.rovkinmax.rxretainexample.test.rangeWithDelay import com.robotium.solo.Solo import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import rx.Observable import rx.Observer import rx.Subscription import rx.observers.TestSubscriber import java.util.concurrent.TimeUnit.SECONDS /** * @author Rovkin Max */ @RunWith(AndroidJUnit4::class) @SdkSuppress(minSdkVersion = 18) class ComposeBindTest { @get:Rule val rule = ActivityTestRule<TestableActivity>(TestableActivity::class.java, false, false) private lateinit var context: Context private lateinit var activity: TestableActivity private lateinit var fragmentManager: FragmentManager private lateinit var solo: Solo private lateinit var device: UiDevice private lateinit var basePackage: String @Before fun setUp() { setUpDevice() context = InstrumentationRegistry.getContext() activity = rule.launchActivity(Intent(context, TestableActivity::class.java)) solo = Solo(InstrumentationRegistry.getInstrumentation(), activity) fragmentManager = activity.fragmentManager basePackage = activity.packageName } private fun setUpDevice() { device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) device.setOrientationNatural() device.unfreezeRotation() } @Test fun testSimpleCompose() { val subscriber = TestSubscriber<Int>() rangeWithDelay(0, 5, SECONDS.toMillis(1)) .bindToThread() .compose(RetainFactory.bindToRetain(fragmentManager)) .subscribeOnUI(subscriber) subscriber.awaitTerminalEvent() subscriber.assertCompleted() } @Test fun testRotationUnsubscribe() { val subscriber = TestSubscriber<Int>() rangeWithDelay(0, 5, SECONDS.toMillis(10)) .bindToThread() .compose(RetainFactory.bindToRetain(fragmentManager, "unsubscribe tag")) .subscribeOnUI(subscriber) subscriber.awaitTerminalEvent(1, SECONDS) changeOrientationAndWait() subscriber.assertUnsubscribed() } @Test fun testBindAfterRotation() { val subscriber = TestSubscriber<Int>() rangeWithDelay(0, 5, SECONDS.toMillis(5)) .bindToThread() .compose(RetainFactory.bindToRetain(fragmentManager, "bind rotation")) .subscribeOnUI(subscriber) subscriber.awaitTerminalEvent(1, SECONDS) changeOrientationAndWait() val secondSubscriber = TestSubscriber<Int>() rangeWithDelay(0, 5, SECONDS.toMillis(5)) .bindToThread() .compose(RetainFactory.bindToRetain(fragmentManager, "bind rotation")) .subscribeOnUI(secondSubscriber) secondSubscriber.awaitTerminalEvent() secondSubscriber.assertReceivedOnNext((0..4).toCollection(arrayListOf())) } @Test fun testRunByClick() { val subscriber = TestSubscriber<Int>() val observable = rangeWithDelay(0, 5, SECONDS.toMillis(5)) .bindToThread() .compose(RetainFactory.bindToRetain(fragmentManager, "run by click")) runOnUIAndWait { activity.performClick({ observable.subscribe(subscriber) }) } subscriber.awaitTerminalEvent() subscriber.assertReceivedOnNext((0..4).toCollection(arrayListOf())) } @After fun tearDown() { solo.finishOpenedActivities() solo.finalize() } private fun changeOrientationAndWait() { device.setOrientationLeft() device.waitForWindowUpdate(basePackage, SECONDS.toMillis(5)) } private fun <T> Observable<T>.subscribeOnUI(subscriber: Observer<T>): Subscription { return runOnUIAndWait { subscribe(subscriber) } } private fun <T> runOnUIAndWait(func: () -> T): T { var result: T? = null InstrumentationRegistry.getInstrumentation().runOnMainSync { result = func() } InstrumentationRegistry.getInstrumentation().waitForIdleSync() return result!! } }
apache-2.0
358e840fddd23956a5c5f22bb1cb72df
31.62585
93
0.697393
4.902863
false
true
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/ide/presentation/PresentationInfo.kt
2
6882
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.presentation import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* class PresentationInfo( element: RsNamedElement, val type: String?, val name: String, private val declaration: DeclarationInfo ) { private val location: String? = element.containingFile?.let { " [${it.name}]" }.orEmpty() val projectStructureItemText: String get() = "$name${declaration.suffix}" val shortSignatureText = "<b>$name</b>${declaration.suffix.escaped}" val signatureText: String = "${declaration.prefix}$shortSignatureText" val quickDocumentationText: String get() = if (declaration.isAmbiguous && type != null) { "<i>$type:</i> " } else { "" } + "$signatureText${valueText.escaped}$location" private val valueText: String get() = if (declaration.value.isEmpty()) { "" } else { " ${declaration.value}" } } val RsNamedElement.presentationInfo: PresentationInfo? get() { val elementName = name ?: return null val declInfo = when (this) { is RsFunction -> Pair("function", createDeclarationInfo(this, identifier, false, listOf(whereClause, retType, valueParameterList))) is RsStructItem -> Pair("struct", createDeclarationInfo(this, identifier, false, if (blockFields != null) listOf(whereClause) else listOf(whereClause, tupleFields))) is RsFieldDecl -> Pair("field", createDeclarationInfo(this, identifier, false, listOf(typeReference))) is RsEnumItem -> Pair("enum", createDeclarationInfo(this, identifier, false, listOf(whereClause))) is RsEnumVariant -> Pair("enum variant", createDeclarationInfo(this, identifier, false, listOf(tupleFields))) is RsTraitItem -> Pair("trait", createDeclarationInfo(this, identifier, false, listOf(whereClause))) is RsTypeAlias -> Pair("type alias", createDeclarationInfo(this, identifier, false, listOf(typeReference, typeParamBounds, whereClause), eq)) is RsConstant -> Pair("constant", createDeclarationInfo(this, identifier, false, listOf(expr, typeReference), eq)) is RsSelfParameter -> Pair("parameter", createDeclarationInfo(this, self, false, listOf(typeReference))) is RsTypeParameter -> Pair("type parameter", createDeclarationInfo(this, identifier, true)) is RsLifetimeParameter -> Pair("lifetime", createDeclarationInfo(this, quoteIdentifier, true)) is RsModItem -> Pair("module", createDeclarationInfo(this, identifier, false)) is RsMacroDefinition -> Pair("macro", createDeclarationInfo(this, nameIdentifier, false)) is RsLabelDecl -> { val p = parent when (p) { is RsLoopExpr -> Pair("label", createDeclarationInfo(p, p.labelDecl?.quoteIdentifier, false, listOf(p.loop))) is RsForExpr -> Pair("label", createDeclarationInfo(p, p.labelDecl?.quoteIdentifier, false, listOf(p.expr, p.`in`, p.`for`))) is RsWhileExpr -> Pair("label", createDeclarationInfo(p, p.labelDecl?.quoteIdentifier, false, listOf(p.condition, p.`while`))) else -> Pair("label", createDeclarationInfo(this, quoteIdentifier, true)) } } is RsPatBinding -> { val patOwner = topLevelPattern.parent when (patOwner) { is RsLetDecl -> Pair("variable", createDeclarationInfo(patOwner, identifier, false, listOf(patOwner.typeReference))) is RsValueParameter -> Pair("value parameter", createDeclarationInfo(patOwner, identifier, true, listOf(patOwner.typeReference))) is RsMatchArm -> Pair("match arm binding", createDeclarationInfo(patOwner, identifier, true, listOf(patOwner.patList.lastOrNull()))) is RsCondition -> Pair("condition binding", createDeclarationInfo(patOwner, identifier, true, listOf(patOwner.lastChild))) else -> Pair("binding", createDeclarationInfo(this, identifier, true)) } } is RsFile -> { val mName = modName if (isCrateRoot) return PresentationInfo(this, "crate", "crate", DeclarationInfo()) else if (mName != null) return PresentationInfo(this, "mod", name.substringBeforeLast(".rs"), DeclarationInfo("mod ")) else Pair("file", DeclarationInfo()) } else -> Pair(javaClass.simpleName, createDeclarationInfo(this, (this as? RsNameIdentifierOwner)?.nameIdentifier, true)) } return declInfo.second?.let { PresentationInfo(this, declInfo.first, elementName, it) } } data class DeclarationInfo( val prefix: String = "", val suffix: String = "", val value: String = "", val isAmbiguous: Boolean = false ) private fun createDeclarationInfo( decl: RsElement, name: PsiElement?, isAmbiguous: Boolean, stopAt: List<PsiElement?> = emptyList(), valueSeparator: PsiElement? = null ): DeclarationInfo? { // Break an element declaration into elements. For example: // // pub const Foo: u32 = 100; // ^^^^^^^^^ signature prefix // ^^^ name // ^^^^^ signature suffix // ^^^^^ value // ^ end if (name == null) return null // Remove leading spaces, comments and attributes val signatureStart = generateSequence(decl.firstChild) { it.nextSibling } .dropWhile { it is PsiWhiteSpace || it is PsiComment || it is RsOuterAttr } .firstOrNull() ?.startOffsetInParent ?: return null val nameStart = name.offsetIn(decl) // pick (in order) elements we should stop at // if they all fail, drop down to the end of the name element val end = stopAt .filterNotNull().firstOrNull() ?.let { it.startOffsetInParent + it.textLength } ?: nameStart + name.textLength val valueStart = valueSeparator?.offsetIn(decl) ?: end val nameEnd = nameStart + name.textLength check(signatureStart <= nameStart && nameEnd <= valueStart && valueStart <= end && end <= decl.textLength) { "Can't generate signature for `${decl.text}`" } val prefix = decl.text.substring(signatureStart, nameStart).escaped val value = decl.text.substring(valueStart, end) val suffix = decl.text.substring(nameEnd, end - value.length) .replace("""\s+""".toRegex(), " ") .replace("( ", "(") .replace(" )", ")") .replace(" ,", ",") .trimEnd() return DeclarationInfo(prefix, suffix, value, isAmbiguous) } private fun PsiElement.offsetIn(owner: PsiElement): Int = ancestors.takeWhile { it != owner }.sumBy { it.startOffsetInParent }
mit
eadf80d2e9a79580b3583992303f2a3c
45.5
173
0.654461
4.77585
false
false
false
false
facebook/litho
codelabs/save-state-rotation/app/src/main/java/com/facebook/litho/codelab/MainActivity.kt
1
2735
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.litho.codelab import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.facebook.litho.ComponentContext import com.facebook.litho.ComponentTree import com.facebook.litho.LithoView import com.facebook.litho.TreeState class MainActivity : AppCompatActivity() { var mComponentTree: ComponentTree? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val treeStateViewModel = ViewModelProvider(this).get(TreeStateViewModel::class.java) val componentContext = ComponentContext(this) /** * When creating the ComponentTree, pass it the TreeState that you saved before the app * configuration changed. This will restore the state value. */ mComponentTree = ComponentTree.create(componentContext, RootComponent.create(componentContext).build()) .treeState(treeStateViewModel.getTreeState()) .build() val lithoView = LithoView(componentContext) lithoView.setComponentTree(mComponentTree) setContentView(lithoView) } override fun onDestroy() { super.onDestroy() val treeStateViewModel = ViewModelProvider(this).get(TreeStateViewModel::class.java) /** * Before destroying the activity, save the TreeState so we can restore the state value after * the configuration change. */ treeStateViewModel.updateTreeState(mComponentTree) } class TreeStateViewModel : ViewModel() { val treeStateData: MutableLiveData<TreeState> = MutableLiveData<TreeState>() fun getTreeState(): TreeState? { return treeStateData.getValue() } fun updateTreeState(componentTree: ComponentTree?) { if (componentTree != null) { /** * The current state values are wrapped in a TreeState that lives on the ComponentTree. call * acquireTreeState to obtain a copy. */ treeStateData.setValue(componentTree.acquireTreeState()) } } } }
apache-2.0
e62e7f0c7683a1aba91aa3ab12683607
31.951807
100
0.734918
4.875223
false
false
false
false
toastkidjp/Jitte
todo/src/main/java/jp/toastkid/todo/view/board/BoardItemViewFactory.kt
1
2047
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.todo.view.board import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import jp.toastkid.lib.view.DraggableTouchListener import jp.toastkid.todo.R import jp.toastkid.todo.databinding.ItemTaskShortBinding import jp.toastkid.todo.model.TodoTask /** * @author toastkidjp */ class BoardItemViewFactory( private val layoutInflater: LayoutInflater, private val showPopup: (View, TodoTask) -> Unit ) { operator fun invoke(parent: ViewGroup?, task: TodoTask, menuColor: Int): View { val itemBinding = DataBindingUtil.inflate<ItemTaskShortBinding>( layoutInflater, R.layout.item_task_short, parent, false ) itemBinding.color.setBackgroundColor(task.color) itemBinding.mainText.text = task.description itemBinding.menu.setColorFilter(menuColor) itemBinding.menu.setOnClickListener { showPopup(itemBinding.menu, task) } val draggableTouchListener = makeListener(task) itemBinding.root.also { it.x = task.x it.y = task.y } itemBinding.root.setOnTouchListener(draggableTouchListener) return itemBinding.root } private fun makeListener(task: TodoTask): DraggableTouchListener { val draggableTouchListener = DraggableTouchListener() draggableTouchListener.setCallback(object : DraggableTouchListener.OnNewPosition { override fun onNewPosition(x: Float, y: Float) { task.x = x task.y = y } }) return draggableTouchListener } }
epl-1.0
154b043f85e5d2175deef40b5d9e9aed
30.507692
90
0.68002
4.771562
false
false
false
false
inorichi/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/browse/migration/search/SearchController.kt
1
5883
package eu.kanade.tachiyomi.ui.browse.migration.search import android.app.Dialog import android.os.Bundle import androidx.core.view.isVisible import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.RouterTransaction import com.google.android.material.dialog.MaterialAlertDialogBuilder import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.source.CatalogueSource import eu.kanade.tachiyomi.ui.base.controller.DialogController import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction import eu.kanade.tachiyomi.ui.browse.migration.MigrationFlags import eu.kanade.tachiyomi.ui.browse.source.globalsearch.GlobalSearchController import eu.kanade.tachiyomi.ui.browse.source.globalsearch.GlobalSearchPresenter import eu.kanade.tachiyomi.ui.manga.MangaController import uy.kohesive.injekt.injectLazy class SearchController( private var manga: Manga? = null ) : GlobalSearchController(manga?.title) { private var newManga: Manga? = null override fun createPresenter(): GlobalSearchPresenter { return SearchPresenter( initialQuery, manga!! ) } override fun onSaveInstanceState(outState: Bundle) { outState.putSerializable(::manga.name, manga) outState.putSerializable(::newManga.name, newManga) super.onSaveInstanceState(outState) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) manga = savedInstanceState.getSerializable(::manga.name) as? Manga newManga = savedInstanceState.getSerializable(::newManga.name) as? Manga } fun migrateManga(manga: Manga? = null, newManga: Manga?) { manga ?: return newManga ?: return (presenter as? SearchPresenter)?.migrateManga(manga, newManga, true) } fun copyManga(manga: Manga? = null, newManga: Manga?) { manga ?: return newManga ?: return (presenter as? SearchPresenter)?.migrateManga(manga, newManga, false) } override fun onMangaClick(manga: Manga) { newManga = manga val dialog = MigrationDialog(this.manga, newManga, this) dialog.targetController = this dialog.showDialog(router) } override fun onMangaLongClick(manga: Manga) { // Call parent's default click listener super.onMangaClick(manga) } fun renderIsReplacingManga(isReplacingManga: Boolean, newManga: Manga?) { binding.progress.isVisible = isReplacingManga if (!isReplacingManga) { router.popController(this) if (newManga != null) { val newMangaController = RouterTransaction.with(MangaController(newManga)) if (router.backstack.last().controller is MangaController) { // Replace old MangaController router.replaceTopController(newMangaController) } else { // Push MangaController on top of MigrationController router.pushController(newMangaController) } } } } class MigrationDialog(private val manga: Manga? = null, private val newManga: Manga? = null, private val callingController: Controller? = null) : DialogController() { private val preferences: PreferencesHelper by injectLazy() @Suppress("DEPRECATION") override fun onCreateDialog(savedViewState: Bundle?): Dialog { val prefValue = preferences.migrateFlags().get() val enabledFlagsPositions = MigrationFlags.getEnabledFlagsPositions(prefValue) val items = MigrationFlags.titles .map { resources?.getString(it) } .toTypedArray() val selected = items .mapIndexed { i, _ -> enabledFlagsPositions.contains(i) } .toBooleanArray() return MaterialAlertDialogBuilder(activity!!) .setTitle(R.string.migration_dialog_what_to_include) .setMultiChoiceItems(items, selected) { _, which, checked -> selected[which] = checked } .setPositiveButton(R.string.migrate) { _, _ -> // Save current settings for the next time val selectedIndices = mutableListOf<Int>() selected.forEachIndexed { i, b -> if (b) selectedIndices.add(i) } val newValue = MigrationFlags.getFlagsFromPositions(selectedIndices.toTypedArray()) preferences.migrateFlags().set(newValue) if (callingController != null) { if (callingController.javaClass == SourceSearchController::class.java) { router.popController(callingController) } } (targetController as? SearchController)?.migrateManga(manga, newManga) } .setNegativeButton(R.string.copy) { _, _, -> if (callingController != null) { if (callingController.javaClass == SourceSearchController::class.java) { router.popController(callingController) } } (targetController as? SearchController)?.copyManga(manga, newManga) } .setNeutralButton(android.R.string.cancel, null) .create() } } override fun onTitleClick(source: CatalogueSource) { presenter.preferences.lastUsedSource().set(source.id) router.pushController(SourceSearchController(manga, source, presenter.query).withFadeTransaction()) } }
apache-2.0
42f69099c1533fef50ea9b05deaa169d
40.429577
170
0.64066
5.215426
false
false
false
false
google/horologist
compose-tools/src/main/java/com/google/android/horologist/compose/tools/WearPreviewDevices.kt
1
15306
/* * 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.google.android.horologist.compose.tools import androidx.compose.ui.tooling.preview.Devices import androidx.compose.ui.tooling.preview.Preview @Preview( device = Devices.WEAR_OS_LARGE_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Devices - Large Round" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Devices - Small Round" ) @Preview( device = Devices.WEAR_OS_SQUARE, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Devices - Square" ) public annotation class WearPreviewDevices @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Devices - Small Round" ) public annotation class WearSmallRoundDevicePreview @Preview( device = Devices.WEAR_OS_LARGE_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Devices - Large Round" ) public annotation class WearLargeRoundDevicePreview @Preview( device = Devices.WEAR_OS_SQUARE, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Devices - Square" ) public annotation class WearSquareDevicePreview @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "en" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "ar" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "as" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "b+es+419" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "bg" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "bn" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "ca" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "cs" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "da" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "de" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "el" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "en-rGB" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "en-rIE" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "es" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "es-rUS" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "et" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "eu" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "fa" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "fi" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "fr" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "fr-rCA" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "gl" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "gu" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "hi" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "hr" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "hu" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "hy" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "in" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "is" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "it" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "iw" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "ja" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "ka" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "kk" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "km" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "kn" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "ko" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "ky" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "lt" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "lv" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "mk" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "ml" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "mn" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "mr" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "ms" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "my" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "nb" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "ne" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "nl" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "or" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "pa" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "pl" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "pt-rBR" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "pt-rPT" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "ro" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "ru" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "si" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "sk" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "sl" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "sq" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "sr" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "sv" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "ta" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "te" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "th" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "tr" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "uk" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "ur" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "uz" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "vi" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "zh-rCN" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "zh-rHK" ) @Preview( device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true, backgroundColor = 0xff000000, showBackground = true, group = "Locales", locale = "zh-rTW" ) public annotation class WearLocalePreview
apache-2.0
4fd834632a574648db78003290d0bef6
22.332317
75
0.648047
3.589587
false
false
false
false
inorichi/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/recent/history/HistoryController.kt
1
8271
package eu.kanade.tachiyomi.ui.recent.history import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import androidx.appcompat.widget.SearchView import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.dialog.MaterialAlertDialogBuilder import dev.chrisbanes.insetter.applyInsetter import eu.davidea.flexibleadapter.FlexibleAdapter import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.backup.BackupRestoreService import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.History import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.databinding.HistoryControllerBinding import eu.kanade.tachiyomi.ui.base.controller.DialogController import eu.kanade.tachiyomi.ui.base.controller.NucleusController import eu.kanade.tachiyomi.ui.base.controller.RootController import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction import eu.kanade.tachiyomi.ui.browse.source.browse.ProgressItem import eu.kanade.tachiyomi.ui.main.MainActivity import eu.kanade.tachiyomi.ui.manga.MangaController import eu.kanade.tachiyomi.ui.reader.ReaderActivity import eu.kanade.tachiyomi.util.system.logcat import eu.kanade.tachiyomi.util.system.toast import eu.kanade.tachiyomi.util.view.onAnimationsFinished import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import logcat.LogPriority import reactivecircus.flowbinding.appcompat.queryTextChanges import uy.kohesive.injekt.injectLazy /** * Fragment that shows recently read manga. */ class HistoryController : NucleusController<HistoryControllerBinding, HistoryPresenter>(), RootController, FlexibleAdapter.OnUpdateListener, FlexibleAdapter.EndlessScrollListener, HistoryAdapter.OnRemoveClickListener, HistoryAdapter.OnResumeClickListener, HistoryAdapter.OnItemClickListener, RemoveHistoryDialog.Listener { private val db: DatabaseHelper by injectLazy() /** * Adapter containing the recent manga. */ var adapter: HistoryAdapter? = null private set /** * Endless loading item. */ private var progressItem: ProgressItem? = null /** * Search query. */ private var query = "" override fun getTitle(): String? { return resources?.getString(R.string.label_recent_manga) } override fun createPresenter(): HistoryPresenter { return HistoryPresenter() } override fun createBinding(inflater: LayoutInflater) = HistoryControllerBinding.inflate(inflater) override fun onViewCreated(view: View) { super.onViewCreated(view) binding.recycler.applyInsetter { type(navigationBars = true) { padding() } } // Initialize adapter binding.recycler.layoutManager = LinearLayoutManager(view.context) adapter = HistoryAdapter(this@HistoryController) binding.recycler.setHasFixedSize(true) binding.recycler.adapter = adapter adapter?.fastScroller = binding.fastScroller } override fun onDestroyView(view: View) { adapter = null super.onDestroyView(view) } /** * Populate adapter with chapters * * @param mangaHistory list of manga history */ fun onNextManga(mangaHistory: List<HistoryItem>, cleanBatch: Boolean = false) { if (adapter?.itemCount ?: 0 == 0) { resetProgressItem() } if (cleanBatch) { adapter?.updateDataSet(mangaHistory) } else { adapter?.onLoadMoreComplete(mangaHistory) } binding.recycler.onAnimationsFinished { (activity as? MainActivity)?.ready = true } } /** * Safely error if next page load fails */ fun onAddPageError(error: Throwable) { adapter?.onLoadMoreComplete(null) adapter?.endlessTargetCount = 1 logcat(LogPriority.ERROR, error) } override fun onUpdateEmptyView(size: Int) { if (size > 0) { binding.emptyView.hide() } else { binding.emptyView.show(R.string.information_no_recent_manga) } } /** * Sets a new progress item and reenables the scroll listener. */ private fun resetProgressItem() { progressItem = ProgressItem() adapter?.endlessTargetCount = 0 adapter?.setEndlessScrollListener(this, progressItem!!) } override fun onLoadMore(lastPosition: Int, currentPage: Int) { val view = view ?: return if (BackupRestoreService.isRunning(view.context.applicationContext)) { onAddPageError(Throwable()) return } val adapter = adapter ?: return presenter.requestNext(adapter.itemCount, query) } override fun noMoreLoad(newItemsSize: Int) {} override fun onResumeClick(position: Int) { val activity = activity ?: return val (manga, chapter, _) = (adapter?.getItem(position) as? HistoryItem)?.mch ?: return val nextChapter = presenter.getNextChapter(chapter, manga) if (nextChapter != null) { val intent = ReaderActivity.newIntent(activity, manga, nextChapter) startActivity(intent) } else { activity.toast(R.string.no_next_chapter) } } override fun onRemoveClick(position: Int) { val (manga, _, history) = (adapter?.getItem(position) as? HistoryItem)?.mch ?: return RemoveHistoryDialog(this, manga, history).showDialog(router) } override fun onItemClick(position: Int) { val manga = (adapter?.getItem(position) as? HistoryItem)?.mch?.manga ?: return router.pushController(MangaController(manga).withFadeTransaction()) } override fun removeHistory(manga: Manga, history: History, all: Boolean) { if (all) { // Reset last read of chapter to 0L presenter.removeAllFromHistory(manga.id!!) } else { // Remove all chapters belonging to manga from library presenter.removeFromHistory(history) } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.history, menu) val searchItem = menu.findItem(R.id.action_search) val searchView = searchItem.actionView as SearchView searchView.maxWidth = Int.MAX_VALUE if (query.isNotEmpty()) { searchItem.expandActionView() searchView.setQuery(query, true) searchView.clearFocus() } searchView.queryTextChanges() .filter { router.backstack.lastOrNull()?.controller == this } .onEach { query = it.toString() presenter.updateList(query) } .launchIn(viewScope) // Fixes problem with the overflow icon showing up in lieu of search searchItem.fixExpand( onExpand = { invalidateMenuOnExpand() } ) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_clear_history -> { val ctrl = ClearHistoryDialogController() ctrl.targetController = this@HistoryController ctrl.showDialog(router) } } return super.onOptionsItemSelected(item) } class ClearHistoryDialogController : DialogController() { override fun onCreateDialog(savedViewState: Bundle?): Dialog { return MaterialAlertDialogBuilder(activity!!) .setMessage(R.string.clear_history_confirmation) .setPositiveButton(android.R.string.ok) { _, _ -> (targetController as? HistoryController)?.clearHistory() } .setNegativeButton(android.R.string.cancel, null) .create() } } private fun clearHistory() { db.deleteHistory().executeAsBlocking() activity?.toast(R.string.clear_history_completed) } }
apache-2.0
e93b1d05a85a0ceb6c34f7bd50983d67
32.897541
101
0.670898
4.831192
false
false
false
false
JavaEden/OrchidCore
plugins/OrchidGroovydoc/src/main/kotlin/com/eden/orchid/groovydoc/helpers/OrchidGroovydocInvokerImpl.kt
1
1606
package com.eden.orchid.groovydoc.helpers import com.caseyjbrooks.clog.Clog import com.copperleaf.groovydoc.json.GroovydocInvoker import com.copperleaf.groovydoc.json.GroovydocInvokerImpl import com.copperleaf.groovydoc.json.models.GroovydocRootdoc import com.eden.orchid.api.OrchidContext import com.eden.orchid.utilities.InputStreamIgnorer import com.eden.orchid.utilities.OrchidUtils import java.io.File import java.nio.file.Path import javax.inject.Inject import javax.inject.Named class OrchidGroovydocInvokerImpl @Inject constructor( @Named("src") val resourcesDir: String, val context: OrchidContext ) : OrchidGroovydocInvoker { var hasRunGroovydoc = false val cacheDir: Path by lazy { OrchidUtils.getCacheDir("groovydoc") } val outputDir: Path by lazy { OrchidUtils.getTempDir("groovydoc", true) } val groovydocRunner: GroovydocInvoker by lazy { GroovydocInvokerImpl(cacheDir) } override fun getRootDoc( sourceDirs: List<String>, extraArgs: List<String> ): GroovydocRootdoc? { if(hasRunGroovydoc) { val cachedRootDoc = groovydocRunner.loadCachedRootDoc(outputDir) if (cachedRootDoc != null) { Clog.i("returning cached groovydoc") return cachedRootDoc } } val sources = sourceDirs.map { File(resourcesDir).toPath().resolve(it) } val rootDoc = groovydocRunner.getRootDoc(sources, outputDir, extraArgs) { inputStream -> InputStreamIgnorer(inputStream) } hasRunGroovydoc = true return rootDoc } }
mit
16a21233e98a67ef3fa8a37f2ce3c7e3
31.795918
96
0.712951
4.376022
false
false
false
false
actions-on-google/actions-on-google-java
src/main/kotlin/com/google/actions/api/impl/DialogflowRequest.kt
1
10953
/* * 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.google.actions.api.impl import com.google.actions.api.APP_DATA_CONTEXT import com.google.actions.api.ActionContext import com.google.actions.api.ActionRequest import com.google.api.services.actions_fulfillment.v2.model.* import com.google.api.services.dialogflow_fulfillment.v2.model.* import com.google.gson.* import com.google.gson.reflect.TypeToken import java.lang.reflect.Type import java.util.* internal class DialogflowRequest internal constructor( override val webhookRequest: WebhookRequest, val aogRequest: AogRequest?) : ActionRequest { override val appRequest: AppRequest? get() = aogRequest?.appRequest // NOTE: Aog request may be null if request did not originate from Aog. override val intent: String get() = webhookRequest.queryResult?.intent?.displayName ?: "INVALID" override val userStorage: MutableMap<String, Any> get() { return when (aogRequest) { null -> HashMap() else -> aogRequest.userStorage } } override var conversationData: MutableMap<String, Any> = HashMap() override val user: User? get() = aogRequest?.user override val device: Device? get() = aogRequest?.device override val surface: Surface? get() = aogRequest?.surface override val availableSurfaces: List<Surface>? get() = aogRequest?.availableSurfaces override val isInSandbox: Boolean get() = aogRequest?.isInSandbox ?: false init { // initialize conversationData val convDataContext = getContext(APP_DATA_CONTEXT) if (convDataContext != null) { val parameters = convDataContext.parameters val serializedData = parameters?.get("data") as String conversationData = Gson().fromJson(serializedData, object : TypeToken<Map<String, Any>>() {}.type) } } override val rawInput: RawInput? get() { return aogRequest?.rawInput } override val rawText: String? get() = aogRequest?.rawText override fun getArgument(name: String): Argument? { return aogRequest?.getArgument(name) } override fun getParameter(name: String): Any? { val parameters = webhookRequest.queryResult?.parameters return parameters?.get(name) } override fun hasCapability(capability: String): Boolean { return aogRequest?.hasCapability(capability) ?: false } override fun isSignInGranted(): Boolean { return aogRequest?.isSignInGranted() ?: false } override fun isUpdateRegistered(): Boolean { return aogRequest?.isUpdateRegistered() ?: false } override fun getPlace(): Location? { return aogRequest?.getPlace() } override fun isPermissionGranted(): Boolean { return aogRequest?.isPermissionGranted() ?: false } override fun getUserConfirmation(): Boolean { return aogRequest?.getUserConfirmation() ?: false } override fun getDateTime(): DateTime? { return aogRequest?.getDateTime() } override fun getMediaStatus(): String? { return aogRequest?.getMediaStatus() } override val repromptCount: Int? get() { return aogRequest?.repromptCount } override val isFinalPrompt: Boolean? get() { return aogRequest?.isFinalPrompt } override fun getSelectedOption(): String? { return aogRequest?.getSelectedOption() } override fun getContexts(): List<ActionContext> { val result: List<ActionContext> val dfContexts = webhookRequest.queryResult?.outputContexts if (dfContexts == null || dfContexts.isEmpty()) { return ArrayList() } result = dfContexts.map { val ctx = ActionContext(it.name, it.lifespanCount) ctx.parameters = it.parameters ctx } return result } override fun getContext(name: String): ActionContext? { val contexts = getContexts() return contexts.find { it.name == getAsNamespaced(name) } } override val sessionId: String get() { return webhookRequest.session } override val locale: Locale get() { return aogRequest?.locale ?: Locale.getDefault() } private fun getAsNamespaced(name: String): String { val namespace = webhookRequest.session + "/contexts/" if (name.startsWith(namespace)) { return name } return namespace + name } companion object { fun create(body: String, headers: Map<*, *>?): DialogflowRequest { val gson = Gson() return create(gson.fromJson(body, JsonObject::class.java), headers) } fun create(json: JsonObject, headers: Map<*, *>?): DialogflowRequest { val gsonBuilder = GsonBuilder() gsonBuilder .registerTypeAdapter(WebhookRequest::class.java, WebhookRequestDeserializer()) .registerTypeAdapter(QueryResult::class.java, QueryResultDeserializer()) .registerTypeAdapter(Context::class.java, ContextDeserializer()) .registerTypeAdapter(OriginalDetectIntentRequest::class.java, OriginalDetectIntentRequestDeserializer()) val gson = gsonBuilder.create() val webhookRequest = gson.fromJson<WebhookRequest>(json, WebhookRequest::class.java) val aogRequest: AogRequest val originalDetectIntentRequest = webhookRequest.originalDetectIntentRequest val payload = originalDetectIntentRequest?.payload if (payload != null) { aogRequest = AogRequest.create(gson.toJson(payload), headers, partOfDialogflowRequest = true) } else { aogRequest = AogRequest.create(JsonObject(), headers, partOfDialogflowRequest = true) } return DialogflowRequest(webhookRequest, aogRequest) } } private class WebhookRequestDeserializer : JsonDeserializer<WebhookRequest> { override fun deserialize( json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): WebhookRequest { val jsonObject = json!!.asJsonObject val webhookRequest = WebhookRequest() webhookRequest.queryResult = context?.deserialize( jsonObject.get("queryResult")?.asJsonObject, QueryResult::class.java) webhookRequest.responseId = jsonObject.get("responseId")?.asString webhookRequest.session = jsonObject.get("session")?.asString webhookRequest.originalDetectIntentRequest = context?.deserialize( jsonObject.get("originalDetectIntentRequest")?.asJsonObject, OriginalDetectIntentRequest::class.java) return webhookRequest } } private class QueryResultDeserializer : JsonDeserializer<QueryResult> { override fun deserialize( json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): QueryResult { val jsonObject = json!!.asJsonObject val queryResult = QueryResult() queryResult.queryText = jsonObject.get("queryText")?.asString queryResult.action = jsonObject.get("action")?.asString queryResult.allRequiredParamsPresent = jsonObject.get("allRequiredParamsPresent")?.asBoolean queryResult.parameters = context?.deserialize( jsonObject.get("parameters"), Map::class.java) queryResult.intent = context?.deserialize(jsonObject.get("intent"), Intent::class.java) queryResult.diagnosticInfo = context?.deserialize( jsonObject.get("diagnosticInfo"), Map::class.java) queryResult.languageCode = jsonObject.get("languageCode")?.asString queryResult.intentDetectionConfidence = jsonObject.get("intentDetectionConfidence")?.asFloat val outputContextArray = jsonObject.get("outputContexts")?.asJsonArray val outputContexts = ArrayList<Context>() if (outputContextArray != null) { for (outputContext in outputContextArray) { outputContexts.add(context?.deserialize(outputContext, Context::class.java)!!) } } queryResult.outputContexts = outputContexts return queryResult } } private class ContextDeserializer : JsonDeserializer<Context> { override fun deserialize( json: JsonElement?, typeOfT: Type?, deserializationContext: JsonDeserializationContext?): Context { val jsonObject = json!!.asJsonObject val context = Context() context.name = jsonObject.get("name")?.asString context.lifespanCount = jsonObject.get("lifespanCount")?.asInt context.parameters = deserializationContext?.deserialize( jsonObject.get("parameters"), Map::class.java) return context } } private class OriginalDetectIntentRequestDeserializer : JsonDeserializer<OriginalDetectIntentRequest> { override fun deserialize( json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): OriginalDetectIntentRequest { val jsonObject = json!!.asJsonObject val originalDetectIntentRequest = OriginalDetectIntentRequest() originalDetectIntentRequest.source = jsonObject.get("source")?.asString originalDetectIntentRequest.payload = context?.deserialize( jsonObject.get("payload"), Map::class.java) return originalDetectIntentRequest } } }
apache-2.0
06c0ae46f808e57d41cea623e618d8e6
36.255102
84
0.621017
5.543016
false
false
false
false
JiangKlijna/blog
src/main/java/com/jiangKlijna/web/bean/Bean.kt
1
3711
package com.jiangKlijna.web.bean import java.lang.System.currentTimeMillis /** * Created by leil7 on 2017/7/13. blog */ data class Article( var id: Int = 0, var title: String? = null, var content: String? = null, var preview: String? = null, var userid: Int? = null, var subjectid: Int? = null, var favoritenumber: Int = 0, var seenumber: Int = 0, var numberofwords: Long = 0, var createtime: Long = currentTimeMillis() ) data class Comment( var id: Int = 0, var content: String? = null, var userid: Int? = null, var articleid: Int? = null, var createtime: Long = currentTimeMillis() ) data class FollowSubject( var id: Int = 0, var fromuser: Int? = null, var tosubject: Int? = null, var createtime: Long = currentTimeMillis() ) data class FollowUser( var id: Int = 0, var fromuser: Int? = null, var touser: Int? = null, var createtime: Long = currentTimeMillis() ) data class Subject( var id: Int = 0, var title: String? = null, var createtime: Long = currentTimeMillis() ) data class User( var id: Int = 0, var username: String? = null, var password: String? = null, var createtime: Long = currentTimeMillis() ) data class Message( var id: Int = 0, var fromuser: Int? = null, var touser: Int? = null, var flag: Int = 0, var isread: Boolean = false, var createtime: Long = currentTimeMillis() ) : java.io.Serializable data class VUser( var id: Int = 0, var username: String? = null, var createtime: Long = currentTimeMillis(), var numberOfArticles: Int? = null, var numberOfConcerns: Int? = null, var numberOfFans: Int? = null, var favoriteNumber: Int? = null, var numberOfWords: Int? = null, var isFollow: Boolean? = null ) data class VArticle( var id: Int = 0, var title: String? = null, var content: String? = null, var preview: String? = null, var userid: Int? = null, var subjectid: Int? = null, var favoritenumber: Int = 0, var seenumber: Int = 0, var numberofwords: Long = 0, var createtime: Long = currentTimeMillis(), var username: String? = null, var numberOfComments: Int? = 0, var subjectname: String? = null ) data class VSubject( var id: Int = 0, var title: String? = null, var createtime: Long = currentTimeMillis(), var numberOfArticles: Int? = null, var numberOfConcerns: Int? = null ) data class VComment( var id: Int = 0, var content: String? = null, var userid: Int? = null, var articleid: Int? = null, var createtime: Long = currentTimeMillis(), var username: String? = null ) data class VFollowUser( var id: Int = 0, var fromuser: Int? = null, var touser: Int? = null, var createtime: Long = currentTimeMillis(), var fromusername: String? = null, var tousername: String? = null ) data class VMessage( var id: Int = 0, var fromuser: Int? = null, var touser: Int? = null, var fromusername: String? = null, var tousername: String? = null, var flag: Int = 0, var isread: Boolean = false, var createtime: Long = currentTimeMillis() ) : java.io.Serializable fun VArticle.toArticle(): Article = Article( id, title, content, preview, userid, subjectid, favoritenumber, seenumber, numberofwords, createtime )
gpl-2.0
0eb6e50c4134d4d5821398f43d345614
27.121212
108
0.579628
3.771341
false
false
false
false
rumboalla/apkupdater
app/src/main/java/com/apkupdater/repository/apkpure/ApkPureUpdater.kt
1
3646
package com.apkupdater.repository.apkpure import android.os.Build import com.apkupdater.R import com.apkupdater.model.apkpure.VerInfo import com.apkupdater.model.ui.AppInstalled import com.apkupdater.model.ui.AppUpdate import com.apkupdater.util.app.AppPrefs import com.apkupdater.util.ifNotEmpty import com.apkupdater.util.ioScope import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import org.jsoup.Jsoup import org.jsoup.nodes.Document import org.jsoup.nodes.Element import org.koin.core.KoinComponent class ApkPureUpdater(private val prefs: AppPrefs) : KoinComponent { private val baseUrl = "https://apkpure.com" private val searchQuery = "/search?q=" private val versionsUrl = "/versions" private val source = R.drawable.apkpure_logo private val excludeArch get() = prefs.settings.excludeArch private val excludeMinApi get() = prefs.settings.excludeMinApi private val arch get() = Build.CPU_ABI private val api get() = Build.VERSION.SDK_INT private fun getApkPackageLink(name: String): String { val doc = Jsoup.connect("$baseUrl$searchQuery$name").get() doc.select("dl > dt > a[href*=$name]")?.let { return it.attr("href") } return "" } private fun getAbsoluteVersionsLink(packageLink: String): String { return baseUrl + packageLink + versionsUrl } private fun getVariantsPage(element: Element): Document { return Jsoup.connect(baseUrl + element.select("div.ver > ul.ver-wrap > li > a").attr("href")).get() } private fun hasVariants(element: Element): Boolean { return element.select("div.ver > ul.ver-wrap > li > a").attr("title").contains("build variant") } private fun resolveVersionsPage(packageLink: String): Pair<Boolean, Element> { val element = Jsoup.connect(getAbsoluteVersionsLink(packageLink)).ignoreHttpErrors(true).get() return Pair(!element.getElementsByTag("title").text().contains("404"), element) } private fun crawlVersionsPage(element: Element, verInfos: MutableList<VerInfo>, app: AppInstalled) { if (hasVariants(element)) { getVariantsPage(element).select("div.ver-info").forEach { variant -> verInfos.add(VerInfo(variant, app.packageName)) } } else { val verInfo = VerInfo(element.select("div.ver > ul.ver-wrap > li > div.ver-info").first(), app.packageName) verInfos.add(verInfo) } } private fun crawlUpdates(verInfos: MutableList<VerInfo>, app: AppInstalled) { getApkPackageLink(app.packageName).ifNotEmpty { packageLink -> val (gotVersionsPage, element) = resolveVersionsPage(packageLink) if (gotVersionsPage) { crawlVersionsPage(element, verInfos, app) } } } fun updateAsync(apps: Sequence<AppInstalled>) = ioScope.async { val updates = mutableListOf<AppUpdate>() val verInfos = mutableListOf<VerInfo>() val jobs = mutableListOf<Job>() val mutex = Mutex() apps.forEach { app -> launch { crawlUpdates(verInfos, app) }.let { mutex.withLock { jobs.add(it) } } } jobs.forEach { it.join() } verInfos.filter { !excludeArch || it.architectures.contains(arch) }.filter { !excludeMinApi || it.minApiLevel <= api }.forEach { verInfo -> apps.find { app -> app.packageName == verInfo.packageName }?.let { app -> updates.add(AppUpdate.from(app, verInfo)) } } Result.success(updates) } private fun AppUpdate.Companion.from(app: AppInstalled, verInfo: VerInfo) = AppUpdate( app.name, app.packageName, verInfo.versionName, verInfo.versionCode, app.version, app.versionCode, "$baseUrl${verInfo.downloadLink}", source ) }
gpl-3.0
b9400f17bc7f79a4bed9cde155f628da
31.553571
110
0.729841
3.423474
false
false
false
false
NordicSemiconductor/Android-nRF-Toolbox
profile_bps/src/main/java/no/nordicsemi/android/bps/data/BPSData.kt
1
2078
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.bps.data import no.nordicsemi.android.ble.common.profile.bp.BloodPressureTypes import java.util.* data class BPSData( val batteryLevel: Int? = null, val cuffPressure: Float = 0f, val unit: Int = 0, val pulseRate: Float? = null, val userID: Int? = null, val status: BloodPressureTypes.BPMStatus? = null, val calendar: Calendar? = null, val systolic: Float = 0f, val diastolic: Float = 0f, val meanArterialPressure: Float = 0f, )
bsd-3-clause
6f670c65ab7b2a1c31d448be07d97998
42.291667
89
0.753609
4.320166
false
false
false
false
Fitbit/MvRx
todomvrx/src/main/java/com/airbnb/mvrx/todomvrx/data/source/db/TasksDao.kt
1
1335
package com.airbnb.mvrx.todomvrx.data.source.db import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.airbnb.mvrx.todomvrx.data.Task import com.airbnb.mvrx.todomvrx.data.Tasks import io.reactivex.Single /** * Data Access Object for the tasks table. */ @Dao interface TasksDao { /** * Select all tasks from the tasks table. * * @return all tasks. */ @Query("SELECT * FROM Tasks") fun getTasks(): Single<Tasks> /** * Insert a task in the database. If the task already exists, replace it. * * @param task the task to be inserted. */ @Insert(onConflict = OnConflictStrategy.REPLACE) fun saveTask(task: Task) /** * Update the complete status of a task. * @param id id of the task * @param complete status to be updated */ @Query("UPDATE tasks SET complete = :complete WHERE id = :id") fun setComplete(id: String, complete: Boolean) /** * Delete a task by id. */ @Query("DELETE FROM Tasks WHERE id = :id") fun deleteTask(id: String) /** * Delete all complete tasks from the table. * * @return the number of tasks deleted. */ @Query("DELETE FROM Tasks WHERE complete = 1") fun clearCompletedTasks(): Int }
apache-2.0
1a3ff52d97c682de5c7e8560ad66d007
23.722222
77
0.648689
3.949704
false
false
false
false
gantsign/restrulz-jvm
com.gantsign.restrulz.validation/src/main/kotlin/com/gantsign/restrulz/validation/ByteValidator.kt
1
3898
/*- * #%L * Restrulz * %% * Copyright (C) 2017 GantSign Ltd. * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.gantsign.restrulz.validation /** * Base class for validating byte values. * * @constructor creates an instance of the byte validator with the specified constraints. * @param minimumValue the minimum permitted value. * @param maximumValue the maximum permitted value. * @throws IllegalArgumentException if minimumValue > maximumValue. */ @Suppress("unused") abstract class ByteValidator protected constructor(private val minimumValue: Byte, private val maximumValue: Byte) { init { if (minimumValue > maximumValue) { throw IllegalArgumentException("Parameter 'minimumValue' ($minimumValue) must be less than or equal to parameter 'maximumValue' ($maximumValue)") } } /** * Checks that the specified parameter value is valid. * * @param parameterName the name of the parameter being validated. * @param value the value to validate. * @return the value if valid. * @throws InvalidArgumentException if the value is invalid. */ fun requireValidValue(parameterName: String, value: Byte): Byte { if (value < minimumValue) { throw InvalidArgumentException(parameterName, "$value is less than the minimum permitted value of $minimumValue") } if (value > maximumValue) { throw InvalidArgumentException(parameterName, "$value is greater than the maximum permitted value of $maximumValue") } return value } /** * Checks that the specified parameter value is valid or null. * * @param parameterName the name of the parameter being validated. * @param value the value to validate. * @return the value if valid or null. * @throws InvalidArgumentException if the value is non-null and invalid. */ fun requireValidValueOrNull(parameterName: String, value: Byte?): Byte? { if (value === null) { return value } return requireValidValue(parameterName, value) } /** * Checks that the specified parameter value is valid. * * @param value the value to validate. * @param validationHandler the handler for validation failures. * @return `true` if the value is valid. */ fun validateValue(value: Byte, validationHandler: ValidationHandler): Boolean { if (value < minimumValue) { validationHandler.handleValidationFailure("$value is less than the minimum permitted value of $minimumValue") return false } if (value > maximumValue) { validationHandler.handleValidationFailure("$value is greater than the maximum permitted value of $maximumValue") return false } return true } /** * Checks that the specified parameter value is valid or null. * * @param value the value to validate. * @param validationHandler the handler for validation failures. * @return `true` if the value is valid or null. */ fun validateValueOrNull(value: Byte?, validationHandler: ValidationHandler): Boolean { if (value === null) { return true } return validateValue(value, validationHandler) } }
apache-2.0
63de15dce9d52e13d3aa6325ef03eaba
35.429907
157
0.66393
4.878598
false
false
false
false
msebire/intellij-community
plugins/devkit/devkit-tests-api/src/org/jetbrains/idea/devkit/inspections/UnregisteredNamedColorInspectionTestBase.kt
1
1296
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.devkit.inspections import org.jetbrains.idea.devkit.util.PsiUtil abstract class UnregisteredNamedColorInspectionTestBase : PluginModuleTestCase() { override fun setUp() { super.setUp() myFixture.enableInspections(UnregisteredNamedColorInspection()) PsiUtil.markAsIdeaProject(myFixture.project, true) //language=JAVA myFixture.addClass(""" package com.intellij.ui; public class JBColor { public static void namedColor(String s, int i) {} } """.trimIndent()) //language=JAVA myFixture.addClass(""" package org.jetbrains.idea.devkit.completion; public class UiDefaultsHardcodedKeys { public static final Set<String> UI_DEFAULTS_KEYS = Sets.newHashSet(); public static final Set<String> NAMED_COLORS = Sets.newHashSet( "RegisteredKey" ); public static final Set<String> ALL_KEYS = Sets.union(UI_DEFAULTS_KEYS, NAMED_COLORS); } """.trimIndent()) } override fun tearDown() { try { PsiUtil.markAsIdeaProject(myFixture.project, false) } finally { super.tearDown() } } }
apache-2.0
937c94c8d30157638f736c0349358ca7
28.454545
140
0.683642
4.39322
false
false
false
false
icanit/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsSyncFragment.kt
1
1829
package eu.kanade.tachiyomi.ui.setting import android.content.Intent import android.os.Bundle import android.support.v7.preference.PreferenceCategory import android.view.View import eu.kanade.tachiyomi.widget.preference.LoginPreference import eu.kanade.tachiyomi.widget.preference.MangaSyncLoginDialog class SettingsSyncFragment : SettingsNestedFragment() { companion object { const val SYNC_CHANGE_REQUEST = 121 fun newInstance(resourcePreference: Int, resourceTitle: Int): SettingsNestedFragment { val fragment = SettingsSyncFragment() fragment.setArgs(resourcePreference, resourceTitle) return fragment } } val syncCategory by lazy { findPreference("pref_category_manga_sync_accounts") as PreferenceCategory } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val themedContext = preferenceManager.context for (sync in settingsActivity.syncManager.services) { val pref = LoginPreference(themedContext).apply { key = preferences.keys.syncUsername(sync.id) title = sync.name setOnPreferenceClickListener { val fragment = MangaSyncLoginDialog.newInstance(sync) fragment.setTargetFragment(this@SettingsSyncFragment, SYNC_CHANGE_REQUEST) fragment.show(fragmentManagerCompat, null) true } } syncCategory.addPreference(pref) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == SYNC_CHANGE_REQUEST) { val pref = findPreference(preferences.keys.syncUsername(resultCode)) as? LoginPreference pref?.notifyChanged() } } }
apache-2.0
67ad4f2c7bd9c5712c6f359ba089215c
34.862745
106
0.670858
5.210826
false
false
false
false
simonlebras/Radio-France
app/src/main/kotlin/fr/simonlebras/radiofrance/models/Radio.kt
1
999
package fr.simonlebras.radiofrance.models /** * Class representing a radio. * * @property id The identifier of the radio. * @property name The name of the radio. * @property description The description of the radio. * @property stream The URL of the audio stream. * @property website The URL of the website. * @property twitter The URL of the Twitter account. * @property facebook The URL of the Facebook account. * @property smallLogo The URL of the logo in small size. * @property mediumLogo The URL of the logo in medium size. * @property largeLogo The URL of the logo in large size. * @constructor Creates a radio. */ data class Radio( var id: String = "", var name: String = "", var description: String = "", var stream: String = "", var website: String = "", var twitter: String = "", var facebook: String = "", var smallLogo: String = "", var mediumLogo: String = "", var largeLogo: String = "" )
mit
0eee8b099e47a2b89d65282a40ab87b0
33.448276
59
0.648649
4.179916
false
false
false
false
cemrich/zapp
app/src/main/java/de/christinecoenen/code/zapp/utils/system/NetworkConnectionHelper.kt
1
2121
package de.christinecoenen.code.zapp.utils.system import android.content.Context import android.net.ConnectivityManager import android.net.Network import android.net.NetworkCapabilities import android.net.NetworkRequest import android.os.Handler import android.os.Looper import androidx.core.net.ConnectivityManagerCompat /** * Detects changes in network status (metered or unmetered). * Call startListenForNetworkChanges to get callbacks whenever isConnectedToUnmeteredNetwork * changes. * Listeners will be called on main thread. */ class NetworkConnectionHelper(context: Context) { var isConnectedToUnmeteredNetwork: Boolean = true private set private var wasConnectedToUnmeteredNetwork = false private val mainThreadHandler = Handler(Looper.getMainLooper()) private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager private var networkChangedCallback: (() -> Unit)? = null private val networkCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { onNetworkChanged() } override fun onLost(network: Network) { onNetworkChanged() } override fun onUnavailable() { onNetworkChanged() } override fun onCapabilitiesChanged( network: Network, networkCapabilities: NetworkCapabilities ) { onNetworkChanged() } } fun startListenForNetworkChanges(networkChangedCallback: () -> Unit) { this.networkChangedCallback = networkChangedCallback connectivityManager.registerNetworkCallback( NetworkRequest.Builder().build(), networkCallback ) } fun endListenForNetworkChanges() { networkChangedCallback = null connectivityManager.unregisterNetworkCallback(networkCallback) } private fun onNetworkChanged() { this.isConnectedToUnmeteredNetwork = !ConnectivityManagerCompat.isActiveNetworkMetered(connectivityManager) if (isConnectedToUnmeteredNetwork != wasConnectedToUnmeteredNetwork) { wasConnectedToUnmeteredNetwork = this.isConnectedToUnmeteredNetwork mainThreadHandler.post { networkChangedCallback?.invoke() } } } }
mit
6b3650cabb38098e28148a1e1946b147
26.545455
92
0.795851
4.391304
false
false
false
false
JetBrains/anko
anko/library/generated/sdk15/src/main/java/Layouts.kt
2
54733
@file:JvmName("Sdk15LayoutsKt") package org.jetbrains.anko import android.content.Context import android.util.AttributeSet import android.view.ViewGroup import android.appwidget.AppWidgetHostView import android.view.View import android.widget.FrameLayout import android.widget.AbsoluteLayout import android.widget.Gallery import android.widget.GridLayout import android.widget.GridView import android.widget.AbsListView import android.widget.HorizontalScrollView import android.widget.ImageSwitcher import android.widget.LinearLayout import android.widget.RadioGroup import android.widget.RelativeLayout import android.widget.ScrollView import android.widget.TableLayout import android.widget.TableRow import android.widget.TextSwitcher import android.widget.ViewAnimator import android.widget.ViewSwitcher open class _AppWidgetHostView(ctx: Context): AppWidgetHostView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _AbsoluteLayout(ctx: Context): AbsoluteLayout(ctx) { inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, x: Int, y: Int, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, x: Int, y: Int ): T { val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: AbsoluteLayout.LayoutParams.() -> Unit ): T { val layoutParams = AbsoluteLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = AbsoluteLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _FrameLayout(ctx: Context): FrameLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _Gallery(ctx: Context): Gallery(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = Gallery.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = Gallery.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: Gallery.LayoutParams.() -> Unit ): T { val layoutParams = Gallery.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = Gallery.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _GridLayout(ctx: Context): GridLayout(ctx) { inline fun <T: View> T.lparams( rowSpec: GridLayout.Spec?, columnSpec: GridLayout.Spec?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( rowSpec: GridLayout.Spec?, columnSpec: GridLayout.Spec? ): T { val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = GridLayout.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.LayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.LayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(params!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.MarginLayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(params!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( params: ViewGroup.MarginLayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(params!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( that: GridLayout.LayoutParams?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(that!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( that: GridLayout.LayoutParams? ): T { val layoutParams = GridLayout.LayoutParams(that!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( context: Context?, attrs: AttributeSet?, init: GridLayout.LayoutParams.() -> Unit ): T { val layoutParams = GridLayout.LayoutParams(context!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( context: Context?, attrs: AttributeSet? ): T { val layoutParams = GridLayout.LayoutParams(context!!, attrs!!) [email protected] = layoutParams return this } } open class _GridView(ctx: Context): GridView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = AbsListView.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = AbsListView.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, viewType: Int, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(width, height, viewType) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, viewType: Int ): T { val layoutParams = AbsListView.LayoutParams(width, height, viewType) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: AbsListView.LayoutParams.() -> Unit ): T { val layoutParams = AbsListView.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = AbsListView.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _HorizontalScrollView(ctx: Context): HorizontalScrollView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ImageSwitcher(ctx: Context): ImageSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _LinearLayout(ctx: Context): LinearLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = LinearLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(width, height, weight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, weight: Float ): T { val layoutParams = LinearLayout.LayoutParams(width, height, weight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: LinearLayout.LayoutParams.() -> Unit ): T { val layoutParams = LinearLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = LinearLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _RadioGroup(ctx: Context): RadioGroup(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = RadioGroup.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = RadioGroup.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = RadioGroup.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: RadioGroup.LayoutParams.() -> Unit ): T { val layoutParams = RadioGroup.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = RadioGroup.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _RelativeLayout(ctx: Context): RelativeLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = RelativeLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: RelativeLayout.LayoutParams.() -> Unit ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = RelativeLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ScrollView(ctx: Context): ScrollView(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TableLayout(ctx: Context): TableLayout(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = TableLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = TableLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = TableLayout.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = TableLayout.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = TableLayout.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: TableLayout.LayoutParams.() -> Unit ): T { val layoutParams = TableLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = TableLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TableRow(ctx: Context): TableRow(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = TableRow.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = TableRow.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(width, height, initWeight) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, initWeight: Float ): T { val layoutParams = TableRow.LayoutParams(width, height, initWeight) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams() layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( ): T { val layoutParams = TableRow.LayoutParams() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( column: Int, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(column) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( column: Int ): T { val layoutParams = TableRow.LayoutParams(column) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(p!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( p: ViewGroup.LayoutParams? ): T { val layoutParams = TableRow.LayoutParams(p!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: TableRow.LayoutParams.() -> Unit ): T { val layoutParams = TableRow.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = TableRow.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _TextSwitcher(ctx: Context): TextSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ViewAnimator(ctx: Context): ViewAnimator(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } } open class _ViewSwitcher(ctx: Context): ViewSwitcher(ctx) { inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( c: Context?, attrs: AttributeSet? ): T { val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT ): T { val layoutParams = FrameLayout.LayoutParams(width, height) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT, gravity: Int ): T { val layoutParams = FrameLayout.LayoutParams(width, height, gravity) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.LayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams?, init: FrameLayout.LayoutParams.() -> Unit ): T { val layoutParams = FrameLayout.LayoutParams(source!!) layoutParams.init() [email protected] = layoutParams return this } inline fun <T: View> T.lparams( source: ViewGroup.MarginLayoutParams? ): T { val layoutParams = FrameLayout.LayoutParams(source!!) [email protected] = layoutParams return this } }
apache-2.0
36d42c1f6c4447009049e65073e91752
31.007602
78
0.611679
4.847919
false
false
false
false
perseacado/feedback-ui
feedback-ui-slack/src/main/java/com/github/perseacado/feedbackui/slack/client/SlackClientImpl.kt
1
2738
package com.github.perseacado.feedbackui.slack.client import org.apache.http.HttpEntity import org.apache.http.client.methods.HttpPost import org.apache.http.entity.ContentType import org.apache.http.entity.mime.MultipartEntityBuilder import org.apache.http.impl.client.HttpClients import java.io.ByteArrayOutputStream import java.io.IOException import java.nio.charset.Charset import java.util.regex.Pattern /** * @author Marco Eigletsberger, 24.06.16. */ internal class SlackClientImpl(val token: String) : SlackClient { private val API_BASE_URI = "https://slack.com" private val API_FILE_UPLOAD = API_BASE_URI + "/api/files.upload" private val API_POST_MESSAGE = API_BASE_URI + "/api/chat.postMessage" private val CHARSET = Charset.forName("UTF-8") private val PARAM_TOKEN = "token" private val PARAM_USERNAME = "username" private val PARAM_CHANNEL = "channel" private val PARAM_CHANNELS = "channels" private val PARAM_FILENAME = "filename" private val PARAM_FILE = "file" private val PARAM_ATTACHMENTS = "attachments" private val httpclient = HttpClients.createMinimal() override fun postMessage(username: String, text: String, channel: String, url: String) { val entity = MultipartEntityBuilder .create() .setCharset(CHARSET) .addTextBody(PARAM_TOKEN, token) .addTextBody(PARAM_USERNAME, username) .addTextBody(PARAM_CHANNEL, channel) .addTextBody(PARAM_ATTACHMENTS, text, ContentType.APPLICATION_JSON) .build() execute(API_POST_MESSAGE, entity) { it } } override fun uploadFile(filename: String, channel: String, file: ByteArray): String { val entity = MultipartEntityBuilder .create() .setCharset(CHARSET) .addBinaryBody(PARAM_FILE, file, ContentType.DEFAULT_BINARY, filename) .addTextBody(PARAM_TOKEN, token) .addTextBody(PARAM_CHANNELS, channel) .addTextBody(PARAM_FILENAME, filename) .build() return execute(API_FILE_UPLOAD, entity) { val matcher = Pattern.compile("\"permalink\":\"([^\"]*)\"").matcher(it) matcher.find() matcher.group(1).replace("\\\\".toRegex(), "") } } @Throws(IOException::class) private fun <T> execute(uri: String, httpEntity: HttpEntity, transformer: (String) -> T): T { val httpPost = HttpPost(uri) httpPost.entity = httpEntity httpclient.execute(httpPost).use { response -> val outputStream = ByteArrayOutputStream() response.entity.writeTo(outputStream) return transformer(outputStream.toString()) } } }
mit
6cc944aac4bb08fbf897c4574ca7a9e5
37.577465
97
0.662893
4.231839
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/AdvancementsEncoder.kt
1
1788
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.vanilla.packet.codec.play import org.lanternpowered.server.network.buffer.ByteBuffer import org.lanternpowered.server.network.packet.PacketEncoder import org.lanternpowered.server.network.packet.CodecContext import org.lanternpowered.server.network.vanilla.advancement.NetworkAdvancement import org.lanternpowered.server.network.vanilla.packet.type.play.AdvancementsPacket object AdvancementsEncoder : PacketEncoder<AdvancementsPacket> { override fun encode(ctx: CodecContext, packet: AdvancementsPacket): ByteBuffer { val buf = ctx.byteBufAlloc().buffer() buf.writeBoolean(packet.reset) val added = packet.added buf.writeVarInt(added.size) for (advancement in added) NetworkAdvancement.write(ctx, buf, advancement) val removed = packet.removed buf.writeVarInt(removed.size) for (data in removed) buf.writeString(data) val progress = packet.progress buf.writeVarInt(progress.size) for ((key, value) in progress) { buf.writeString(key) buf.writeVarInt(value.size) for (entry1 in value.object2LongEntrySet()) { buf.writeString(entry1.key) val time = entry1.longValue buf.writeBoolean(time != -1L) if (time != -1L) buf.writeLong(time) } } return buf } }
mit
7f953712ba87f6ab5267007991391273
37.042553
84
0.670582
4.329298
false
true
false
false
jonninja/node.kt
src/main/kotlin/node/express/middleware/auth/BasicAuth.kt
1
1921
package node.express.middleware.auth import node.express.Handler import node.express.Request import node.express.Response import node.util.splitToMap import node.crypto.decode import node.express.RouteHandler /** * Middleware to parse (and optionally validate) basic authentication credentials. Credentials are * saved to the request attributes as 'username' and 'password'. */ public fun basicAuth(realm: String, validator: (String?, String?)->Boolean): RouteHandler.()->Unit { return { var username: String? = null; var password: String? = null; try { var authHeaderValue = req.header("authorization") if (authHeaderValue != null) { var auth = authHeaderValue.splitToMap(" ", "type", "data") val authString = auth["data"]!!.decode("base64") auth = authString.splitToMap(":", "username", "password") username = auth["username"] password = auth["password"] } } catch (t: Throwable) { } if (validator(username, password)) { if (username != null) { req.attributes["user"] = username } next() } else { res.header("WWW-Authenticate", "Basic realm=\"" + realm + "\"") res send 401 } } } /** * Parses token authorization and calls your validator to ensure that the requestor has permissions * to access the resource. */ public fun tokenAuth(realm: String, validator: (String?,Request)->Boolean): RouteHandler.()->Unit { return { var token: String? = null var authHeaderValue = req.header("authorization") if (authHeaderValue != null) { val auth = authHeaderValue.splitToMap("=", "type", "token") if (auth["type"] == "token") { token = auth["token"]!!.replace("^\"|\"$".toRegex(), "") } } if (validator(token, req)) { next() } else { res.header("WWW-Authenticate", "Basic realm=\"$realm\"") res send 401 } } }
mit
20665d87d0726e9fc6c4932fdc84d3d3
29.03125
100
0.628319
4.11349
false
false
false
false
debop/debop4k
debop4k-core/src/main/kotlin/debop4k/core/retry/backoff/Backoff.kt
1
1926
/* * Copyright (c) 2016. Sunghyouk Bae <[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 debop4k.core.retry.backoff import debop4k.core.retry.RetryContext /** * Backoff * @author debop [email protected] */ interface Backoff { fun delayMillis(context: RetryContext): Long fun withUniformJitter(): Backoff = UniformRandomBackoff(this) fun withUniformJitter(range: Long): Backoff = UniformRandomBackoff(this, range = range) fun withProportionalJitter(): Backoff = ProportionalRandomBackoff(this) fun withProportionalJitter(multiplier: Double): Backoff = ProportionalRandomBackoff(this, multiplier = multiplier) fun withMinDelay(): Backoff = BoundedMinBackoff(this) fun withMinDelay(minDelayMillis: Long): Backoff = BoundedMinBackoff(this, minDelayMillis) fun withMaxDelay(): Backoff = BoundedMaxBackoff(this) fun withMaxDelay(maxDelayMillis: Long): Backoff = BoundedMaxBackoff(this, maxDelayMillis) fun withFirstRetryNoDelay(): Backoff = FirstRetryNoDelayBackoff(this) fun withExponentialDelay(initialDelayMillis: Long, multiplier: Double): Backoff = ExponentialDelayBackoff(initialDelayMillis, multiplier) fun withFixedInterval(): Backoff = FixedIntervalBackoff() fun withFixedInterval(fixedInterval: Long): Backoff = FixedIntervalBackoff(fixedInterval) }
apache-2.0
f24fc627dfcfcbc0ee0f72ba2970961a
28.646154
81
0.744548
4.177874
false
false
false
false
SimonVT/cathode
cathode-sync/src/main/java/net/simonvt/cathode/actions/comments/SyncCommentReplies.kt
1
4801
/* * Copyright (C) 2015 Simon Vig Therkildsen * * 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 net.simonvt.cathode.actions.comments import android.content.ContentProviderOperation import android.content.Context import net.simonvt.cathode.actions.PagedAction import net.simonvt.cathode.actions.PagedResponse import net.simonvt.cathode.actions.comments.SyncCommentReplies.Params import net.simonvt.cathode.api.entity.Comment import net.simonvt.cathode.api.enumeration.Extended import net.simonvt.cathode.api.service.CommentsService import net.simonvt.cathode.common.database.getInt import net.simonvt.cathode.common.database.getLong import net.simonvt.cathode.provider.DatabaseContract.CommentColumns import net.simonvt.cathode.provider.DatabaseSchematic.Tables import net.simonvt.cathode.provider.ProviderSchematic.Comments import net.simonvt.cathode.provider.batch import net.simonvt.cathode.provider.helper.CommentsHelper import net.simonvt.cathode.provider.helper.UserDatabaseHelper import net.simonvt.cathode.provider.query import retrofit2.Call import javax.inject.Inject class SyncCommentReplies @Inject constructor( private val context: Context, private val usersHelper: UserDatabaseHelper, private val commentsService: CommentsService ) : PagedAction<Params, Comment>() { override fun key(params: Params): String = "SyncCommentReplies&traktId=${params.traktId}" override fun getCall(params: Params, page: Int): Call<List<Comment>> { return commentsService.replies( params.traktId, page, LIMIT, Extended.FULL_IMAGES ) } override suspend fun handleResponse( params: Params, pagedResponse: PagedResponse<Params, Comment> ) { val ops = arrayListOf<ContentProviderOperation>() val itemType: Int val itemId: Long val parentComment = context.contentResolver.query( Comments.withId(params.traktId), arrayOf(CommentColumns.ITEM_TYPE, CommentColumns.ITEM_ID) ) parentComment.moveToFirst() itemType = parentComment.getInt(CommentColumns.ITEM_TYPE) itemId = parentComment.getLong(CommentColumns.ITEM_ID) val existingComments = mutableListOf<Long>() val deleteComments = mutableListOf<Long>() val localComments = context.contentResolver.query( Comments.withParent(params.traktId), arrayOf(Tables.COMMENTS + "." + CommentColumns.ID) ) while (localComments.moveToNext()) { val id = localComments.getLong(CommentColumns.ID) existingComments.add(id) deleteComments.add(id) } localComments.close() var page: PagedResponse<Params, Comment>? = pagedResponse do { for (comment in page!!.response) { val profile = comment.user val idResult = usersHelper.updateOrCreate(profile) val userId = idResult.id val values = CommentsHelper.getValues(comment) values.put(CommentColumns.USER_ID, userId) values.put(CommentColumns.ITEM_TYPE, itemType) values.put(CommentColumns.ITEM_ID, itemId) val commentId = comment.id var exists = existingComments.contains(commentId) if (!exists) { // May have been created by user likes val c = context.contentResolver.query( Comments.withId(commentId), arrayOf(CommentColumns.ID) ) exists = c.moveToFirst() c.close() } if (exists) { deleteComments.remove(commentId) val op = ContentProviderOperation.newUpdate(Comments.withId(commentId)).withValues(values) ops.add(op.build()) } else { // The same comment can exist multiple times in the result from Trakt, so any comments we // insert are added to the list of existing comments. existingComments.add(commentId) val op = ContentProviderOperation.newInsert(Comments.COMMENTS).withValues(values) ops.add(op.build()) } } page = page.nextPage() } while (page != null) for (id in deleteComments) { val op = ContentProviderOperation.newDelete(Comments.withId(id)) ops.add(op.build()) } context.contentResolver.batch(ops) } data class Params(val traktId: Long) companion object { private const val LIMIT = 100 } }
apache-2.0
882bef81c7c993efdb177507d5e1ec76
33.049645
100
0.716517
4.392498
false
false
false
false
hsyed/blast.browser
blast.browser/src/main/kotlin/blast/browser/components/Model.kt
1
6413
package blast.browser.components import blast.browser.utils.getValue import blast.browser.utils.setValue import blast.browser.utils.xmlSafeUUID import com.intellij.icons.AllIcons import com.intellij.ide.projectView.PresentationData import com.intellij.ide.util.treeView.NodeDescriptor import com.intellij.openapi.actionSystem.DataKey import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.ui.treeStructure.SimpleNode import com.intellij.ui.treeStructure.SimpleTreeStructure import com.intellij.ui.treeStructure.Tree import com.intellij.util.containers.ContainerUtil import org.jdom.Element import javax.swing.tree.TreePath import kotlin.comparisons.compareValuesBy object BlastBrowser { object DataKeys { val TARGET_TREE: DataKey<Tree> = DataKey.create<Tree>("targetBookmarkTree") } } interface IDNode : Comparable<BookmarkNode> { val displayName: String val id: String get override fun compareTo(other: BookmarkNode): Int = compareValuesBy(this, other, { it.id }) fun type(): String fun treePath(): TreePath } abstract class BookmarkNode(internal var element: Element, val p: NodeDescriptor<*>? = null) : SimpleNode(), IDNode { override val id: String get() { return element.name } override var displayName: String by element init { element.setAttribute("type", this.type()) } override fun getParentDescriptor(): NodeDescriptor<*>? = p override fun getName(): String = displayName override fun update(presentation: PresentationData) { super.update(presentation) presentation.presentableText = displayName } override fun treePath(): TreePath { val path = mutableListOf(this) var currentNode: BookmarkNode = this while(currentNode.parent != null) { val parent = currentNode.parent as BookmarkNode path.add(parent) currentNode = parent } return TreePath(path.asReversed().toTypedArray()) } } class BookmarkDirectory(element: Element, parentDescriptor: NodeDescriptor<*>? = null) : BookmarkNode(element, parentDescriptor) { constructor(name: String, id: String) : this(Element(id)) { displayName = name element.name = id } override fun type(): String = "directory" override fun isAlwaysLeaf(): Boolean = false override fun getChildren(): Array<out BookmarkNode> = element.children.map { val type: String = it.getAttribute("type").value when (type) { "directory" -> BookmarkDirectory(it, this) "bookmark" -> Bookmark(it, this) else -> throw Exception("$type not recognised") } }.toTypedArray() override fun update(presentation: PresentationData) { super.update(presentation) presentation.setIcon(AllIcons.Nodes.Folder) } internal fun addNodeAt(node: BookmarkNode, pos: Int) { element.addContent(pos, node.element) } internal fun addNode(node: BookmarkNode) { element.addContent(node.element) } internal fun removeNode(node: BookmarkNode) { element.removeChild(node.id) } } class Bookmark(element: Element, parentDescriptor: NodeDescriptor<*>? = null) : BookmarkNode(element, parentDescriptor) { var url: String by element constructor(name: String, url: String) : this(Element(xmlSafeUUID())) { displayName = name this.url = url } override fun update(presentation: PresentationData) { super.update(presentation) presentation.locationString = url presentation.setIcon(AllIcons.General.Web!!) } override fun type() = "bookmark" override fun isAlwaysLeaf(): Boolean = true override fun getChildren(): Array<out SimpleNode> = emptyArray() } interface BookmarkManager { fun addBookmarkListener(listener: BookmarkListener) fun removeBookmarkListener(listener: BookmarkListener) fun addNode(parent: BookmarkDirectory, node: BookmarkNode) fun addNodeAt(parent: BookmarkDirectory, node: BookmarkNode, at: Int) fun removeNode(parent: BookmarkDirectory, node: BookmarkNode) fun updateNode(node: BookmarkNode) } interface BookmarkListener { fun rootsChanged() fun itemUpdated(node: BookmarkNode) fun itemAdded(parent: BookmarkDirectory, node: BookmarkNode) fun itemRemoved(parent: BookmarkDirectory, node: BookmarkNode) fun parentChanged(parent: BookmarkDirectory) } @State(name = "bookmarks", storages = arrayOf(Storage("bookmark.xml"))) class BookmarkManagerImpl : SimpleTreeStructure(), PersistentStateComponent<Element>, BookmarkManager { val root = BookmarkDirectory("root", "root") private val myListeners: MutableList<BookmarkListener> = ContainerUtil.createLockFreeCopyOnWriteList() override fun getState(): Element = root.element.clone() override fun loadState(state: Element) { root.element.addContent(state.cloneContent()) } override fun getRootElement(): Any = root override fun addBookmarkListener(listener: BookmarkListener) { // FIXTURES if (root.element.contentSize == 0) { root.addNode(Bookmark("Google", "http://www.google.com")) val f = BookmarkDirectory("Programming", "programming") f.addNode(Bookmark("Stackoverflow", "http://www.stackoverflow.com")) root.addNode(f) } myListeners.add(listener) listener.rootsChanged() } override fun removeBookmarkListener(listener: BookmarkListener) { myListeners.remove(listener) } override fun addNode(parent: BookmarkDirectory, node: BookmarkNode) { parent.addNode(node) myListeners.forEach { it.parentChanged(parent); it.itemAdded(parent, node) } } override fun addNodeAt(parent: BookmarkDirectory, node: BookmarkNode, at: Int) { parent.addNodeAt(node, at) myListeners.forEach { it.parentChanged(parent); it.itemAdded(parent, node) } } override fun removeNode(parent: BookmarkDirectory, node: BookmarkNode) { parent.removeNode(node) myListeners.forEach { it.parentChanged(parent); it.itemRemoved(parent, node) } } override fun updateNode(node: BookmarkNode) { myListeners.forEach { it.itemUpdated(node) } } }
mit
0548ed270c7d7bdaeb60ebcc2e156ed5
32.757895
130
0.703259
4.525759
false
false
false
false
cfig/Android_boot_image_editor
bbootimg/src/main/kotlin/bootimg/v3/VendorBootHeader.kt
1
5616
// Copyright 2021 [email protected] // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cfig.bootimg.v3 import cc.cfig.io.Struct import org.slf4j.LoggerFactory import java.io.InputStream class VendorBootHeader( var headerVersion: Int = 0, var pageSize: Int = 0, var kernelLoadAddr: Long = 0, var ramdiskLoadAddr: Long = 0, var vndRamdiskTotalSize: Int = 0, var cmdline: String = "", var tagsLoadAddr: Long = 0, var product: String = "", var headerSize: Int = 0, var dtbSize: Int = 0, var dtbLoadAddr: Long = 0, var vrtSize: Int = 0, var vrtEntryNum: Int = 0, var vrtEntrySize: Int = 0, var bootconfigSize: Int = 0 ) { @Throws(IllegalArgumentException::class) constructor(iS: InputStream?) : this() { if (iS == null) { return } log.warn("VendorBootHeader constructor") val info = Struct(FORMAT_STRING).unpack(iS) check(16 == info.size) if (info[0] != magic) { throw IllegalArgumentException("stream doesn't look like Android Vendor Boot Image") } this.headerVersion = (info[1] as UInt).toInt() this.pageSize = (info[2] as UInt).toInt() this.kernelLoadAddr = (info[3] as UInt).toLong() this.ramdiskLoadAddr = (info[4] as UInt).toLong() this.vndRamdiskTotalSize = (info[5] as UInt).toInt() this.cmdline = info[6] as String this.tagsLoadAddr = (info[7] as UInt).toLong() this.product = info[8] as String this.headerSize = (info[9] as UInt).toInt() this.dtbSize = (info[10] as UInt).toInt() this.dtbLoadAddr = (info[11] as ULong).toLong() this.vrtSize = (info[12] as UInt).toInt() this.vrtEntryNum = (info[13] as UInt).toInt() this.vrtEntrySize = (info[14] as UInt).toInt() this.bootconfigSize = (info[15] as UInt).toInt() if (this.headerSize !in arrayOf(VENDOR_BOOT_IMAGE_HEADER_V3_SIZE, VENDOR_BOOT_IMAGE_HEADER_V4_SIZE)) { throw IllegalArgumentException("header size " + this.headerSize + " invalid") } if (this.headerVersion !in 3..4) { throw IllegalArgumentException("header version " + this.headerVersion + " invalid") } } // https://github.com/cfig/Android_boot_image_editor/issues/67 // support vendor_boot headerVersion downgrade from 4 to 3 during re-pack fun feature67(): VendorBootHeader { val newHeaderSize = when (this.headerVersion) { 3 -> VendorBootHeader.VENDOR_BOOT_IMAGE_HEADER_V3_SIZE else -> VendorBootHeader.VENDOR_BOOT_IMAGE_HEADER_V4_SIZE } if (newHeaderSize != headerSize) { log.warn("wrong headerSize, fixed.($headerSize -> $newHeaderSize)") headerSize = newHeaderSize } if (vrtSize != 0 && headerVersion == 3) { log.warn("trim vrt for headerVersion=3") vrtSize = 0 vrtEntryNum = 0 vrtEntrySize = 0 } return this } fun encode(): ByteArray { return Struct(FORMAT_STRING).pack( magic, headerVersion, pageSize, kernelLoadAddr, ramdiskLoadAddr, vndRamdiskTotalSize, cmdline, tagsLoadAddr, product, headerSize, dtbSize, dtbLoadAddr, vrtSize, vrtEntryNum, vrtEntrySize, bootconfigSize ) } companion object { private val log = LoggerFactory.getLogger(VendorBootHeader::class.java) const val magic = "VNDRBOOT" const val VENDOR_BOOT_IMAGE_HEADER_V3_SIZE = 2112 const val VENDOR_BOOT_IMAGE_HEADER_V4_SIZE = 2128 const val FORMAT_STRING = "8s" + //magic "I" + //header version "I" + //page size "I" + //kernel physical load addr "I" + //ramdisk physical load addr "I" + //vendor ramdisk size "2048s" + //cmdline "I" + //kernel tag load addr "16s" + //product name "I" + //header size "I" + //dtb size "Q" + //dtb physical load addr "I" + //[v4] vendor ramdisk table size "I" + //[v4] vendor ramdisk table entry num "I" + //[v4] vendor ramdisk table entry size "I" //[v4] bootconfig size init { check(Struct(FORMAT_STRING).calcSize() == VENDOR_BOOT_IMAGE_HEADER_V4_SIZE) } } override fun toString(): String { return "VendorBootHeader(headerVersion=$headerVersion, pageSize=$pageSize, kernelLoadAddr=$kernelLoadAddr, ramdiskLoadAddr=$ramdiskLoadAddr, vndRamdiskSize=$vndRamdiskTotalSize, cmdline='$cmdline', tagsLoadAddr=$tagsLoadAddr, product='$product', headerSize=$headerSize, dtbSize=$dtbSize, dtbLoadAddr=$dtbLoadAddr, vrtSize=$vrtSize, vrtEntryNum=$vrtEntryNum, vrtEntrySize=$vrtEntrySize, bootconfigSize=$bootconfigSize)" } }
apache-2.0
5c5d8d845afaf5a8422a6ccb7cd52c5d
37.465753
426
0.599537
3.927273
false
false
false
false
if710/if710.github.io
2019-10-02/SystemServices/app/src/main/java/br/ufpe/cin/android/systemservices/phonesms/SmsReceivedActivity.kt
1
844
package br.ufpe.cin.android.systemservices.phonesms import android.app.Activity import android.os.Bundle import android.widget.Toast import br.ufpe.cin.android.systemservices.R import kotlinx.android.synthetic.main.activity_sms_received.* class SmsReceivedActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sms_received) val i = intent val msgFromExtra = i.getStringExtra("msgFrom") val msgBodyExtra = i.getStringExtra("msgBody") if (msgFromExtra != null && msgBodyExtra != null) { msgFrom.text = msgFromExtra msgBody.text = msgBodyExtra } else { Toast.makeText(this, "Intent vazio", Toast.LENGTH_SHORT).show() finish() } } }
mit
c90b66034b6c1a9c4d3c647d70731c9b
31.461538
75
0.67654
4.097087
false
false
false
false
danrien/projectBlueWater
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/stored/library/sync/GivenAnExternalStoragePreference/WhenLookingUpTheSyncDrive.kt
2
1812
package com.lasthopesoftware.bluewater.client.stored.library.sync.GivenAnExternalStoragePreference import com.lasthopesoftware.bluewater.client.browsing.library.access.FakeLibraryProvider import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId import com.lasthopesoftware.bluewater.client.stored.library.sync.SyncDirectoryLookup import com.lasthopesoftware.bluewater.shared.promises.extensions.FuturePromise import com.lasthopesoftware.storage.directories.FakePrivateDirectoryLookup import com.lasthopesoftware.storage.directories.FakePublicDirectoryLookup import org.assertj.core.api.AssertionsForClassTypes.assertThat import org.junit.BeforeClass import org.junit.Test import java.io.File class WhenLookingUpTheSyncDrive { @Test fun thenTheDriveIsTheOneWithTheMostSpace() { assertThat(file!!.path).isEqualTo("/storage/0/my-big-sd-card/14") } companion object { private var file: File? = null @BeforeClass @JvmStatic fun before() { val publicDrives = FakePublicDirectoryLookup() publicDrives.addDirectory("", 1) publicDrives.addDirectory("", 2) publicDrives.addDirectory("", 3) publicDrives.addDirectory("/storage/0/my-big-sd-card", 4) val fakePrivateDirectoryLookup = FakePrivateDirectoryLookup() fakePrivateDirectoryLookup.addDirectory("fake-private-path", 3) fakePrivateDirectoryLookup.addDirectory("/fake-private-path", 5) val syncDirectoryLookup = SyncDirectoryLookup( FakeLibraryProvider( Library().setSyncedFileLocation(Library.SyncedFileLocation.EXTERNAL).setId(14) ), publicDrives, fakePrivateDirectoryLookup, publicDrives ) file = FuturePromise(syncDirectoryLookup.promiseSyncDirectory(LibraryId(14))).get() } } }
lgpl-3.0
de10526943e69ab6c84283095b28cd8c
38.391304
98
0.812362
4.017738
false
false
false
false
phw/PicardBarcodeScanner
app/src/main/java/org/musicbrainz/picard/barcodescanner/activities/ScannerActivity.kt
1
3507
/* * Copyright (C) 2012, 2021 Philipp Wolfer <[email protected]> * Copyright (C) 2021 Akshat Tiwari * * This file is part of MusicBrainz Picard Barcode Scanner. * * MusicBrainz Picard Barcode Scanner 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. * * MusicBrainz Picard Barcode Scanner 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 * MusicBrainz Picard Barcode Scanner. If not, see * <http://www.gnu.org/licenses/>. */ package org.musicbrainz.picard.barcodescanner.activities import android.content.Intent import android.os.Bundle import org.musicbrainz.picard.barcodescanner.databinding.ActivityScannerBinding import org.musicbrainz.picard.barcodescanner.util.Constants import com.journeyapps.barcodescanner.ScanContract import com.journeyapps.barcodescanner.ScanIntentResult import com.journeyapps.barcodescanner.ScanOptions class ScannerActivity : BaseActivity() { private var mAutoStart = false private lateinit var binding: ActivityScannerBinding /** Called when the activity is first created. */ public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityScannerBinding.inflate(layoutInflater) setContentView(binding.root) binding.btnScanBarcode.setOnClickListener { startScanner() } binding.connectionStatusBox.setOnClickListener { startPreferencesActivity() } handleIntents() when { !preferences.connectionConfigured -> { startPreferencesActivity() } mAutoStart -> { startScanner() } } } override fun handleIntents() { super.handleIntents() val extras = intent.extras if (extras != null) { mAutoStart = extras.getBoolean(Constants.INTENT_EXTRA_AUTOSTART_SCANNER, false) } binding.connectionStatusBox.updateStatus(preferences.ipAddress, preferences.port) } private fun startPreferencesActivity() { val configurePicard = Intent( this@ScannerActivity, PreferencesActivity::class.java ) startActivity(configurePicard) } private fun startSearchActivity(barcode: String) { val resultIntent = Intent( this@ScannerActivity, PerformSearchActivity::class.java ) resultIntent.putExtra(Constants.INTENT_EXTRA_BARCODE, barcode) startActivity(resultIntent) } private val barcodeLauncher = registerForActivityResult(ScanContract()) { result: ScanIntentResult -> val barcode = result.contents if (barcode != null) { startSearchActivity(barcode) } } private fun startScanner() { val options = ScanOptions() options.setOrientationLocked(false) options.setDesiredBarcodeFormats( ScanOptions.EAN_13, ScanOptions.EAN_8, ScanOptions.UPC_A, ScanOptions.UPC_E, ) barcodeLauncher.launch(options) } }
gpl-3.0
8e8b1cdc2fd4b7f9742f1333a0330f5f
33.382353
105
0.689763
4.707383
false
false
false
false
dafi/photoshelf
app/src/main/java/com/ternaryop/photoshelf/activity/impl/ImageViewerActivityStarterImpl.kt
1
1822
package com.ternaryop.photoshelf.activity.impl import android.content.Context import android.content.Intent import com.ternaryop.photoshelf.activity.ImageViewerActivityStarter import com.ternaryop.photoshelf.activity.ImageViewerData import com.ternaryop.photoshelf.activity.TagPhotoBrowserData import com.ternaryop.photoshelf.imagepicker.activity.ImagePickerActivity import com.ternaryop.photoshelf.imagepicker.repository.ImageGalleryRepository import com.ternaryop.photoshelf.imageviewer.activity.ImageViewerActivity import com.ternaryop.photoshelf.tagphotobrowser.activity.TagPhotoBrowserActivity import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import javax.inject.Inject import javax.inject.Singleton import kotlin.coroutines.CoroutineContext @Singleton class ImageViewerActivityStarterImpl @Inject constructor( private val imageGalleryRepository: ImageGalleryRepository ) : ImageViewerActivityStarter, CoroutineScope { private var job = Job() override val coroutineContext: CoroutineContext get() = job + Dispatchers.Default override fun startImagePicker(context: Context, url: String) = ImagePickerActivity.startImagePicker(context, url) override fun startImagePickerPrefetch(urls: List<String>) { launch { imageGalleryRepository.prefetch(urls) } } override fun tagPhotoBrowserIntent( context: Context, tagPhotoBrowserData: TagPhotoBrowserData, returnSelectedPost: Boolean ): Intent = TagPhotoBrowserActivity.createIntent(context, tagPhotoBrowserData, returnSelectedPost) override fun startImageViewer( context: Context, data: ImageViewerData ) = ImageViewerActivity.startImageViewer(context, data) }
mit
5730ac4b55f6e2f368780509b12b4e81
38.608696
117
0.809001
5.075209
false
false
false
false
natanieljr/droidmate
project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/modelFeatures/misc/ApiCountTable.kt
1
3281
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2018. Saarland University // // 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/>. // // Current Maintainers: // Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland> // Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland> // // Former Maintainers: // Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de> // // web: www.droidmate.org package org.droidmate.exploration.modelFeatures.misc import org.droidmate.device.logcat.ApiLogcatMessage import org.droidmate.device.logcat.IApiLogcatMessage import org.droidmate.exploration.ExplorationContext import org.droidmate.explorationModel.interaction.Interaction import java.time.Duration import java.util.* class ApiCountTable : CountsPartitionedByTimeTable { constructor(data: ExplorationContext<*,*,*>) : super( data.getExplorationTimeInMs(), listOf( headerTime, headerApisSeen, headerApiEventsSeen ), listOf( data.uniqueApisCountByTime, data.uniqueEventApiPairsCountByTime ) ) companion object { const val headerTime = "Time_seconds" const val headerApisSeen = "Apis_seen" const val headerApiEventsSeen = "Api+Event_pairs_seen" /** the collection of Apis triggered , grouped based on the apis timestamp * Map<time, List<(action,api)>> is for each timestamp the list of the triggered action with the observed api*/ private val ExplorationContext<*,*,*>.apisByTime get() = LinkedList<Pair<Interaction<*>, IApiLogcatMessage>>().apply { // create a list of (widget.id,IApiLogcatMessage) explorationTrace.getActions().forEach { action -> // collect all apiLogs over the whole trace action.deviceLogs.forEach { add(Pair(action, ApiLogcatMessage.from(it))) } } }.groupBy { (_, api) -> Duration.between(explorationStartTime, api.time).toMillis() } // group them by their start time (i.e. how may milli seconds elapsed since exploration start) /** map of seconds elapsed during app exploration until the api was called To the set of api calls (their unique string) **/ private val ExplorationContext<*,*,*>.uniqueApisCountByTime: Map<Long, Iterable<String>> get() = apisByTime.mapValues { it.value.map { (_, api) -> api.uniqueString } } // instead of the whole IApiLogcatMessage only keep the unique string for the Api /** map of seconds elapsed during app exploration until the api was triggered To **/ private val ExplorationContext<*,*,*>.uniqueEventApiPairsCountByTime: Map<Long, Iterable<String>> get() = apisByTime.mapValues { it.value.map { (action, api) -> "${action.actionString()}_${api.uniqueString}" } } } }
gpl-3.0
01946dba06fe30768a74688d5b495eb7
42.184211
184
0.73819
4.011002
false
false
false
false
pgutkowski/KGraphQL
src/main/kotlin/com/github/pgutkowski/kgraphql/schema/dsl/TypeDSL.kt
1
3656
package com.github.pgutkowski.kgraphql.schema.dsl import com.github.pgutkowski.kgraphql.defaultKQLTypeName import com.github.pgutkowski.kgraphql.schema.SchemaException import com.github.pgutkowski.kgraphql.schema.model.FunctionWrapper import com.github.pgutkowski.kgraphql.schema.model.PropertyDef import com.github.pgutkowski.kgraphql.schema.model.TypeDef import com.github.pgutkowski.kgraphql.schema.model.Transformation import kotlin.reflect.KClass import kotlin.reflect.KProperty1 open class TypeDSL<T : Any>( private val supportedUnions: Collection<TypeDef.Union>, val kClass: KClass<T>, block: TypeDSL<T>.() -> Unit ) : ItemDSL() { var name = kClass.defaultKQLTypeName() internal val transformationProperties = mutableSetOf<Transformation<T, *>>() internal val extensionProperties = mutableSetOf<PropertyDef.Function<T, *>>() internal val unionProperties = mutableSetOf<PropertyDef.Union<T>>() internal val describedKotlinProperties = mutableMapOf<KProperty1<T, *>, PropertyDef.Kotlin<T, *>>() fun <R, E> transformation(kProperty: KProperty1<T, R>, function: (R, E) -> R) { transformationProperties.add(Transformation(kProperty, FunctionWrapper.on(function, true))) } fun <R, E, W> transformation(kProperty: KProperty1<T, R>, function: (R, E, W) -> R) { transformationProperties.add(Transformation(kProperty, FunctionWrapper.on(function, true))) } fun <R, E, W, Q> transformation(kProperty: KProperty1<T, R>, function: (R, E, W, Q) -> R) { transformationProperties.add(Transformation(kProperty, FunctionWrapper.on(function, true))) } fun <R, E, W, Q, A> transformation(kProperty: KProperty1<T, R>, function: (R, E, W, Q, A) -> R) { transformationProperties.add(Transformation(kProperty, FunctionWrapper.on(function, true))) } fun <R, E, W, Q, A, S> transformation(kProperty: KProperty1<T, R>, function: (R, E, W, Q, A, S) -> R) { transformationProperties.add(Transformation(kProperty, FunctionWrapper.on(function, true))) } fun <R> property(kProperty: KProperty1<T, R>, block : KotlinPropertyDSL<T, R>.() -> Unit){ val dsl = KotlinPropertyDSL(kProperty, block) describedKotlinProperties[kProperty] = dsl.toKQLProperty() } fun <R> property(name : String, block : PropertyDSL<T, R>.() -> Unit){ val dsl = PropertyDSL(name, block) extensionProperties.add(dsl.toKQLProperty()) } fun <R> KProperty1<T, R>.configure(block : KotlinPropertyDSL<T, R>.() -> Unit){ property(this, block) } fun <R> KProperty1<T, R>.ignore(){ describedKotlinProperties[this] = PropertyDef.Kotlin(kProperty = this, isIgnored = true) } fun unionProperty(name : String, block : UnionPropertyDSL<T>.() -> Unit){ val property = UnionPropertyDSL(name, block) val union = supportedUnions.find { property.returnType.typeID.equals(it.name, true) } ?: throw SchemaException("Union Type: ${property.returnType.typeID} does not exist") unionProperties.add(property.toKQLProperty(union)) } init { block() } internal fun toKQLObject() : TypeDef.Object<T> { return TypeDef.Object( name = name, kClass = kClass, kotlinProperties = describedKotlinProperties.toMap(), extensionProperties = extensionProperties.toList(), unionProperties = unionProperties.toList(), transformations = transformationProperties.associate { it.kProperty to it }, description = description ) } }
mit
8c5a809effbb0a5a9c1da175b86c1405
39.633333
107
0.675055
4.107865
false
false
false
false
SpectraLogic/ds3_autogen
ds3-autogen-go/src/main/kotlin/com/spectralogic/ds3autogen/go/generators/response/HeadObjectResponseGenerator.kt
2
2456
/* * ****************************************************************************** * Copyright 2014-2018 Spectra Logic Corporation. 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. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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.spectralogic.ds3autogen.go.generators.response import com.google.common.collect.ImmutableList import com.spectralogic.ds3autogen.api.models.apispec.Ds3ResponseCode import com.spectralogic.ds3autogen.go.models.response.ResponseCode import com.spectralogic.ds3autogen.go.utils.goIndent class HeadObjectResponseGenerator : BaseResponseGenerator() { override fun toResponsePayloadStruct(expectedResponseCodes: ImmutableList<Ds3ResponseCode>?): String { return "BlobChecksumType ChecksumType\n" + goIndent(1) + "BlobChecksums map[int64]string" } /** * Converts a Ds3ResponseCode into a ResponseCode model which contains the Go * code for parsing the specified response. */ override fun toResponseCode(ds3ResponseCode: Ds3ResponseCode, responseName: String): ResponseCode { if (ds3ResponseCode.code == 200) { val parsingCode = "checksumType, err := getBlobChecksumType(webResponse.Header())\n" + goIndent(2) + "if err != nil {\n" + goIndent(3) + "return nil, err\n" + goIndent(2) + "}\n" + goIndent(2) + "checksumMap, err := getBlobChecksumMap(webResponse.Header())\n" + goIndent(2) + "if err != nil {\n" + goIndent(3) + "return nil, err\n" + goIndent(2) + "}\n" + goIndent(2) + "return &$responseName{BlobChecksumType: checksumType, BlobChecksums: checksumMap, Headers: webResponse.Header()}, nil" return ResponseCode(ds3ResponseCode.code, parsingCode) } return toStandardResponseCode(ds3ResponseCode, responseName) } }
apache-2.0
b37b8adb297dc92959c7da7eb247c52c
49.142857
153
0.630293
4.39356
false
false
false
false
ledao/chatbot
src/main/kotlin/com/davezhao/web/controllers/QaController.kt
1
1458
package com.davezhao.web.controllers import com.davezhao.services.ChatBotService import com.fasterxml.jackson.databind.ObjectMapper import com.iyanuadelekan.kanary.core.KanaryController import com.iyanuadelekan.kanary.helpers.http.request.done import com.iyanuadelekan.kanary.helpers.http.response.send import com.iyanuadelekan.kanary.helpers.http.response.sendJson import com.iyanuadelekan.kanary.helpers.http.response.withStatus import org.eclipse.jetty.server.Request import org.slf4j.LoggerFactory import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse class QaController : KanaryController() { val log = LoggerFactory.getLogger(this::class.java) val chatBotService = ChatBotService() fun getQueryResult(baseRequest: Request, request: HttpServletRequest, response: HttpServletResponse) { log.info("in query") response.characterEncoding = "utf8" val mapper = ObjectMapper() val responseDataNode = mapper.createObjectNode() val question = baseRequest.getParameter("q") if (question == null) { response withStatus 201 send "bad request" baseRequest.done() return } val resp = this.chatBotService.queryRobot(question) with(responseDataNode) { put("q", question) put("answer", resp) } response.sendJson(responseDataNode) baseRequest.done() } }
gpl-3.0
64c0112c8aa7bf1fc33b2be458424ff6
32.930233
106
0.72428
4.365269
false
false
false
false
jereksel/LibreSubstratum
app/src/main/kotlin/com/jereksel/libresubstratum/data/InstalledOverlay.kt
1
1303
/* * 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.data import android.graphics.drawable.Drawable data class InstalledOverlay ( val overlayId: String, //Source theme val sourceThemeId: String, val sourceThemeName: String, val sourceThemeDrawable: Drawable?, //Target app val targetId: String, val targetName: String, val targetDrawable: Drawable?, val type1a: String? = null, val type1b: String? = null, val type1c: String? = null, val type2: String? = null, val type3: String? = null )
mit
6ae0b60b2d989b63575ebb0643b952c2
34.216216
73
0.688411
4.216828
false
false
false
false
jonalmeida/focus-android
app/src/main/java/org/mozilla/focus/exceptions/ExceptionsListFragment.kt
1
10343
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.exceptions import androidx.fragment.app.Fragment import android.content.Context import android.graphics.Color import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.ItemTouchHelper.SimpleCallback import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.CompoundButton import android.widget.TextView import kotlinx.android.synthetic.main.fragment_exceptions_domains.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.launch import org.mozilla.focus.R import org.mozilla.focus.autocomplete.AutocompleteDomainFormatter import org.mozilla.focus.settings.BaseSettingsFragment import org.mozilla.focus.telemetry.TelemetryWrapper import java.util.Collections import org.mozilla.focus.utils.ViewUtils import kotlin.coroutines.CoroutineContext typealias DomainFormatter = (String) -> String /** * Fragment showing settings UI listing all exception domains. */ open class ExceptionsListFragment : Fragment(), CoroutineScope { private var job = Job() override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main /** * ItemTouchHelper for reordering items in the domain list. */ val itemTouchHelper: ItemTouchHelper = ItemTouchHelper( object : SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, 0) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { val from = viewHolder.adapterPosition val to = target.adapterPosition (recyclerView.adapter as DomainListAdapter).move(from, to) return true } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {} override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) { super.onSelectedChanged(viewHolder, actionState) if (viewHolder is DomainViewHolder) { viewHolder.onSelected() } } override fun clearView( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder ) { super.clearView(recyclerView, viewHolder) if (viewHolder is DomainViewHolder) { viewHolder.onCleared() } } }) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } /** * In selection mode the user can select and remove items. In non-selection mode the list can * be reordered by the user. */ open fun isSelectionMode() = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View = inflater.inflate(R.layout.fragment_exceptions_domains, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { exceptionList.layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false) exceptionList.adapter = DomainListAdapter() exceptionList.setHasFixedSize(true) if (!isSelectionMode()) { itemTouchHelper.attachToRecyclerView(exceptionList) } removeAllExceptions.setOnClickListener { val domains = ExceptionDomains.load(context!!) TelemetryWrapper.removeAllExceptionDomains(domains.size) ExceptionDomains.remove(context!!, domains) fragmentManager!!.popBackStack() } } override fun onResume() { super.onResume() job = Job() (activity as BaseSettingsFragment.ActionBarUpdater).apply { updateTitle(R.string.preference_exceptions) updateIcon(R.drawable.ic_back) } (exceptionList.adapter as DomainListAdapter).refresh(activity!!) { if ((exceptionList.adapter as DomainListAdapter).itemCount == 0) { fragmentManager!!.popBackStack() } activity?.invalidateOptionsMenu() } } override fun onStop() { job.cancel() super.onStop() } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { inflater?.inflate(R.menu.menu_exceptions_list, menu) } override fun onPrepareOptionsMenu(menu: Menu?) { val removeItem = menu?.findItem(R.id.remove) removeItem?.let { it.isVisible = isSelectionMode() || exceptionList.adapter!!.itemCount > 0 val isEnabled = !isSelectionMode() || (exceptionList.adapter as DomainListAdapter).selection().isNotEmpty() ViewUtils.setMenuItemEnabled(it, isEnabled) } } override fun onOptionsItemSelected(item: MenuItem?): Boolean = when (item?.itemId) { R.id.remove -> { fragmentManager!! .beginTransaction() .replace(R.id.container, ExceptionsRemoveFragment()) .addToBackStack(null) .commit() true } else -> super.onOptionsItemSelected(item) } /** * Adapter implementation for the list of exception domains. */ inner class DomainListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val domains: MutableList<String> = mutableListOf() private val selectedDomains: MutableList<String> = mutableListOf() fun refresh(context: Context, body: (() -> Unit)? = null) { [email protected](Main) { val updatedDomains = async { ExceptionDomains.load(context) }.await() domains.clear() domains.addAll(updatedDomains) notifyDataSetChanged() body?.invoke() } } override fun getItemViewType(position: Int) = DomainViewHolder.LAYOUT_ID override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = when (viewType) { DomainViewHolder.LAYOUT_ID -> DomainViewHolder( LayoutInflater.from(parent.context).inflate(viewType, parent, false), { AutocompleteDomainFormatter.format(it) }) else -> throw IllegalArgumentException("Unknown view type: $viewType") } override fun getItemCount(): Int = domains.size override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder is DomainViewHolder) { holder.bind( domains[position], isSelectionMode(), selectedDomains, itemTouchHelper, this@ExceptionsListFragment ) } } override fun onViewRecycled(holder: RecyclerView.ViewHolder) { if (holder is DomainViewHolder) { holder.checkBoxView.setOnCheckedChangeListener(null) } } fun selection(): List<String> = selectedDomains fun move(from: Int, to: Int) { Collections.swap(domains, from, to) notifyItemMoved(from, to) launch(IO) { ExceptionDomains.save(activity!!.applicationContext, domains) } } } /** * ViewHolder implementation for a domain item in the list. */ private class DomainViewHolder( itemView: View, val domainFormatter: DomainFormatter? = null ) : RecyclerView.ViewHolder(itemView) { val domainView: TextView = itemView.findViewById(R.id.domainView) val checkBoxView: CheckBox = itemView.findViewById(R.id.checkbox) val handleView: View = itemView.findViewById(R.id.handleView) companion object { val LAYOUT_ID = R.layout.item_custom_domain } fun bind( domain: String, isSelectionMode: Boolean, selectedDomains: MutableList<String>, itemTouchHelper: ItemTouchHelper, fragment: ExceptionsListFragment ) { domainView.text = domainFormatter?.invoke(domain) ?: domain checkBoxView.visibility = if (isSelectionMode) View.VISIBLE else View.GONE checkBoxView.isChecked = selectedDomains.contains(domain) checkBoxView.setOnCheckedChangeListener { _: CompoundButton, isChecked: Boolean -> if (isChecked) { selectedDomains.add(domain) } else { selectedDomains.remove(domain) } fragment.activity?.invalidateOptionsMenu() } handleView.visibility = if (isSelectionMode) View.GONE else View.VISIBLE handleView.setOnTouchListener { _, event -> if (event.actionMasked == MotionEvent.ACTION_DOWN) { itemTouchHelper.startDrag(this) } false } if (isSelectionMode) { itemView.setOnClickListener { checkBoxView.isChecked = !checkBoxView.isChecked } } } fun onSelected() { itemView.setBackgroundColor(Color.DKGRAY) } fun onCleared() { itemView.setBackgroundColor(0) } } }
mpl-2.0
1573b4d22b13f9d1eee8276d7dc7589d
33.824916
107
0.627381
5.452293
false
false
false
false
wiltonlazary/kotlin-native
samples/gitchurn/src/gitChurnMain/kotlin/GitDiff.kt
1
1305
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package sample.gitchurn import kotlinx.cinterop.* import libgit2.* class GitDiff(val repository: GitRepository, val handle: CPointer<git_diff>) { fun deltas(): List<GifDiffDelta> { val size = git_diff_num_deltas(handle).toInt() val results = ArrayList<GifDiffDelta>(size) for (index in 0..size - 1) { val delta = git_diff_get_delta(handle, index.convert()) results.add(GifDiffDelta(this, delta!!)) } return results } fun close() { git_diff_free(handle) } } class GifDiffDelta(val diff: GitDiff, val handle: CPointer<git_diff_delta>) { val status get() = handle.pointed.status val newPath get() = handle.pointed.new_file.path!!.toKString() val oldPath get() = handle.pointed.old_file.path!!.toKString() fun status(): String { return when (status) { GIT_DELTA_ADDED -> "A" GIT_DELTA_DELETED -> "D" GIT_DELTA_MODIFIED -> "M" GIT_DELTA_RENAMED -> "R" GIT_DELTA_COPIED -> "C" else -> throw Exception("Unsupported delta status $status") } } }
apache-2.0
beff84d8cdabb318fefbf025f1c0f4f1
28
101
0.607663
3.686441
false
false
false
false
nemerosa/ontrack
ontrack-model/src/main/java/net/nemerosa/ontrack/model/form/FormExtensions.kt
1
3306
package net.nemerosa.ontrack.model.form import net.nemerosa.ontrack.model.annotations.getPropertyDescription import net.nemerosa.ontrack.model.annotations.getPropertyLabel import kotlin.reflect.KProperty1 fun <T> Form.textField(property: KProperty1<T, String?>, value: String?): Form = with( Text.of(property.name) .label(getPropertyLabel(property)) .help(getPropertyDescription(property)) .optional(property.returnType.isMarkedNullable) .value(value) ) fun <T> Form.passwordField(property: KProperty1<T, String?>): Form = with( Password.of(property.name) .label(getPropertyLabel(property)) .help(getPropertyDescription(property)) .optional(property.returnType.isMarkedNullable) ) fun <T> Form.urlField(property: KProperty1<T, String?>, value: String?): Form = with( Url.of(property.name) .label(getPropertyLabel(property)) .help(getPropertyDescription(property)) .optional(property.returnType.isMarkedNullable) .value(value) ) fun <T> Form.yesNoField(property: KProperty1<T, Boolean?>, value: Boolean?): Form = with( YesNo.of(property.name) .label(getPropertyLabel(property)) .help(getPropertyDescription(property)) .optional(property.returnType.isMarkedNullable) .value(value) ) fun <T> Form.intField(property: KProperty1<T, kotlin.Int?>, value: kotlin.Int?): Form = with( Int.of(property.name) .label(getPropertyLabel(property)) .help(getPropertyDescription(property)) .optional(property.returnType.isMarkedNullable) .value(value) ) fun <T> Form.longField(property: KProperty1<T, Long>, value: Long?): Form = with( Int.of(property.name) .label(getPropertyLabel(property)) .help(getPropertyDescription(property)) .optional(property.returnType.isMarkedNullable) .value(value) ) fun Form.selectionOfString( property: KProperty1<*, String?>, items: List<String>, value: String?, ): Form = with( Selection.of(property.name) .label(getPropertyLabel(property)) .help(getPropertyDescription(property)) .optional(property.returnType.isMarkedNullable) .items(items.map { IdName(it, it) }) .value(value) ) /** * Multiform field */ fun <T> Form.multiform( property: KProperty1<*, List<T>>, items: List<T>?, formCreation: () -> Form, ): Form = with( MultiForm.of(property.name, formCreation()) .label(getPropertyLabel(property)) .help(getPropertyDescription(property)) .value(items ?: emptyList<T>()) ) inline fun <reified E : Enum<E>> Form.enumField( property: KProperty1<*, E?>, value: E?, ): Form = with( Selection.of(property.name) .label(getPropertyLabel(property)) .help(getPropertyDescription(property)) .optional(property.returnType.isMarkedNullable) .items( enumValues<E>().map { e -> IdName(id = e.name, name = e.name) } ) .value(value?.name) )
mit
e444e7454435e2218ad7833d58ed76f2
30.788462
87
0.615245
4.238462
false
false
false
false
goodwinnk/intellij-community
platform/diff-impl/tests/com/intellij/diff/DiffTestCase.kt
2
9480
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff import com.intellij.diff.comparison.ComparisonManagerImpl import com.intellij.diff.comparison.iterables.DiffIterableUtil import com.intellij.diff.util.DiffUtil import com.intellij.diff.util.ThreeSide import com.intellij.openapi.editor.Document import com.intellij.openapi.progress.DumbProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.LocalFilePath import com.intellij.testFramework.UsefulTestCase import com.intellij.util.text.CharSequenceSubSequence import junit.framework.ComparisonFailure import junit.framework.TestCase import org.junit.Assert import java.util.* import java.util.concurrent.atomic.AtomicLong abstract class DiffTestCase : TestCase() { private val DEFAULT_CHAR_COUNT = 12 private val DEFAULT_CHAR_TABLE: Map<Int, Char> = { val map = HashMap<Int, Char>() listOf('\n', '\n', '\t', ' ', ' ', '.', '<', '!').forEachIndexed { i, c -> map.put(i, c) } map }() val RNG: Random = Random() private var gotSeedException = false val INDICATOR: ProgressIndicator = DumbProgressIndicator.INSTANCE val MANAGER: ComparisonManagerImpl = ComparisonManagerImpl() override fun setUp() { super.setUp() DiffIterableUtil.setVerifyEnabled(true) } override fun tearDown() { DiffIterableUtil.setVerifyEnabled(Registry.`is`("diff.verify.iterable")) super.tearDown() } fun getTestName() = UsefulTestCase.getTestName(name, true) // // Misc // fun getLineCount(document: Document): Int { return DiffUtil.getLineCount(document) } fun createFilePath(path: String) = LocalFilePath(path, path.endsWith('/') || path.endsWith('\\')) // // AutoTests // fun doAutoTest(seed: Long, runs: Int, test: (DebugData) -> Unit) { RNG.setSeed(seed) var lastSeed: Long = -1 val debugData = DebugData() for (i in 1..runs) { if (i % 1000 == 0) println(i) try { lastSeed = getCurrentSeed() test(debugData) debugData.reset() } catch (e: Throwable) { println("Seed: " + seed) println("Runs: " + runs) println("I: " + i) println("Current seed: " + lastSeed) debugData.dump() throw e } } } fun generateText(maxLength: Int, charCount: Int, predefinedChars: Map<Int, Char>): String { val length = RNG.nextInt(maxLength + 1) val builder = StringBuilder(length) for (i in 1..length) { val rnd = RNG.nextInt(charCount) val char = predefinedChars[rnd] ?: (rnd + 97).toChar() builder.append(char) } return builder.toString() } fun generateText(maxLength: Int): String { return generateText(maxLength, DEFAULT_CHAR_COUNT, DEFAULT_CHAR_TABLE) } fun getCurrentSeed(): Long { if (gotSeedException) return -1 try { val seedField = RNG.javaClass.getDeclaredField("seed") seedField.isAccessible = true val seedFieldValue = seedField.get(RNG) as AtomicLong return seedFieldValue.get() xor 0x5DEECE66DL } catch (e: Exception) { gotSeedException = true System.err.println("Can't get random seed: " + e.message) return -1 } } class DebugData { private val data: MutableList<Pair<String, Any>> = ArrayList() fun put(key: String, value: Any) { data.add(Pair(key, value)) } fun reset() { data.clear() } fun dump() { data.forEach { println(it.first + ": " + it.second) } } } // // Helpers // open class Trio<out T>(val data1: T, val data2: T, val data3: T) { companion object { fun <V> from(f: (ThreeSide) -> V): Trio<V> = Trio(f(ThreeSide.LEFT), f(ThreeSide.BASE), f(ThreeSide.RIGHT)) } fun <V> map(f: (T) -> V): Trio<V> = Trio(f(data1), f(data2), f(data3)) fun <V> map(f: (T, ThreeSide) -> V): Trio<V> = Trio(f(data1, ThreeSide.LEFT), f(data2, ThreeSide.BASE), f(data3, ThreeSide.RIGHT)) fun forEach(f: (T, ThreeSide) -> Unit): Unit { f(data1, ThreeSide.LEFT) f(data2, ThreeSide.BASE) f(data3, ThreeSide.RIGHT) } operator fun invoke(side: ThreeSide): T = side.select(data1, data2, data3) as T override fun toString(): String { return "($data1, $data2, $data3)" } override fun equals(other: Any?): Boolean { return other is Trio<*> && other.data1 == data1 && other.data2 == data2 && other.data3 == data3 } override fun hashCode(): Int { var h = 0 if (data1 != null) h = h * 31 + data1.hashCode() if (data2 != null) h = h * 31 + data2.hashCode() if (data3 != null) h = h * 31 + data3.hashCode() return h } } companion object { // // Assertions // fun assertTrue(actual: Boolean, message: String = "") { assertTrue(message, actual) } fun assertFalse(actual: Boolean, message: String = "") { assertFalse(message, actual) } fun assertEquals(expected: Any?, actual: Any?, message: String = "") { assertEquals(message, expected, actual) } fun assertEquals(expected: CharSequence?, actual: CharSequence?, message: String = "") { if (!StringUtil.equals(expected, actual)) throw ComparisonFailure(message, expected?.toString(), actual?.toString()) } fun assertEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean, skipLastNewline: Boolean) { if (skipLastNewline && !ignoreSpaces) { assertTrue(StringUtil.equals(chunk1, chunk2) || StringUtil.equals(stripNewline(chunk1), chunk2) || StringUtil.equals(chunk1, stripNewline(chunk2))) } else { assertTrue(isEqualsCharSequences(chunk1, chunk2, ignoreSpaces)) } } fun assertNotEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean, skipLastNewline: Boolean) { if (skipLastNewline && !ignoreSpaces) { assertTrue(!StringUtil.equals(chunk1, chunk2) || !StringUtil.equals(stripNewline(chunk1), chunk2) || !StringUtil.equals(chunk1, stripNewline(chunk2))) } else { assertFalse(isEqualsCharSequences(chunk1, chunk2, ignoreSpaces)) } } fun isEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean): Boolean { if (ignoreSpaces) { return StringUtil.equalsIgnoreWhitespaces(chunk1, chunk2) } else { return StringUtil.equals(chunk1, chunk2) } } fun assertOrderedEquals(expected: Collection<*>, actual: Collection<*>, message: String = "") { UsefulTestCase.assertOrderedEquals(message, actual, expected) } fun assertSetsEquals(expected: BitSet, actual: BitSet, message: String = "") { val sb = StringBuilder(message) sb.append(": \"") for (i in 0..actual.length()) { sb.append(if (actual[i]) '-' else ' ') } sb.append('"') val fullMessage = sb.toString() Assert.assertEquals(fullMessage, expected, actual) } // // Parsing // fun textToReadableFormat(text: CharSequence?): String { if (text == null) return "null" return "\"" + text.toString().replace('\n', '*').replace('\t', '+') + "\"" } fun parseSource(string: CharSequence): String = string.toString().replace('_', '\n') fun parseMatching(matching: String): BitSet { val set = BitSet() matching.filterNot { it == '.' }.forEachIndexed { i, c -> if (c != ' ') set.set(i) } return set } fun parseLineMatching(matching: String, document: Document): BitSet { return parseLineMatching(matching, document.charsSequence) } fun parseLineMatching(matching: String, text: CharSequence): BitSet { assertEquals(matching.length, text.length) val lines1 = matching.split('_', '*') val lines2 = text.split('\n') assertEquals(lines1.size, lines2.size) for (i in 0..lines1.size - 1) { assertEquals(lines1[i].length, lines2[i].length, "line $i") } val set = BitSet() var index = 0 var lineNumber = 0 while (index < matching.length) { var end = matching.indexOfAny(listOf("_", "*"), index) + 1 if (end == 0) end = matching.length val line = matching.subSequence(index, end) if (line.find { it != ' ' && it != '_' } != null) { assert(!line.contains(' ')) set.set(lineNumber) } lineNumber++ index = end } return set } private fun stripNewline(text: CharSequence): CharSequence? { return when (StringUtil.endsWithChar(text, '\n')) { true -> CharSequenceSubSequence(text, 0, text.length - 1) false -> null } } } }
apache-2.0
12c617d57ad5ab40464c4a9eee7546a8
29.003165
134
0.634916
4.054748
false
false
false
false
deadpixelsociety/twodee
src/main/kotlin/com/thedeadpixelsociety/twodee/TimeController.kt
1
3303
package com.thedeadpixelsociety.twodee /** * Controller for global duration keeping. Tracks the current update delta duration and the accumulated total duration. This * controller also accepts tick events that can be triggered at intervals and repeated. * @see TickEvent */ object TimeController { const val INFINITE = -1 private val events = gdxArray<TickEvent>() private val addEventQueue = gdxArray<TickEvent>() private val removeEventQueue = gdxArray<TickEvent>() /** * The current update delta duration, in seconds. */ var deltaTime = 0f get private set /** * The total accumulated duration, in seconds. */ var totalTime = 0f get private set /** * Resets the delta duration, total duration and clears all tick events. */ fun reset() { deltaTime = 0f totalTime = 0f events.clear() } /** * Updates the controller with the current delta duration. * @param deltaTime The current delta duration, in seconds. */ fun update(deltaTime: Float) { addEventQueue.forEach { events.add(it) } removeEventQueue.forEach { events.removeValue(it, true) } addEventQueue.clear() removeEventQueue.clear() runEvents() this.deltaTime = deltaTime totalTime += deltaTime } /** * Registers a tick event. * @param event The tick event. * @see TickEvent */ fun register(event: TickEvent) { addEventQueue.add(event) } /** * Unregisters a tick event. * @param event The tick event. */ fun unregister(event: TickEvent) { removeEventQueue.add(event) } private fun runEvents() { events.toList().forEach { if (it.cancel) { events.removeValue(it, true) } else { if (it.delayExpired() && it.intervalReady()) { it.func() it.lastTime = totalTime it.count++ } if (!it.delayExpired()) it.delayTimer += deltaTime if (it.expired()) events.removeValue(it, true) } } } /** * An event that will be fired at each tick up to [repeat] number of times. At each tick [func] will be * invoked. At least one invocation of [func] will always occur. * @param delay The initial delay before the event happens. * @param interval The interval between ticks. * @param repeat The number of times to repeat the event after the first invocation. * @param func The function to perform at each tick. */ open class TickEvent( val delay: Float = 0f, val interval: Float = 0f, val repeat: Int = 0, val func: Func<Unit> ) { /** * Cancels the event if true. */ var cancel = false internal var delayTimer = 0f internal var lastTime = 0f internal var count = 0 internal fun delayExpired() = delayTimer >= delay internal fun intervalReady() = lastTime == 0f || (totalTime() - lastTime) >= interval internal fun expired() = repeat != INFINITE && delayExpired() && count > repeat } }
mit
2ea9715f66719d7751ed251825e8ab41
27.482759
124
0.58129
4.62605
false
false
false
false
hewking/HUILibrary
app/src/main/java/com/hewking/custom/TideRippleView.kt
1
6373
package com.hewking.custom import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.View import android.view.animation.LinearInterpolator import com.hewking.custom.util.dp2px import java.util.concurrent.CopyOnWriteArrayList /** * 项目名称:FlowChat * 类的描述: * 创建人员:hewking * 创建时间:2018/12/11 0011 * 修改人员:hewking * 修改时间:2018/12/11 0011 * 修改备注: * Version: 1.0.0 */ class TideRippleView(ctx: Context, attrs: AttributeSet) : View(ctx, attrs) { private var radiuls: Int = 0 private val rippleCircles = CopyOnWriteArrayList<RippleCircle>() init { } private val ripplePaint by lazy { Paint().apply { style = Paint.Style.STROKE strokeWidth = dp2px(0.5f).toFloat() color = Color.BLUE isAntiAlias = true } } private val backPaint by lazy { Paint().apply { style= Paint.Style.FILL_AND_STROKE isAntiAlias = true strokeWidth = dp2px(0.5f).toFloat() } } private var sweepProgress = 0 set(value) { if (value >= 360) { field = 0 } else { field = value } } private var fps: Int = 0 private var fpsPaint = Paint().apply { isAntiAlias = true style = Paint.Style.STROKE color = Color.GREEN textSize = dp2px(20f).toFloat() strokeWidth = dp2px(1f).toFloat() } private val renderAnimator by lazy { ValueAnimator.ofInt(0, 60) .apply { interpolator = LinearInterpolator() duration = 1000 repeatMode = ValueAnimator.RESTART repeatCount = ValueAnimator.INFINITE addUpdateListener { postInvalidateOnAnimation() fps++ sweepProgress ++ } addListener(object : AnimatorListenerAdapter() { override fun onAnimationRepeat(animation: Animator?) { super.onAnimationRepeat(animation) fps = 0 } }) } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val wMode = MeasureSpec.getMode(widthMeasureSpec) val wSize = MeasureSpec.getSize(widthMeasureSpec) val hMode = MeasureSpec.getMode(heightMeasureSpec) val hSize = MeasureSpec.getSize(heightMeasureSpec) val size = Math.min(wSize, hSize) if (wMode == MeasureSpec.AT_MOST || hMode == MeasureSpec.AT_MOST) { radiuls = size.div(2) } } var backCanvas : Canvas? = null var backBitmap : Bitmap? = null override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) backBitmap?.recycle() if (w != 0 && h != 0){ backBitmap = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888) backCanvas = Canvas(backBitmap) } } override fun onDraw(canvas: Canvas?) { canvas ?: return canvas.save() // canvas.translate(width.div(2f),height.div(2f)) /* rippleCircles.forEach { }*/ for (i in 0 until rippleCircles.size) { rippleCircles[i].draw(canvas) } canvas.restore() backCanvas?.let { val maxRadius = Math.min(width, height).div(2).toFloat() val radius = maxRadius.div(2) it.save() // backPaint.color = Color.WHITE backPaint.setXfermode(PorterDuffXfermode(PorterDuff.Mode.CLEAR)) it.drawPaint(backPaint) backPaint.setXfermode(null) it.rotate(sweepProgress.toFloat(),width.div(2f),height.div(2f)) backPaint.setShader(SweepGradient(width.div(2).toFloat(),height.div(2).toFloat(),Color.RED,Color.WHITE)) it.drawCircle(width.div(2).toFloat(),height.div(2).toFloat(),radius,backPaint) backPaint.setXfermode(PorterDuffXfermode(PorterDuff.Mode.SRC_OUT)) // backPaint.color = Color.TRANSPARENT it.drawCircle(width.div(2f),height.div(2f),radius.div(3f),backPaint) it.restore() canvas.drawBitmap(backBitmap,0f,0f,null) } if (BuildConfig.DEBUG) { canvas.drawText(fps.toString(), paddingStart.toFloat() , height - dp2px(10f).toFloat() - paddingBottom, fpsPaint) } } override fun onAttachedToWindow() { super.onAttachedToWindow() // start anim startRipple() renderAnimator.start() } private fun startRipple() { val runnable = Runnable { rippleCircles.add(RippleCircle().apply { cx = width.div(2).toFloat() cy = height.div(2).toFloat() val maxRadius = Math.min(width, height).div(2).toFloat() startRadius = maxRadius.div(2) endRadius = maxRadius }) startRipple() } postOnAnimationDelayed(runnable, 2000) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() // end anim renderAnimator.end() backBitmap?.recycle() } inner class RippleCircle { // 4s * 60 frms = 240 private val slice = 300 var startRadius = 0f var endRadius = 0f var cx = 0f var cy = 0f private var progress = 0 fun draw(canvas: Canvas) { if (progress >= slice) { // remove post { rippleCircles.remove(this) } return } progress++ ripplePaint.alpha = (1 - progress.div(slice * 1.0f)).times(255).toInt() val radis = startRadius + (endRadius - startRadius).div(slice).times(progress) canvas.drawCircle(cx, cy, radis, ripplePaint) } } }
mit
a6fe2add19edcf641b72554b3809093a
29.75122
116
0.56132
4.610827
false
false
false
false
material-components/material-components-android-examples
Reply/app/src/main/java/com/materialstudies/reply/ui/home/ReboundingSwipeActionCallback.kt
1
5654
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.materialstudies.reply.ui.home import android.graphics.Canvas import android.view.View import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import kotlin.math.abs import kotlin.math.ln // The intensity at which dX of a swipe should be decreased as we approach the swipe // threshold. private const val swipeReboundingElasticity = 0.8F // The 'true' percentage of total swipe distance needed to consider a view as 'swiped'. This // is used in favor of getSwipeThreshold since that has been overridden to return an impossible // to reach value. private const val trueSwipeThreshold = 0.4F class ReboundingSwipeActionCallback : ItemTouchHelper.SimpleCallback( 0, ItemTouchHelper.RIGHT ) { interface ReboundableViewHolder { /** * A view from the view holder which should be translated for swipe events. */ val reboundableView: View /** * Called as a view holder is actively being swiped/rebounded. * * @param currentSwipePercentage The total percentage the view has been swiped. * @param swipeThreshold The percentage needed to consider a swipe as "rebounded" * or "swiped" * @param currentTargetHasMetThresholdOnce Whether or not during a contiguous interaction * with a single view holder, the swipe percentage has ever been greater than the swipe * threshold. */ fun onReboundOffsetChanged( currentSwipePercentage: Float, swipeThreshold: Float, currentTargetHasMetThresholdOnce: Boolean ) /** * Called once all interaction (user initiated swiping and animations) has ended and this * view holder has been swiped passed the swipe threshold. */ fun onRebounded() } // Track the view holder currently being swiped. private var currentTargetPosition: Int = -1 private var currentTargetHasMetThresholdOnce: Boolean = false // Never dismiss. override fun getSwipeThreshold(viewHolder: RecyclerView.ViewHolder): Float = Float.MAX_VALUE // Never dismiss. override fun getSwipeVelocityThreshold(defaultValue: Float): Float { return Float.MAX_VALUE } // Never dismiss. override fun getSwipeEscapeVelocity(defaultValue: Float): Float { return Float.MAX_VALUE } override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean = false override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) { // After animations to replace view have run, notify viewHolders that they have // been swiped. This waits for animations to finish so RecyclerView's DefaultItemAnimator // doesn't try to run updating animations while swipe animations are still running. if (currentTargetHasMetThresholdOnce && viewHolder is ReboundableViewHolder){ currentTargetHasMetThresholdOnce = false viewHolder.onRebounded() } super.clearView(recyclerView, viewHolder) } override fun onChildDraw( c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean ) { if (viewHolder !is ReboundableViewHolder) return if (currentTargetPosition != viewHolder.adapterPosition) { currentTargetPosition = viewHolder.adapterPosition currentTargetHasMetThresholdOnce = false } val itemView = viewHolder.itemView val currentSwipePercentage = abs(dX) / itemView.width viewHolder.onReboundOffsetChanged( currentSwipePercentage, trueSwipeThreshold, currentTargetHasMetThresholdOnce ) translateReboundingView(itemView, viewHolder, dX) if (currentSwipePercentage >= trueSwipeThreshold && !currentTargetHasMetThresholdOnce) { currentTargetHasMetThresholdOnce = true } } private fun translateReboundingView( itemView: View, viewHolder: ReboundableViewHolder, dX: Float ) { // Progressively decrease the amount by which the view is translated to give a 'spring' // affect to the item. val swipeDismissDistanceHorizontal = itemView.width * trueSwipeThreshold val dragFraction = ln( (1 + (dX / swipeDismissDistanceHorizontal)).toDouble()) / ln(3.toDouble() ) val dragTo = dragFraction * swipeDismissDistanceHorizontal * swipeReboundingElasticity viewHolder.reboundableView.translationX = dragTo.toFloat() } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { // Do nothing. Overriding getSwipeThreshold to an impossible number means this will // never be called. } }
apache-2.0
62662502c50f0bb18a793be7219300f7
35.483871
97
0.689777
5.298969
false
false
false
false
openHPI/android-app
app/src/main/java/de/xikolo/controllers/course/ProgressFragment.kt
1
2361
package de.xikolo.controllers.course import android.os.Bundle import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.yatatsu.autobundle.AutoBundleField import de.xikolo.R import de.xikolo.controllers.base.ViewModelFragment import de.xikolo.extensions.observe import de.xikolo.models.dao.CourseProgressDao import de.xikolo.viewmodels.course.ProgressViewModel import de.xikolo.views.SpaceItemDecoration class ProgressFragment : ViewModelFragment<ProgressViewModel>() { companion object { val TAG: String = ProgressFragment::class.java.simpleName } @AutoBundleField lateinit var courseId: String private lateinit var adapter: ProgressListAdapter override val layoutResource: Int = R.layout.fragment_course_progress override fun createViewModel(): ProgressViewModel { return ProgressViewModel(courseId) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val recyclerView = view.findViewById<RecyclerView>(R.id.content_view) adapter = ProgressListAdapter(activity!!) val layoutManager = LinearLayoutManager(activity) recyclerView.layoutManager = layoutManager recyclerView.adapter = adapter recyclerView.addItemDecoration(SpaceItemDecoration( 0, activity!!.resources.getDimensionPixelSize(R.dimen.card_vertical_margin), false, object : SpaceItemDecoration.RecyclerViewInfo { override fun isHeader(position: Int): Boolean { return false } override val spanCount: Int get() = 1 override val itemCount: Int get() = adapter.itemCount } )) viewModel.sectionProgresses .observe(viewLifecycleOwner) { sp -> val cp = CourseProgressDao.Unmanaged.find(courseId) if (sp.isNotEmpty() && cp != null) { adapter.update(cp, sp) showContent() } } } }
bsd-3-clause
33802697f214d722226f6447bf8f7250
30.48
85
0.663278
5.440092
false
false
false
false
soywiz/korge
korge-editor/src/commonMain/kotlin/Main.kt
1
12388
import com.soywiz.kds.* import com.soywiz.klock.* import com.soywiz.korev.* import com.soywiz.korge.* import com.soywiz.korge.component.docking.* import com.soywiz.korge.input.* import com.soywiz.korge.scene.* import com.soywiz.korge.tiled.* import com.soywiz.korge.view.* import com.soywiz.korge.view.animation.* import com.soywiz.korim.atlas.* import com.soywiz.korim.bitmap.* import com.soywiz.korim.color.* import com.soywiz.korim.format.* import com.soywiz.korio.file.std.* import com.soywiz.korio.stream.* import com.soywiz.korma.geom.* import com.soywiz.korma.geom.ds.* import com.soywiz.korma.geom.shape.* import com.soywiz.korma.geom.vector.* import com.soywiz.korma.random.* import kotlinx.coroutines.* import kotlin.random.* //suspend fun main() { // for (n in 0 until 1000) { // val sw = Stopwatch().start() // val atlas = MutableAtlasUnit(1024, 1024) // atlas.add(Bitmap32(64, 64)) // //val ase = resourcesVfs["vampire.ase"].readImageData(ASE, atlas = atlas) // //val slices = resourcesVfs["slice-example.ase"].readImageDataContainer(ASE, atlas = atlas) // //resourcesVfs["korim.png"].readBitmapSlice().split(32, 32).toAtlas(atlas = atlas) // //val korim = resourcesVfs["korim.png"].readBitmapSlice(atlas = atlas) // val aseAll = resourcesVfs["characters.ase"].readImageDataContainer(ASE, atlas = atlas) // val slices = resourcesVfs["slice-example.ase"].readImageDataContainer(ASE, atlas = atlas) // val vampireSprite = aseAll["vampire"] // val vampSprite = aseAll["vamp"] // val tiledMap = resourcesVfs["Tilemap/untitled.tmx"].readTiledMap(atlas = atlas) // //val ase = aseAll["vamp"] // //for (n in 0 until 10000) { // // resourcesVfs["vampire.ase"].readImageData(ASE, atlas = atlas) // // resourcesVfs["slice-example.ase"].readImageDataContainer(ASE, atlas = atlas) // //} // println(sw.elapsed) // } //} suspend fun main() = Korge { //mainBVH() mainCircles() //mainVampire() //mainCompression() //println("HELLO WORLD!") //withContext(Dispatchers.Unconfined) { } var SolidRect.movingDirection by extraProperty { -1 } suspend fun Stage.mainBVH() { val bvh = BVH2D<View>() val rand = Random(0) val rects = arrayListOf<SolidRect>() for (n in 0 until 2_000) { val x = rand[0.0, width] val y = rand[0.0, height] val width = rand[1.0, 50.0] val height = rand[1.0, 50.0] val view = solidRect(width, height, rand[Colors.RED, Colors.BLUE]).xy(x, y) view.movingDirection = if (rand.nextBoolean()) -1 else +1 rects += view bvh.insertOrUpdate(view.globalBounds, view) } addUpdater { for (n in rects.size - 100 until rects.size) { val view = rects[n] if (view.x < 0) { view.movingDirection = +1 } if (view.x > stage.width) { view.movingDirection = -1 } view.x += view.movingDirection bvh.insertOrUpdate(view.globalBounds, view) } } val center = Point(width / 2, height / 2) val dir = Point(-1, -1) val ray = Ray(center, dir) val statusText = text("", font = debugBmpFont) var selectedRectangle = Rectangle(Point(100, 100) - Point(50, 50), Size(100, 100)) val rayLine = line(center, center + (dir * 1000), Colors.WHITE) val selectedRect = outline(buildPath { rect(selectedRectangle) }) //outline(buildPath { star(5, 50.0, 100.0, x = 100.0, y = 100.0) }) //debugLine(center, center + (dir * 1000), Colors.WHITE) fun updateRay() { var allObjectsSize = 0 var rayObjectsSize = 0 var rectangleObjectsSize = 0 val allObjects = bvh.search(Rectangle(0.0, 0.0, width, height)) val time = measureTime { val rayObjects = bvh.intersect(ray) val rectangleObjects = bvh.search(selectedRectangle) for (result in allObjects) result.value?.alpha = 0.2 for (result in rectangleObjects) result.value?.alpha = 0.8 for (result in rayObjects) result.obj.value?.alpha = 1.0 allObjectsSize = allObjects.size rayObjectsSize = rayObjects.size rectangleObjectsSize = rectangleObjects.size } statusText.text = "All objects: ${allObjectsSize}, raycast = ${rayObjectsSize}, rect = ${rectangleObjectsSize}, time = $time" } updateRay() addUpdater { //println("moved") val mousePos = stage.mouseXY val angle = Point.angleFull(center, mousePos) //println("center=$center, mousePos=$mousePos, angle = $angle") dir.setTo(angle.cosine, angle.sine) rayLine.setPoints(center, center + (dir * 1000)) updateRay() } mouse { onDown { selectedRectangle = Rectangle(stage.mouseXY - Point(50, 50), Size(100, 100)) selectedRect.vectorPath = buildPath { rect(selectedRectangle) } } onMouseDrag { selectedRectangle = Rectangle(stage.mouseXY - Point(50, 50), Size(100, 100)) selectedRect.vectorPath = buildPath { rect(selectedRectangle) } } } } suspend fun Stage.mainCircles() { // @TODO: USe BVH2D to limit collision view checkings lateinit var collisionViews: List<View> val rect1 = circle(50.0, fill = Colors.RED).xy(300, 300).centered val rect1b = circle(50.0, fill = Colors.RED).xy(520, 300).centered val rect2 = circle(50.0, fill = Colors.GREEN).xy(120, 0).draggable(autoMove = false) { //it.view.xy(it.viewPrevXY) it.view.moveWithCollisions(collisionViews, it.viewDeltaXY) } collisionViews = fastArrayListOf<View>(rect1, rect1b, rect2) println(rect1.hitShape2d) println(rect2.hitShape2d) addUpdater { dt -> val dx = keys.getDeltaAxis(Key.LEFT, Key.RIGHT) val dy = keys.getDeltaAxis(Key.UP, Key.DOWN) //if (dx != 0.0 || dy != 0.0) { val speed = (dt / 16.milliseconds) * 5.0 rect2.moveWithCollisions(collisionViews, dx * speed, dy * speed) //} //rect2.alpha = if (rect1.collidesWith(rect2, kind = CollisionKind.SHAPE)) 1.0 else 0.3 } } suspend fun Stage.mainVampire() { val atlas = MutableAtlasUnit(1024, 512, border = 2) val sw = Stopwatch().start() resourcesVfs["korim.png"].readBitmapSlice().split(32, 32).toAtlas(atlas = atlas) val korim = resourcesVfs["korim.png"].readBitmapSlice(atlas = atlas) val characters = resourcesVfs["characters.ase"].readImageDataContainer(ASE, atlas = atlas) val slices = resourcesVfs["slice-example.ase"].readImageDataContainer(ASE, atlas = atlas) val tiledMap = resourcesVfs["Tilemap/untitled.tmx"].readTiledMap(atlas = atlas) println(sw.elapsed) //image(korim) //image(atlas.bitmap);return lateinit var tiledMapView: TiledMapView container { scale(2.0) //tiledMapView(tiledMap, smoothing = false) tiledMapView = tiledMapView(tiledMap, smoothing = true) } container { scale = 2.0 imageDataView(slices["wizHat"]).xy(0, 50) imageDataView(slices["giantHilt"]).xy(32, 50) imageDataView(slices["pumpkin"]).xy(64, 50) } //image(tiledMapView.collisionToBitmap()).scale(2.0) //val ase2 = resourcesVfs["vampire.ase"].readImageData(ASE, atlas = atlas) //val ase3 = resourcesVfs["vampire.ase"].readImageData(ASE, atlas = atlas) //for (bitmap in atlas.allBitmaps) image(bitmap) // atlas generation //val gg = buildPath { // rect(300, 0, 100, 100) // circle(400, 400, 50) // star(5, 30.0, 100.0, x = 400.0, y = 300.0) // //star(400, 400, 50) //} val gg = graphics { fill(Colors.RED) { rect(300, 0, 100, 100) } fill(Colors.RED) { circle(400, 400, 50) } fill(Colors.BLUE) { star(5, 30.0, 100.0, x = 400.0, y = 300.0) //star(400, 400, 50) } } container { keepChildrenSortedByY() val character1 = imageDataView(characters["vampire"], "down") { stop() xy(200, 200) hitShape2d = Shape2d.Rectangle.fromBounds(-8.0, -3.0, +8.0, +3.0) } val character2 = imageDataView(characters["vamp"], "down") { stop() xy(160, 110) } //val hitTestable = listOf(tiledMapView, gg).toHitTestable() val hitTestable = listOf(gg) controlWithKeyboard(character1, hitTestable, up = Key.UP, right = Key.RIGHT, down = Key.DOWN, left = Key.LEFT,) controlWithKeyboard(character2, hitTestable, up = Key.W, right = Key.D, down = Key.S, left = Key.A) } } fun TiledMapView.collisionToBitmap(): Bitmap { val bmp = Bitmap32(this.width.toInt(), this.height.toInt()) for (y in 0 until bmp.height) for (x in 0 until bmp.width) { bmp[x, y] = if (pixelHitTest(x, y) != null) Colors.WHITE else Colors.TRANSPARENT_BLACK } return bmp } fun Stage.controlWithKeyboard( char: ImageDataView, collider: List<View>, up: Key = Key.UP, right: Key = Key.RIGHT, down: Key = Key.DOWN, left: Key = Key.LEFT, ) { addUpdater { dt -> val speed = 5.0 * (dt / 16.0.milliseconds) val dx = keys.getDeltaAxis(left, right) val dy = keys.getDeltaAxis(up, down) if (dx != 0.0 || dy != 0.0) { val dpos = Point(dx, dy).normalized * speed char.moveWithCollisions(collider, dpos.x, dpos.y) } char.animation = when { dx < 0.0 -> "left" dx > 0.0 -> "right" dy < 0.0 -> "up" dy > 0.0 -> "down" else -> char.animation } if (dx != 0.0 || dy != 0.0) { char.play() } else { char.stop() char.rewind() } } } suspend fun mainCompression() { //run { withContext(Dispatchers.Unconfined) { val mem = MemoryVfsMix() val zipFile = localVfs("c:/temp", async = true)["1.zip"] val zipBytes = zipFile.readAll() println("ELAPSED TIME [NATIVE]: " + measureTime { //localVfs("c:/temp")["1.zip"].openAsZip()["2012-07-15-wheezy-raspbian.img"].copyTo(mem["test.img"]) //localVfs("c:/temp")["iTunes64Setup.zip"].openAsZip().listSimple().first().copyTo(mem["test.out"]) //localVfs("c:/temp")["iTunes64Setup.zip"].readAll().openAsync().openAsZip().listSimple().first().copyTo(mem["test.out"]) //localVfs("c:/temp")["iTunes64Setup.zip"].openAsZip().listSimple().first().copyTo(mem["test.out"]) //localVfs("c:/temp")["1.zip"].readAll().openAsync().openAsZip()["2012-07-15-wheezy-raspbian.img"].copyTo(localVfs("c:/temp/temp.img")) //localVfs("c:/temp")["1.zip"].openAsZip(useNativeDecompression = true)["2012-07-15-wheezy-raspbian.img"].copyTo(localVfs("c:/temp/temp.img")) zipBytes.openAsync().openAsZip(useNativeDecompression = true)["2012-07-15-wheezy-raspbian.img"].copyTo( DummyAsyncOutputStream ) }) println("ELAPSED TIME [PORTABLE]: " + measureTime { //localVfs("c:/temp")["1.zip"].openAsZip()["2012-07-15-wheezy-raspbian.img"].copyTo(mem["test.img"]) //localVfs("c:/temp")["iTunes64Setup.zip"].openAsZip().listSimple().first().copyTo(mem["test.out"]) //localVfs("c:/temp")["iTunes64Setup.zip"].readAll().openAsync().openAsZip().listSimple().first().copyTo(mem["test.out"]) //localVfs("c:/temp")["iTunes64Setup.zip"].openAsZip().listSimple().first().copyTo(mem["test.out"]) //localVfs("c:/temp")["1.zip"].readAll().openAsync().openAsZip()["2012-07-15-wheezy-raspbian.img"].copyTo(localVfs("c:/temp/temp.img")) //localVfs("c:/temp")["1.zip"].openAsZip(useNativeDecompression = false)["2012-07-15-wheezy-raspbian.img"].copyTo(localVfs("c:/temp/temp2.img")) //localVfs("c:/temp", async = true)["1.zip"].openAsZip(useNativeDecompression = false)["2012-07-15-wheezy-raspbian.img"].copyTo(DummyAsyncOutputStream) zipBytes.openAsync().openAsZip(useNativeDecompression = false)["2012-07-15-wheezy-raspbian.img"].copyTo( DummyAsyncOutputStream ) }) } }
apache-2.0
06d4a33bc19ce26bef88e5c747547f69
38.96129
163
0.606232
3.450696
false
false
false
false
donald-w/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/dialogs/CardBrowserOrderDialog.kt
1
3355
/**************************************************************************************** * Copyright (c) 2015 Enno Hermann <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.anki.dialogs import android.app.Dialog import android.os.Bundle import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.MaterialDialog.ListCallbackSingleChoice import com.ichi2.anki.CardBrowser import com.ichi2.anki.R import com.ichi2.anki.analytics.AnalyticsDialogFragment class CardBrowserOrderDialog : AnalyticsDialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { super.onCreate(savedInstanceState) val res = resources val items = res.getStringArray(R.array.card_browser_order_labels) // Set sort order arrow for (i in items.indices) { if (i != CardBrowser.CARD_ORDER_NONE && i == requireArguments().getInt("order")) { if (requireArguments().getBoolean("isOrderAsc")) { items[i] = items[i].toString() + " (\u25b2)" } else { items[i] = items[i].toString() + " (\u25bc)" } } } return MaterialDialog.Builder(requireActivity()) .title(res.getString(R.string.card_browser_change_display_order_title)) .content(res.getString(R.string.card_browser_change_display_order_reverse)) .items(*items) .itemsCallbackSingleChoice(requireArguments().getInt("order"), mOrderDialogListener!!) .build() } companion object { private var mOrderDialogListener: ListCallbackSingleChoice? = null @JvmStatic fun newInstance( order: Int, isOrderAsc: Boolean, orderDialogListener: ListCallbackSingleChoice? ): CardBrowserOrderDialog { val f = CardBrowserOrderDialog() val args = Bundle() args.putInt("order", order) args.putBoolean("isOrderAsc", isOrderAsc) mOrderDialogListener = orderDialogListener f.arguments = args return f } } }
gpl-3.0
f2e5e9a9fba7339d1ee23387612d9993
49.074627
98
0.53383
5.342357
false
false
false
false
cashapp/sqldelight
sqldelight-compiler/src/main/kotlin/app/cash/sqldelight/core/lang/SqlDelightFile.kt
1
3735
package app.cash.sqldelight.core.lang import app.cash.sqldelight.core.SqlDelightFileIndex import app.cash.sqldelight.core.SqlDelightProjectService import app.cash.sqldelight.core.lang.util.AnsiSqlTypeResolver import app.cash.sqldelight.dialect.api.SqlDelightModule import app.cash.sqldelight.dialect.api.TypeResolver import com.alecstrong.sql.psi.core.SqlFileBase import com.intellij.lang.Language import com.intellij.openapi.module.Module import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.FileViewProvider import com.intellij.psi.PsiManager import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.GlobalSearchScopesCore import java.util.ServiceLoader abstract class SqlDelightFile( viewProvider: FileViewProvider, language: Language, ) : SqlFileBase(viewProvider, language) { val module: Module? get() = virtualFile?.let { SqlDelightProjectService.getInstance(project).module(it) } val generatedDirectories by lazy { val packageName = packageName ?: return@lazy null generatedDirectories(packageName) } internal fun generatedDirectories(packageName: String): List<String>? { val module = module ?: return null return SqlDelightFileIndex.getInstance(module).outputDirectory(this).map { outputDirectory -> "$outputDirectory/${packageName.replace('.', '/')}" } } internal val dialect get() = SqlDelightProjectService.getInstance(project).dialect internal val treatNullAsUnknownForEquality get() = SqlDelightProjectService.getInstance(project).treatNullAsUnknownForEquality internal val generateAsync get() = SqlDelightProjectService.getInstance(project).generateAsync internal val typeResolver: TypeResolver by lazy { var parentResolver: TypeResolver = AnsiSqlTypeResolver ServiceLoader.load(SqlDelightModule::class.java, dialect::class.java.classLoader).forEach { parentResolver = it.typeResolver(parentResolver) } dialect.typeResolver(parentResolver) } abstract val packageName: String? override fun getVirtualFile(): VirtualFile? { if (myOriginalFile != null) return myOriginalFile.virtualFile return super.getVirtualFile() } override fun searchScope(): GlobalSearchScope { val default = GlobalSearchScope.fileScope(this) val module = module ?: return default val index = SqlDelightFileIndex.getInstance(module) val sourceFolders = index.sourceFolders(virtualFile ?: return default) if (sourceFolders.isEmpty()) return default // TODO Deal with database files? return sourceFolders .map { GlobalSearchScopesCore.directoryScope(project, it, true) } .reduce { totalScope, directoryScope -> totalScope.union(directoryScope) } } fun findDbFile(): SqlFileBase? { val module = module ?: return null val manager = PsiManager.getInstance(project) var result: SqlFileBase? = null val folders = SqlDelightFileIndex.getInstance(module).sourceFolders(virtualFile ?: return null) folders.forEach { dir -> VfsUtilCore.iterateChildrenRecursively( dir, { it.isDirectory || it.fileType == DatabaseFileType }, { file -> if (file.isDirectory) return@iterateChildrenRecursively true val vFile = (manager.findViewProvider(file) as? DatabaseFileViewProvider)?.getSchemaFile() ?: return@iterateChildrenRecursively true manager.findFile(vFile)?.let { psiFile -> if (psiFile is SqlFileBase) { result = psiFile return@iterateChildrenRecursively false } } return@iterateChildrenRecursively true }, ) } return result } }
apache-2.0
6266867c50a3f29c6a7aac89565805e5
34.235849
100
0.741365
4.901575
false
false
false
false
panpf/sketch
sample/src/main/java/com/github/panpf/sketch/sample/MyServices.kt
1
2150
/* * 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.sample import android.content.Context import android.view.View import androidx.fragment.app.Fragment import com.github.panpf.sketch.sample.data.api.ApiServices import com.github.panpf.sketch.sample.util.ParamLazy object MyServices { val apiServiceLazy = ParamLazy<Context, ApiServices> { ApiServices(it) } val prefsServiceLazy = ParamLazy<Context, PrefsService> { PrefsService(it) } val eventServiceLazy = ParamLazy<Context, EventService> { EventService() } } val Context.apiService: ApiServices get() = MyServices.apiServiceLazy.get(this.applicationContext) val Fragment.apiService: ApiServices get() = MyServices.apiServiceLazy.get(this.requireContext().applicationContext) val View.apiService: ApiServices get() = MyServices.apiServiceLazy.get(this.context.applicationContext) val Context.prefsService: PrefsService get() = MyServices.prefsServiceLazy.get(this.applicationContext) val Fragment.prefsService: PrefsService get() = MyServices.prefsServiceLazy.get(this.requireContext().applicationContext) val View.prefsService: PrefsService get() = MyServices.prefsServiceLazy.get(this.context.applicationContext) val Context.eventService: EventService get() = MyServices.eventServiceLazy.get(this.applicationContext) val Fragment.eventService: EventService get() = MyServices.eventServiceLazy.get(this.requireContext().applicationContext) val View.eventService: EventService get() = MyServices.eventServiceLazy.get(this.context.applicationContext)
apache-2.0
94b1da3d23e657ee014701f1bd6491f2
42.897959
85
0.786512
4.110899
false
false
false
false
panpf/sketch
sketch-zoom/src/main/java/com/github/panpf/sketch/zoom/internal/ScaleDragHelper.kt
1
21642
/* * 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.zoom.internal import android.content.Context import android.graphics.Matrix import android.graphics.Point import android.graphics.PointF import android.graphics.Rect import android.graphics.RectF import android.view.MotionEvent import android.widget.ImageView.ScaleType import com.github.panpf.sketch.util.Logger import com.github.panpf.sketch.util.Size import com.github.panpf.sketch.zoom.Edge import com.github.panpf.sketch.zoom.ScaleState.Initial import com.github.panpf.sketch.zoom.internal.ScaleDragGestureDetector.OnActionListener import com.github.panpf.sketch.zoom.internal.ScaleDragGestureDetector.OnGestureListener import kotlin.math.abs import kotlin.math.roundToInt internal class ScaleDragHelper constructor( private val context: Context, private val logger: Logger, private val zoomerHelper: ZoomerHelper, val onUpdateMatrix: () -> Unit, val onViewDrag: (dx: Float, dy: Float) -> Unit, val onDragFling: (startX: Float, startY: Float, velocityX: Float, velocityY: Float) -> Unit, val onScaleChanged: (scaleFactor: Float, focusX: Float, focusY: Float) -> Unit, ) { private val view = zoomerHelper.view /* Stores default scale and translate information */ private val baseMatrix = Matrix() /* Stores zoom, translate and externally set rotation information generated by the user through touch events */ private val supportMatrix = Matrix() /* Store the fused information of baseMatrix and supportMatrix for drawing */ private val drawMatrix = Matrix() private val drawRectF = RectF() /* Cache the coordinates of the last zoom gesture, used when restoring zoom */ private var lastScaleFocusX: Float = 0f private var lastScaleFocusY: Float = 0f private var flingRunnable: FlingRunnable? = null private var locationRunnable: LocationRunnable? = null private var animatedScaleRunnable: AnimatedScaleRunnable? = null private val scaleDragGestureDetector: ScaleDragGestureDetector private var _horScrollEdge: Edge = Edge.NONE private var _verScrollEdge: Edge = Edge.NONE private var blockParentIntercept: Boolean = false private var dragging = false private var manualScaling = false val horScrollEdge: Edge get() = _horScrollEdge val verScrollEdge: Edge get() = _verScrollEdge val isScaling: Boolean get() = animatedScaleRunnable?.isRunning == true || manualScaling val baseScale: Float get() = baseMatrix.getScale() val supportScale: Float get() = supportMatrix.getScale() val scale: Float get() = drawMatrix.apply { getDrawMatrix(this) }.getScale() init { scaleDragGestureDetector = ScaleDragGestureDetector(context, object : OnGestureListener { override fun onDrag(dx: Float, dy: Float) = doDrag(dx, dy) override fun onFling( startX: Float, startY: Float, velocityX: Float, velocityY: Float ) = doFling(startX, startY, velocityX, velocityY) override fun onScaleBegin(): Boolean = doScaleBegin() override fun onScale( scaleFactor: Float, focusX: Float, focusY: Float, dx: Float, dy: Float ) = doScale(scaleFactor, focusX, focusY, dx, dy) override fun onScaleEnd() = doScaleEnd() }).apply { onActionListener = object : OnActionListener { override fun onActionDown(ev: MotionEvent) = actionDown() override fun onActionUp(ev: MotionEvent) = actionUp() override fun onActionCancel(ev: MotionEvent) = actionUp() } } } fun reset() { resetBaseMatrix() resetSupportMatrix() checkAndApplyMatrix() } fun clean() { animatedScaleRunnable?.cancel() animatedScaleRunnable = null locationRunnable?.cancel() locationRunnable = null flingRunnable?.cancel() flingRunnable = null } fun onTouchEvent(event: MotionEvent): Boolean { /* Location operations cannot be interrupted */ if (this.locationRunnable?.isRunning == true) { logger.v(ZoomerHelper.MODULE) { "onTouchEvent. requestDisallowInterceptTouchEvent true. locating" } requestDisallowInterceptTouchEvent(true) return true } return scaleDragGestureDetector.onTouchEvent(event) } private fun resetBaseMatrix() { baseMatrix.reset() when (val initState = zoomerHelper.scaleState.initial) { is Initial.Normal -> { baseMatrix.postScale(initState.scale, initState.scale) baseMatrix.postTranslate(initState.translateX, initState.translateY) } is Initial.FitXy -> { baseMatrix.setRectToRect( initState.srcRectF, initState.dstRectF, Matrix.ScaleToFit.FILL ) } } baseMatrix.postRotate(zoomerHelper.rotateDegrees.toFloat()) } private fun resetSupportMatrix() { supportMatrix.reset() } private fun checkAndApplyMatrix() { if (checkMatrixBounds()) { onUpdateMatrix() } } private fun checkMatrixBounds(): Boolean { val drawRectF = drawRectF.apply { getDrawRect(this) } if (drawRectF.isEmpty) { _horScrollEdge = Edge.NONE _verScrollEdge = Edge.NONE return false } var deltaX = 0f val viewWidth = zoomerHelper.viewSize.width val displayWidth = drawRectF.width() when { displayWidth.toInt() <= viewWidth -> { deltaX = when (zoomerHelper.scaleType) { ScaleType.FIT_START -> -drawRectF.left ScaleType.FIT_END -> viewWidth - displayWidth - drawRectF.left else -> (viewWidth - displayWidth) / 2 - drawRectF.left } } drawRectF.left.toInt() > 0 -> { deltaX = -drawRectF.left } drawRectF.right.toInt() < viewWidth -> { deltaX = viewWidth - drawRectF.right } } var deltaY = 0f val viewHeight = zoomerHelper.viewSize.height val displayHeight = drawRectF.height() when { displayHeight.toInt() <= viewHeight -> { deltaY = when (zoomerHelper.scaleType) { ScaleType.FIT_START -> -drawRectF.top ScaleType.FIT_END -> viewHeight - displayHeight - drawRectF.top else -> (viewHeight - displayHeight) / 2 - drawRectF.top } } drawRectF.top.toInt() > 0 -> { deltaY = -drawRectF.top } drawRectF.bottom.toInt() < viewHeight -> { deltaY = viewHeight - drawRectF.bottom } } // Finally actually translate the matrix supportMatrix.postTranslate(deltaX, deltaY) _verScrollEdge = when { displayHeight.toInt() <= viewHeight -> Edge.BOTH drawRectF.top.toInt() >= 0 -> Edge.START drawRectF.bottom.toInt() <= viewHeight -> Edge.END else -> Edge.NONE } _horScrollEdge = when { displayWidth.toInt() <= viewWidth -> Edge.BOTH drawRectF.left.toInt() >= 0 -> Edge.START drawRectF.right.toInt() <= viewWidth -> Edge.END else -> Edge.NONE } return true } fun translateBy(dx: Float, dy: Float) { supportMatrix.postTranslate(dx, dy) checkAndApplyMatrix() } fun location(xInDrawable: Float, yInDrawable: Float, animate: Boolean) { locationRunnable?.cancel() cancelFling() val (viewWidth, viewHeight) = zoomerHelper.viewSize.takeIf { !it.isEmpty } ?: return val pointF = PointF(xInDrawable, yInDrawable).apply { rotatePoint(this, zoomerHelper.rotateDegrees, zoomerHelper.drawableSize) } val newX = pointF.x val newY = pointF.y var nowScale = scale.format(2) val fullZoomScale = zoomerHelper.fullScale.format(2) if (nowScale == fullZoomScale) { scale( scale = zoomerHelper.originScale, focalX = zoomerHelper.viewSize.width / 2f, focalY = zoomerHelper.viewSize.height / 2f, animate = false ) } val drawRectF = drawRectF.apply { getDrawRect(this) } nowScale = scale val scaleLocationX = (newX * nowScale).toInt() val scaleLocationY = (newY * nowScale).toInt() val scaledLocationX = scaleLocationX.coerceAtLeast(0).coerceAtMost(drawRectF.width().toInt()) val scaledLocationY = scaleLocationY.coerceAtLeast(0).coerceAtMost(drawRectF.height().toInt()) val centerLocationX = (scaledLocationX - viewWidth / 2).coerceAtLeast(0) val centerLocationY = (scaledLocationY - viewHeight / 2).coerceAtLeast(0) val startX = abs(drawRectF.left.toInt()) val startY = abs(drawRectF.top.toInt()) logger.v(ZoomerHelper.MODULE) { "location. inDrawable=%dx%d, start=%dx%d, end=%dx%d" .format(xInDrawable, yInDrawable, startX, startY, centerLocationX, centerLocationY) } if (animate) { locationRunnable?.cancel() locationRunnable = LocationRunnable( context = context, zoomerHelper = zoomerHelper, scaleDragHelper = this@ScaleDragHelper, startX = startX, startY = startY, endX = centerLocationX, endY = centerLocationY ) locationRunnable?.start() } else { val dx = -(centerLocationX - startX).toFloat() val dy = -(centerLocationY - startY).toFloat() translateBy(dx, dy) } } fun scale(scale: Float, focalX: Float, focalY: Float, animate: Boolean) { animatedScaleRunnable?.cancel() if (animate) { animatedScaleRunnable = AnimatedScaleRunnable( zoomerHelper = zoomerHelper, scaleDragHelper = this@ScaleDragHelper, startScale = zoomerHelper.scale, endScale = scale, scaleFocalX = focalX, scaleFocalY = focalY ) animatedScaleRunnable?.start() } else { val baseScale = baseScale val supportZoomScale = supportScale val finalScale = scale / baseScale val addScale = finalScale / supportZoomScale scaleBy(addScale, focalX, focalY) } } fun getDrawMatrix(matrix: Matrix) { matrix.set(baseMatrix) matrix.postConcat(supportMatrix) } fun getDrawRect(rectF: RectF) { val drawableSize = zoomerHelper.drawableSize rectF[0f, 0f, drawableSize.width.toFloat()] = drawableSize.height.toFloat() drawMatrix.apply { getDrawMatrix(this) }.mapRect(rectF) } /** * Gets the area that the user can see on the drawable (not affected by rotation) */ fun getVisibleRect(rect: Rect) { rect.setEmpty() val drawRectF = drawRectF.apply { getDrawRect(this) }.takeIf { !it.isEmpty } ?: return val viewSize = zoomerHelper.viewSize.takeIf { !it.isEmpty } ?: return val drawableSize = zoomerHelper.drawableSize.takeIf { !it.isEmpty } ?: return val (drawableWidth, drawableHeight) = drawableSize.let { if (zoomerHelper.rotateDegrees % 180 == 0) it else Size(it.height, it.width) } val displayWidth = drawRectF.width() val displayHeight = drawRectF.height() val widthScale = displayWidth / drawableWidth val heightScale = displayHeight / drawableHeight var left: Float = if (drawRectF.left >= 0) 0f else abs(drawRectF.left) var right: Float = if (displayWidth >= viewSize.width) viewSize.width + left else drawRectF.right - drawRectF.left var top: Float = if (drawRectF.top >= 0) 0f else abs(drawRectF.top) var bottom: Float = if (displayHeight >= viewSize.height) viewSize.height + top else drawRectF.bottom - drawRectF.top left /= widthScale right /= widthScale top /= heightScale bottom /= heightScale rect.set(left.roundToInt(), top.roundToInt(), right.roundToInt(), bottom.roundToInt()) reverseRotateRect(rect, zoomerHelper.rotateDegrees, drawableSize) } fun touchPointToDrawablePoint(touchPoint: PointF): Point? { val drawableSize = zoomerHelper.drawableSize.takeIf { !it.isEmpty } ?: return null val drawRect = RectF().apply { getDrawRect(this) } if (!drawRect.contains(touchPoint.x, touchPoint.y)) { return null } val zoomScale: Float = scale val drawableX = ((touchPoint.x - drawRect.left) / zoomScale).roundToInt().coerceAtLeast(0) .coerceAtMost(drawableSize.width) val drawableY = ((touchPoint.y - drawRect.top) / zoomScale).roundToInt().coerceAtLeast(0) .coerceAtMost(drawableSize.height) return Point(drawableX, drawableY) } /** * Whether you can scroll horizontally in the specified direction * * @param direction Negative to check scrolling left, positive to check scrolling right. */ fun canScrollHorizontally(direction: Int): Boolean { return if (direction < 0) { horScrollEdge != Edge.START && horScrollEdge != Edge.BOTH } else { horScrollEdge != Edge.END && horScrollEdge != Edge.BOTH } } /** * Whether you can scroll vertically in the specified direction * * @param direction Negative to check scrolling up, positive to check scrolling down. */ fun canScrollVertically(direction: Int): Boolean { return if (direction < 0) { verScrollEdge != Edge.START && horScrollEdge != Edge.BOTH } else { verScrollEdge != Edge.END && horScrollEdge != Edge.BOTH } } private fun doDrag(dx: Float, dy: Float) { logger.v(ZoomerHelper.MODULE) { "onDrag. dx: $dx, dy: $dy" } if (scaleDragGestureDetector.isScaling) { logger.v(ZoomerHelper.MODULE) { "onDrag. isScaling" } return } supportMatrix.postTranslate(dx, dy) checkAndApplyMatrix() onViewDrag(dx, dy) val scaling = scaleDragGestureDetector.isScaling val disallowParentInterceptOnEdge = !zoomerHelper.allowParentInterceptOnEdge val blockParent = blockParentIntercept val disallow = if (dragging || scaling || blockParent || disallowParentInterceptOnEdge) { logger.d(ZoomerHelper.MODULE) { "onDrag. DisallowParentIntercept. dragging=%s, scaling=%s, blockParent=%s, disallowParentInterceptOnEdge=%s" .format(dragging, scaling, blockParent, disallowParentInterceptOnEdge) } true } else { val slop = zoomerHelper.view.resources.displayMetrics.density * 3 val result = (horScrollEdge == Edge.NONE && (dx >= slop || dx <= -slop)) || (horScrollEdge == Edge.START && dx <= -slop) || (horScrollEdge == Edge.END && dx >= slop) || (verScrollEdge == Edge.NONE && (dy >= slop || dy <= -slop)) || (verScrollEdge == Edge.START && dy <= -slop) || (verScrollEdge == Edge.END && dy >= slop) if (result) { logger.d(ZoomerHelper.MODULE) { "onDrag. DisallowParentIntercept. scrollEdge=%s-%s, d=%sx%s" .format(horScrollEdge, verScrollEdge, dx, dy) } } else { logger.d(ZoomerHelper.MODULE) { "onDrag. AllowParentIntercept. scrollEdge=%s-%s, d=%sx%s" .format(horScrollEdge, verScrollEdge, dx, dy) } } dragging = result result } requestDisallowInterceptTouchEvent(disallow) } private fun doFling(startX: Float, startY: Float, velocityX: Float, velocityY: Float) { logger.v(ZoomerHelper.MODULE) { "fling. startX=$startX, startY=$startY, velocityX=$velocityX, velocityY=$velocityY" } flingRunnable?.cancel() flingRunnable = FlingRunnable( context = context, zoomerHelper = zoomerHelper, scaleDragHelper = this@ScaleDragHelper, velocityX = velocityX.toInt(), velocityY = velocityY.toInt() ) flingRunnable?.start() onDragFling(startX, startY, velocityX, velocityY) } private fun cancelFling() { flingRunnable?.cancel() } private fun doScaleBegin(): Boolean { logger.v(ZoomerHelper.MODULE) { "onScaleBegin" } manualScaling = true return true } private fun scaleBy(addScale: Float, focalX: Float, focalY: Float) { supportMatrix.postScale(addScale, addScale, focalX, focalY) checkAndApplyMatrix() } internal fun doScale(scaleFactor: Float, focusX: Float, focusY: Float, dx: Float, dy: Float) { logger.v(ZoomerHelper.MODULE) { "onScale. scaleFactor: $scaleFactor, focusX: $focusX, focusY: $focusY, dx: $dx, dy: $dy" } /* Simulate a rubber band effect when zoomed to max or min */ var newScaleFactor = scaleFactor lastScaleFocusX = focusX lastScaleFocusY = focusY val oldSupportScale = supportScale var newSupportScale = oldSupportScale * newScaleFactor if (newScaleFactor > 1.0f) { // The maximum zoom has been reached. Simulate the effect of pulling a rubber band val maxSupportScale = zoomerHelper.maxScale / baseMatrix.getScale() if (oldSupportScale >= maxSupportScale) { var addScale = newSupportScale - oldSupportScale addScale *= 0.4f newSupportScale = oldSupportScale + addScale newScaleFactor = newSupportScale / oldSupportScale } } else if (newScaleFactor < 1.0f) { // The minimum zoom has been reached. Simulate the effect of pulling a rubber band val minSupportScale = zoomerHelper.minScale / baseMatrix.getScale() if (oldSupportScale <= minSupportScale) { var addScale = newSupportScale - oldSupportScale addScale *= 0.4f newSupportScale = oldSupportScale + addScale newScaleFactor = newSupportScale / oldSupportScale } } supportMatrix.postScale(newScaleFactor, newScaleFactor, focusX, focusY) supportMatrix.postTranslate(dx, dy) checkAndApplyMatrix() onScaleChanged(newScaleFactor, focusX, focusY) } private fun doScaleEnd() { logger.v(ZoomerHelper.MODULE) { "onScaleEnd" } val currentScale = scale.format(2) val overMinZoomScale = currentScale < zoomerHelper.minScale.format(2) val overMaxZoomScale = currentScale > zoomerHelper.maxScale.format(2) if (!overMinZoomScale && !overMaxZoomScale) { manualScaling = false onUpdateMatrix() } } private fun actionDown() { logger.v(ZoomerHelper.MODULE) { "onActionDown. disallow parent intercept touch event" } lastScaleFocusX = 0f lastScaleFocusY = 0f dragging = false requestDisallowInterceptTouchEvent(true) cancelFling() } private fun actionUp() { /* Roll back to minimum or maximum scaling */ val currentScale = scale.format(2) val minZoomScale = zoomerHelper.minScale.format(2) val maxZoomScale = zoomerHelper.maxScale.format(2) if (currentScale < minZoomScale) { val drawRectF = drawRectF.apply { getDrawRect(this) } if (!drawRectF.isEmpty) { scale(minZoomScale, drawRectF.centerX(), drawRectF.centerY(), true) } } else if (currentScale > maxZoomScale) { val lastScaleFocusX = lastScaleFocusX val lastScaleFocusY = lastScaleFocusY if (lastScaleFocusX != 0f && lastScaleFocusY != 0f) { scale(maxZoomScale, lastScaleFocusX, lastScaleFocusY, true) } } } private fun requestDisallowInterceptTouchEvent(disallowIntercept: Boolean) { view.parent?.requestDisallowInterceptTouchEvent(disallowIntercept) } }
apache-2.0
88b2dc0c9a8a381ebbde25022a800ae9
37.648214
124
0.610249
4.602722
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/page/edithistory/EditHistoryListViewModel.kt
1
8688
package org.wikipedia.page.edithistory import android.os.Bundle import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import androidx.paging.* import kotlinx.coroutines.* import kotlinx.coroutines.flow.map import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.mwapi.MwQueryPage import org.wikipedia.dataclient.restbase.EditCount import org.wikipedia.dataclient.restbase.Metrics import org.wikipedia.page.PageTitle import org.wikipedia.settings.Prefs import org.wikipedia.util.DateUtil import org.wikipedia.util.Resource import org.wikipedia.util.log.L import retrofit2.HttpException import java.io.IOException import java.util.* class EditHistoryListViewModel(bundle: Bundle) : ViewModel() { val editHistoryStatsData = MutableLiveData<Resource<EditHistoryStats>>() var pageTitle: PageTitle = bundle.getParcelable(EditHistoryListActivity.INTENT_EXTRA_PAGE_TITLE)!! var pageId = -1 private set var comparing = false private set var selectedRevisionFrom: MwQueryPage.Revision? = null private set var selectedRevisionTo: MwQueryPage.Revision? = null private set var currentQuery = "" var actionModeActive = false var editHistorySource: EditHistoryPagingSource? = null private val cachedRevisions = mutableListOf<MwQueryPage.Revision>() private var cachedContinueKey: String? = null val editHistoryFlow = Pager(PagingConfig(pageSize = 50), pagingSourceFactory = { editHistorySource = EditHistoryPagingSource(pageTitle) editHistorySource!! }).flow.map { pagingData -> val anonEditsOnly = Prefs.editHistoryFilterType == EditCount.EDIT_TYPE_ANONYMOUS val userEditsOnly = Prefs.editHistoryFilterType == EditCount.EDIT_TYPE_EDITORS pagingData.insertSeparators { before, after -> if (before != null && after != null) { before.diffSize = before.size - after.size } null }.filter { when { anonEditsOnly -> { it.isAnon } userEditsOnly -> { !it.isAnon } else -> { true } } }.filter { if (currentQuery.isNotEmpty()) { it.comment.contains(currentQuery, true) || it.content.contains(currentQuery, true) || it.user.contains(currentQuery, true) } else true }.map { EditHistoryItem(it) }.insertSeparators { before, after -> val dateBefore = if (before != null) DateUtil.getShortDateString(DateUtil.iso8601DateParse(before.item.timeStamp)) else "" val dateAfter = if (after != null) DateUtil.getShortDateString(DateUtil.iso8601DateParse(after.item.timeStamp)) else "" if (dateAfter.isNotEmpty() && dateAfter != dateBefore) { EditHistorySeparator(dateAfter) } else { null } } }.cachedIn(viewModelScope) init { loadEditHistoryStatsAndEditCounts() } private fun loadEditHistoryStatsAndEditCounts() { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> L.e(throwable) }) { withContext(Dispatchers.IO) { val calendar = Calendar.getInstance() val today = DateUtil.getYMDDateString(calendar.time) calendar.add(Calendar.YEAR, -1) val lastYear = DateUtil.getYMDDateString(calendar.time) val mwResponse = async { ServiceFactory.get(pageTitle.wikiSite).getRevisionDetailsAscending(pageTitle.prefixedText, 0, null) } val editCountsResponse = async { ServiceFactory.getCoreRest(pageTitle.wikiSite).getEditCount(pageTitle.prefixedText, EditCount.EDIT_TYPE_EDITS) } val editCountsUserResponse = async { ServiceFactory.getCoreRest(pageTitle.wikiSite).getEditCount(pageTitle.prefixedText, EditCount.EDIT_TYPE_EDITORS) } val editCountsAnonResponse = async { ServiceFactory.getCoreRest(pageTitle.wikiSite).getEditCount(pageTitle.prefixedText, EditCount.EDIT_TYPE_ANONYMOUS) } val editCountsBotResponse = async { ServiceFactory.getCoreRest(pageTitle.wikiSite).getEditCount(pageTitle.prefixedText, EditCount.EDIT_TYPE_BOT) } val articleMetricsResponse = async { ServiceFactory.getRest(WikiSite("wikimedia.org")).getArticleMetrics(pageTitle.wikiSite.authority(), pageTitle.prefixedText, lastYear, today) } val page = mwResponse.await().query?.pages?.first() pageId = page?.pageId ?: -1 editHistoryStatsData.postValue(Resource.Success(EditHistoryStats( page?.revisions?.first()!!, articleMetricsResponse.await().firstItem.results, editCountsResponse.await(), editCountsUserResponse.await(), editCountsAnonResponse.await(), editCountsBotResponse.await() ))) } } } fun toggleCompareState() { comparing = !comparing if (!comparing) { cancelSelectRevision() } } private fun cancelSelectRevision() { selectedRevisionFrom = null selectedRevisionTo = null } fun toggleSelectRevision(revision: MwQueryPage.Revision): Boolean { if (selectedRevisionFrom == null && selectedRevisionTo?.revId != revision.revId) { selectedRevisionFrom = revision return true } else if (selectedRevisionTo == null && selectedRevisionFrom?.revId != revision.revId) { selectedRevisionTo = revision return true } else if (selectedRevisionFrom?.revId == revision.revId) { selectedRevisionFrom = null return true } else if (selectedRevisionTo?.revId == revision.revId) { selectedRevisionTo = null return true } return false } fun getSelectedState(revision: MwQueryPage.Revision): Int { if (!comparing) { return SELECT_INACTIVE } else if (selectedRevisionFrom?.revId == revision.revId) { return SELECT_FROM } else if (selectedRevisionTo?.revId == revision.revId) { return SELECT_TO } return SELECT_NONE } fun clearCache() { cachedRevisions.clear() } inner class EditHistoryPagingSource( val pageTitle: PageTitle ) : PagingSource<String, MwQueryPage.Revision>() { override suspend fun load(params: LoadParams<String>): LoadResult<String, MwQueryPage.Revision> { return try { if (params.key == null && cachedRevisions.isNotEmpty()) { return LoadResult.Page(cachedRevisions, null, cachedContinueKey) } val response = ServiceFactory.get(WikiSite.forLanguageCode(pageTitle.wikiSite.languageCode)) .getRevisionDetailsDescending(pageTitle.prefixedText, 500, null, params.key) val revisions = response.query!!.pages?.first()?.revisions!! cachedContinueKey = response.continuation?.rvContinuation cachedRevisions.addAll(revisions) LoadResult.Page(revisions, null, cachedContinueKey) } catch (e: IOException) { LoadResult.Error(e) } catch (e: HttpException) { LoadResult.Error(e) } } override fun getRefreshKey(state: PagingState<String, MwQueryPage.Revision>): String? { return null } } open class EditHistoryItemModel class EditHistoryItem(val item: MwQueryPage.Revision) : EditHistoryItemModel() class EditHistorySeparator(val date: String) : EditHistoryItemModel() class EditHistoryStats(val revision: MwQueryPage.Revision, val metrics: List<Metrics.Results>, val allEdits: EditCount, val userEdits: EditCount, val anonEdits: EditCount, val botEdits: EditCount) : EditHistoryItemModel() class Factory(private val bundle: Bundle) : ViewModelProvider.Factory { @Suppress("unchecked_cast") override fun <T : ViewModel> create(modelClass: Class<T>): T { return EditHistoryListViewModel(bundle) as T } } companion object { const val SELECT_INACTIVE = 0 const val SELECT_NONE = 1 const val SELECT_FROM = 2 const val SELECT_TO = 3 } }
apache-2.0
cd9692041f9a7049807b6c6feca23bd6
40.371429
195
0.648135
4.908475
false
false
false
false
AlexLandau/semlang
kotlin/semlang-transforms/src/test/kotlin/preventDuplicateVariableNamesTest.kt
1
1888
package net.semlang.transforms.test import net.semlang.api.CURRENT_NATIVE_MODULE_VERSION import net.semlang.api.ModuleName import net.semlang.api.ValidatedModule import net.semlang.internal.test.getCompilableFilesWithAssociatedLibraries import net.semlang.internal.test.runAnnotationTests import net.semlang.parser.parseFile import net.semlang.parser.writeToString import net.semlang.transforms.preventDuplicateVariableNames import net.semlang.validator.validateModule import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import java.io.File @RunWith(Parameterized::class) class PreventDuplicateVariableNamesTest(private val file: File, private val libraries: List<ValidatedModule>) { companion object ParametersSource { @Parameterized.Parameters(name = "{0}") @JvmStatic fun data(): Collection<Array<Any?>> { return getCompilableFilesWithAssociatedLibraries() } } @Test fun testVariableRenaming() { val context = parseFile(file).assumeSuccess() val variablesRenamed = preventDuplicateVariableNames(context) val validated = validateModule(variablesRenamed, ModuleName("semlang", "testFile"), CURRENT_NATIVE_MODULE_VERSION, libraries).assumeSuccess() try { try { val testsRun = runAnnotationTests(validated) if (testsRun == 0 && file.name.contains("-corpus/")) { Assert.fail("Found no @Test annotations in corpus file $file") } } catch (e: AssertionError) { throw AssertionError("Transformed context was:\n" + writeToString(variablesRenamed), e) } } catch (e: RuntimeException) { throw RuntimeException("Transformed context was:\n" + writeToString(variablesRenamed), e) } } }
apache-2.0
53d4b1233561cbdc17a812c27edbff7a
38.333333
149
0.705508
4.661728
false
true
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/Transpose.kt
1
2880
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations import org.nd4j.autodiff.samediff.SDVariable import org.nd4j.autodiff.samediff.SameDiff import org.nd4j.autodiff.samediff.internal.SameDiffOp import org.nd4j.linalg.factory.Nd4j import org.nd4j.samediff.frameworkimport.ImportGraph import org.nd4j.samediff.frameworkimport.hooks.PreImportHook import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry import org.nd4j.shade.protobuf.GeneratedMessageV3 import org.nd4j.shade.protobuf.ProtocolMessageEnum /** * A port of cast.py from onnx tensorflow for samediff: * https://github.com/onnx/onnx-tensorflow/blob/master/onnx_tf/handlers/backend/cast.py * * @author Adam Gibson */ @PreHookRule(nodeNames = [],opNames = ["Transpose"],frameworkName = "onnx") class Transpose : PreImportHook { override fun doImport( sd: SameDiff, attributes: Map<String, Any>, outputNames: List<String>, op: SameDiffOp, mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>, importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>, dynamicVariables: Map<String, GeneratedMessageV3> ): Map<String, List<SDVariable>> { // Parameter docs below are from the onnx operator docs: // https://github.com/onnx/onnx/blob/master/docs/Operators.md#cast var inputVariable = sd.getVariable(op.inputsToOp[0]) val perm = attributes["perm"] as List<Long> val permInput = sd.constant(Nd4j.create(Nd4j.createBuffer(perm.toLongArray()))) val outputVar = sd.permute(outputNames[0],inputVariable,permInput) return mapOf(outputVar.name() to listOf(outputVar)) } }
apache-2.0
bd44b09f2e541e463290f79f031322f5
45.467742
184
0.709375
4.19214
false
false
false
false
hannesa2/owncloud-android
owncloudData/src/main/java/com/owncloud/android/data/folderbackup/db/FolderBackUpEntity.kt
2
1428
/** * ownCloud Android client application * * @author Abel García de Prada * Copyright (C) 2021 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.data.folderbackup.db import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.owncloud.android.data.ProviderMeta @Entity(tableName = ProviderMeta.ProviderTableMeta.FOLDER_BACKUP_TABLE_NAME) data class FolderBackUpEntity( val accountName: String, val behavior: String, val sourcePath: String, val uploadPath: String, val wifiOnly: Boolean, val chargingOnly: Boolean, @ColumnInfo(name = folderBackUpEntityNameField) val name: String, val lastSyncTimestamp: Long, ) { @PrimaryKey(autoGenerate = true) var id: Int = 0 companion object { internal const val folderBackUpEntityNameField = "name" } }
gpl-2.0
fcdffeea2de357538781823e66e0486b
32.97619
76
0.746321
4.197059
false
false
false
false
AndroidX/androidx
tv/tv-foundation/src/main/java/androidx/tv/foundation/lazy/grid/LazyMeasuredItemProvider.kt
3
2746
/* * 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.tv.foundation.lazy.grid import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.lazy.layout.LazyLayoutMeasureScope import androidx.compose.ui.layout.Placeable import androidx.compose.ui.unit.Constraints /** * Abstracts away the subcomposition from the measuring logic. */ @Suppress("IllegalExperimentalApiUsage") // TODO (b/233188423): Address before moving to beta @OptIn(ExperimentalFoundationApi::class) internal class LazyMeasuredItemProvider @ExperimentalFoundationApi constructor( private val itemProvider: LazyGridItemProvider, private val measureScope: LazyLayoutMeasureScope, private val defaultMainAxisSpacing: Int, private val measuredItemFactory: MeasuredItemFactory ) { /** * Used to subcompose individual items of lazy grids. Composed placeables will be measured * with the provided [constraints] and wrapped into [LazyMeasuredItem]. */ fun getAndMeasure( index: ItemIndex, mainAxisSpacing: Int = defaultMainAxisSpacing, constraints: Constraints ): LazyMeasuredItem { val key = itemProvider.getKey(index.value) val placeables = measureScope.measure(index.value, constraints) val crossAxisSize = if (constraints.hasFixedWidth) { constraints.minWidth } else { require(constraints.hasFixedHeight) constraints.minHeight } return measuredItemFactory.createItem( index, key, crossAxisSize, mainAxisSpacing, placeables ) } /** * Contains the mapping between the key and the index. It could contain not all the items of * the list as an optimization. **/ val keyToIndexMap: Map<Any, Int> get() = itemProvider.keyToIndexMap } // This interface allows to avoid autoboxing on index param internal fun interface MeasuredItemFactory { fun createItem( index: ItemIndex, key: Any, crossAxisSize: Int, mainAxisSpacing: Int, placeables: List<Placeable> ): LazyMeasuredItem }
apache-2.0
7dfdc962d6dbf9934ba1587e026cf605
34.662338
96
0.710852
4.868794
false
false
false
false
Dr-Horv/Advent-of-Code-2017
src/main/kotlin/solutions/day18/Day18.kt
1
3604
package solutions.day18 import solutions.Solver import utils.* import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingDeque import java.util.concurrent.TimeUnit class Program(number: Long, private val instructions: List<String>, private val sendQueue: BlockingQueue<Long>, private val receiveQueue: BlockingQueue<Long>): Runnable { private val registers = mutableMapOf(Pair("p", number)).withDefault { 0L } private var sent = 0 override fun run() { var index = 0L loop@ while (index < instructions.size) { val instruction = instructions[index.toInt()].splitAtWhitespace() when (instruction[0]) { "set" -> set(registers, instruction[1], instruction[2]) "add" -> add(registers, instruction[1], instruction[2]) "mul" -> mul(registers, instruction[1], instruction[2]) "mod" -> mod(registers, instruction[1], instruction[2]) "snd" -> { sendQueue.add(getValue(registers, instruction[1])) sent++ } "rcv" -> { val received = receiveQueue.poll(10, TimeUnit.SECONDS) ?: return registers.put(instruction[1], received) } "jgz" -> { if (getValue(registers, instruction[1]) > 0L) { index += getValue(registers, instruction[2]) continue@loop } } } index++ } } fun timesSent(): Int { return sent } } class Day18: Solver { override fun solve(input: List<String>, partTwo: Boolean): String { if(!partTwo) { return part1(input) } val q1 = LinkedBlockingDeque<Long>() val q2 = LinkedBlockingDeque<Long>() val p0 = Program(0, input, q1, q2) val p1 = Program(1, input, q2, q1) val t1 = Thread(p0) val t2 = Thread(p1) t1.start() t2.start() while (t1.isAlive && t2.isAlive) { Thread.sleep(1000L) } return p1.timesSent().toString() } private fun part1(input: List<String>): String { val registers = mutableMapOf<String, Long>().withDefault { 0L } val instructions = input var index = 0L var sound = -1L var recovered = -1L loop@ while (index < instructions.size) { val instruction = instructions[index.toInt()].splitAtWhitespace() when (instruction[0]) { "set" -> set(registers, instruction[1], instruction[2]) "add" -> add(registers, instruction[1], instruction[2]) "mul" -> mul(registers, instruction[1], instruction[2]) "mod" -> mod(registers, instruction[1], instruction[2]) "snd" -> { sound = getValue(registers, instruction[1]) } "rcv" -> { if (getValue(registers, instruction[1]) != 0L) { recovered = sound return recovered.toString() } } "jgz" -> { if (getValue(registers, instruction[1]) > 0L) { index += getValue(registers, instruction[2]) continue@loop } } } index++ } return "" } }
mit
90dd9e7b6f675ffdaabe666c6fa2c939
30.33913
84
0.495838
4.596939
false
false
false
false
tenebras/Spero
src/main/kotlin/com/tenebras/spero/route/Routes.kt
1
1708
package com.tenebras.spero.route import kotlin.reflect.KFunction class Routes { //(initializer: Routes.()->Route = {}) val routes: MutableList<Route> = mutableListOf() // init { add(initializer) } /* // infix fun String.by(x: (request: Request)->Response): Route { // val route = Route.fromString(this, x) // routes.add(route) // return route // } // infix fun List<String>.by(action: (request: Request)->Response): Route { // // val route = Route(this, action) // routes.add(route) // return route // } */ // infix fun String.by(x: KFunction<String>): Route { // val route = Route.fromString(this, x) // routes.add(route) // return route // } // infix fun String.with(x: KFunction<String>): Route { // val route = Route.fromString(this, x) // routes.add(route) // return route // } infix fun String.with(x: KFunction<Any>): Route { val route = Route.fromString(this, x) routes.add(route) return route } fun group(prefix: String, initializer: Routes.() -> Any): Route { return Route(emptyList(), "", ::String) } fun group(initializer: Routes.() -> Any): Route { return Route(emptyList(), "", ::String) } fun add(route: Route) = routes.add(route) fun add(initializer: Routes.() -> Any) = initializer.invoke(this) fun isEmpty(): Boolean = routes.size == 0 fun find(method: String, uri: String): Route { for (route in routes) { if (route.isSatisfied(method, uri)) { return route } } throw Exception("Route not found") } }
mit
d3177fc7b0e038b4ff7c923844735af7
24.893939
78
0.563817
3.753846
false
false
false
false
McGars/basekitk
basekitk/src/main/kotlin/com/mcgars/basekitk/tools/pagecontroller/Page.kt
1
791
package com.mcgars.basekitk.tools.pagecontroller /** * Created by Феофилактов on 16.07.2015. * Used from PageController * like * Page(key1 = "param1") * CustomFragment extend Fragment{} * equals * Bundle b = new Bundle() * b.putObject(key1(), val1); * b.putObject(key2(), val2); * controller.setArguments(b); * use instead of * public static CustomFragment newInstance(Object val1, Object val2){ * Bundle b = new Bundle() * b.putObject("param1", val1); * b.putObject("param2", val2); * controller = new CustomFragment(); * controller.setArguments(b); * return controller; * } */ @Target(AnnotationTarget.CLASS, AnnotationTarget.FILE) @kotlin.annotation.Retention() annotation class Page(val key1: String = "", val key2: String = "", val key3: String = "")
apache-2.0
d04508a6fad33f2fdb98cc9b14d20c35
25.896552
90
0.696154
3.362069
false
false
false
false
androidx/androidx
paging/paging-common/src/main/kotlin/androidx/paging/MutableCombinedLoadStateCollection.kt
3
5843
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.paging import androidx.paging.LoadState.Error import androidx.paging.LoadState.Loading import androidx.paging.LoadState.NotLoading import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.filterNotNull import java.util.concurrent.CopyOnWriteArrayList /** * Helper to construct [CombinedLoadStates] that accounts for previous state to set the convenience * properties correctly. * * This class exposes a [flow] and handles dispatches to tracked [listeners] intended for use * with presenter APIs, which has the nuance of filtering out the initial value and dispatching to * listeners immediately as they get added. */ internal class MutableCombinedLoadStateCollection { /** * Tracks whether this [MutableCombinedLoadStateCollection] has been updated with real state * or has just been instantiated with its initial values. */ private var isInitialized: Boolean = false private val listeners = CopyOnWriteArrayList<(CombinedLoadStates) -> Unit>() private var refresh: LoadState = NotLoading.Incomplete private var prepend: LoadState = NotLoading.Incomplete private var append: LoadState = NotLoading.Incomplete var source: LoadStates = LoadStates.IDLE private set var mediator: LoadStates? = null private set private val _stateFlow = MutableStateFlow<CombinedLoadStates?>(null) val flow: Flow<CombinedLoadStates> = _stateFlow.filterNotNull() fun set(sourceLoadStates: LoadStates, remoteLoadStates: LoadStates?) { isInitialized = true source = sourceLoadStates mediator = remoteLoadStates updateHelperStatesAndDispatch() } fun set(type: LoadType, remote: Boolean, state: LoadState): Boolean { isInitialized = true val didChange = if (remote) { val lastMediator = mediator mediator = (mediator ?: LoadStates.IDLE).modifyState(type, state) mediator != lastMediator } else { val lastSource = source source = source.modifyState(type, state) source != lastSource } updateHelperStatesAndDispatch() return didChange } fun get(type: LoadType, remote: Boolean): LoadState? { return (if (remote) mediator else source)?.get(type) } /** * When a new listener is added, it will be immediately called with the current [snapshot] * unless no state has been set yet, and thus has no valid state to emit. */ fun addListener(listener: (CombinedLoadStates) -> Unit) { // Note: Important to add the listener first before sending off events, in case the // callback triggers removal, which could lead to a leak if the listener is added // afterwards. listeners.add(listener) snapshot()?.also { listener(it) } } fun removeListener(listener: (CombinedLoadStates) -> Unit) { listeners.remove(listener) } private fun snapshot(): CombinedLoadStates? = when { !isInitialized -> null else -> CombinedLoadStates( refresh = refresh, prepend = prepend, append = append, source = source, mediator = mediator, ) } private fun updateHelperStatesAndDispatch() { refresh = computeHelperState( previousState = refresh, sourceRefreshState = source.refresh, sourceState = source.refresh, remoteState = mediator?.refresh ) prepend = computeHelperState( previousState = prepend, sourceRefreshState = source.refresh, sourceState = source.prepend, remoteState = mediator?.prepend ) append = computeHelperState( previousState = append, sourceRefreshState = source.refresh, sourceState = source.append, remoteState = mediator?.append ) val snapshot = snapshot() if (snapshot != null) { _stateFlow.value = snapshot listeners.forEach { it(snapshot) } } } /** * Computes the next value for the convenience helpers in [CombinedLoadStates], which * generally defers to remote state, but waits for both source and remote states to become * [NotLoading] before moving to that state. This provides a reasonable default for the common * use-case where you generally want to wait for both RemoteMediator to return and for the * update to get applied before signaling to UI that a network fetch has "finished". */ private fun computeHelperState( previousState: LoadState, sourceRefreshState: LoadState, sourceState: LoadState, remoteState: LoadState? ): LoadState { if (remoteState == null) return sourceState return when (previousState) { is Loading -> when { sourceRefreshState is NotLoading && remoteState is NotLoading -> remoteState remoteState is Error -> remoteState else -> previousState } else -> remoteState } } }
apache-2.0
bd888724edcbf6dc01dd0d82bf4a331f
35.748428
99
0.664042
5.03273
false
true
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/mcp/at/AtElementFactory.kt
1
4454
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ @file:Suppress("unused") // this file represents an API package com.demonwav.mcdev.platform.mcp.at import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtArgument import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtAsterisk import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtClassName import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtEntry import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtFieldName import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtFuncName import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtFunction import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtKeyword import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtReturnValue import com.demonwav.mcdev.platform.mcp.at.gen.psi.AtTypes import com.intellij.openapi.project.Project import com.intellij.psi.PsiComment import com.intellij.psi.PsiFileFactory object AtElementFactory { fun createFile(project: Project, text: String): AtFile { return PsiFileFactory.getInstance(project).createFileFromText("name", AtFileType, text) as AtFile } fun createArgument(project: Project, text: String): AtArgument { val line = "public c.c f($text)V" val file = createFile(project, line) return file.firstChild.node.findChildByType(AtTypes.FUNCTION)!! .findChildByType(AtTypes.ARGUMENT)!!.psi as AtArgument } fun createClassName(project: Project, name: String): AtClassName { val line = "public $name f(Z)V" val file = createFile(project, line) return file.firstChild.node.findChildByType(AtTypes.CLASS_NAME)!!.psi as AtClassName } fun createEntry(project: Project, entry: String): AtEntry { val file = createFile(project, entry) return file.firstChild as AtEntry } fun createFieldName(project: Project, name: String): AtFieldName { val line = "public c.c $name" val file = createFile(project, line) return file.firstChild.node.findChildByType(AtTypes.FIELD_NAME)!!.psi as AtFieldName } fun createFuncName(project: Project, name: String): AtFuncName { val line = "public c.c $name(Z)V" val file = createFile(project, line) return file.firstChild.node.findChildByType(AtTypes.FUNCTION)!! .findChildByType(AtTypes.FUNC_NAME)!!.psi as AtFuncName } fun createFunction(project: Project, function: String): AtFunction { val line = "public c.c $function" val file = createFile(project, line) return file.firstChild.node.findChildByType(AtTypes.FUNCTION)!!.psi as AtFunction } fun createAsterisk(project: Project): AtAsterisk { val line = "public c.c *" val file = createFile(project, line) return file.firstChild.node.findChildByType(AtTypes.FUNCTION)!! .findChildByType(AtTypes.ASTERISK)!!.psi as AtAsterisk } fun createKeyword(project: Project, keyword: Keyword): AtKeyword { val line = "${keyword.text} c.c f(Z)V" val file = createFile(project, line) return file.firstChild.node.findChildByType(AtTypes.KEYWORD)!!.psi as AtKeyword } fun createReturnValue(project: Project, returnValue: String): AtReturnValue { val line = "public c.c f(Z)$returnValue" val file = createFile(project, line) return file.firstChild.node.findChildByType(AtTypes.FUNCTION)!! .findChildByType(AtTypes.RETURN_VALUE)!!.psi as AtReturnValue } fun createComment(project: Project, comment: String): PsiComment { val line = "# $comment" val file = createFile(project, line) return file.node.findChildByType(AtTypes.COMMENT)!!.psi as PsiComment } enum class Keyword(val text: String) { PRIVATE("private"), PRIVATE_MINUS_F("private-f"), PRIVATE_PLUS_F("private+f"), PROTECTED("protected"), PROTECTED_MINUS_F("protected-f"), PROTECTED_PLUS_F("protected+f"), PUBLIC("public"), PUBLIC_MINUS_F("public-f"), PUBLIC_PLUS_F("public+f"), DEFAULT("default"), DEFAULT_MINUS_F("default-f"), DEFAULT_PLUS_F("default+f"); companion object { fun match(s: String) = values().firstOrNull { it.text == s } fun softMatch(s: String) = values().filter { it.text.contains(s) } } } }
mit
50227c392ec4e41b6f7ab77d7fa07b01
34.349206
105
0.678042
3.948582
false
false
false
false
qikh/kong-lang
src/main/kotlin/antlr/NodeValue.kt
1
2726
package antlr class NodeValue : Comparable<NodeValue> { private var value: Any? = null private constructor() { // private constructor: only used for NULL and VOID value = Any() } constructor(v: Any?) { if (v == null) { throw RuntimeException("v == null") } value = v // only accept boolean, list, number or string types if (!(isBoolean || isList || isNumber || isString)) { throw RuntimeException("invalid data type: " + v + " (" + v.javaClass + ")") } } fun asBoolean(): Boolean { return value as Boolean } fun asDouble(): Double { return (value as Number).toDouble() } fun asInt(): Int { return (value as Number).toInt() } fun asList(): MutableList<NodeValue> { return value as MutableList<NodeValue> } fun asString(): String { return value as String } //@Override override fun compareTo(that: NodeValue): Int { if (this.isNumber && that.isNumber) { if (this == that) { return 0 } else { return this.asDouble()!!.compareTo(that.asDouble()!!) } } else if (this.isString && that.isString) { return this.asString().compareTo(that.asString()) } else { throw RuntimeException("illegal expression: can't compare `" + this + "` to `" + that + "`") } } override fun equals(o: Any?): Boolean { if (this === VOID || o === VOID) { throw RuntimeException("can't use VOID: " + this + " ==/!= " + o) } if (this === o) { return true } if (o == null || this.javaClass != o.javaClass) { return false } val that = o as NodeValue? if (this.isNumber && that!!.isNumber) { val diff = Math.abs(this.asDouble()!! - that.asDouble()!!) return diff < 0.00000000001 } else { return this.value == that!!.value } } override fun hashCode(): Int { return value!!.hashCode() } val isBoolean: Boolean get() = value is Boolean val isNumber: Boolean get() = value is Number val isList: Boolean get() = value is List<*> val isNull: Boolean get() = this === NULL val isVoid: Boolean get() = this === VOID val isString: Boolean get() = value is String override fun toString(): String { return if (isNull) "NULL" else if (isVoid) "VOID" else value.toString() } companion object { val NULL = NodeValue() val VOID = NodeValue() } }
apache-2.0
a4b6cede775e32ed31cc475eee6b2a2d
24.240741
104
0.516508
4.52073
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/nbt/tags/TagList.kt
1
2349
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.tags import java.io.DataOutputStream import java.util.Objects class TagList(val type: NbtTypeId, val tags: List<NbtTag>) : NbtTag { // TAG_List has nameless tags, so we don't need to do anything for the names of tags override val payloadSize = 5 + tags.sumOf { it.payloadSize } override val typeId = NbtTypeId.LIST override fun write(stream: DataOutputStream) { stream.writeByte(type.typeIdByte.toInt()) stream.writeInt(tags.size) tags.forEach { it.write(stream) } } override fun equals(other: Any?): Boolean { if (other !is TagList) { return false } if (other === this) { return true } if (other.type != this.type) { return false } if (other.tags.size != this.tags.size) { return false } return (0 until this.tags.size).all { i -> other.tags[i] == this.tags[i] } } override fun hashCode() = Objects.hash(type, tags) override fun toString() = toString(StringBuilder(), 0, WriterState.COMPOUND).toString() override fun toString(sb: StringBuilder, indentLevel: Int, writerState: WriterState): StringBuilder { sb.append('[') if (tags.isEmpty()) { sb.append(']') return sb } val isCollection = when (type) { NbtTypeId.COMPOUND, NbtTypeId.LIST, NbtTypeId.BYTE_ARRAY, NbtTypeId.INT_ARRAY, NbtTypeId.LONG_ARRAY -> true else -> false } for (tag in tags) { if (isCollection) { sb.append('\n') indent(sb, indentLevel + 1) } else { sb.append(' ') } tag.toString(sb, indentLevel + 1, WriterState.LIST) sb.append(',') } if (isCollection) { sb.append('\n') indent(sb, indentLevel) sb.append(']') } else { sb.append(" ]") } return sb } override fun copy(): TagList { val newTags = ArrayList<NbtTag>(tags.size) tags.mapTo(newTags) { it.copy() } return TagList(type, newTags) } }
mit
20db3dc630aa7c99e80ae99543c68566
24.813187
119
0.549596
4.099476
false
false
false
false
wealthfront/magellan
magellan-lint/src/main/java/com/wealthfront/magellan/AvoidUsingActivity.kt
1
2091
package com.wealthfront.magellan import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.getContainingUClass internal val AVOID_USING_ACTIVITY = Issue.create( id = AvoidUsingActivity::class.simpleName!!, briefDescription = "Use the context provided in the lifecycle objects instead.", explanation = "Activity is available here only for use to set the title of the navigable.", category = Category.CORRECTNESS, priority = PRIORITY_MED, severity = Severity.WARNING, implementation = Implementation(AvoidUsingActivity::class.java, Scope.JAVA_FILE_SCOPE) ) private const val ACTIVITY = "android.app.Activity" private const val NAVIGABLE_COMPAT = "com.wealthfront.magellan.navigation.NavigableCompat" internal class AvoidUsingActivity : Detector(), Detector.UastScanner { override fun getApplicableUastTypes() = listOf(UCallExpression::class.java) override fun createUastHandler(context: JavaContext) = ActivityAccessChecker(context) class ActivityAccessChecker(private val context: JavaContext) : UElementHandler() { override fun visitCallExpression(node: UCallExpression) { if (node.isSubtypeOfNavigableCompat() && node.receiverType?.canonicalText == ACTIVITY) { context.report( AVOID_USING_ACTIVITY, node, context.getLocation(node), "Avoid using the activity instance present in the superclass. " + "Instead use the context provided in the lifecycle methods." ) } } } } private fun UCallExpression.isSubtypeOfNavigableCompat(): Boolean { return getContainingUClass()?.superTypes?.any { it.canonicalText == NAVIGABLE_COMPAT } ?: false }
apache-2.0
95a0eeab10e82818212a8147f4684f09
40
97
0.76901
4.467949
false
false
false
false
world-federation-of-advertisers/panel-exchange-client
src/test/kotlin/org/wfanet/panelmatch/client/exchangetasks/CopyFromSharedStorageTaskTest.kt
1
5530
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.panelmatch.client.exchangetasks import com.google.common.truth.Truth.assertThat import com.google.protobuf.ByteString import com.google.protobuf.kotlin.toByteStringUtf8 import kotlin.test.assertFails import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.measurement.api.v2alpha.ExchangeWorkflow.Step.CopyOptions.LabelType import org.wfanet.measurement.api.v2alpha.ExchangeWorkflow.Step.CopyOptions.LabelType.BLOB import org.wfanet.measurement.api.v2alpha.ExchangeWorkflow.Step.CopyOptions.LabelType.MANIFEST import org.wfanet.measurement.api.v2alpha.ExchangeWorkflowKt.StepKt.copyOptions import org.wfanet.measurement.storage.testing.InMemoryStorageClient import org.wfanet.panelmatch.client.storage.signatureBlobKeyFor import org.wfanet.panelmatch.client.storage.testing.makeTestSigningStorageClient import org.wfanet.panelmatch.client.storage.testing.makeTestVerifyingStorageClient import org.wfanet.panelmatch.common.storage.toByteString import org.wfanet.panelmatch.common.testing.runBlockingTest private const val SOURCE_BLOB_KEY = "source-blob-key" private const val DESTINATION_BLOB_KEY = "destination-blob-key" private val BLOB_CONTENTS = "some-blob-contents".toByteStringUtf8() private val MANIFEST_CONTENTS = "foo-?-of-2".toByteStringUtf8() private const val SHARD_BLOB_KEY1 = "foo-0-of-2" private const val SHARD_BLOB_KEY2 = "foo-1-of-2" private val SHARD_CONTENTS1 = "shard-1-contents".toByteStringUtf8() private val SHARD_CONTENTS2 = "shard-2-contents".toByteStringUtf8() @RunWith(JUnit4::class) class CopyFromSharedStorageTaskTest { private val underlyingSource = InMemoryStorageClient() private val signingStorage = makeTestSigningStorageClient(underlyingSource) private val source = makeTestVerifyingStorageClient(underlyingSource) private val destination = InMemoryStorageClient() private suspend fun executeTask(labelType: LabelType) { CopyFromSharedStorageTask( source, destination, copyOptions { this.labelType = labelType }, SOURCE_BLOB_KEY, DESTINATION_BLOB_KEY ) .execute() } private suspend fun addUnsignedSourceBlob(blobKey: String, contents: ByteString = BLOB_CONTENTS) { underlyingSource.writeBlob(blobKey, contents) } private suspend fun addSignedSourceBlob(blobKey: String, contents: ByteString = BLOB_CONTENTS) { signingStorage.writeBlob(blobKey, contents) } private val destinationByteStrings: List<Pair<String, ByteString>> get() = runBlocking { destination.contents.mapValues { it.value.toByteString() }.toList() } @Test fun singleFile() = runBlockingTest { addSignedSourceBlob(SOURCE_BLOB_KEY) executeTask(BLOB) val sourceBlob = source.getBlob(SOURCE_BLOB_KEY) assertThat(destinationByteStrings) .containsExactly( DESTINATION_BLOB_KEY to sourceBlob.toByteString(), signatureBlobKeyFor(DESTINATION_BLOB_KEY) to sourceBlob.signature ) } @Test fun manifest() = runBlockingTest { addSignedSourceBlob(SOURCE_BLOB_KEY, MANIFEST_CONTENTS) addSignedSourceBlob(SHARD_BLOB_KEY1, SHARD_CONTENTS1) addSignedSourceBlob(SHARD_BLOB_KEY2, SHARD_CONTENTS2) executeTask(MANIFEST) assertThat(destinationByteStrings) .containsExactly( DESTINATION_BLOB_KEY to MANIFEST_CONTENTS, signatureBlobKeyFor(DESTINATION_BLOB_KEY) to source.getBlob(SOURCE_BLOB_KEY).signature, SHARD_BLOB_KEY1 to SHARD_CONTENTS1, signatureBlobKeyFor(SHARD_BLOB_KEY1) to source.getBlob(SHARD_BLOB_KEY1).signature, SHARD_BLOB_KEY2 to SHARD_CONTENTS2, signatureBlobKeyFor(SHARD_BLOB_KEY2) to source.getBlob(SHARD_BLOB_KEY2).signature ) } @Test fun missingFiles() = runBlockingTest { assertFails { executeTask(BLOB) } assertFails { executeTask(MANIFEST) } } @Test fun missingSignature() = runBlockingTest { addUnsignedSourceBlob(SOURCE_BLOB_KEY) assertFails { executeTask(BLOB) } } @Test fun missingManifestSignature() = runBlockingTest { addUnsignedSourceBlob(SOURCE_BLOB_KEY, MANIFEST_CONTENTS) addSignedSourceBlob(SHARD_BLOB_KEY1) addSignedSourceBlob(SHARD_BLOB_KEY2) assertFails { executeTask(MANIFEST) } } @Test fun missingManifestFileSignature() = runBlockingTest { addSignedSourceBlob(SOURCE_BLOB_KEY, MANIFEST_CONTENTS) addSignedSourceBlob(SHARD_BLOB_KEY1) addUnsignedSourceBlob(SHARD_BLOB_KEY2) assertFails { executeTask(MANIFEST) } } @Test fun missingManifestFile() = runBlockingTest { addSignedSourceBlob(SOURCE_BLOB_KEY, MANIFEST_CONTENTS) addSignedSourceBlob(SHARD_BLOB_KEY1) assertFails { executeTask(MANIFEST) } } @Test fun nonManifestContents() = runBlockingTest { addSignedSourceBlob(SOURCE_BLOB_KEY, BLOB_CONTENTS) assertFails { executeTask(MANIFEST) } } }
apache-2.0
c1f6051bfceb2ffd4961145c7800743e
35.866667
100
0.767631
4.033552
false
true
false
false
pbauerochse/youtrack-worklog-viewer
application/src/main/java/de/pbauerochse/worklogviewer/fx/components/plugins/PluginMenu.kt
1
2260
package de.pbauerochse.worklogviewer.fx.components.plugins import de.pbauerochse.worklogviewer.fx.dialog.Dialog import de.pbauerochse.worklogviewer.plugins.WorklogViewerPlugin import de.pbauerochse.worklogviewer.plugins.actions.PluginActionContext import de.pbauerochse.worklogviewer.plugins.actions.PluginMenuItem import de.pbauerochse.worklogviewer.plugins.dialog.DialogSpecification import de.pbauerochse.worklogviewer.util.FormattingUtil import javafx.event.EventHandler import javafx.scene.control.Menu import javafx.scene.control.MenuItem import javafx.scene.control.SeparatorMenuItem import org.slf4j.LoggerFactory /** * The plugin menu submenu for the given plugin. Contains at least * a single MenuItem, that show details about the plugin in a popup. * * Will also contain all MenuItems for each [WorklogViewerPlugin.menuItems] */ class PluginMenu(private val plugin: WorklogViewerPlugin, private val pluginContextFactory: () -> PluginActionContext) : Menu(plugin.name) { init { addPluginActions() addInfoAction() } private fun addPluginActions() { plugin.menuItems.forEach { pluginMenuItem -> val menuItem = MenuItem(pluginMenuItem.name) menuItem.onAction = EventHandler { triggerMenuItemAction(pluginMenuItem) } items.add(menuItem) } } private fun addInfoAction() { if (plugin.menuItems.isNotEmpty()) { items.add(SeparatorMenuItem()) } val pluginInfoMenuItem = MenuItem(FormattingUtil.getFormatted("plugins.info")) pluginInfoMenuItem.onAction = EventHandler { showPluginInfoPopup() } items.add(pluginInfoMenuItem) } private fun triggerMenuItemAction(pluginMenuItem: PluginMenuItem) { LOGGER.debug("Plugin Action triggered: ${plugin.name} -> ${pluginMenuItem.name}") pluginMenuItem.actionHandler.onAction(pluginContextFactory.invoke()) } private fun showPluginInfoPopup() { LOGGER.info("Showing Plugin Popup for ${plugin.name}") Dialog(parentPopup.scene).openDialog(PluginDetailPopupContent(plugin), DialogSpecification(plugin.name)) } companion object { private val LOGGER = LoggerFactory.getLogger(PluginMenu::class.java) } }
mit
4e23a8a03405eef94f6a7867ab6bc096
36.683333
140
0.74292
4.659794
false
false
false
false
raxden/square
square-commons/src/main/java/com/raxdenstudios/square/interceptor/commons/autoinflatelayout/AutoInflateLayoutActivityInterceptor.kt
2
1821
package com.raxdenstudios.square.interceptor.commons.autoinflatelayout import android.app.Activity import android.content.Context import android.os.Bundle import android.view.View import com.raxdenstudios.square.interceptor.ActivityInterceptor /** * Created by Ángel Gómez on 22/05/2015. */ class AutoInflateLayoutActivityInterceptor( callback: HasAutoInflateLayoutInterceptor ) : ActivityInterceptor<AutoInflateLayoutInterceptor, HasAutoInflateLayoutInterceptor>(callback), AutoInflateLayoutInterceptor { private var mLayoutId: Int = 0 override fun setLayoutId(layoutId: Int) { mLayoutId = layoutId } override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { super.onActivityCreated(activity, savedInstanceState) onCreateView(activity)?.let { view -> activity.setContentView(view) mCallback.onContentViewCreated(view) } } private fun onCreateView(activity: Activity): View? = when { mLayoutId != 0 -> activity.layoutInflater.inflate(mLayoutId, null) else -> { getLayoutId(activity, getLayoutName(activity)).let { layoutId -> if (layoutId != 0) activity.layoutInflater.inflate(layoutId, null) else null } } } private fun getLayoutName(activity: Activity): String { return activity.javaClass.simpleName .decapitalize() .split("(?=\\p{Upper})".toRegex()) .joinToString(separator = "_") .toLowerCase() } private fun getLayoutId(context: Context, name: String?): Int = name?.takeIf { it.isNotEmpty() }?.let { context.resources.getIdentifier(it.replace("R.layout.", ""), "layout", context.packageName) } ?: 0 }
apache-2.0
99ba550b6055c4c960127694cce5128d
32.072727
107
0.664651
4.929539
false
false
false
false
Gnar-Team/Gnar-bot
src/main/kotlin/xyz/gnarbot/gnar/music/MusicManager.kt
1
12038
package xyz.gnarbot.gnar.music import com.sedmelluq.discord.lavaplayer.filter.equalizer.EqualizerFactory import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler import com.sedmelluq.discord.lavaplayer.player.AudioPlayer import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager import com.sedmelluq.discord.lavaplayer.source.bandcamp.BandcampAudioSourceManager import com.sedmelluq.discord.lavaplayer.source.beam.BeamAudioSourceManager import com.sedmelluq.discord.lavaplayer.source.beam.BeamAudioTrack import com.sedmelluq.discord.lavaplayer.source.twitch.TwitchStreamAudioSourceManager import com.sedmelluq.discord.lavaplayer.source.twitch.TwitchStreamAudioTrack import com.sedmelluq.discord.lavaplayer.source.vimeo.VimeoAudioSourceManager import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager import com.sedmelluq.discord.lavaplayer.tools.FriendlyException import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist import com.sedmelluq.discord.lavaplayer.track.AudioTrack import com.sedmelluq.lava.extensions.youtuberotator.YoutubeIpRotatorSetup import com.sedmelluq.lava.extensions.youtuberotator.planner.AbstractRoutePlanner import com.sedmelluq.lava.extensions.youtuberotator.planner.RotatingNanoIpRoutePlanner import com.sedmelluq.lava.extensions.youtuberotator.tools.ip.IpBlock import com.sedmelluq.lava.extensions.youtuberotator.tools.ip.Ipv6Block import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.Guild import net.dv8tion.jda.api.entities.TextChannel import net.dv8tion.jda.api.entities.VoiceChannel import xyz.gnarbot.gnar.Bot import xyz.gnarbot.gnar.Configuration import xyz.gnarbot.gnar.commands.Context import xyz.gnarbot.gnar.commands.music.embedTitle import xyz.gnarbot.gnar.utils.response.respond import java.net.Inet6Address import java.net.InetAddress import java.util.* import java.util.concurrent.Future import java.util.concurrent.TimeUnit class MusicManager(val bot: Bot, val guild: Guild, val playerRegistry: PlayerRegistry, val playerManager: AudioPlayerManager) { fun search(query: String, maxResults: Int = -1, callback: (results: List<AudioTrack>) -> Unit) { playerManager.loadItem(query, object : AudioLoadResultHandler { override fun trackLoaded(track: AudioTrack) { callback(listOf(track)) } override fun playlistLoaded(playlist: AudioPlaylist) { if (!playlist.isSearchResult) { return } if (maxResults == -1) { callback(playlist.tracks) } else { callback(playlist.tracks.subList(0, maxResults.coerceAtMost(playlist.tracks.size))) } } override fun noMatches() { callback(emptyList()) } override fun loadFailed(e: FriendlyException) { callback(emptyList()) } }) } @Volatile private var leaveTask: Future<*>? = null private var equalizer: EqualizerFactory = EqualizerFactory() private var equalizerEnabled = false /** @return Audio player for the guild. */ val player: AudioPlayer = playerManager.createPlayer().also { it.volume = bot.options.ofGuild(guild).music.volume } /** @return Track scheduler for the player.*/ val scheduler: TrackScheduler = TrackScheduler(bot, this, player).also(player::addListener) /** @return Wrapper around AudioPlayer to use it as an AudioSendHandler. */ private val sendHandler: AudioPlayerSendHandler = AudioPlayerSendHandler(player) /** * @return Voting cooldown. */ var lastVoteTime: Long = 0L /** * @return Whether there is a vote to skip the song or not. */ var isVotingToSkip = false val currentRequestChannel: TextChannel? get() { return (player.playingTrack ?: scheduler.lastTrack) ?.getUserData(TrackContext::class.java) ?.requestedChannel ?.let(guild::getTextChannelById) } /** * @return If the user is listening to DiscordFM */ var discordFMTrack: DiscordFMTrackContext? = null fun destroy() { player.destroy() disableBass() closeAudioConnection() } fun openAudioConnection(channel: VoiceChannel, context: Context): Boolean { when { !bot.configuration.musicEnabled -> { context.send().error("Music is disabled.").queue() playerRegistry.destroy(guild) return false } !guild.selfMember.hasPermission(channel, Permission.VOICE_CONNECT) -> { context.send().error("The bot can't connect to this channel due to a lack of permission.").queue() playerRegistry.destroy(guild) return false } channel.userLimit != 0 && guild.selfMember.hasPermission(channel, Permission.VOICE_MOVE_OTHERS) && channel.members.size >= channel.userLimit -> { context.send().error("The bot can't join due to the user limit.").queue() playerRegistry.destroy(guild) return false } else -> { guild.audioManager.sendingHandler = sendHandler guild.audioManager.openAudioConnection(channel) context.send().embed("Music Playback") { desc { "Joining channel `${channel.name}`." } }.action().queue() return true } } } fun moveAudioConnection(channel: VoiceChannel) { guild.let { if (!guild.selfMember.voiceState!!.inVoiceChannel()) { throw IllegalStateException("Bot is not in a voice channel") } if (!guild.selfMember.hasPermission(channel, Permission.VOICE_CONNECT)) { currentRequestChannel?.respond()?.error("I don't have permission to join `${channel.name}`.")?.queue() playerRegistry.destroy(guild) return } player.isPaused = true it.audioManager.openAudioConnection(channel) player.isPaused = false currentRequestChannel?.respond()?.embed("Music Playback") { desc { "Moving to channel `${channel.name}`." } }?.action()?.queue() } } fun closeAudioConnection() { guild.let { it.audioManager.closeAudioConnection() it.audioManager.sendingHandler = null } } fun isAlone(): Boolean { return guild.selfMember.voiceState!!.channel?.members?.let { it.size == 1 && it[0] == guild.selfMember } != false } fun queueLeave() { leaveTask?.cancel(false) leaveTask = createLeaveTask() player.isPaused = true } fun cancelLeave() { leaveTask?.cancel(false) leaveTask = null player.isPaused = false } private fun createLeaveTask() = playerRegistry.executor.schedule({ playerRegistry.destroy(guild) }, 30, TimeUnit.SECONDS) fun loadAndPlay(context: Context, trackUrl: String, trackContext: TrackContext, footnote: String? = null) { playerManager.loadItemOrdered(this, trackUrl, object : AudioLoadResultHandler { override fun trackLoaded(track: AudioTrack) { if (!guild.selfMember.voiceState!!.inVoiceChannel()) { if (!openAudioConnection(context.voiceChannel, context)) { return } } if (scheduler.queue.size >= bot.configuration.queueLimit) { context.send().error("The queue can not exceed ${bot.configuration.queueLimit} songs.").queue() return } if (track !is TwitchStreamAudioTrack && track !is BeamAudioTrack) { if (track.duration > bot.configuration.durationLimit.toMillis()) { context.send().error("The track can not exceed ${bot.configuration.durationLimitText}.").queue() return } } track.userData = trackContext scheduler.queue(track) context.send().embed("Music Queue") { desc { "Added __**[${track.info.embedTitle}](${track.info.uri})**__ to queue." } footer { footnote } }.action().queue() } override fun playlistLoaded(playlist: AudioPlaylist) { if (playlist.isSearchResult) { trackLoaded(playlist.tracks.first()) return } if (!guild.selfMember.voiceState!!.inVoiceChannel()) { if (!context.member.voiceState!!.inVoiceChannel()) { context.send().error("You left the channel before the track is loaded.").queue() // Track is not supposed to load and the queue is empty // destroy player if (scheduler.queue.isEmpty()) { playerRegistry.destroy(guild) } return } if (!openAudioConnection(context.voiceChannel, context)) { return } } val tracks = playlist.tracks var ignored = 0 var added = 0 for (track in tracks) { if (scheduler.queue.size + 1 >= bot.configuration.queueLimit) { ignored = tracks.size - added break } track.userData = trackContext scheduler.queue(track) added++ } context.send().embed("Music Queue") { desc { buildString { append("Added `$added` tracks to queue from playlist `${playlist.name}`.\n") if (ignored > 0) { append("Ignored `$ignored` songs as the queue can not exceed `${bot.configuration.queueLimit}` songs.") } } } footer { footnote } }.action().queue() } override fun noMatches() { // No track found and queue is empty // destroy player if (scheduler.queue.isEmpty()) { playerRegistry.destroy(guild) } context.send().error("Nothing found by `$trackUrl`.").queue() } override fun loadFailed(e: FriendlyException) { // No track found and queue is empty // destroy player if (e.message!!.contains("decoding")) { return } if (scheduler.queue.isEmpty()) { playerRegistry.destroy(guild) } context.send().exception(e).queue() } }) } //Credit to JukeBot and CircuitCRay fun boostBass(b1: Float, b2: Float) { equalizer.setGain(0, b1) equalizer.setGain(1, b2) if (!equalizerEnabled) { player.setFilterFactory(equalizer) equalizerEnabled = true } } fun disableBass() { if (equalizerEnabled) { equalizer.setGain(0, 0F) equalizer.setGain(1, 0F) player.setFilterFactory(null) equalizerEnabled = false } } }
mit
8e440b12c87dca0e775cb0a7053deeb9
36.26935
135
0.57684
5.024207
false
false
false
false
steck/kpoc
src/main/kotlin/com/steckinc/services/DataService.kt
1
1011
package com.steckinc.services import com.steckinc.dtos.PostDto import com.steckinc.entity.Comment import com.steckinc.entity.CommentRepository import com.steckinc.entity.Post import com.steckinc.entity.PostRepository import org.springframework.stereotype.Service @Service class DataService(val postRepository: PostRepository) { fun loadAllPost() : List<PostDto>{ return postRepository.findAll().map { PostDto.fromPost(it) } } fun loadWithComment(id: Long) : PostDto{ return PostDto.fromPost(postRepository.findOneWithDependencies(id)) } fun addComment(id: Long, text: String) : PostDto{ val post = postRepository.findOneWithDependencies(id) post.comments.add(Comment(body = text, post = post)) return PostDto.fromPost(postRepository.save(post)) } fun newPost(header: String, body: String): Long { val post = Post(header = header, body = body) val savedPost = postRepository.save(post) return savedPost.id } }
mit
b78cd2eaf9cd235c6d8d12f68b7579d4
31.645161
76
0.71909
3.858779
false
false
false
false
inorichi/tachiyomi-extensions
src/ru/remanga/src/eu/kanade/tachiyomi/extension/ru/remanga/Remanga.kt
1
27701
package eu.kanade.tachiyomi.extension.ru.remanga import BookDto import BranchesDto import GenresDto import LibraryDto import MangaDetDto import PageDto import PageWrapperDto import PaidPageDto import SeriesWrapperDto import UserDto import android.annotation.SuppressLint import android.annotation.TargetApi import android.app.Application import android.content.SharedPreferences import android.os.Build import android.text.InputType import android.widget.Toast import eu.kanade.tachiyomi.lib.dataimage.DataImageInterceptor import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.network.asObservable import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.source.ConfigurableSource import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.HttpSource import kotlinx.serialization.SerializationException import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.decodeFromJsonElement import kotlinx.serialization.json.put import okhttp3.Headers import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.Interceptor import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import org.jsoup.Jsoup import rx.Observable import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import uy.kohesive.injekt.injectLazy import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import kotlin.math.absoluteValue import kotlin.random.Random class Remanga : ConfigurableSource, HttpSource() { override val name = "Remanga" override val baseUrl = "https://api.remanga.org" override val lang = "ru" override val supportsLatest = true private var token: String = "" protected open val userAgentRandomizer = " ${Random.nextInt().absoluteValue}" override fun headersBuilder(): Headers.Builder = Headers.Builder() .add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/78.0$userAgentRandomizer") .add("Referer", "https://www.google.com") private val preferences: SharedPreferences by lazy { Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000) } private fun authIntercept(chain: Interceptor.Chain): Response { val request = chain.request() if (username.isEmpty() or password.isEmpty()) { return chain.proceed(request) } if (token.isEmpty()) { token = this.login(chain, username, password) } val authRequest = request.newBuilder() .addHeader("Authorization", "bearer $token") .build() return chain.proceed(authRequest) } override val client: OkHttpClient = network.client.newBuilder() .addInterceptor(DataImageInterceptor()) .addInterceptor { authIntercept(it) } .build() private val count = 30 private var branches = mutableMapOf<String, List<BranchesDto>>() private fun login(chain: Interceptor.Chain, username: String, password: String): String { val jsonObject = buildJsonObject { put("user", username) put("password", password) } val body = jsonObject.toString().toRequestBody(MEDIA_TYPE) val response = chain.proceed(POST("$baseUrl/api/users/login/", headers, body)) if (response.code >= 400) { throw Exception("Failed to login") } val user = json.decodeFromString<SeriesWrapperDto<UserDto>>(response.body!!.string()) return user.content.access_token } override fun popularMangaRequest(page: Int) = GET("$baseUrl/api/search/catalog/?ordering=-rating&count=$count&page=$page", headers) override fun popularMangaParse(response: Response): MangasPage = searchMangaParse(response) override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/api/titles/last-chapters/?page=$page&count=$count", headers) override fun latestUpdatesParse(response: Response): MangasPage = searchMangaParse(response) override fun searchMangaParse(response: Response): MangasPage { val page = json.decodeFromString<PageWrapperDto<LibraryDto>>(response.body!!.string()) val mangas = page.content.map { it.toSManga() } return MangasPage(mangas, page.props.page < page.props.total_pages) } private fun LibraryDto.toSManga(): SManga = SManga.create().apply { // Do not change the title name to ensure work with a multilingual catalog! title = en_name url = "/api/titles/$dir/" thumbnail_url = if (img.high.isNotEmpty()) { "$baseUrl/${img.high}" } else "$baseUrl/${img.mid}" } private val simpleDateFormat by lazy { SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US) } private fun parseDate(date: String?): Long { date ?: return Date().time return try { simpleDateFormat.parse(date)!!.time } catch (_: Exception) { Date().time } } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { var url = "$baseUrl/api/search/catalog/?page=$page".toHttpUrlOrNull()!!.newBuilder() if (query.isNotEmpty()) { url = "$baseUrl/api/search/?page=$page".toHttpUrlOrNull()!!.newBuilder() url.addQueryParameter("query", query) } (if (filters.isEmpty()) getFilterList() else filters).forEach { filter -> when (filter) { is OrderBy -> { val ord = arrayOf("id", "chapter_date", "rating", "votes", "views", "count_chapters", "random")[filter.state!!.index] url.addQueryParameter("ordering", if (filter.state!!.ascending) ord else "-$ord") } is CategoryList -> filter.state.forEach { category -> if (category.state != Filter.TriState.STATE_IGNORE) { url.addQueryParameter(if (category.isIncluded()) "categories" else "exclude_categories", category.id) } } is TypeList -> filter.state.forEach { type -> if (type.state != Filter.TriState.STATE_IGNORE) { url.addQueryParameter(if (type.isIncluded()) "types" else "exclude_types", type.id) } } is StatusList -> filter.state.forEach { status -> if (status.state) { url.addQueryParameter("status", status.id) } } is AgeList -> filter.state.forEach { age -> if (age.state) { url.addQueryParameter("age_limit", age.id) } } is GenreList -> filter.state.forEach { genre -> if (genre.state != Filter.TriState.STATE_IGNORE) { url.addQueryParameter(if (genre.isIncluded()) "genres" else "exclude_genres", genre.id) } } } } return GET(url.toString(), headers) } private fun parseStatus(status: Int): Int { return when (status) { 0 -> SManga.COMPLETED 1 -> SManga.ONGOING 2 -> SManga.ONGOING 3 -> SManga.ONGOING 5 -> SManga.LICENSED else -> SManga.UNKNOWN } } private fun parseType(type: GenresDto): GenresDto { return when (type.name) { "Западный комикс" -> GenresDto(type.id, "Комикс") else -> type } } private fun parseAge(age_limit: Int): String { return when (age_limit) { 2 -> "18+" 1 -> "16+" else -> "0+" } } private fun MangaDetDto.toSManga(): SManga { val ratingValue = avg_rating.toFloat() val ratingStar = when { ratingValue > 9.5 -> "★★★★★" ratingValue > 8.5 -> "★★★★✬" ratingValue > 7.5 -> "★★★★☆" ratingValue > 6.5 -> "★★★✬☆" ratingValue > 5.5 -> "★★★☆☆" ratingValue > 4.5 -> "★★✬☆☆" ratingValue > 3.5 -> "★★☆☆☆" ratingValue > 2.5 -> "★✬☆☆☆" ratingValue > 1.5 -> "★☆☆☆☆" ratingValue > 0.5 -> "✬☆☆☆☆" else -> "☆☆☆☆☆" } val o = this return SManga.create().apply { // Do not change the title name to ensure work with a multilingual catalog! title = en_name url = "/api/titles/$dir/" thumbnail_url = "$baseUrl/${img.high}" var altName = "" if (another_name.isNotEmpty()) { altName = "Альтернативные названия:\n" + another_name + "\n\n" } this.description = rus_name + "\n" + ratingStar + " " + ratingValue + " (голосов: " + count_rating + ")\n" + altName + Jsoup.parse(o.description).text() genre = (genres + parseType(type)).joinToString { it.name } + ", " + parseAge(age_limit) status = parseStatus(o.status.id) } } private fun titleDetailsRequest(manga: SManga): Request { val titleId = manga.url val newHeaders = headersBuilder().build() return GET("$baseUrl/$titleId", newHeaders) } // Workaround to allow "Open in browser" use the real URL. override fun fetchMangaDetails(manga: SManga): Observable<SManga> { var warnLogin = false return client.newCall(titleDetailsRequest(manga)) .asObservable().doOnNext { response -> if (!response.isSuccessful) { response.close() if (response.code == 401) warnLogin = true else throw Exception("HTTP error ${response.code}") } } .map { response -> (if (warnLogin) manga.apply { description = "Авторизуйтесь для просмотра списка глав" } else mangaDetailsParse(response)) .apply { initialized = true } } } override fun mangaDetailsRequest(manga: SManga): Request { return GET(baseUrl.replace("api.", "") + "/manga/" + manga.url.substringAfter("/api/titles/", "/"), headers) } override fun mangaDetailsParse(response: Response): SManga { val series = json.decodeFromString<SeriesWrapperDto<MangaDetDto>>(response.body!!.string()) branches[series.content.en_name] = series.content.branches return series.content.toSManga() } private fun mangaBranches(manga: SManga): List<BranchesDto> { val responseString = client.newCall(GET("$baseUrl/${manga.url}")).execute().body?.string() ?: return emptyList() // manga requiring login return "content" as a JsonArray instead of the JsonObject we expect val content = json.decodeFromString<JsonObject>(responseString)["content"] return if (content is JsonObject) { val series = json.decodeFromJsonElement<MangaDetDto>(content) branches[series.en_name] = series.branches series.branches } else { emptyList() } } private fun selector(b: BranchesDto): Int = b.count_chapters override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> { val branch = branches.getOrElse(manga.title) { mangaBranches(manga) } return when { branch.isEmpty() -> { return Observable.just(listOf()) } manga.status == SManga.LICENSED -> { Observable.error(Exception("Licensed - No chapters to show")) } else -> { val branchId = branch.maxByOrNull { selector(it) }!!.id client.newCall(chapterListRequest(branchId)) .asObservableSuccess() .map { response -> chapterListParse(response) } } } } private fun chapterListRequest(branch: Long): Request { return GET("$baseUrl/api/titles/chapters/?branch_id=$branch", headers) } @SuppressLint("DefaultLocale") private fun chapterName(book: BookDto): String { var chapterName = "${book.tome}. Глава ${book.chapter}" if (book.name.isNotBlank()) { chapterName += " ${book.name.capitalize()}" } return chapterName } override fun chapterListParse(response: Response): List<SChapter> { val chapters = json.decodeFromString<SeriesWrapperDto<List<BookDto>>>(response.body!!.string()) return chapters.content.filter { !it.is_paid or (it.is_bought == true) }.map { chapter -> SChapter.create().apply { chapter_number = chapter.chapter.split(".").take(2).joinToString(".").toFloat() name = chapterName(chapter) url = "/api/titles/chapters/${chapter.id}" date_upload = parseDate(chapter.upload_date) scanlator = if (chapter.publishers.isNotEmpty()) { chapter.publishers.joinToString { it.name } } else null } } } @TargetApi(Build.VERSION_CODES.N) override fun pageListParse(response: Response): List<Page> { val body = response.body?.string()!! return try { val page = json.decodeFromString<SeriesWrapperDto<PageDto>>(body) page.content.pages.filter { it.height > 1 }.map { Page(it.page, "", it.link) } } catch (e: SerializationException) { val page = json.decodeFromString<SeriesWrapperDto<PaidPageDto>>(body) val result = mutableListOf<Page>() page.content.pages.forEach { it.filter { page -> page.height > 10 }.forEach { page -> result.add(Page(result.size, "", page.link)) } } return result } } override fun fetchImageUrl(page: Page): Observable<String> = Observable.just(page.imageUrl!!) override fun imageUrlRequest(page: Page): Request = throw NotImplementedError("Unused") override fun imageUrlParse(response: Response): String = throw NotImplementedError("Unused") private fun searchMangaByIdRequest(id: String): Request { return GET("$baseUrl/api/titles/$id", headers) } override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> { return if (query.startsWith(PREFIX_SLUG_SEARCH)) { val realQuery = query.removePrefix(PREFIX_SLUG_SEARCH) client.newCall(searchMangaByIdRequest(realQuery)) .asObservableSuccess() .map { response -> val details = mangaDetailsParse(response) details.url = "/api/titles/$realQuery" MangasPage(listOf(details), false) } } else { client.newCall(searchMangaRequest(page, query, filters)) .asObservableSuccess() .map { response -> searchMangaParse(response) } } } override fun imageRequest(page: Page): Request { val refererHeaders = headersBuilder().build() return GET(page.imageUrl!!, refererHeaders) } private class SearchFilter(name: String, val id: String) : Filter.TriState(name) private class CheckFilter(name: String, val id: String) : Filter.CheckBox(name) private class CategoryList(categories: List<SearchFilter>) : Filter.Group<SearchFilter>("Категории", categories) private class TypeList(types: List<SearchFilter>) : Filter.Group<SearchFilter>("Типы", types) private class StatusList(statuses: List<CheckFilter>) : Filter.Group<CheckFilter>("Статус", statuses) private class GenreList(genres: List<SearchFilter>) : Filter.Group<SearchFilter>("Жанры", genres) private class AgeList(ages: List<CheckFilter>) : Filter.Group<CheckFilter>("Возрастное ограничение", ages) override fun getFilterList() = FilterList( OrderBy(), GenreList(getGenreList()), CategoryList(getCategoryList()), TypeList(getTypeList()), StatusList(getStatusList()), AgeList(getAgeList()) ) private class OrderBy : Filter.Sort( "Сортировка", arrayOf("Новизне", "Последним обновлениям", "Популярности", "Лайкам", "Просмотрам", "По кол-ву глав", "Мне повезет"), Selection(2, false) ) private fun getAgeList() = listOf( CheckFilter("Для всех", "0"), CheckFilter("16+", "1"), CheckFilter("18+", "2") ) private fun getTypeList() = listOf( SearchFilter("Манга", "0"), SearchFilter("Манхва", "1"), SearchFilter("Маньхуа", "2"), SearchFilter("Западный комикс", "3"), SearchFilter("Русскомикс", "4"), SearchFilter("Индонезийский комикс", "5"), SearchFilter("Новелла", "6"), SearchFilter("Другое", "7") ) private fun getStatusList() = listOf( CheckFilter("Закончен", "0"), CheckFilter("Продолжается", "1"), CheckFilter("Заморожен", "2"), CheckFilter("Нет переводчика", "3"), CheckFilter("Анонс", "4"), CheckFilter("Лицензировано", "5") ) private fun getCategoryList() = listOf( SearchFilter("алхимия", "47"), SearchFilter("ангелы", "48"), SearchFilter("антигерой", "26"), SearchFilter("антиутопия", "49"), SearchFilter("апокалипсис", "50"), SearchFilter("аристократия", "117"), SearchFilter("армия", "51"), SearchFilter("артефакты", "52"), SearchFilter("боги", "45"), SearchFilter("борьба за власть", "52"), SearchFilter("будущее", "55"), SearchFilter("в цвете", "6"), SearchFilter("вампиры", "112"), SearchFilter("веб", "5"), SearchFilter("вестерн", "56"), SearchFilter("видеоигры", "35"), SearchFilter("виртуальная реальность", "44"), SearchFilter("владыка демонов", "57"), SearchFilter("военные", "29"), SearchFilter("волшебные существа", "59"), SearchFilter("воспоминания из другого мира", "60"), SearchFilter("врачи / доктора", "116"), SearchFilter("выживание", "41"), SearchFilter("гг женщина", "63"), SearchFilter("гг мужчина", "64"), SearchFilter("гг силён с самого начала", "110"), SearchFilter("геймеры", "61"), SearchFilter("гильдии", "62"), SearchFilter("гяру", "28"), SearchFilter("девушки-монстры", "37"), SearchFilter("демоны", "15"), SearchFilter("драконы", "66"), SearchFilter("дружба", "67"), SearchFilter("ёнкома", "62"), SearchFilter("жестокий мир", "69"), SearchFilter("животные компаньоны", "70"), SearchFilter("завоевание мира", "71"), SearchFilter("зверолюди", "19"), SearchFilter("зомби", "14"), SearchFilter("игровые элементы", "73"), SearchFilter("исекай", "115"), SearchFilter("квесты", "75"), SearchFilter("космос", "76"), SearchFilter("кулинария", "16"), SearchFilter("культивация", "18"), SearchFilter("лоли", "108"), SearchFilter("магическая академия", "78"), SearchFilter("магия", "22"), SearchFilter("мафия", "24"), SearchFilter("медицина", "17"), SearchFilter("месть", "79"), SearchFilter("монстры", "38"), SearchFilter("музыка", "39"), SearchFilter("навыки / способности", "80"), SearchFilter("наёмники", "81"), SearchFilter("насилие / жестокость", "82"), SearchFilter("нежить", "83"), SearchFilter("ниндзя", "30"), SearchFilter("оборотни", "113"), SearchFilter("обратный гарем", "40"), SearchFilter("пародия", "85"), SearchFilter("подземелья", "86"), SearchFilter("политика", "87"), SearchFilter("полиция", "32"), SearchFilter("преступники / криминал", "36"), SearchFilter("призраки / духи", "27"), SearchFilter("прокачка", "118"), SearchFilter("путешествия во времени", "43"), SearchFilter("разумные расы", "88"), SearchFilter("ранги силы", "68"), SearchFilter("реинкарнация", "13"), SearchFilter("роботы", "89"), SearchFilter("рыцари", "90"), SearchFilter("самураи", "33"), SearchFilter("сборник", "10"), SearchFilter("сингл", "11"), SearchFilter("система", "91"), SearchFilter("скрытие личности", "93"), SearchFilter("спасение мира", "94"), SearchFilter("средневековье", "25"), SearchFilter("спасение мира", "94"), SearchFilter("средневековье", "25"), SearchFilter("стимпанк", "92"), SearchFilter("супергерои", "95"), SearchFilter("традиционные игры", "34"), SearchFilter("тупой гг", "109"), SearchFilter("умный гг", "111"), SearchFilter("управление", "114"), SearchFilter("философия", "97"), SearchFilter("хентай", "12"), SearchFilter("хикикомори", "21"), SearchFilter("шантаж", "99"), SearchFilter("эльфы", "46") ) private fun getGenreList() = listOf( SearchFilter("арт", "1"), SearchFilter("бдсм", "44"), SearchFilter("боевик", "2"), SearchFilter("боевые искусства", "3"), SearchFilter("вампиры", "4"), SearchFilter("гарем", "5"), SearchFilter("гендерная интрига", "6"), SearchFilter("героическое фэнтези", "7"), SearchFilter("детектив", "8"), SearchFilter("дзёсэй", "9"), SearchFilter("додзинси", "10"), SearchFilter("драма", "11"), SearchFilter("игра", "12"), SearchFilter("история", "13"), SearchFilter("киберпанк", "14"), SearchFilter("кодомо", "15"), SearchFilter("комедия", "16"), SearchFilter("махо-сёдзё", "17"), SearchFilter("меха", "18"), SearchFilter("мистика", "19"), SearchFilter("научная фантастика", "20"), SearchFilter("повседневность", "21"), SearchFilter("постапокалиптика", "22"), SearchFilter("приключения", "23"), SearchFilter("психология", "24"), SearchFilter("романтика", "25"), SearchFilter("сверхъестественное", "27"), SearchFilter("сёдзё", "28"), SearchFilter("сёдзё-ай", "29"), SearchFilter("сёнэн", "30"), SearchFilter("сёнэн-ай", "31"), SearchFilter("спорт", "32"), SearchFilter("сэйнэн", "33"), SearchFilter("трагедия", "34"), SearchFilter("триллер", "35"), SearchFilter("ужасы", "36"), SearchFilter("фантастика", "37"), SearchFilter("фэнтези", "38"), SearchFilter("школа", "39"), SearchFilter("эротика", "42"), SearchFilter("этти", "40"), SearchFilter("юри", "41"), SearchFilter("яой", "43") ) override fun setupPreferenceScreen(screen: androidx.preference.PreferenceScreen) { screen.addPreference(screen.editTextPreference(USERNAME_TITLE, USERNAME_DEFAULT, username)) screen.addPreference(screen.editTextPreference(PASSWORD_TITLE, PASSWORD_DEFAULT, password, true)) } private fun androidx.preference.PreferenceScreen.editTextPreference(title: String, default: String, value: String, isPassword: Boolean = false): androidx.preference.EditTextPreference { return androidx.preference.EditTextPreference(context).apply { key = title this.title = title summary = value this.setDefaultValue(default) dialogTitle = title if (isPassword) { if (value.isNotBlank()) { summary = "*****" } setOnBindEditTextListener { it.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD } } setOnPreferenceChangeListener { _, newValue -> try { val res = preferences.edit().putString(title, newValue as String).commit() Toast.makeText(context, "Перезапустите Tachiyomi, чтобы применить новую настройку.", Toast.LENGTH_LONG).show() res } catch (e: Exception) { e.printStackTrace() false } } } } private fun getPrefUsername(): String = preferences.getString(USERNAME_TITLE, USERNAME_DEFAULT)!! private fun getPrefPassword(): String = preferences.getString(PASSWORD_TITLE, PASSWORD_DEFAULT)!! private val json: Json by injectLazy() private val username by lazy { getPrefUsername() } private val password by lazy { getPrefPassword() } companion object { private val MEDIA_TYPE = "application/json; charset=utf-8".toMediaTypeOrNull() private const val USERNAME_TITLE = "Username" private const val USERNAME_DEFAULT = "" private const val PASSWORD_TITLE = "Password" private const val PASSWORD_DEFAULT = "" const val PREFIX_SLUG_SEARCH = "slug:" } }
apache-2.0
2ac9c261d33057eefa13f8f824c83e7c
39.49142
189
0.597072
4.04851
false
false
false
false
0x1bad1d3a/Kaku
app/src/main/java/ca/fuwafuwa/kaku/Windows/KanjiChoiceWindow.kt
2
12511
package ca.fuwafuwa.kaku.Windows import android.content.Context import android.graphics.Bitmap import android.graphics.Color import android.graphics.PixelFormat import android.os.Build import android.util.TypedValue import android.view.Gravity import android.view.MotionEvent import android.view.View import android.view.WindowManager import android.widget.ImageView import android.widget.LinearLayout import android.widget.RelativeLayout import android.widget.TextView import androidx.core.content.ContextCompat import ca.fuwafuwa.kaku.LangUtils import ca.fuwafuwa.kaku.Ocr.BoxParams import ca.fuwafuwa.kaku.R import ca.fuwafuwa.kaku.Windows.Data.ISquareChar import ca.fuwafuwa.kaku.Windows.Data.SquareCharOcr import ca.fuwafuwa.kaku.dpToPx enum class ChoiceResultType { EDIT, DELETE, SWAP, NONE } class KanjiChoiceWindow(context: Context, windowCoordinator: WindowCoordinator) : Window(context, windowCoordinator, R.layout.window_kanji_choice) { private val choiceWindow = window.findViewById<RelativeLayout>(R.id.kanji_choice_window)!! private val currentKanjiViews = mutableListOf<View>() private lateinit var mKanjiBoxParams : BoxParams private var drawnOnTop = false /** * KanjiChoiceWindow does not need to reInit layout as its getDefaultParams() are all relative. Re-initing will cause bugs. */ override fun reInit(options: Window.ReinitOptions) { options.reinitViewLayout = false super.reInit(options) } fun onSquareScrollStart(squareChar: ISquareChar, kanjiBoxParams: BoxParams) { if (squareChar !is SquareCharOcr) { show() mKanjiBoxParams = kanjiBoxParams mKanjiBoxParams.y -= statusBarHeight return } val topRectHeight = kanjiBoxParams.y - statusBarHeight val bottomRectHeight = realDisplaySize.y - kanjiBoxParams.y - kanjiBoxParams.height - (realDisplaySize.y - viewHeight - statusBarHeight) if (bottomRectHeight > topRectHeight) { drawnOnTop = false drawOnBottom(squareChar, kanjiBoxParams, calculateBounds(kanjiBoxParams, topRectHeight, bottomRectHeight)) } else { drawnOnTop = true drawOnTop(squareChar, kanjiBoxParams, calculateBounds(kanjiBoxParams, topRectHeight, bottomRectHeight)) } mKanjiBoxParams = kanjiBoxParams mKanjiBoxParams.y -= statusBarHeight show() } fun onSquareScroll(e: MotionEvent) : Int { var inKanji = false for (kanjiView in currentKanjiViews) { val isTextView = kanjiView is TextView if (checkForSelection(kanjiView, e) && isTextView) { inKanji = true kanjiView.setBackgroundResource(R.drawable.bg_solid_border_0_blue_black) } else if (isTextView) { kanjiView.setBackgroundResource(R.drawable.bg_solid_border_0_white_black) } } return when (getResultTypeForMotionEvent(e, inKanji, drawnOnTop)) { ChoiceResultType.EDIT -> { R.drawable.icon_edit } ChoiceResultType.DELETE -> { R.drawable.icon_delete } else -> { R.drawable.icon_swap } } } fun onSquareScrollEnd(e: MotionEvent) : Pair<ChoiceResultType, String> { var swappedKanji = "" for (kanjiView in currentKanjiViews) { if (checkForSelection(kanjiView, e) && kanjiView is TextView) { swappedKanji = kanjiView.text.toString() } } removeKanjiViews() hide() return Pair(getResultTypeForMotionEvent(e, swappedKanji != "", drawnOnTop), swappedKanji) } private fun getResultTypeForMotionEvent(e: MotionEvent, inKanji: Boolean, drawnOnTop: Boolean) : ChoiceResultType { if (inKanji) { return ChoiceResultType.SWAP } val midpoint = mKanjiBoxParams.x + (mKanjiBoxParams.width / 2) val height = if (drawnOnTop) mKanjiBoxParams.y + mKanjiBoxParams.height + statusBarHeight else mKanjiBoxParams.y + statusBarHeight return if (e.rawX < midpoint && heightCheckForResult(e, height, drawnOnTop)) { ChoiceResultType.EDIT } else if (e.rawX > midpoint && heightCheckForResult(e, height, drawnOnTop)) { ChoiceResultType.DELETE } else { ChoiceResultType.NONE } } private fun heightCheckForResult(e: MotionEvent, height: Int, drawnOnTop: Boolean) : Boolean { return if (drawnOnTop) e.rawY > height else e.rawY < height } private fun checkForSelection(kanjiView: View, e: MotionEvent): Boolean { var pos = IntArray(2) kanjiView.getLocationOnScreen(pos) return pos[0] < e.rawX && e.rawX < pos[0] + kanjiView.width && pos[1] < e.rawY && e.rawY < pos[1] + kanjiView.height } private fun removeKanjiViews() { for (k in currentKanjiViews) { choiceWindow.removeView(k) } currentKanjiViews.clear() } private fun calculateBounds(kanjiBoxParams: BoxParams, topRectHeight: Int, bottomRectHeight: Int) : BoxParams { val midPoint = kanjiBoxParams.x + (kanjiBoxParams.width / 2) var maxWidth = dpToPx(context, 400) var xPos = 0 if (realDisplaySize.x > maxWidth) { xPos = midPoint - (maxWidth / 2) if (xPos < 0) { xPos = 0 } else if (xPos + maxWidth > realDisplaySize.x) { xPos = realDisplaySize.x - maxWidth } } maxWidth = minOf(realDisplaySize.x, maxWidth) if (topRectHeight > bottomRectHeight) { return BoxParams(xPos, 0, maxWidth, topRectHeight) } else { return BoxParams(xPos, kanjiBoxParams.y + kanjiBoxParams.height - statusBarHeight, maxWidth, bottomRectHeight) } } private fun drawOnBottom(squareChar: SquareCharOcr, kanjiBoxParams: BoxParams, choiceParams: BoxParams) { val kanjiHeight = kanjiBoxParams.height * 2 val kanjiWidth = kanjiBoxParams.width * 2 val outerPadding = dpToPx(context, 10) val startHeight = choiceParams.y + outerPadding val drawableWidth = choiceParams.width - outerPadding val minPadding = dpToPx(context, 5) val numColumns = minOf(calculateNumColumns(drawableWidth, kanjiWidth, minPadding), squareChar.allChoices.size + 1) val outerSpacing = (choiceParams.width - (kanjiWidth + minPadding * 2) * numColumns) / 2 val innerSpacing = minPadding var currColumn = 0 var currWidth = choiceParams.x + outerSpacing + innerSpacing var currHeight = startHeight drawKanjiImage(squareChar, currWidth, currHeight, kanjiWidth, kanjiHeight) currWidth += kanjiWidth + innerSpacing currColumn++ for (choice in squareChar.allChoices) { if (currColumn >= numColumns) { currHeight += kanjiHeight + innerSpacing currWidth = choiceParams.x + outerSpacing + innerSpacing currColumn = 0 } drawKanjiText(choice.first, currWidth, currHeight, kanjiWidth, kanjiHeight) currWidth += kanjiWidth + innerSpacing currColumn++ } } private fun drawOnTop(squareChar: SquareCharOcr, kanjiBoxParams: BoxParams, choiceParams: BoxParams) { val kanjiHeight = kanjiBoxParams.height * 2 val kanjiWidth = kanjiBoxParams.width * 2 val outerPadding = dpToPx(context, 10) val startHeight = kanjiBoxParams.y - statusBarHeight - kanjiHeight - outerPadding val drawableWidth = choiceParams.width - outerPadding val minPadding = dpToPx(context, 5) val numColumns = minOf(calculateNumColumns(drawableWidth, kanjiWidth, minPadding), squareChar.allChoices.size + 1) val outerSpacing = (choiceParams.width - (kanjiWidth + minPadding * 2) * numColumns) / 2 val innerSpacing = minPadding var currColumn = 0 var currWidth = choiceParams.x + outerSpacing + innerSpacing var currHeight = startHeight drawKanjiImage(squareChar, currWidth, currHeight, kanjiWidth, kanjiHeight) currWidth += kanjiWidth + innerSpacing currColumn++ for (choice in squareChar.allChoices) { if (currColumn >= numColumns) { currHeight -= kanjiHeight + innerSpacing currWidth = choiceParams.x + outerSpacing + innerSpacing currColumn = 0 } drawKanjiText(choice.first, currWidth, currHeight, kanjiWidth, kanjiHeight) currWidth += kanjiWidth + innerSpacing currColumn++ } } private fun drawKanjiText(kanji: String, x: Int, y: Int, kanjiWidth: Int, kanjiHeight: Int) { val tv = TextView(context) tv.text = kanji tv.gravity = Gravity.CENTER tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, (kanjiWidth / 1.5).toFloat()) when { LangUtils.IsHiragana(kanji[0]) -> tv.setTextColor(ContextCompat.getColor(context, R.color.kana_pink)) LangUtils.IsKatakana(kanji[0]) -> tv.setTextColor(ContextCompat.getColor(context, R.color.kana_blue)) LangUtils.IsKanji(kanji[0]) -> tv.setTextColor(Color.BLACK) else -> tv.setTextColor(Color.GRAY) } tv.setBackgroundResource(R.drawable.bg_solid_border_0_white_black) tv.width = kanjiWidth tv.height = kanjiHeight tv.x = x.toFloat() tv.y = y.toFloat() choiceWindow.addView(tv) currentKanjiViews.add(tv) } private fun drawKanjiImage(squareChar: SquareCharOcr, x: Int, y: Int, kanjiWidth: Int, kanjiHeight: Int) { // Image nonsense val pos = squareChar.bitmapPos val dp10 = dpToPx(context, 10) val orig = squareChar.displayData.bitmap var width = pos[2] - pos[0] var height = pos[3] - pos[1] width = if (width <= 0) 1 else width height = if (height <= 0) 1 else height val bitmapChar = Bitmap.createBitmap(orig, pos[0], pos[1], width, height) val charImage = ImageView(context) charImage.setPadding(dp10, dp10, dp10, dp10) charImage.layoutParams = LinearLayout.LayoutParams(kanjiWidth, kanjiHeight) charImage.x = x.toFloat() charImage.y = y.toFloat() charImage.scaleType = ImageView.ScaleType.FIT_CENTER charImage.cropToPadding = true charImage.setImageBitmap(bitmapChar) charImage.background = context.getDrawable(R.drawable.bg_translucent_border_0_black_black) choiceWindow.addView(charImage) currentKanjiViews.add(charImage) } private fun calculateNumColumns(drawableWidth: Int, columnWidth: Int, minPadding: Int) : Int { var count = 0 var width = 0 val columnAndPadding = columnWidth + (minPadding * 2) while ((width + columnAndPadding) < drawableWidth) { width += columnAndPadding count++ } return count } override fun onTouch(e: MotionEvent): Boolean { return false } override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean { return false } override fun onResize(e: MotionEvent): Boolean { return false } override fun getDefaultParams(): WindowManager.LayoutParams { val params = WindowManager.LayoutParams( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, if (Build.VERSION.SDK_INT > 25) WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY else WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, PixelFormat.TRANSLUCENT) params.x = 0 params.y = 0 return params } }
bsd-3-clause
bf8b95da78ea9361f9ad615eb86315ff
31.839895
146
0.628007
4.403731
false
false
false
false
ZieIony/Carbon
carbon/src/main/java/carbon/drawable/ColorStateListFactory.kt
1
11402
package carbon.drawable import android.content.Context import android.content.res.ColorStateList import carbon.Carbon import carbon.R object ColorStateListFactory { private fun make(context: Context, defaultColor: Int, activated: Int, disabled: Int, invalid: Int = Carbon.getThemeColor(context, R.attr.colorError)): ColorStateList { return ColorStateList( arrayOf( intArrayOf(-android.R.attr.state_enabled), intArrayOf(R.attr.carbon_state_invalid), intArrayOf(R.attr.carbon_state_indeterminate), intArrayOf(android.R.attr.state_checked), intArrayOf(android.R.attr.state_activated), intArrayOf(android.R.attr.state_selected), intArrayOf(android.R.attr.state_focused), intArrayOf() ), intArrayOf( disabled, invalid, activated, activated, activated, activated, activated, defaultColor ) ) } private fun makeAlpha(context: Context, defaultColor: Int, activated: Int, disabled: Int, invalid: Int = Carbon.getThemeColor(context, R.attr.colorError)): ColorStateList { return AlphaWithParentDrawable.AlphaWithParentColorStateList( arrayOf( intArrayOf(-android.R.attr.state_enabled), intArrayOf(R.attr.carbon_state_invalid), intArrayOf(R.attr.carbon_state_indeterminate), intArrayOf(android.R.attr.state_checked), intArrayOf(android.R.attr.state_activated), intArrayOf(android.R.attr.state_selected), intArrayOf(android.R.attr.state_focused), intArrayOf() ), intArrayOf( disabled, invalid, activated, activated, activated, activated, activated, defaultColor ) ) } private fun make2(context: Context, defaultColor: Int, disabled: Int, invalid: Int = Carbon.getThemeColor(context, R.attr.colorError)): ColorStateList { return ColorStateList( arrayOf( intArrayOf(-android.R.attr.state_enabled), intArrayOf(R.attr.carbon_state_invalid), intArrayOf() ), intArrayOf( disabled, invalid, defaultColor ) ) } private fun makeAlpha2(context: Context, defaultColor: Int, disabled: Int, invalid: Int = Carbon.getThemeColor(context, R.attr.colorError)): ColorStateList { return AlphaWithParentDrawable.AlphaWithParentColorStateList( arrayOf( intArrayOf(-android.R.attr.state_enabled), intArrayOf(R.attr.carbon_state_invalid), intArrayOf() ), intArrayOf( disabled, invalid, defaultColor ) ) } fun makeHighlight(context: Context) = make(context, 0, (0x12000000 or (Carbon.getThemeColor(context, R.attr.carbon_colorControlActivated) and 0xffffff)), 0, (0x12000000 or (Carbon.getThemeColor(context, R.attr.colorError) and 0xffffff))) fun makeHighlightPrimary(context: Context) = make(context, 0, (0x12000000 or (Carbon.getThemeColor(context, R.attr.colorPrimary) and 0xffffff)), 0, (0x12000000 or (Carbon.getThemeColor(context, R.attr.colorError) and 0xffffff)) ) fun makeHighlightSecondary(context: Context) = make(context, 0, (0x12000000 or (Carbon.getThemeColor(context, R.attr.colorSecondary) and 0xffffff)), 0, (0x12000000 or (Carbon.getThemeColor(context, R.attr.colorError) and 0xffffff)) ) fun makeMenuSelection(context: Context) = MenuSelectionDrawable( Carbon.getThemeDimen(context, R.attr.carbon_menuSelectionRadius), Carbon.getThemeDimen(context, R.attr.carbon_menuSelectionInset), makeHighlight(context)) fun makeMenuSelectionPrimary(context: Context) = MenuSelectionDrawable( Carbon.getThemeDimen(context, R.attr.carbon_menuSelectionRadius), Carbon.getThemeDimen(context, R.attr.carbon_menuSelectionInset), makeHighlightPrimary(context)) fun makeMenuSelectionSecondary(context: Context) = MenuSelectionDrawable( Carbon.getThemeDimen(context, R.attr.carbon_menuSelectionRadius), Carbon.getThemeDimen(context, R.attr.carbon_menuSelectionInset), makeHighlightSecondary(context)) fun makePrimary(context: Context) = makeAlpha2(context, Carbon.getThemeColor(context, R.attr.colorPrimary), Carbon.getThemeColor(context, R.attr.carbon_colorControlDisabled) ) fun makePrimaryInverse(context: Context) = makeAlpha2(context, Carbon.getThemeColor(context, R.attr.colorPrimary), Carbon.getThemeColor(context, R.attr.carbon_colorControlDisabledInverse) ) fun makeSecondary(context: Context) = makeAlpha2(context, Carbon.getThemeColor(context, R.attr.colorSecondary), Carbon.getThemeColor(context, R.attr.carbon_colorControlDisabled) ) fun makeSecondaryInverse(context: Context) = makeAlpha2(context, Carbon.getThemeColor(context, R.attr.colorSecondary), Carbon.getThemeColor(context, R.attr.carbon_colorControlDisabledInverse) ) fun makeControl(context: Context) = makeAlpha(context, Carbon.getThemeColor(context, R.attr.carbon_colorControl), Carbon.getThemeColor(context, R.attr.carbon_colorControlActivated), Carbon.getThemeColor(context, R.attr.carbon_colorControlDisabled) ) fun makeControlInverse(context: Context) = makeAlpha(context, Carbon.getThemeColor(context, R.attr.carbon_colorControlInverse), Carbon.getThemeColor(context, R.attr.carbon_colorControlActivatedInverse), Carbon.getThemeColor(context, R.attr.carbon_colorControlDisabledInverse) ) fun makeControlPrimary(context: Context) = makeAlpha(context, Carbon.getThemeColor(context, R.attr.carbon_colorControl), Carbon.getThemeColor(context, R.attr.colorPrimary), Carbon.getThemeColor(context, R.attr.carbon_colorControlDisabled) ) fun makeControlPrimaryInverse(context: Context) = makeAlpha(context, Carbon.getThemeColor(context, R.attr.carbon_colorControlInverse), Carbon.getThemeColor(context, R.attr.colorPrimary), Carbon.getThemeColor(context, R.attr.carbon_colorControlDisabledInverse) ) fun makeControlSecondary(context: Context) = makeAlpha(context, Carbon.getThemeColor(context, R.attr.carbon_colorControl), Carbon.getThemeColor(context, R.attr.colorSecondary), Carbon.getThemeColor(context, R.attr.carbon_colorControlDisabled) ) fun makeControlSecondaryInverse(context: Context) = makeAlpha(context, Carbon.getThemeColor(context, R.attr.carbon_colorControlInverse), Carbon.getThemeColor(context, R.attr.colorSecondary), Carbon.getThemeColor(context, R.attr.carbon_colorControlDisabledInverse) ) fun makeTextSecondary(context: Context) = make2(context, Carbon.getThemeColor(context, R.attr.colorSecondary), Carbon.getThemeColor(context, android.R.attr.textColorTertiary) ) fun makeTextSecondaryInverse(context: Context) = make2(context, Carbon.getThemeColor(context, R.attr.colorSecondary), Carbon.getThemeColor(context, android.R.attr.textColorTertiaryInverse) ) fun makeTextPrimary(context: Context) = make2(context, Carbon.getThemeColor(context, R.attr.colorPrimary), Carbon.getThemeColor(context, android.R.attr.textColorTertiary) ) fun makeTextPrimaryInverse(context: Context) = make2(context, Carbon.getThemeColor(context, R.attr.colorPrimary), Carbon.getThemeColor(context, android.R.attr.textColorTertiaryInverse) ) fun makePrimaryText(context: Context) = make2(context, Carbon.getThemeColor(context, android.R.attr.textColorPrimary), Carbon.getThemeColor(context, android.R.attr.textColorTertiary) ) fun makePrimaryTextInverse(context: Context) = make2(context, Carbon.getThemeColor(context, android.R.attr.textColorPrimaryInverse), Carbon.getThemeColor(context, android.R.attr.textColorTertiaryInverse) ) fun makeSecondaryText(context: Context) = make2(context, Carbon.getThemeColor(context, android.R.attr.textColorSecondary), Carbon.getThemeColor(context, android.R.attr.textColorTertiary) ) fun makeSecondaryTextInverse(context: Context) = make2(context, Carbon.getThemeColor(context, android.R.attr.textColorSecondaryInverse), Carbon.getThemeColor(context, android.R.attr.textColorTertiaryInverse) ) fun makeIcon(context: Context) = make2(context, Carbon.getThemeColor(context, R.attr.carbon_iconColor), Carbon.getThemeColor(context, R.attr.carbon_iconColorDisabled) ) fun makeIconInverse(context: Context) = make2(context, Carbon.getThemeColor(context, R.attr.carbon_iconColorInverse), Carbon.getThemeColor(context, R.attr.carbon_iconColorDisabledInverse) ) fun makeIconPrimary(context: Context) = make(context, Carbon.getThemeColor(context, R.attr.carbon_iconColor), Carbon.getThemeColor(context, R.attr.colorPrimary), Carbon.getThemeColor(context, R.attr.carbon_iconColorDisabled) ) fun makeIconPrimaryInverse(context: Context) = make(context, Carbon.getThemeColor(context, R.attr.carbon_iconColorInverse), Carbon.getThemeColor(context, R.attr.colorPrimary), Carbon.getThemeColor(context, R.attr.carbon_iconColorDisabledInverse) ) fun makeIconSecondary(context: Context) = make(context, Carbon.getThemeColor(context, R.attr.carbon_iconColor), Carbon.getThemeColor(context, R.attr.colorSecondary), Carbon.getThemeColor(context, R.attr.carbon_iconColorDisabled) ) fun makeIconSecondaryInverse(context: Context) = make(context, Carbon.getThemeColor(context, R.attr.carbon_iconColorInverse), Carbon.getThemeColor(context, R.attr.colorSecondary), Carbon.getThemeColor(context, R.attr.carbon_iconColorDisabledInverse) ) }
apache-2.0
b8832d800cda9c253c4fda761f2cbe37
41.864662
110
0.626908
4.76274
false
false
false
false
google/cross-device-sdk
crossdevice/src/main/kotlin/com/google/ambient/crossdevice/sessions/SessionsAnalyticsLogger.kt
1
5013
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.ambient.crossdevice.sessions import android.content.Context import android.os.Build import android.util.Log import androidx.annotation.RequiresApi import com.google.ambient.crossdevice.analytics.FirelogLoggerTransport import com.google.ambient.crossdevice.logs.proto.ClientLogEnums.SessionAction import com.google.ambient.crossdevice.logs.proto.ClientLogProtos.Result import com.google.ambient.crossdevice.logs.proto.ClientLogProtos.SessionsLog import com.google.ambient.crossdevice.logs.proto.SessionsLogKt.sessionEvent import com.google.ambient.crossdevice.logs.proto.dtdiClientLog import com.google.ambient.crossdevice.logs.proto.sessionsLog import com.google.android.gms.dtdi.analytics.AnalyticsLogger import com.google.android.gms.dtdi.analytics.ClientInfo import com.google.android.gms.dtdi.analytics.CorrelationData import com.google.android.gms.dtdi.analytics.LoggerTransport import com.google.android.gms.dtdi.analytics.LoggingConfigurationStrategy import com.google.android.gms.dtdi.analytics.PackageLoggingConfigurationStrategy import com.google.android.gms.dtdi.core.ApiSurface.Companion.SESSIONS import com.google.common.io.BaseEncoding import com.google.protobuf.duration as durationDsl import java.security.MessageDigest import kotlin.time.Duration /** * Analytics logging for SessionsLog events. * * @hide */ @RequiresApi(Build.VERSION_CODES.O) interface SessionsAnalyticsLogger { /** Log all of the details of a SessionEvent. */ fun logSessionEvent( sessionAction: SessionAction, result: Result, sessionId: SessionId, applicationSessionTag: ApplicationSessionTag?, duration: Duration?, correlationData: CorrelationData?, ) } // TODO: Mark class as internal after moving tests to //third_party/cross_device_sdk /** @hide */ @RequiresApi(Build.VERSION_CODES.O) class SessionsAnalyticsLoggerImpl( context: Context, private val clientInfo: ClientInfo? = ClientInfo.fromPackageName(context, context.packageName), loggingConfigurationStrategy: LoggingConfigurationStrategy = PackageLoggingConfigurationStrategy.fromContext(context, SESSIONS), loggerTransport: LoggerTransport = FirelogLoggerTransport(context), ) : SessionsAnalyticsLogger { private val logger = AnalyticsLogger.create<SessionsLog>( context = context, logCreator = { event -> dtdiClientLog { sessionsLog = event }.toByteArray() }, loggingConfigurationStrategy = loggingConfigurationStrategy, loggerTransport = loggerTransport, userType = AnalyticsLogger.AnalyticsUserType.USER_TYPE_UNKNOWN, ) /** Log all of the details of a SessionEvent. */ override fun logSessionEvent( sessionAction: SessionAction, result: Result, sessionId: SessionId, applicationSessionTag: ApplicationSessionTag?, duration: Duration?, correlationData: CorrelationData?, ) { val event = sessionsLog { this.sessionId = sessionId.id sessionEvent = sessionEvent { this.result = result this.sessionAction = sessionAction duration?.let { this.duration = it.toComponents { seconds, nanos -> durationDsl { this.seconds = seconds this.nanos = nanos } } } applicationSessionTag?.let { hashApplicationSessionTag(applicationSessionTag)?.let { hash -> applicationSessionTagHash = hash } } } } logger.log(event, correlationData ?: CorrelationData.createNew(), clientInfo) } internal companion object { private const val TAG = "SessionsAnalyticsLogger" internal fun hashApplicationSessionTag(applicationSessionTag: ApplicationSessionTag): String? { return try { // Get the Base64-encoded SHA-256 hash of the UTF-8 encoded session tag. val md = MessageDigest.getInstance("SHA-256") md.update(applicationSessionTag.sessionTag.toByteArray(Charsets.UTF_8)) BaseEncoding.base64Url().omitPadding().encode(md.digest()) } catch (ex: Exception) { // We would expect NoSuchAlgorithmException or some other Exception, but both cases fold // into logging the same string so we use this catch-all case. Log.w(TAG, "unable to create application session hash", ex) // Nothing to return if we can't hash the ApplicationSessionTag. null } } } }
apache-2.0
044d3e770b1f4f527d3ad9a630012d9b
37.267176
99
0.739278
4.408971
false
true
false
false
JavaEden/Orchid
OrchidCore/src/main/kotlin/com/eden/orchid/api/theme/assets/AssetPage.kt
2
2725
package com.eden.orchid.api.theme.assets import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.annotations.Archetype import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.options.archetypes.AssetMetadataArchetype import com.eden.orchid.api.render.RenderService.RenderMode import com.eden.orchid.api.resources.resource.ExternalResource import com.eden.orchid.api.resources.resource.InlineResource import com.eden.orchid.api.resources.resource.OrchidResource import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.api.theme.pages.OrchidReference import com.eden.orchid.utilities.OrchidUtils import com.eden.orchid.utilities.debugger import java.util.HashMap @Archetype(value = AssetMetadataArchetype::class, key = "assetmeta") @Description( value = "A static asset, like Javascript, CSS, or an image.", name = "Asset" ) open class AssetPage( val origin: AssetManagerDelegate, resource: OrchidResource, key: String?, title: String? ) : OrchidPage( resource, getAssetRenderMode(resource.reference.context, resource.reference), key, title ) { var isRendered = false @Option @Description("The asset alt text.") lateinit var alt: String open fun configureReferences() { reference = OrchidReference(resource.reference)// copy reference so we can update it reference.isUsePrettyUrl = false // it's just a local file, apply the prefix as needed if (origin.prefix != null) { reference.path = OrchidUtils.normalizePath(origin.prefix) + "/" + reference.path } } open val shouldInline: Boolean get() { return when { resource is InlineResource -> true else -> false } } open fun renderAssetToPage(): String? { return "" } protected fun renderAttrs(attrs: MutableMap<String, String>): String { return attrs.entries.joinToString(separator = " ", prefix = " ") { "${it.key}=\"${it.value}\"" } } override fun getLink(): String { return if (!isRendered) { val actualPage = context.assetManager.getActualAsset(origin, this, true) check(actualPage.isRendered) actualPage.getLink() } else { super.getLink() } } companion object { private fun getAssetRenderMode(context: OrchidContext, reference: OrchidReference): RenderMode { return if (context.isBinaryExtension(reference.outputExtension)) { RenderMode.BINARY } else { RenderMode.RAW } } } }
lgpl-3.0
1979c2ca3b32970c41d62fdcde0c62d2
31.440476
104
0.677431
4.346093
false
false
false
false
felipebz/sonar-plsql
zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/XPathCheck.kt
1
2483
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plsqlopen.checks import com.felipebz.flr.api.AstNode import com.felipebz.flr.xpath.api.AstNodeXPathQuery import org.sonar.plsqlopen.squid.AnalysisException import org.sonar.plugins.plsqlopen.api.annotations.* @Rule(priority = Priority.MAJOR) @RuleInfo(scope = RuleInfo.Scope.ALL) @RuleTemplate class XPathCheck : AbstractBaseCheck() { @RuleProperty(key = "xpathQuery") var xpathQuery = DEFAULT_XPATH_QUERY @RuleProperty(key = "message", defaultValue = "" + DEFAULT_MESSAGE) var message = DEFAULT_MESSAGE private var query: AstNodeXPathQuery<Any>? = null private fun query(): AstNodeXPathQuery<Any>? { if (query == null && xpathQuery.isNotEmpty()) { try { query = AstNodeXPathQuery.create(xpathQuery) } catch (e: RuntimeException) { throw AnalysisException( "Unable to initialize the XPath engine, perhaps because of an invalid query: $xpathQuery", e) } } return query } override fun visitFile(node: AstNode) { if (query() != null) { val objects = query()?.selectNodes(node) ?: emptyList() for (obj in objects) { (obj as? AstNode)?.let { addIssue(it, message) } ?: if (obj is Boolean && obj) { addFileIssue(message) } } } } companion object { private const val DEFAULT_XPATH_QUERY = "" private const val DEFAULT_MESSAGE = "The XPath expression matches this piece of code" } }
lgpl-3.0
96856a441727c21d146852780359e23a
33.971831
117
0.649617
4.39469
false
false
false
false