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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bugsnag/bugsnag-android-gradle-plugin | src/main/kotlin/com/bugsnag/android/gradle/BugsnagUploadSoSymTask.kt | 1 | 9073 | package com.bugsnag.android.gradle
import com.android.build.gradle.api.BaseVariantOutput
import com.bugsnag.android.gradle.internal.AbstractSoMappingTask
import com.bugsnag.android.gradle.internal.BugsnagHttpClientHelper
import com.bugsnag.android.gradle.internal.NdkToolchain
import com.bugsnag.android.gradle.internal.UploadRequestClient
import com.bugsnag.android.gradle.internal.md5HashCode
import com.bugsnag.android.gradle.internal.taskNameSuffix
import okhttp3.RequestBody.Companion.asRequestBody
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFile
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.Nested
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.StopExecutionException
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.TaskProvider
import java.io.File
import java.net.HttpURLConnection.HTTP_NOT_FOUND
internal abstract class BugsnagUploadSoSymTask : DefaultTask(), AndroidManifestInfoReceiver, BugsnagFileUploadTask {
@get:InputDirectory
abstract val symbolFilesDir: DirectoryProperty
@get:OutputFile
abstract val requestOutputFile: RegularFileProperty
@get:Input
abstract val projectRoot: Property<String>
@get:Nested
abstract val ndkToolchain: Property<NdkToolchain>
@get:Input
@get:Optional
abstract val uploadType: Property<UploadType>
@get:Internal
internal abstract val uploadRequestClient: Property<UploadRequestClient>
init {
group = BugsnagPlugin.GROUP_NAME
description = "Uploads SO Symbol files to Bugsnag"
}
@TaskAction
fun upload() {
val rootDir = symbolFilesDir.asFile.get()
logger.info("Bugsnag: Found shared object files for upload: $rootDir")
if (ndkToolchain.get().preferredMappingTool() == NdkToolchain.MappingTool.OBJDUMP) {
// uploadType == objdump
val abiDirs = rootDir.listFiles().filter { it.isDirectory }
abiDirs.forEach { abiDir ->
val arch = abiDir.name
abiDir.listFiles()
.filter { it.extension == "gz" }
.forEach { sharedObjectFile ->
uploadObjdump(sharedObjectFile, arch)
}
}
} else {
rootDir.walkTopDown()
.filter { it.isFile && it.extension == "gz" && it.length() >= VALID_SO_FILE_THRESHOLD }
.forEach { uploadSymbols(it) }
}
}
/**
* Uploads the given shared object mapping information
* @param mappingFile the file to upload
*/
private fun uploadSymbols(mappingFile: File) {
val sharedObjectName = mappingFile.nameWithoutExtension
val requestEndpoint = endpoint.get() + ENDPOINT_SUFFIX
val request = BugsnagMultiPartUploadRequest.from(this, requestEndpoint)
val manifestInfo = parseManifestInfo()
val mappingFileHash = mappingFile.md5HashCode()
val response = uploadRequestClient.get().makeRequestIfNeeded(manifestInfo, mappingFileHash) {
logger.lifecycle("Bugsnag: Uploading SO mapping file from $mappingFile")
val body = request.createMultipartBody { builder ->
builder
.addFormDataPart("apiKey", manifestInfo.apiKey)
.addFormDataPart("appId", manifestInfo.applicationId)
.addFormDataPart("versionCode", manifestInfo.versionCode)
.addFormDataPart("versionName", manifestInfo.versionName)
.addFormDataPart("soFile", mappingFile.name, mappingFile.asRequestBody())
.addFormDataPart("sharedObjectName", sharedObjectName)
.addFormDataPart("projectRoot", projectRoot.get())
}
request.uploadRequest(body) { response ->
if (response.code == HTTP_NOT_FOUND && endpoint.get() != UPLOAD_ENDPOINT_DEFAULT) {
throw StopExecutionException(
"Bugsnag instance does not support the new NDK symbols upload mechanism. " +
"Please set legacyNDKSymbolsUpload or upgrade your Bugsnag instance. " +
"See https://docs.bugsnag.com/api/ndk-symbol-mapping-upload/ for details."
)
}
if (!response.isSuccessful) {
"Failure"
} else {
response.body!!.string()
}
}
}
requestOutputFile.asFile.get().writeText(response)
}
private fun uploadObjdump(mappingFile: File, arch: String) {
// a SO file may not contain debug info. if that's the case then the mapping file should be very small,
// so we try and reject it here as otherwise the event-worker will reject it with a 400 status code.
if (!mappingFile.exists() || mappingFile.length() < VALID_SO_FILE_THRESHOLD) {
logger.warn("Bugsnag: Skipping upload of empty/invalid mapping file: $mappingFile")
return
}
val sharedObjectName = mappingFile.nameWithoutExtension
val requestEndpoint = uploadType.get().endpoint(endpoint.get())
val soUploadKey = uploadType.get().uploadKey
val request = BugsnagMultiPartUploadRequest.from(this, requestEndpoint)
val manifestInfo = parseManifestInfo()
val mappingFileHash = mappingFile.md5HashCode()
val response = uploadRequestClient.get().makeRequestIfNeeded(manifestInfo, mappingFileHash) {
logger.lifecycle(
"Bugsnag: Uploading SO mapping file for $sharedObjectName ($arch) from $mappingFile"
)
request.uploadMultipartEntity(retryCount.get()) { builder ->
builder.addAndroidManifestInfo(manifestInfo)
builder.addFormDataPart(soUploadKey, mappingFile.name, mappingFile.asRequestBody())
builder.addFormDataPart("arch", arch)
builder.addFormDataPart("sharedObjectName", sharedObjectName)
builder.addFormDataPart("projectRoot", projectRoot.get())
}
}
requestOutputFile.asFile.get().writeText(response)
}
companion object {
private const val ENDPOINT_SUFFIX = "/ndk-symbol"
private const val VALID_SO_FILE_THRESHOLD = 1024
fun taskNameFor(variant: BaseVariantOutput, uploadType: UploadType) =
"uploadBugsnag${uploadType.name.toLowerCase().capitalize()}${variant.baseName.capitalize()}Mapping"
internal fun requestOutputFileFor(project: Project, output: BaseVariantOutput): Provider<RegularFile> {
val path = "intermediates/bugsnag/requests/symFor${output.taskNameSuffix()}.json"
return project.layout.buildDirectory.file(path)
}
fun register(
project: Project,
variant: BaseVariantOutput,
ndkToolchain: NdkToolchain,
uploadType: UploadType,
generateTaskProvider: TaskProvider<out AbstractSoMappingTask>,
httpClientHelperProvider: Provider<out BugsnagHttpClientHelper>,
ndkUploadClientProvider: Provider<out UploadRequestClient>,
): TaskProvider<BugsnagUploadSoSymTask> {
val bugsnag = project.extensions.getByType(BugsnagPluginExtension::class.java)
return project.tasks.register(
taskNameFor(variant, uploadType),
BugsnagUploadSoSymTask::class.java
) { task ->
task.dependsOn(generateTaskProvider)
task.usesService(httpClientHelperProvider)
task.usesService(ndkUploadClientProvider)
task.endpoint.set(bugsnag.endpoint)
task.uploadType.set(uploadType)
task.ndkToolchain.set(ndkToolchain)
task.manifestInfo.set(BugsnagManifestUuidTask.manifestInfoForOutput(project, variant))
task.symbolFilesDir.set(generateTaskProvider.flatMap { it.outputDirectory })
task.requestOutputFile.set(requestOutputFileFor(project, variant))
task.projectRoot.set(bugsnag.projectRoot.getOrElse(project.projectDir.toString()))
task.httpClientHelper.set(httpClientHelperProvider)
task.uploadRequestClient.set(ndkUploadClientProvider)
task.configureWith(bugsnag)
}
}
}
enum class UploadType(private val path: String, val uploadKey: String) {
NDK("so-symbol", "soSymbolFile"),
UNITY("so-symbol-table", "soSymbolTableFile");
fun endpoint(base: String): String {
return "$base/$path"
}
}
}
| mit | b396fccba373332612ffb5b7653fe569 | 42.204762 | 116 | 0.659209 | 4.906977 | false | false | false | false |
yuttadhammo/BodhiTimer | app/src/main/java/org/yuttadhammo/BodhiTimer/Util/SettingsDelegate.kt | 1 | 3217 | package org.yuttadhammo.BodhiTimer.Util
import android.content.SharedPreferences
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import org.yuttadhammo.BodhiTimer.BodhiApp
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* Yet another implementation of Shared Preferences using Delegated Properties
*
* Check out https://medium.com/@FrostRocketInc/delegated-shared-preferences-in-kotlin-45b82d6e52d0
* for a detailed walkthrough.
*
* @author Matthew Groves
*/
abstract class SettingsDelegate<T> : ReadWriteProperty<Any, T> {
protected val sharedPreferences: SharedPreferences by lazy {
PreferenceManager.getDefaultSharedPreferences(BodhiApp.applicationContext())
}
}
class StringSetting(private val key: String, private val defaultValue: String = "") :
SettingsDelegate<String>() {
override fun getValue(thisRef: Any, property: KProperty<*>) =
sharedPreferences.getString(key, defaultValue)!!
override fun setValue(thisRef: Any, property: KProperty<*>, value: String) =
sharedPreferences.edit { putString(key, value) }
}
class IntSetting(private val key: String, private val defaultValue: Int = 0) :
SettingsDelegate<Int>() {
override fun getValue(thisRef: Any, property: KProperty<*>) =
sharedPreferences.getInt(key, defaultValue)
override fun setValue(thisRef: Any, property: KProperty<*>, value: Int) =
sharedPreferences.edit { putInt(key, value) }
}
class StringIntSetting(private val key: String, private val defaultValue: Int = 0) :
SettingsDelegate<Int>() {
override fun getValue(thisRef: Any, property: KProperty<*>) =
sharedPreferences.getString(key, defaultValue.toString())!!.toInt()
override fun setValue(thisRef: Any, property: KProperty<*>, value: Int) =
sharedPreferences.edit { putString(key, value.toString()) }
}
class LongSetting(private val key: String, private val defaultValue: Long = 0.toLong()) :
SettingsDelegate<Long>() {
override fun getValue(thisRef: Any, property: KProperty<*>) =
sharedPreferences.getLong(key, defaultValue)
override fun setValue(thisRef: Any, property: KProperty<*>, value: Long) =
sharedPreferences.edit { putLong(key, value) }
}
class FloatSetting(
private val key: String,
private val defaultValue: Float = 0.toFloat()
) : SettingsDelegate<Float>() {
override fun getValue(thisRef: Any, property: KProperty<*>) =
sharedPreferences.getFloat(key, defaultValue)
override fun setValue(thisRef: Any, property: KProperty<*>, value: Float) =
sharedPreferences.edit { putFloat(key, value) }
}
class BooleanSetting(private val key: String, private val defaultValue: Boolean = false) :
SettingsDelegate<Boolean>() {
override fun getValue(thisRef: Any, property: KProperty<*>) =
sharedPreferences.getBoolean(key, defaultValue)
override fun setValue(thisRef: Any, property: KProperty<*>, value: Boolean) =
sharedPreferences.edit { putBoolean(key, value) }
constructor(stringId: Int, defaultValue: Boolean = false) : this(
BodhiApp.applicationContext().getString(stringId), defaultValue
)
}
| gpl-3.0 | b39825de069dcc9e9c99440d473a1a5e | 37.759036 | 99 | 0.726453 | 4.524613 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/glNext/tut02/vertexColor.kt | 2 | 2034 | package glNext.tut02
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL.*
import com.jogamp.opengl.GL3
import glNext.*
import glm.vec._4.Vec4
import main.framework.Framework
import uno.buffer.*
import uno.glsl.programOf
/**
* Created by GBarbieri on 21.02.2017.
*/
fun main(args: Array<String>) {
VertexColor_Next().setup("Tutorial 02 - Vertex Colors")
}
class VertexColor_Next : Framework() {
val VERTEX_SHADER = "tut02/vertex-colors.vert"
val FRAGMENT_SHADER = "tut02/vertex-colors.frag"
var theProgram = 0
val vertexBufferObject = intBufferBig(1)
val vao = intBufferBig(1)
val vertexData = floatBufferOf(
+0.0f, +0.500f, 0.0f, 1.0f,
+0.5f, -0.366f, 0.0f, 1.0f,
-0.5f, -0.366f, 0.0f, 1.0f,
+1.0f, +0.000f, 0.0f, 1.0f,
+0.0f, +1.000f, 0.0f, 1.0f,
+0.0f, +0.000f, 1.0f, 1.0f)
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
initializeVertexBuffer(gl)
glGenVertexArray(vao)
glBindVertexArray(vao)
}
fun initializeProgram(gl: GL3) {
theProgram = programOf(gl, javaClass, "tut02", "vertex-colors.vert", "vertex-colors.frag")
}
fun initializeVertexBuffer(gl: GL3) = gl.initArrayBuffer(vertexBufferObject) { data(vertexData, GL_STATIC_DRAW) }
override fun display(gl: GL3) = with(gl) {
clear { color(0) }
usingProgram(theProgram) {
withVertexLayout(vertexBufferObject, glf.pos4_col4, 0, Vec4.SIZE * 3) { glDrawArrays(3) }
}
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
glViewport(w, h)
}
override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
glDeleteBuffer(vertexBufferObject)
glDeleteVertexArray(vao)
destroyBuffers(vertexBufferObject, vao, vertexData)
}
override fun keyPressed(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
}
}
}
| mit | e6592938fbb8e1e2dd28cd62c433169d | 24.746835 | 117 | 0.618486 | 3.345395 | false | false | false | false |
ramadani/Loecasi | app/src/main/java/org/loecasi/android/data/network/service/AuthService.kt | 1 | 1347 | package org.loecasi.android.data.network.service
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.GoogleAuthProvider
import io.reactivex.Observable
import org.loecasi.android.data.model.User
import org.loecasi.android.data.network.Auth
import javax.inject.Inject
/**
* Created by dani on 10/31/17.
*/
class AuthService @Inject constructor(private val auth: FirebaseAuth) : Auth {
override fun user(): User {
val currentUser = auth.currentUser!!
return with(currentUser) {
User(uid, displayName!!, email!!, photoUrl)
}
}
override fun check(): Boolean = auth.currentUser != null
override fun googleSignIn(token: String): Observable<User> {
return Observable.create { subscribe ->
val credential = GoogleAuthProvider.getCredential(token, null)
auth.signInWithCredential(credential).addOnCompleteListener {
if (it.isSuccessful) {
val currentUser = auth.currentUser!!
val user = User(name = currentUser.displayName!!, email = currentUser.email!!)
subscribe.onNext(user)
} else {
subscribe.onError(it.exception!!)
}
}
}
}
override fun logout() {
auth.signOut()
}
} | mit | 4fc97b944206029fc146c0be6d80f120 | 30.348837 | 98 | 0.626578 | 4.70979 | false | false | false | false |
LorittaBot/Loritta | web/spicy-morenitta/src/main/kotlin/net/perfectdreams/spicymorenitta/routes/guilds/dashboard/LevelUpRoute.kt | 1 | 24301 | package net.perfectdreams.spicymorenitta.routes.guilds.dashboard
import LoriDashboard
import jq
import kotlinx.browser.document
import kotlinx.dom.addClass
import kotlinx.dom.clear
import kotlinx.dom.removeClass
import kotlinx.html.*
import kotlinx.html.dom.append
import kotlinx.html.js.onChangeFunction
import kotlinx.html.js.onClickFunction
import kotlinx.html.stream.createHTML
import kotlinx.serialization.Serializable
import legacyLocale
import net.perfectdreams.spicymorenitta.SpicyMorenitta
import net.perfectdreams.spicymorenitta.application.ApplicationCall
import net.perfectdreams.spicymorenitta.locale
import net.perfectdreams.spicymorenitta.routes.UpdateNavbarSizePostRender
import net.perfectdreams.spicymorenitta.utils.*
import net.perfectdreams.spicymorenitta.utils.DashboardUtils.launchWithLoadingScreenAndFixContent
import net.perfectdreams.spicymorenitta.utils.DashboardUtils.switchContentAndFixLeftSidebarScroll
import net.perfectdreams.spicymorenitta.utils.levelup.LevelUpAnnouncementType
import net.perfectdreams.spicymorenitta.utils.locale.buildAsHtml
import net.perfectdreams.spicymorenitta.views.dashboard.ServerConfig
import net.perfectdreams.spicymorenitta.views.dashboard.Stuff
import net.perfectdreams.spicymorenitta.views.dashboard.getPlan
import org.w3c.dom.*
import kotlin.js.Json
import kotlin.js.json
class LevelUpRoute(val m: SpicyMorenitta) : UpdateNavbarSizePostRender("/guild/{guildid}/configure/level") {
companion object {
private const val LOCALE_PREFIX = "modules.levelUp"
}
@Serializable
class PartialGuildConfiguration(
val activeDonationKeys: List<ServerConfig.DonationKey>,
val textChannels: List<ServerConfig.TextChannel>,
val roles: List<ServerConfig.Role>,
val levelUpConfig: ServerConfig.LevelUpConfig
)
val rolesByExperience = mutableListOf<ServerConfig.RoleByExperience>()
val experienceRoleRates = mutableListOf<ServerConfig.ExperienceRoleRate>()
val noXpRoles = mutableListOf<Long>()
val noXpChannels = mutableListOf<Long>()
override fun onUnload() {
rolesByExperience.clear()
experienceRoleRates.clear()
noXpRoles.clear()
noXpChannels.clear()
}
override val keepLoadingScreen: Boolean
get() = true
override fun onRender(call: ApplicationCall) {
launchWithLoadingScreenAndFixContent(call) {
val guild = DashboardUtils.retrievePartialGuildConfiguration<PartialGuildConfiguration>(call.parameters["guildid"]!!, "activekeys", "textchannels", "roles", "level")
switchContentAndFixLeftSidebarScroll(call)
document.select<HTMLButtonElement>("#save-button").onClick {
prepareSave()
}
val stuff = document.select<HTMLDivElement>("#level-stuff")
stuff.append {
generateLevelUpAnnouncementSection(guild)
hr {}
div {
h5(classes = "section-title") {
+ locale["$LOCALE_PREFIX.roleGiveType.title"]
}
createRadioButton(
"role-level-up-style",
locale["$LOCALE_PREFIX.roleGiveType.types.stack.title"],
locale["$LOCALE_PREFIX.roleGiveType.types.stack.description"],
"STACK",
guild.levelUpConfig.roleGiveType == "STACK"
)
createRadioButton(
"role-level-up-style",
locale["$LOCALE_PREFIX.roleGiveType.types.remove.title"],
locale["$LOCALE_PREFIX.roleGiveType.types.remove.description"],
"REMOVE",
guild.levelUpConfig.roleGiveType == "REMOVE"
)
}
hr {}
div {
h5(classes = "section-title") {
+ locale["$LOCALE_PREFIX.roleByXpLevel.title"]
}
locale.getList("$LOCALE_PREFIX.roleByXpLevel.description").forEach {
p {
+ it
}
}
div(classes = "add-role") {
locale.buildAsHtml(locale["$LOCALE_PREFIX.roleByXpLevel.whenUserGetsToXp"], { num ->
if (num == 0) {
input(InputType.number, classes = "required-xp") {
placeholder = "1000"
min = "0"
max = "10000000"
step = "1000"
onChangeFunction = {
document.select<HTMLSpanElement>("#give-role-level-calc")
.innerText = ((document.select<HTMLInputElement>(".add-role .required-xp")
.valueOrPlaceholderIfEmpty("1000").toLong() / 1000).toString())
}
}
}
if (num == 1) {
span {
id = "give-role-level-calc"
+ "0"
}
}
if (num == 2) {
select {
id = "choose-role"
style = "width: 320px;"
}
}
}) { str ->
+ str
}
+ " "
button(classes = "button-discord button-discord-info pure-button") {
+ locale["loritta.add"]
onClickFunction = {
val plan = guild.activeDonationKeys.getPlan()
if (rolesByExperience.size >= plan.maxLevelUpRoles) {
Stuff.showPremiumFeatureModal {
h2 {
+ "Adicione mais cargos para Level Up!"
}
p {
+ "Faça upgrade para poder adicionar mais cargos!"
}
}
} else {
addRoleToRoleByExperienceList(
guild,
ServerConfig.RoleByExperience(
document.select<HTMLInputElement>(".add-role .required-xp")
.valueOrPlaceholderIfEmpty("1000"),
listOf(
document.select<HTMLSelectElement>("#choose-role").value.toLong()
)
)
)
}
}
}
}
div(classes = "roles-by-xp-list list-wrapper") {}
}
hr {}
div {
h5(classes = "section-title") {
+ locale["$LOCALE_PREFIX.customRoleRate.title"]
}
locale.getList("$LOCALE_PREFIX.customRoleRate.description").forEach {
p {
+ it
}
}
div(classes = "add-custom-rate-role") {
locale.buildAsHtml(locale["$LOCALE_PREFIX.customRoleRate.whenUserHasRoleRate"], { num ->
if (num == 0) {
select {
id = "choose-role-custom-rate"
style = "width: 320px;"
}
}
if (num == 1) {
input(InputType.number, classes = "xp-rate") {
placeholder = "1.0"
min = "0"
max = "10"
step = "0.05"
}
}
}) { str ->
+ str
}
+ " "
button(classes = "button-discord button-discord-info pure-button") {
+ locale["loritta.add"]
onClickFunction = {
addRoleToRolesWithCustomRateList(
guild,
ServerConfig.ExperienceRoleRate(
document.select<HTMLSelectElement>("#choose-role-custom-rate").value.toLong(),
document.select<HTMLInputElement>(".add-custom-rate-role .xp-rate")
.valueOrPlaceholderIfEmpty("1.0").toDouble()
)
)
}
}
}
div(classes = "roles-with-custom-rate-list list-wrapper") {}
}
hr {}
div {
h5(classes = "section-title") {
+ locale["$LOCALE_PREFIX.noXpRoles.title"]
}
locale.getList("$LOCALE_PREFIX.noXpRoles.description").forEach {
p {
+ it
}
}
select {
id = "choose-role-no-xp"
style = "width: 320px;"
}
button(classes = "button-discord button-discord-info pure-button") {
+ locale["loritta.add"]
onClickFunction = {
val role = document.select<HTMLSelectElement>("#choose-role-no-xp").value
noXpRoles.add(role.toLong())
updateNoXpRoleList(guild)
}
}
div(classes = "list-wrapper") {
id = "choose-role-no-xp-list"
}
}
hr {}
div {
h5(classes = "section-title") {
+ locale["$LOCALE_PREFIX.noXpChannels.title"]
}
locale.getList("$LOCALE_PREFIX.noXpChannels.description").forEach {
p {
+ it
}
}
select {
id = "choose-channel-no-xp"
style = "width: 320px;"
for (channel in guild.textChannels) {
option {
+ ("#${channel.name}")
value = channel.id.toString()
}
}
}
button(classes = "button-discord button-discord-info pure-button") {
+ locale["loritta.add"]
onClickFunction = {
val role = document.select<HTMLSelectElement>("#choose-channel-no-xp").value
noXpChannels.add(role.toLong())
updateNoXpChannelsList(guild)
}
}
div(classes = "list-wrapper") {
id = "choose-channel-no-xp-list"
}
hr {}
button(classes = "button-discord button-discord-attention pure-button") {
i(classes = "fas fa-redo") {}
+ " ${locale["$LOCALE_PREFIX.resetXp.title"]}"
onClickFunction = {
val modal = TingleModal(
TingleOptions(
footer = true,
cssClass = arrayOf("tingle-modal--overflow")
)
)
modal.addFooterBtn("<i class=\"fas fa-redo\"></i> ${locale["$LOCALE_PREFIX.resetXp.clearAll"]}", "button-discord button-discord-attention pure-button button-discord-modal") {
modal.close()
SaveUtils.prepareSave("reset_xp", {})
}
modal.addFooterBtn("<i class=\"fas fa-times\"></i> ${locale["$LOCALE_PREFIX.resetXp.cancel"]}", "button-discord pure-button button-discord-modal button-discord-modal-secondary-action") {
modal.close()
}
modal.setContent(
createHTML().div {
div(classes = "category-name") {
+ locale["$LOCALE_PREFIX.resetXp.areYouSure"]
}
div {
style = "text-align: center;"
img(src = "https://loritta.website/assets/img/fanarts/l6.png") {
width = "250"
}
locale.getList("$LOCALE_PREFIX.resetXp.description").forEach {
p {
+ it
}
}
}
}
)
modal.open()
}
}
}
}
val optionData = mutableListOf<dynamic>()
val chooseRoleToAddOptionData = mutableListOf<dynamic>()
fun generateOptionForRole(role: ServerConfig.Role): dynamic {
val option = object {}.asDynamic()
option.id = role.id
var text = "<span style=\"font-weight: 600;\">${role.name}</span>"
val color = role.getColor()
if (color != null) {
text = "<span style=\"font-weight: 600; color: rgb(${color.red}, ${color.green}, ${color.blue})\">${role.name}</span>"
}
option.text = text
if (!role.canInteract || role.isManaged) {
if (role.isManaged) {
option.text = "${text} <span class=\"keyword\" style=\"background-color: rgb(225, 149, 23);\">${legacyLocale["DASHBOARD_RoleByIntegration"]}</span>"
} else {
option.text = "${text} <span class=\"keyword\" style=\"background-color: rgb(231, 76, 60);\">${legacyLocale["DASHBOARD_NoPermission"]}</span>"
}
}
return option
}
for (it in guild.roles.filter { !it.isPublicRole }) {
chooseRoleToAddOptionData.add(generateOptionForRole(it))
}
for (it in guild.roles) {
optionData.add(generateOptionForRole(it))
}
val options = object {}.asDynamic()
options.data = optionData.toTypedArray()
options.escapeMarkup = { str: dynamic ->
str
}
val optionsRoleToAdd = object {}.asDynamic()
optionsRoleToAdd.data = chooseRoleToAddOptionData.toTypedArray()
optionsRoleToAdd.escapeMarkup = { str: dynamic ->
str
}
jq("#choose-role-no-xp").asDynamic().select2(
options
)
jq("#choose-role").asDynamic().select2(
optionsRoleToAdd
)
jq("#choose-role-custom-rate").asDynamic().select2(
options
)
guild.levelUpConfig.rolesByExperience.forEach {
addRoleToRoleByExperienceList(guild, it)
}
guild.levelUpConfig.experienceRoleRates.forEach {
addRoleToRolesWithCustomRateList(guild, it)
}
noXpRoles.addAll(guild.levelUpConfig.noXpRoles)
noXpChannels.addAll(guild.levelUpConfig.noXpChannels)
updateNoXpRoleList(guild)
updateNoXpChannelsList(guild)
LoriDashboard.configureTextArea(
jq("#announcement-message"),
true,
false,
null,
true,
EmbedEditorStuff.userInContextPlaceholders(locale) +
EmbedEditorStuff.userCurrentExperienceInContextPlaceholders(locale),
/* Placeholders.DEFAULT_PLACEHOLDERS *//* .toMutableMap().apply {
put("previous-level", "Qual era o nível do usuário antes dele ter passado de nível")
put("previous-xp", "Quanta experiência o usuário tinha antes dele ter passado de nível")
put("level", "O novo nível que o usuário está")
put("xp", "A nova quantidade de experiência que o usuário tem")
},
customTokens = mapOf(
"previous-level" to "99",
"previous-xp" to "99987",
"level" to "100",
"xp" to "100002"
), */
showTemplates = true,
templates = mapOf(
locale["$LOCALE_PREFIX.levelUpAnnouncement.templates.default.title"] to locale["$LOCALE_PREFIX.levelUpAnnouncement.templates.default.content", "<a:lori_yay_wobbly:638040459721310238>"],
locale["$LOCALE_PREFIX.levelUpAnnouncement.templates.embed.title"] to """{
"content":"{@user}",
"embed":{
"color":-12591736,
"title":" **<a:lori_yay_wobbly:638040459721310238> | LEVEL UP!**",
"description":" ${locale["$LOCALE_PREFIX.levelUpAnnouncement.templates.default.content", "<:lori_heart:640158506049077280>"]}",
"footer": { "text": "${locale["$LOCALE_PREFIX.levelUpAnnouncement.templates.embed.footer"]}" }
}
}"""
)
)
updateDisabledSections()
}
}
fun updateDisabledSections() {
val announcementTypeSelect = document.select<HTMLSelectElement>("#announcement-type")
val announcementValue = LevelUpAnnouncementType.valueOf(announcementTypeSelect.value)
if (announcementValue != LevelUpAnnouncementType.DISABLED) {
document.select<HTMLDivElement>("#level-up-message").removeClass("blurSection")
} else {
document.select<HTMLDivElement>("#level-up-message").addClass("blurSection")
}
if (announcementValue == LevelUpAnnouncementType.DIFFERENT_CHANNEL) {
document.select<HTMLDivElement>("#select-custom-channel").removeClass("blurSection")
} else {
document.select<HTMLDivElement>("#select-custom-channel").addClass("blurSection")
}
}
fun addRoleToRolesWithCustomRateList(guild: PartialGuildConfiguration, experienceRoleRate: ServerConfig.ExperienceRoleRate) {
experienceRoleRates.add(experienceRoleRate)
updateRolesWithCustomRateList(guild)
}
fun updateRolesWithCustomRateList(guild: PartialGuildConfiguration) {
val list = document.select<HTMLDivElement>(".roles-with-custom-rate-list")
list.clear()
val invalidEntries = mutableListOf<ServerConfig.ExperienceRoleRate>()
for (experienceRoleRate in experienceRoleRates.sortedByDescending { it.rate.toLong() }) {
val theRealRoleId = experienceRoleRate.role
val guildRole = guild.roles.firstOrNull { it.id == theRealRoleId }
if (guildRole == null) {
debug("Role ${theRealRoleId} not found! Removing $experienceRoleRate")
invalidEntries.add(experienceRoleRate)
continue
}
val color = guildRole.getColor()
list.append {
div {
button(classes = "button-discord button-discord-info pure-button remove-action") {
i(classes = "fas fa-trash") {}
onClickFunction = {
experienceRoleRates.remove(experienceRoleRate)
updateRolesWithCustomRateList(guild)
}
}
+ " "
locale.buildAsHtml(locale["$LOCALE_PREFIX.customRoleRate.whenUserHasRoleRate"], { num ->
if (num == 0) {
span(classes = "discord-mention") {
if (color != null)
style = "color: rgb(${color.red}, ${color.green}, ${color.blue}); background-color: rgba(${color.red}, ${color.green}, ${color.blue}, 0.298039);"
+ "@${guildRole.name}"
}
}
if (num == 1) {
strong {
+ experienceRoleRate.rate.toString()
}
}
}) { str ->
+ str
}
}
}
}
experienceRoleRates.removeAll(invalidEntries)
}
fun addRoleToRoleByExperienceList(guild: PartialGuildConfiguration, roleByExperience: ServerConfig.RoleByExperience) {
rolesByExperience.add(roleByExperience)
updateRoleByExperienceList(guild)
}
fun updateRoleByExperienceList(guild: PartialGuildConfiguration) {
val list = document.select<HTMLDivElement>(".roles-by-xp-list")
list.clear()
val invalidEntries = mutableListOf<ServerConfig.RoleByExperience>()
for (roleByExperience in rolesByExperience.sortedByDescending { it.requiredExperience.toLong() }) {
val theRealRoleId = roleByExperience.roles.firstOrNull() ?: continue
val guildRole = guild.roles.firstOrNull { it.id == theRealRoleId }
if (guildRole == null) {
debug("Role ${theRealRoleId} not found! Removing $roleByExperience")
invalidEntries.add(roleByExperience)
continue
}
val color = guildRole.getColor()
list.append {
div {
button(classes = "button-discord button-discord-info pure-button remove-action") {
i(classes = "fas fa-trash") {}
onClickFunction = {
rolesByExperience.remove(roleByExperience)
updateRoleByExperienceList(guild)
}
}
+ " "
locale.buildAsHtml(locale["$LOCALE_PREFIX.roleByXpLevel.whenUserGetsToXp"], { num ->
if (num == 0) {
strong {
+ (roleByExperience.requiredExperience)
}
}
if (num == 1) {
span {
+ (roleByExperience.requiredExperience.toLong() / 1000).toString()
}
}
if (num == 2) {
span(classes = "discord-mention") {
if (color != null)
style = "color: rgb(${color.red}, ${color.green}, ${color.blue}); background-color: rgba(${color.red}, ${color.green}, ${color.blue}, 0.298039);"
+ "@${guildRole.name}"
}
}
}) { str ->
+ str
}
}
}
}
rolesByExperience.removeAll(invalidEntries)
}
fun updateNoXpRoleList(guild: PartialGuildConfiguration) {
val list = document.select<HTMLDivElement>("#choose-role-no-xp-list")
list.clear()
list.append {
noXpRoles.forEach { noXpRoleId ->
val guildRole = guild.roles.firstOrNull { it.id.toLong() == noXpRoleId } ?: return@forEach
list.append {
val color = guildRole.getColor()
span(classes = "discord-mention") {
style = "cursor: pointer; margin-right: 4px;"
if (color != null)
style = "cursor: pointer; margin-right: 4px; color: rgb(${color.red}, ${color.green}, ${color.blue}); background-color: rgba(${color.red}, ${color.green}, ${color.blue}, 0.298039);"
else
style = "cursor: pointer; margin-right: 4px;"
+"@${guildRole.name}"
onClickFunction = {
noXpRoles.remove(noXpRoleId)
updateNoXpRoleList(guild)
}
span {
style = "border-left: 1px solid rgba(0, 0, 0, 0.15);opacity: 0.7;padding-left: 3px;font-size: 14px;margin-left: 3px;padding-right: 3px;"
i(classes = "fas fa-times") {}
}
}
}
}
}
}
fun updateNoXpChannelsList(guild: PartialGuildConfiguration) {
val list = document.select<HTMLDivElement>("#choose-channel-no-xp-list")
list.clear()
list.append {
noXpChannels.forEach { noXpChannelId ->
val guildChannel = guild.textChannels.firstOrNull { it.id.toLong() == noXpChannelId } ?: return@forEach
list.append {
span(classes = "discord-mention") {
style = "cursor: pointer; margin-right: 4px;"
+ "#${guildChannel.name}"
onClickFunction = {
noXpChannels.remove(noXpChannelId)
updateNoXpChannelsList(guild)
}
span {
style = "border-left: 1px solid rgba(0, 0, 0, 0.15);opacity: 0.7;padding-left: 3px;font-size: 14px;margin-left: 3px;padding-right: 3px;"
i(classes = "fas fa-times") {}
}
}
}
}
}
}
@JsName("prepareSave")
fun prepareSave() {
SaveUtils.prepareSave("level", extras = {
it["roleGiveType"] = document.select<HTMLInputElement>("input[name='role-level-up-style']:checked").value
it["noXpChannels"] = noXpChannels.map { it.toString() }
it["noXpRoles"] = noXpRoles.map { it.toString() }
val announcements = mutableListOf<Json>()
val announcementType = document.select<HTMLInputElement>("#announcement-type").value
val announcementMessage = document.select<HTMLInputElement>("#announcement-message").value
if (announcementType != "DISABLED") {
val json = json(
"type" to announcementType,
"message" to announcementMessage,
"onlyIfUserReceivedRoles" to document.select<HTMLInputElement>("#only-if-user-received-roles").checked
)
if (announcementType == "DIFFERENT_CHANNEL") {
json["channelId"] = document.select<HTMLSelectElement>("#choose-channel-custom-channel").value
}
announcements.add(json)
}
it["announcements"] = announcements
val rolesByExperience = mutableListOf<Json>()
this.rolesByExperience.forEach {
val inner = json(
"requiredExperience" to it.requiredExperience,
"roles" to it.roles.map { it.toString() }
)
rolesByExperience.add(inner)
}
it["rolesByExperience"] = rolesByExperience
val experienceRoleRates = mutableListOf<Json>()
this.experienceRoleRates.forEach {
val inner = json(
"rate" to it.rate.toString(),
"role" to it.role.toString()
)
experienceRoleRates.add(inner)
}
it["experienceRoleRates"] = experienceRoleRates
})
}
private fun TagConsumer<HTMLElement>.generateLevelUpAnnouncementSection(guild: PartialGuildConfiguration) {
val announcement = guild.levelUpConfig.announcements.firstOrNull()
div {
h5(classes = "section-title") {
+locale["$LOCALE_PREFIX.levelUpAnnouncement.title"]
}
locale.getList("$LOCALE_PREFIX.levelUpAnnouncement.description").forEach {
p {
+it
}
}
div {
style = "display: flex; flex-direction: column;"
div {
style = "display: flex; flex-direction: row;"
div {
style = "flex-grow: 1; margin-right: 10px;"
h5(classes = "section-title") {
+locale["$LOCALE_PREFIX.levelUpAnnouncement.tellWhere"]
}
select {
style = "width: 100%;"
id = "announcement-type"
for (entry in LevelUpAnnouncementType.values()) {
option {
+when (entry) {
LevelUpAnnouncementType.DISABLED -> locale["$LOCALE_PREFIX.channelTypes.disabled"]
LevelUpAnnouncementType.SAME_CHANNEL -> locale["$LOCALE_PREFIX.channelTypes.sameChannel"]
LevelUpAnnouncementType.DIRECT_MESSAGE -> locale["$LOCALE_PREFIX.channelTypes.directMessage"]
LevelUpAnnouncementType.DIFFERENT_CHANNEL -> locale["$LOCALE_PREFIX.channelTypes.differentChannel"]
}
value = entry.name
if (entry.name == announcement?.type) {
selected = true
}
}
}
onChangeFunction = {
updateDisabledSections()
}
}
}
div(classes = "blurSection") {
style = "flex-grow: 1; margin-left: 16px;"
id = "select-custom-channel"
h5(classes = "section-title") {
+locale["$LOCALE_PREFIX.levelUpAnnouncement.channel"]
}
select {
style = "width: 100%;"
id = "choose-channel-custom-channel"
// style = "width: 320px;"
for (channel in guild.textChannels) {
option {
+("#${channel.name}")
value = channel.id.toString()
if (channel.id == announcement?.channelId) {
selected = true
}
}
}
}
}
}
div {
createToggle(
locale["modules.levelUp.levelUpAnnouncement.onlyIfUserReceivedRoles.title"],
locale["modules.levelUp.levelUpAnnouncement.onlyIfUserReceivedRoles.subtext"],
id = "only-if-user-received-roles",
isChecked = announcement?.onlyIfUserReceivedRoles ?: false
)
}
div(classes = "blurSection") {
id = "level-up-message"
style = "flex-grow: 1;"
h5(classes = "section-title") {
+locale["$LOCALE_PREFIX.levelUpAnnouncement.theMessage"]
}
textArea {
id = "announcement-message"
+(announcement?.message
?: locale["$LOCALE_PREFIX.levelUpAnnouncement.templates.default.content", "<a:lori_yay_wobbly:638040459721310238>"])
}
}
}
}
}
private fun HTMLInputElement.valueOrPlaceholderIfEmpty(newValue: String): String {
val value = this.value
if (value.isEmpty())
return newValue
return value
}
} | agpl-3.0 | 10feffd920780cdbcfa2544c745456f3 | 27.016148 | 193 | 0.636337 | 3.565619 | false | false | false | false |
NoodleMage/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/network/NetworkHelper.kt | 1 | 739 | package eu.kanade.tachiyomi.network
import android.content.Context
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
class NetworkHelper(context: Context) {
private val cacheDir = File(context.cacheDir, "network_cache")
private val cacheSize = 5L * 1024 * 1024 // 5 MiB
private val cookieManager = PersistentCookieJar(context)
val client = OkHttpClient.Builder()
.cookieJar(cookieManager)
.cache(Cache(cacheDir, cacheSize))
.build()
val cloudflareClient = client.newBuilder()
.addInterceptor(CloudflareInterceptor())
.build()
val cookies: PersistentCookieStore
get() = cookieManager.store
}
| apache-2.0 | 9b341e0dcf3b355a7a44d2ae2d86f84e | 24.392857 | 66 | 0.661705 | 4.830065 | false | false | false | false |
nguyenhoanglam/ImagePicker | imagepicker/src/main/java/com/nguyenhoanglam/imagepicker/widget/SnackBarView.kt | 1 | 3227 | /*
* Copyright (C) 2021 Image Picker
* Author: Nguyen Hoang Lam <[email protected]>
*/
package com.nguyenhoanglam.imagepicker.widget
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.view.animation.Interpolator
import android.widget.Button
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.annotation.AttrRes
import androidx.core.view.ViewCompat
import androidx.interpolator.view.animation.FastOutLinearInInterpolator
import com.nguyenhoanglam.imagepicker.R
class SnackBarView : RelativeLayout {
private lateinit var messageText: TextView
private lateinit var actionButton: Button
var isShowing = false
private set
constructor(context: Context) : super(context) {
init(context)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(context)
}
constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
init(context)
}
private fun init(context: Context) {
View.inflate(context, R.layout.imagepicker_snackbar, this)
if (isInEditMode) {
return
}
setBackgroundColor(Color.parseColor("#323232"))
translationY = height.toFloat()
alpha = 0f
isShowing = false
val horizontalPadding = convertDpToPixels(context, 24f)
val verticalPadding = convertDpToPixels(context, 14f)
setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding)
messageText = findViewById(R.id.text_snackbar_message)
actionButton = findViewById(R.id.button_snackbar_action)
}
private fun setText(textResId: Int) {
messageText.setText(textResId)
}
private fun setOnActionClickListener(actionText: String, onClickListener: OnClickListener) {
actionButton.text = actionText
actionButton.setOnClickListener { view -> hide { onClickListener.onClick(view) } }
}
fun show(textResId: Int, onClickListener: OnClickListener) {
setText(textResId)
setOnActionClickListener(context.getString(R.string.imagepicker_action_ok), onClickListener)
ViewCompat.animate(this)
.translationY(0f)
.setDuration(ANIM_DURATION.toLong())
.setInterpolator(INTERPOLATOR)
.alpha(1f)
isShowing = true
}
private fun hide(runnable: Runnable) {
ViewCompat.animate(this)
.translationY(height.toFloat())
.setDuration(ANIM_DURATION.toLong())
.alpha(0.5f)
.withEndAction(runnable)
isShowing = false
}
private fun convertDpToPixels(context: Context, dp: Float): Int {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp,
context.resources.displayMetrics
)
.toInt()
}
companion object {
private const val ANIM_DURATION = 200
private val INTERPOLATOR: Interpolator = FastOutLinearInInterpolator()
}
} | apache-2.0 | 061d8811f7e69b06b480dedb74af21ea | 30.339806 | 100 | 0.679888 | 4.690407 | false | false | false | false |
chRyNaN/GuitarChords | core/src/commonMain/kotlin/com.chrynan.chords/parser/ChordProParser.kt | 1 | 7202 | package com.chrynan.chords.parser
import com.chrynan.chords.exception.ChordProParseException
import com.chrynan.chords.model.*
/**
* An implementation of a [ChordParser] that parses a [String] in the ChordPro "define" and "chord"
* directives format and returns a [ChordParseResult]. For more information about the ChordPro
* format, refer to the documentation:
* https://www.chordpro.org/chordpro/index.html
*
* Examples of supported input formats include:
* {define: Bes base-fret 1 frets 1 1 3 3 3 1 fingers 1 1 2 3 4 1}
* {define: As base-fret 4 frets 1 3 3 2 1 1 fingers 1 3 4 2 1 1}
* {chord: Am}
* {chord: Bes base-fret 1 frets 1 1 3 3 3 1 fingers 1 1 2 3 4 1}
* {chord: As base-fret 4 frets 1 3 3 2 1 1 fingers 1 3 4 2 1 1}
*
* @author chRyNaN
*/
class ChordProParser : ChordParser<String> {
companion object {
private const val COLON = ':'
private const val DEFINE = "define"
private const val CHORD = "chord"
private const val BASE_FRET = "base-fret"
private const val FRETS = "frets"
private const val FINGERS = "fingers"
private val OPEN_STRING_DELIMITERS = setOf("0", "o", "O")
private val MUTED_STRING_DELIMITERS = setOf("N", "n", "X", "x")
}
// This is probably not the most optimized implementation
override suspend fun parse(input: String): ChordParseResult {
val formattedInput = input.removeSurrounding(prefix = "{", suffix = "}").removeSurrounding(prefix = "[", suffix = "]").trim()
val containsDefine = formattedInput.contains(DEFINE, true)
val containsChord = formattedInput.contains(CHORD, true)
if (!containsDefine && !containsChord) throw ChordProParseException(message = "Expecting \'$DEFINE\' or \'$CHORD\' in input for ${ChordProParser::class.simpleName}.")
val colonIndex = formattedInput.indexOf(COLON)
val baseFretIndex = formattedInput.indexOf(BASE_FRET)
val fretsIndex = formattedInput.indexOf(FRETS)
val fingersIndex = formattedInput.indexOf(FINGERS)
if (colonIndex == -1) throw ChordProParseException(message = "Expecting \':\' before Chord name in input for ${ChordProParser::class.simpleName}.")
val name = getName(colonIndex = colonIndex, baseFretIndex = baseFretIndex, input = formattedInput)
val stringLabels = mutableSetOf<StringLabel>()
var baseFret: FretNumber? = null
val chord = if (baseFretIndex != -1 && fretsIndex != -1) {
baseFret = getBaseFret(startIndex = baseFretIndex + BASE_FRET.length, endIndex = fretsIndex, input = formattedInput)
val fretNumbers = getFretNumbers(startIndex = fretsIndex + FRETS.length, endIndex = if (fingersIndex == -1) null else fingersIndex, input = formattedInput, baseFret = baseFret)
val fingers = getFingers(startIndex = fingersIndex + FINGERS.length, input = formattedInput)
if (fretNumbers.isEmpty()) throw ChordProParseException(message = "Expecting fret numbers in input for ${ChordProParser::class.simpleName}.")
if (fingers.isNotEmpty() && fretNumbers.size != fingers.size) throw ChordProParseException(message = "Expecting included finger positions to be the same size as the fret positions for input in ${ChordProParser::class.simpleName}.")
fretNumbers.forEachIndexed { index, _ ->
stringLabels.add(StringLabel(string = StringNumber(index + 1), label = null))
}
val markers = getMarkers(frets = fretNumbers, fingers = fingers)
Chord(name = name, markers = markers)
} else {
Chord(name = name, markers = emptySet())
}
return ChordParseResult(chord = chord, stringLabels = stringLabels, baseFret = baseFret)
}
private fun getName(colonIndex: Int, baseFretIndex: Int, input: String): String =
if (baseFretIndex == -1) {
input.substring(colonIndex).trim()
} else {
input.substring(colonIndex, baseFretIndex).trim()
}
private fun getBaseFret(startIndex: Int, endIndex: Int? = null, input: String): FretNumber {
val end = endIndex ?: input.length
if (startIndex >= end) throw ChordProParseException(message = "Expecting base fret in input for ${ChordProParser::class.simpleName}. End index was less than or equal to start index.")
val baseFret = input.substring(startIndex = startIndex, endIndex = end).trim().toIntOrNull()
?: throw ChordProParseException(message = "Expecting base fret in input for ${ChordProParser::class.simpleName}. Base fret was not an integer.")
return FretNumber(baseFret)
}
private fun getFretNumbers(startIndex: Int, endIndex: Int? = null, input: String, baseFret: FretNumber): List<FretNumber> {
val end = endIndex ?: input.length
if (startIndex >= end) throw ChordProParseException(message = "Expecting fret numbers in input for ${ChordProParser::class.simpleName}. End index was less than or equal to start index.")
val stringValues = input.substring(startIndex, end).trim().split(' ')
return stringValues.map { s ->
// A fret number is relative to the base fret with a value of zero meaning an open string.
// We need to convert it to an absolute value here.
val fretInt = s.toIntOrNull()?.let { baseFret.number + (it - 1) }
when {
MUTED_STRING_DELIMITERS.contains(s) -> FretNumber(-1) // Using a value of -1 to indicate a muted string here
OPEN_STRING_DELIMITERS.contains(s) -> FretNumber(0) // Using a value of 0 to indicate an open string here
fretInt == null -> throw ChordProParseException(message = "Invalid fret number found in input for ${ChordProParser::class.simpleName}. Fret number = $fretInt")
else -> FretNumber(fretInt)
}
}
}
private fun getFingers(startIndex: Int, endIndex: Int? = null, input: String): List<Finger> {
val end = endIndex ?: input.length
if (startIndex >= end) return emptyList()
val stringValues = input.substring(startIndex, end).trim().split(' ')
return stringValues.map {
val fingerInt = it.toIntOrNull() ?: -1
Finger.fromPosition(fingerInt)
}
}
private fun getMarkers(frets: List<FretNumber>, fingers: List<Finger>): Set<ChordMarker> =
frets.mapIndexed<FretNumber, ChordMarker> { index, fretNumber ->
// Frets are in order starting from the lowest String in tone to the highest. This means it's opposite of
// the actual String value.
val stringInt = frets.size - index
val finger = fingers.getOrNull(index) ?: Finger.UNKNOWN
when (fretNumber.number) {
-1 -> ChordMarker.Muted(string = StringNumber(stringInt))
0 -> ChordMarker.Open(string = StringNumber(stringInt))
else -> ChordMarker.Note(fret = fretNumber, string = StringNumber(stringInt), finger = finger)
}
}.toSet()
} | apache-2.0 | df7603037b2e35263de5f7192a1bd815 | 48.675862 | 243 | 0.649403 | 4.269117 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/library/views/access/SelectedLibraryViewProvider.kt | 2 | 1534 | package com.lasthopesoftware.bluewater.client.browsing.library.views.access
import com.lasthopesoftware.bluewater.client.browsing.library.access.ILibraryStorage
import com.lasthopesoftware.bluewater.client.browsing.library.access.session.ISelectedBrowserLibraryProvider
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library
import com.lasthopesoftware.bluewater.client.browsing.library.views.DownloadViewItem
import com.lasthopesoftware.bluewater.client.browsing.library.views.ViewItem
import com.namehillsoftware.handoff.promises.Promise
class SelectedLibraryViewProvider(
private val selectedLibrary: ISelectedBrowserLibraryProvider,
private val libraryViews: ProvideLibraryViews,
private val libraryStorage: ILibraryStorage) : ProvideSelectedLibraryView {
override fun promiseSelectedOrDefaultView(): Promise<ViewItem?> =
selectedLibrary.browserLibrary.eventually { library ->
libraryViews.promiseLibraryViews(library.libraryId).eventually { views ->
if (views.isNotEmpty()) {
when {
library.selectedViewType == Library.ViewType.DownloadView -> Promise(DownloadViewItem() as ViewItem)
library.selectedView > 0 -> Promise(views.first { it.key == library.selectedView })
else -> {
val selectedView = views.first()
library
.setSelectedView(selectedView.key)
.setSelectedViewType(Library.ViewType.StandardServerView)
libraryStorage.saveLibrary(library).then { selectedView }
}
}
}
else Promise.empty()
}
}
}
| lgpl-3.0 | c9b390ffc6ac3430de020b4ce970b7ae | 44.117647 | 108 | 0.787484 | 4.408046 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/accessors/runtime/Runtime.kt | 1 | 3167 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.accessors.runtime
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.ExternalModuleDependency
import org.gradle.api.artifacts.dsl.DependencyHandler
import org.gradle.api.internal.HasConvention
import org.gradle.api.plugins.Convention
import org.gradle.api.plugins.ExtensionAware
import org.gradle.kotlin.dsl.support.mapOfNonNullValuesOf
import org.gradle.kotlin.dsl.support.uncheckedCast
fun extensionOf(target: Any, extensionName: String): Any =
(target as ExtensionAware).extensions.getByName(extensionName)
fun conventionPluginOf(target: Any, name: String) =
conventionPluginByName(conventionOf(target), name)
fun conventionPluginByName(convention: Convention, name: String): Any =
convention.plugins[name] ?: throw IllegalStateException("A convention named '$name' could not be found.")
fun conventionOf(target: Any): Convention = when (target) {
is Project -> target.convention
is HasConvention -> target.convention
else -> throw IllegalStateException("Object `$target` doesn't support conventions!")
}
fun <T : Dependency> addDependencyTo(
dependencies: DependencyHandler,
configuration: String,
dependencyNotation: Any,
configurationAction: Action<T>
): T = dependencies.run {
uncheckedCast<T>(create(dependencyNotation)).also { dependency ->
configurationAction.execute(dependency)
add(configuration, dependency)
}
}
fun addExternalModuleDependencyTo(
dependencyHandler: DependencyHandler,
targetConfiguration: String,
group: String,
name: String,
version: String?,
configuration: String?,
classifier: String?,
ext: String?,
action: Action<ExternalModuleDependency>?
): ExternalModuleDependency = externalModuleDependencyFor(
dependencyHandler,
group,
name,
version,
configuration,
classifier,
ext
).also {
action?.execute(it)
dependencyHandler.add(targetConfiguration, it)
}
fun externalModuleDependencyFor(
dependencyHandler: DependencyHandler,
group: String,
name: String,
version: String?,
configuration: String?,
classifier: String?,
ext: String?
): ExternalModuleDependency = dependencyHandler.create(
mapOfNonNullValuesOf(
"group" to group,
"name" to name,
"version" to version,
"configuration" to configuration,
"classifier" to classifier,
"ext" to ext
)
) as ExternalModuleDependency
| apache-2.0 | ae1ad49d44fa1ec6ccca5323207131dd | 29.161905 | 109 | 0.737922 | 4.492199 | false | true | false | false |
Ph1b/MaterialAudiobookPlayer | data/src/main/kotlin/de/ph1b/audiobook/data/Bookmark.kt | 1 | 1387 | package de.ph1b.audiobook.data
import android.net.Uri
import androidx.core.net.toUri
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
import de.ph1b.audiobook.common.comparator.NaturalOrderComparator
import java.io.File
import java.time.Instant
import java.util.UUID
@Entity(tableName = "bookmark")
data class Bookmark(
@ColumnInfo(name = "file")
val mediaFile: File,
@ColumnInfo(name = "title")
val title: String?,
@ColumnInfo(name = "time")
val time: Long,
@ColumnInfo(name = "addedAt")
val addedAt: Instant,
@ColumnInfo(name = "setBySleepTimer")
val setBySleepTimer: Boolean,
@ColumnInfo(name = "id")
@PrimaryKey
val id: UUID
) : Comparable<Bookmark> {
@Ignore
val mediaUri: Uri = mediaFile.toUri()
override fun compareTo(other: Bookmark): Int {
// compare uri
val uriCompare = NaturalOrderComparator.uriComparator.compare(mediaUri, other.mediaUri)
if (uriCompare != 0) {
return uriCompare
}
// if files are the same compare time
val timeCompare = time.compareTo(other.time)
if (timeCompare != 0) return timeCompare
// if time is the same compare the titles
val titleCompare = NaturalOrderComparator.stringComparator.compare(title, other.title)
if (titleCompare != 0) return titleCompare
return id.compareTo(other.id)
}
}
| lgpl-3.0 | 2567c8cbb43a03b88cfc3ad7aa259b4d | 26.196078 | 91 | 0.730353 | 3.81044 | false | false | false | false |
FrancYescO/PokemonGoBot | src/main/kotlin/ink/abb/pogo/scraper/util/pokemon/PokemonData.kt | 2 | 2232 | /**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.util.pokemon
import POGOProtos.Data.PokemonDataOuterClass.PokemonData
import ink.abb.pogo.scraper.Settings
fun PokemonData.getIv(): Int {
val iv = individualAttack + individualDefense + individualStamina
return iv
}
fun PokemonData.getIvPercentage(): Int {
val iv = getIv()
val ivPercentage = (iv * 100) / 45
return ivPercentage
}
//fun PokemonData.getCpPercentageToPlayer(playerlevel: Int): Int {
// // TODO replace this when api has implemented this see Pokemon.kt
// return -1
//}
fun PokemonData.getStatsFormatted(): String {
val details = "Stamina: $individualStamina | Attack: $individualAttack | Defense: $individualDefense"
return details + " | IV: ${getIv()} (${(getIvPercentage())}%)"
}
// TODO: Deduplicate this
fun PokemonData.shouldTransfer(settings: Settings): Pair<Boolean, String> {
val obligatoryTransfer = settings.obligatoryTransfer
val ignoredPokemon = settings.ignoredPokemon
val ivPercentage = getIvPercentage()
val minIVPercentage = settings.transferIvThreshold
val minCP = settings.transferCpThreshold
var shouldRelease = obligatoryTransfer.contains(this.pokemonId)
var reason: String = "Obligatory transfer"
if (!ignoredPokemon.contains(this.pokemonId)) {
if (!shouldRelease) {
var ivTooLow = false
var cpTooLow = false
// never transfer > min IV percentage (unless set to -1)
if (ivPercentage < minIVPercentage || minIVPercentage == -1) {
ivTooLow = true
}
// never transfer > min CP (unless set to -1)
if (this.cp < minCP || minCP == -1) {
cpTooLow = true
}
reason = "CP < $minCP and IV < $minIVPercentage%"
shouldRelease = ivTooLow && cpTooLow
}
}
return Pair(shouldRelease, reason)
}
| gpl-3.0 | 8e5e3893b3232ff9ad4c9121b8ba7e66 | 34.428571 | 105 | 0.673835 | 4.179775 | false | false | false | false |
facebook/litho | litho-widget-kotlin/src/main/kotlin/com/facebook/litho/kotlin/widget/ExperimentalRecyclerWrapper.kt | 1 | 4348 | /*
* 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 main.kotlin.com.facebook.litho.kotlin.widget
import android.graphics.Color
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SnapHelper
import com.facebook.litho.Dimen
import com.facebook.litho.Style
import com.facebook.litho.dp
import com.facebook.litho.kotlin.widget.ExperimentalRecycler
import com.facebook.litho.widget.Binder
import com.facebook.litho.widget.LithoRecyclerView
import com.facebook.litho.widget.RecyclerEventsController
import com.facebook.litho.widget.SectionsRecyclerView
fun ExperimentalRecyclerWrapper(
binder: Binder<RecyclerView>,
hasFixedSize: Boolean? = null,
isClipToPaddingEnabled: Boolean? = null,
refreshProgressBarBackgroundColor: Int? = null,
refreshProgressBarColor: Int? = null,
isClipChildrenEnabled: Boolean? = null,
nestedScrollingEnabled: Boolean? = null,
scrollBarStyle: Int? = null,
itemDecoration: RecyclerView.ItemDecoration? = null,
horizontalFadingEdgeEnabled: Boolean? = null,
verticalFadingEdgeEnabled: Boolean? = null,
fadingEdgeLength: Dimen? = null,
recyclerViewId: Int? = null,
overScrollMode: Int? = null,
contentDescription: CharSequence? = null,
itemAnimator: RecyclerView.ItemAnimator? = ExperimentalRecycler.DEFAULT_ITEM_ANIMATOR,
recyclerEventsController: RecyclerEventsController? = null,
onScrollListeners: List<RecyclerView.OnScrollListener?>? = null,
snapHelper: SnapHelper? = null,
pullToRefresh: Boolean? = null,
touchInterceptor: LithoRecyclerView.TouchInterceptor? = null,
onItemTouchListener: RecyclerView.OnItemTouchListener? = null,
onRefresh: (() -> Unit)? = null,
sectionsViewLogger: SectionsRecyclerView.SectionsRecyclerViewLogger? = null,
useTwoBindersRecycler: Boolean = false,
enableSeparateAnimatorBinder: Boolean = false,
leftPadding: Int = 0,
topPadding: Int = 0,
rightPadding: Int = 0,
bottomPadding: Int = 0,
style: Style? = null
): ExperimentalRecycler =
ExperimentalRecycler(
binder = binder,
hasFixedSize = hasFixedSize ?: true,
isClipToPaddingEnabled = isClipToPaddingEnabled ?: true,
refreshProgressBarBackgroundColor = refreshProgressBarBackgroundColor,
refreshProgressBarColor = refreshProgressBarColor ?: Color.BLACK,
isClipChildrenEnabled = isClipChildrenEnabled ?: true,
isNestedScrollingEnabled = nestedScrollingEnabled ?: true,
scrollBarStyle = scrollBarStyle ?: View.SCROLLBARS_INSIDE_OVERLAY,
itemDecoration = itemDecoration,
isHorizontalFadingEdgeEnabled = horizontalFadingEdgeEnabled ?: false,
isVerticalFadingEdgeEnabled = verticalFadingEdgeEnabled ?: false,
fadingEdgeLength = fadingEdgeLength ?: 0.dp,
recyclerViewId = recyclerViewId ?: View.NO_ID,
overScrollMode = overScrollMode ?: View.OVER_SCROLL_ALWAYS,
contentDescription = contentDescription,
itemAnimator = itemAnimator ?: ExperimentalRecycler.DEFAULT_ITEM_ANIMATOR,
recyclerEventsController = recyclerEventsController,
onScrollListeners = onScrollListeners ?: emptyList(),
snapHelper = snapHelper,
isPullToRefreshEnabled = pullToRefresh ?: true,
touchInterceptor = touchInterceptor,
onItemTouchListener = onItemTouchListener,
onRefresh = onRefresh,
sectionsViewLogger = sectionsViewLogger,
useTwoBindersRecycler = useTwoBindersRecycler,
enableSeparateAnimatorBinder = enableSeparateAnimatorBinder,
leftPadding = leftPadding,
topPadding = topPadding,
rightPadding = rightPadding,
bottomPadding = bottomPadding,
style = style)
| apache-2.0 | 925d08a1d369068cd958935128624a89 | 44.291667 | 90 | 0.74448 | 4.815061 | false | false | false | false |
DadosAbertosBrasil/android-radar-politico | app/src/main/kotlin/br/edu/ifce/engcomp/francis/radarpolitico/models/Voto.kt | 1 | 269 | package br.edu.ifce.engcomp.francis.radarpolitico.models
/**
* Created by francisco on 12/03/16.
*/
data class Voto(
var voto: String? = "",
var nome: String? = "",
var partido: String? = "",
var idCadastro: String? = "",
var uf: String? = ""
)
| gpl-2.0 | 067ac2d6971b573eae34d5d9877c899d | 19.692308 | 56 | 0.594796 | 3.091954 | false | false | false | false |
moxi/weather-app-demo | weather-app/src/main/java/rcgonzalezf/org/weather/common/analytics/observer/GoogleAnalyticsObserver.kt | 1 | 2593 | package rcgonzalezf.org.weather.common.analytics.observer
import com.google.android.gms.analytics.GoogleAnalytics
import com.google.android.gms.analytics.HitBuilders
import com.google.android.gms.analytics.HitBuilders.ScreenViewBuilder
import com.google.android.gms.analytics.Tracker
import rcgonzalezf.org.weather.R
import rcgonzalezf.org.weather.WeatherApp
import rcgonzalezf.org.weather.common.analytics.AnalyticsBaseData
import rcgonzalezf.org.weather.common.analytics.AnalyticsEvent
import rcgonzalezf.org.weather.common.analytics.AnalyticsManager
import rcgonzalezf.org.weather.common.analytics.AnalyticsObserver
class GoogleAnalyticsObserver : AnalyticsObserver {
private var tracker: Tracker? = null
companion object {
private const val OS_VERSION = 1
private const val APP_VERSION = 2
private const val NETWORK = 3
private const val MULTIPANE = 4
}
// To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
@get:Synchronized
private val defaultTracker: Tracker?
private get() {
if (tracker == null) {
val analytics = GoogleAnalytics.getInstance(WeatherApp.getAppInstance())
// To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
tracker = analytics.newTracker(R.xml.global_tracker)
tracker?.setAnonymizeIp(true)
}
return tracker
}
override fun onScreen(screenName: String, analyticsBaseData: AnalyticsBaseData) {
tracker = defaultTracker
tracker?.setScreenName(screenName)
tracker?.send(ScreenViewBuilder().build())
}
override fun onAction(analyticsEvent: AnalyticsEvent, screenName: String,
analyticsBaseData: AnalyticsBaseData) {
val builder = HitBuilders.EventBuilder().setCategory(analyticsEvent.name)
if (analyticsEvent.additionalValue != null) {
builder.setAction(analyticsEvent.additionalValue)
}
builder.setCustomDimension(OS_VERSION,
analyticsBaseData.data()[AnalyticsManager.ANDROID_VERSION])
builder.setCustomDimension(APP_VERSION,
analyticsBaseData.data()[AnalyticsManager.APP_VERSION])
builder.setCustomDimension(NETWORK, analyticsBaseData.data()[AnalyticsManager.NETWORK])
builder.setCustomDimension(MULTIPANE,
analyticsBaseData.data()[AnalyticsManager.MULTIPANE])
tracker = defaultTracker
tracker?.setScreenName(screenName)
tracker?.send(builder.build())
}
}
| mit | 65b87d07295e104e8c572d707d12d0e5 | 41.508197 | 95 | 0.709217 | 4.883239 | false | false | false | false |
jdinkla/groovy-java-ray-tracer | src/main/kotlin/net/dinkla/raytracer/objects/utilities/ListUtilities.kt | 1 | 1586 | package net.dinkla.raytracer.objects.utilities
import net.dinkla.raytracer.math.Axis
import net.dinkla.raytracer.math.BBox
import net.dinkla.raytracer.math.Point3D
import net.dinkla.raytracer.objects.GeometricObject
import java.util.Collections
import java.util.Comparator
object ListUtilities {
fun splitByAxis(objects: List<GeometricObject>, split: Double, axis: Axis, objectsL: MutableList<GeometricObject>, objectsR: MutableList<GeometricObject>) {
objectsL.clear()
objectsR.clear()
for (`object` in objects) {
val bbox = `object`.boundingBox
if (bbox.p.ith(axis) <= split) {
objectsL.add(`object`)
}
if (bbox.q.ith(axis) >= split) {
objectsR.add(`object`)
}
}
}
fun compare(oP: GeometricObject, oQ: GeometricObject, axis: Axis): Int{
val bboxP = oP.boundingBox
val bboxQ = oQ.boundingBox
val p = bboxP.q
val pP = bboxP.p.ith(axis)
val widthP = bboxP.q.ith(axis) - pP
val medP = pP + 0.5 * widthP
val pQ = bboxQ.p.ith(axis)
val widthQ = bboxQ.q.ith(axis) - pQ
val medQ = pQ + 0.5 * widthQ
val q = bboxQ.q
return java.lang.Double.compare(medP, medQ)
}
fun sortByAxis(objects: List<GeometricObject>, axis: Axis) {
return Collections.sort(objects, { p, q -> compare(p, q, axis) })
}
fun size(objects: List<GeometricObject>): Int {
val size = 0
for (`object` in objects) {
}
return size
}
}
| apache-2.0 | e1d089a2acd5d8add6461c0c8528ca28 | 27.836364 | 160 | 0.600883 | 3.69697 | false | false | false | false |
consp1racy/android-commons | commons-services/src/main/java/net/xpece/android/app/SystemServices.kt | 1 | 12991 | @file:Suppress("unused")
package net.xpece.android.app
import android.accounts.AccountManager
import android.app.*
import android.app.admin.DevicePolicyManager
import android.app.job.JobScheduler
import android.app.usage.NetworkStatsManager
import android.app.usage.StorageStatsManager
import android.app.usage.UsageStatsManager
import android.appwidget.AppWidgetManager
import android.bluetooth.BluetoothManager
import android.companion.CompanionDeviceManager
import android.content.ClipboardManager
import android.content.Context
import android.content.RestrictionsManager
import android.content.pm.LauncherApps
import android.content.pm.ShortcutManager
import android.hardware.ConsumerIrManager
import android.hardware.SensorManager
import android.hardware.camera2.CameraManager
import android.hardware.display.DisplayManager
import android.hardware.fingerprint.FingerprintManager
import android.hardware.input.InputManager
import android.hardware.usb.UsbManager
import android.location.LocationManager
import android.media.AudioManager
import android.media.MediaRouter
import android.media.midi.MidiManager
import android.media.projection.MediaProjectionManager
import android.media.session.MediaSessionManager
import android.media.tv.TvInputManager
import android.net.ConnectivityManager
import android.net.nsd.NsdManager
import android.net.wifi.WifiManager
import android.net.wifi.aware.WifiAwareManager
import android.net.wifi.p2p.WifiP2pManager
import android.nfc.NfcManager
import android.os.*
import android.os.health.SystemHealthManager
import android.os.storage.StorageManager
import android.print.PrintManager
import android.support.annotation.RequiresApi
import android.support.v4.app.NotificationManagerCompat
import android.support.v4.hardware.display.DisplayManagerCompat
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat
import android.telecom.TelecomManager
import android.telephony.CarrierConfigManager
import android.telephony.SubscriptionManager
import android.telephony.TelephonyManager
import android.view.LayoutInflater
import android.view.WindowManager
import android.view.accessibility.AccessibilityManager
import android.view.accessibility.CaptioningManager
import android.view.inputmethod.InputMethodManager
import android.view.textclassifier.TextClassificationManager
import android.view.textservice.TextServicesManager
/**
* Never null.
*/
inline val Context.activityManager: ActivityManager
get() = getSystemServiceOrThrow(Context.ACTIVITY_SERVICE)
/**
* Never null.
*/
inline val Context.alarmManager: AlarmManager
get() = getSystemServiceOrThrow(Context.ALARM_SERVICE)
/**
* Never null.
*/
inline val Context.audioManager: AudioManager
get() = getSystemServiceOrThrow(Context.AUDIO_SERVICE)
inline val Context.clipboardManager: ClipboardManager?
get() = getSystemServiceOrNull(Context.CLIPBOARD_SERVICE)
inline val Context.connectivityManager: ConnectivityManager?
get() = getSystemServiceOrNull(Context.CONNECTIVITY_SERVICE)
/**
* Never null.
*/
inline val Context.keyguardManager: KeyguardManager
get() = getSystemServiceOrThrow(Context.KEYGUARD_SERVICE)
/**
* Never null.
*/
inline val Context.layoutInflater: LayoutInflater
get() = getSystemServiceOrThrow(Context.LAYOUT_INFLATER_SERVICE)
inline val Context.locationManager: LocationManager?
get() = getSystemServiceOrNull(Context.LOCATION_SERVICE)
/**
* Never null.
*/
inline val Context.notificationManager: NotificationManager
get() = getSystemServiceOrThrow(Context.NOTIFICATION_SERVICE)
/**
* Never null.
*
* Requires `support-compat` library version 24.2.0 or later
* or `support-v4` library version 22.0.0 or later.
*/
inline val Context.notificationManagerCompat: NotificationManagerCompat
get() = NotificationManagerCompat.from(this)
/**
* Never null.
*/
inline val Context.powerManager: PowerManager
get() = getSystemServiceOrThrow(Context.POWER_SERVICE)
inline val Context.searchManager: SearchManager?
get() = getSystemServiceOrNull(Context.SEARCH_SERVICE)
/**
* Never null.
*/
inline val Context.sensorManager: SensorManager
get() = getSystemServiceOrThrow(Context.SENSOR_SERVICE)
/**
* Never null.
*/
inline val Context.telephonyManager: TelephonyManager
get() = getSystemServiceOrThrow(Context.TELEPHONY_SERVICE)
/**
* Never null.
*/
inline val Context.vibrator: Vibrator
get() = getSystemServiceOrThrow(Context.VIBRATOR_SERVICE)
inline val Context.wallpaperService: WallpaperManager?
get() = getSystemServiceOrNull(Context.WALLPAPER_SERVICE)
inline val Context.wifiManager: WifiManager?
get() = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
applicationContext.getSystemServiceOrNull(Context.WIFI_SERVICE)
} else {
getSystemServiceOrNull(Context.WIFI_SERVICE)
}
/**
* Never null.
*/
inline val Context.windowManager: WindowManager
get() = getSystemServiceOrThrow(Context.WINDOW_SERVICE)
/**
* Never null.
*/
inline val Context.inputMethodManager: InputMethodManager
get() = getSystemServiceOrThrow(Context.INPUT_METHOD_SERVICE)
/**
* Never null.
*/
inline val Context.accessibilityManager: AccessibilityManager
get() = getSystemServiceOrThrow(Context.ACCESSIBILITY_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(5)
inline val Context.accountManager: AccountManager
get() = getSystemServiceOrThrow(Context.ACCOUNT_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(8)
inline val Context.devicePolicyManager: DevicePolicyManager
get() = getSystemServiceOrThrow(Context.DEVICE_POLICY_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(8)
inline val Context.dropBoxManager: DropBoxManager
get() = getSystemServiceOrThrow(Context.DROPBOX_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(8)
inline val Context.uiModeManager: UiModeManager
get() = getSystemServiceOrThrow(Context.UI_MODE_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(9)
inline val Context.downloadManager: DownloadManager
get() = getSystemServiceOrThrow(Context.DOWNLOAD_SERVICE)
@get:RequiresApi(9)
inline val Context.storageManager: StorageManager?
get() = getSystemServiceOrNull(Context.STORAGE_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(10)
inline val Context.nfcManager: NfcManager
get() = getSystemServiceOrThrow(Context.NFC_SERVICE)
@get:RequiresApi(12)
inline val Context.usbManager: UsbManager?
get() = getSystemServiceOrNull(Context.USB_SERVICE)
@get:RequiresApi(14)
inline val Context.textServicesManager: TextServicesManager?
get() = getSystemServiceOrNull(Context.TEXT_SERVICES_MANAGER_SERVICE)
@get:RequiresApi(14)
inline val Context.wifiP2pManager: WifiP2pManager?
get() = getSystemServiceOrNull(Context.WIFI_P2P_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(16)
inline val Context.inputManager: InputManager
get() = getSystemServiceOrThrow(Context.INPUT_SERVICE)
@get:RequiresApi(16)
inline val Context.mediaRouter: MediaRouter?
get() = getSystemServiceOrNull(Context.MEDIA_ROUTER_SERVICE)
@get:RequiresApi(16)
inline val Context.nsdManager: NsdManager?
get() = getSystemServiceOrNull(Context.NSD_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(17)
inline val Context.displayManager: DisplayManager
get() = getSystemServiceOrThrow(Context.DISPLAY_SERVICE)
/**
* Never null.
*
* Requires `support-compat` library version 24.2.0 or later
* or `support-v4` library version 22.0.0 or later.
*/
inline val Context.displayManagerCompat: DisplayManagerCompat
get() = DisplayManagerCompat.getInstance(this)
/**
* Never null.
*/
@get:RequiresApi(17)
inline val Context.userManager: UserManager
get() = getSystemServiceOrThrow(Context.USER_SERVICE)
@get:RequiresApi(18)
inline val Context.bluetoothManager: BluetoothManager?
get() = getSystemServiceOrNull(Context.BLUETOOTH_SERVICE)
@get:RequiresApi(19)
inline val Context.appOpsManager: AppOpsManager?
get() = getSystemServiceOrNull(Context.APP_OPS_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(19)
inline val Context.captioningManager: CaptioningManager
get() = getSystemServiceOrThrow(Context.CAPTIONING_SERVICE)
@get:RequiresApi(19)
inline val Context.consumerIrManager: ConsumerIrManager?
get() = getSystemServiceOrNull(Context.CONSUMER_IR_SERVICE)
@get:RequiresApi(19)
inline val Context.printManager: PrintManager?
get() = getSystemServiceOrNull(Context.PRINT_SERVICE)
@get:RequiresApi(21)
inline val Context.appWidgetManager: AppWidgetManager?
get() = getSystemServiceOrNull(Context.APPWIDGET_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(21)
inline val Context.batteryManager: BatteryManager
get() = getSystemServiceOrThrow(Context.BATTERY_SERVICE)
@get:RequiresApi(21)
inline val Context.cameraManager: CameraManager?
get() = getSystemServiceOrNull(Context.CAMERA_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(21)
inline val Context.jobScheduler: JobScheduler
get() = getSystemServiceOrThrow(Context.JOB_SCHEDULER_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(21)
inline val Context.launcherApps: LauncherApps
get() = getSystemServiceOrThrow(Context.LAUNCHER_APPS_SERVICE)
@get:RequiresApi(21)
inline val Context.mediaProjectionManager: MediaProjectionManager?
get() = getSystemServiceOrNull(Context.MEDIA_PROJECTION_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(21)
inline val Context.mediaSessionManager: MediaSessionManager
get() = getSystemServiceOrThrow(Context.MEDIA_SESSION_SERVICE)
@get:RequiresApi(21)
inline val Context.restrictionsManager: RestrictionsManager?
get() = getSystemServiceOrNull(Context.RESTRICTIONS_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(21)
inline val Context.telecomManager: TelecomManager
get() = getSystemServiceOrThrow(Context.TELECOM_SERVICE)
@get:RequiresApi(21)
inline val Context.tvInputManager: TvInputManager?
get() = getSystemServiceOrNull(Context.TV_INPUT_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(22)
inline val Context.subscriptionManager: SubscriptionManager
get() = getSystemServiceOrThrow(Context.TELEPHONY_SUBSCRIPTION_SERVICE)
@get:RequiresApi(22)
inline val Context.usageStatsManager: UsageStatsManager?
get() = getSystemServiceOrNull(Context.USAGE_STATS_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(23)
inline val Context.carrierConfigManager: CarrierConfigManager
get() = getSystemServiceOrThrow(Context.CARRIER_CONFIG_SERVICE)
@get:RequiresApi(23)
inline val Context.fingerprintManager: FingerprintManager?
get() = getSystemServiceOrNull(Context.FINGERPRINT_SERVICE)
/**
* Never null.
*
* Requires `support-compat` library version 23.0.0 or later.
*/
inline val Context.fingerprintManagerCompat: FingerprintManagerCompat
get() = FingerprintManagerCompat.from(this)
@get:RequiresApi(23)
inline val Context.midiManager: MidiManager?
get() = getSystemServiceOrNull(Context.MIDI_SERVICE)
@get:RequiresApi(23)
inline val Context.networkStatsManager: NetworkStatsManager?
get() = getSystemServiceOrNull(Context.NETWORK_STATS_SERVICE)
@get:RequiresApi(24)
inline val Context.hardwarePropertiesManager: HardwarePropertiesManager?
get() = getSystemServiceOrNull(Context.HARDWARE_PROPERTIES_SERVICE)
@get:RequiresApi(24)
inline val Context.systemHealthManager: SystemHealthManager?
get() = getSystemServiceOrNull(Context.SYSTEM_HEALTH_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(25)
inline val Context.shortcutManager: ShortcutManager
get() = getSystemServiceOrThrow(Context.SHORTCUT_SERVICE)
@get:RequiresApi(26)
inline val Context.companionDeviceManager: CompanionDeviceManager?
get() = getSystemServiceOrNull(Context.COMPANION_DEVICE_SERVICE)
@get:RequiresApi(26)
inline val Context.storageStatsManager: StorageStatsManager?
get() = getSystemServiceOrNull(Context.STORAGE_STATS_SERVICE)
/**
* Never null.
*/
@get:RequiresApi(26)
inline val Context.textClassificationManager: TextClassificationManager
get() = getSystemServiceOrThrow(Context.TEXT_CLASSIFICATION_SERVICE)
@get:RequiresApi(26)
inline val Context.wifiAwareManager: WifiAwareManager?
get() = getSystemServiceOrNull(Context.WIFI_AWARE_SERVICE)
inline fun <reified T> Context.getSystemServiceOrNull(name: String): T? =
getSystemService(name) as T?
/**
* @throws ServiceNotFoundException When service is not found.
*/
inline fun <reified T> Context.getSystemServiceOrThrow(name: String): T =
getSystemServiceOrNull<T>(name) ?:
throw ServiceNotFoundException(
"${T::class.java.simpleName} not found.")
@RequiresApi(23)
inline fun <reified T> Context.getSystemServiceOrNull(): T? =
getSystemService(T::class.java)
/**
* @throws ServiceNotFoundException When service is not found.
*/
@RequiresApi(23)
inline fun <reified T> Context.getSystemServiceOrThrow(): T =
getSystemServiceOrNull<T>() ?:
throw ServiceNotFoundException(
"${T::class.java.simpleName} not found.")
| apache-2.0 | 4615c7244f5eb72c72ecee5d1ce65690 | 28.727689 | 75 | 0.783004 | 4.301656 | false | false | false | false |
epabst/kotlin-showcase | src/jsMain/kotlin/firebase/auth/firebase.index.firebase.auth.kt | 1 | 10599 | @file:[JsModule("firebase/app") JsQualifier("auth") JsNonModule]
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "unused", "ClassName")
package firebase.auth
import firebase.Unsubscribe
import firebase.app.App
import firebase.app.Observer
import firebase.app.User
import kotlin.js.*
import kotlin.js.Json
open external class ActionCodeURL {
open var apiKey: String
open var code: String
open var continueUrl: String?
open var languageCode: String?
open var operation: Operation
open var tenantId: String?
companion object {
fun parseLink(link: String): ActionCodeURL?
}
}
external interface `T$6` {
var email: String? get() = definedExternally; set(value) = definedExternally
var fromEmail: String? get() = definedExternally; set(value) = definedExternally
}
external interface ActionCodeInfo {
var data: `T$6`
var operation: String
}
external interface `T$7` {
var installApp: Boolean? get() = definedExternally; set(value) = definedExternally
var minimumVersion: String? get() = definedExternally; set(value) = definedExternally
var packageName: String
}
external interface `T$8` {
var bundleId: String
}
external interface ActionCodeSettings {
var android: `T$7`? get() = definedExternally; set(value) = definedExternally
var handleCodeInApp: Boolean? get() = definedExternally; set(value) = definedExternally
var iOS: `T$8`? get() = definedExternally; set(value) = definedExternally
var url: String
var dynamicLinkDomain: String? get() = definedExternally; set(value) = definedExternally
}
external interface AdditionalUserInfo {
var isNewUser: Boolean
var profile: Any?
var providerId: String
var username: String? get() = definedExternally; set(value) = definedExternally
}
external interface ApplicationVerifier {
var type: String
fun verify(): Promise<String>
}
external interface AuthSettings {
var appVerificationDisabledForTesting: Boolean
}
external interface Auth {
var app: App
fun applyActionCode(code: String): Promise<Unit>
fun checkActionCode(code: String): Promise<ActionCodeInfo>
fun confirmPasswordReset(code: String, newPassword: String): Promise<Unit>
fun createUserWithEmailAndPassword(email: String, password: String): Promise<UserCredential>
var currentUser: User?
fun fetchSignInMethodsForEmail(email: String): Promise<Array<String>>
fun isSignInWithEmailLink(emailLink: String): Boolean
fun getRedirectResult(): Promise<UserCredential>
var languageCode: String?
var settings: AuthSettings
fun onAuthStateChanged(nextOrObserver: Observer<Any, Error>, error: ((a: Error) -> Any)? = definedExternally /* null */, completed: Unsubscribe? = definedExternally /* null */): Unsubscribe
fun onAuthStateChanged(nextOrObserver: (a: User?) -> Any, error: ((a: Error) -> Any)? = definedExternally /* null */, completed: Unsubscribe? = definedExternally /* null */): Unsubscribe
fun onIdTokenChanged(nextOrObserver: Observer<Any,Error>, error: ((a: Error) -> Any)? = definedExternally /* null */, completed: Unsubscribe? = definedExternally /* null */): Unsubscribe
fun onIdTokenChanged(nextOrObserver: (a: User?) -> Any, error: ((a: Error) -> Any)? = definedExternally /* null */, completed: Unsubscribe? = definedExternally /* null */): Unsubscribe
fun sendSignInLinkToEmail(email: String, actionCodeSettings: ActionCodeSettings): Promise<Unit>
fun sendPasswordResetEmail(email: String, actionCodeSettings: ActionCodeSettings? = definedExternally /* null */): Promise<Unit>
fun setPersistence(persistence: Persistence): Promise<Unit>
fun signInAndRetrieveDataWithCredential(credential: AuthCredential): Promise<UserCredential>
fun signInAnonymously(): Promise<UserCredential>
fun signInWithCredential(credential: AuthCredential): Promise<UserCredential>
fun signInWithCustomToken(token: String): Promise<UserCredential>
fun signInWithEmailAndPassword(email: String, password: String): Promise<UserCredential>
fun signInWithPhoneNumber(phoneNumber: String, applicationVerifier: ApplicationVerifier): Promise<ConfirmationResult>
fun signInWithEmailLink(email: String, emailLink: String? = definedExternally /* null */): Promise<UserCredential>
fun signInWithPopup(provider: AuthProvider): Promise<UserCredential>
fun signInWithRedirect(provider: AuthProvider): Promise<Unit>
fun signOut(): Promise<Unit>
var tenantId: String?
fun updateCurrentUser(user: User?): Promise<Unit>
fun useDeviceLanguage()
fun verifyPasswordResetCode(code: String): Promise<String>
}
open external class AuthCredential {
open var providerId: String
open var signInMethod: String
open fun toJSON(): Any
companion object {
fun fromJSON(json: Any): AuthCredential?
fun fromJSON(json: String): AuthCredential?
}
}
open external class OAuthCredential : AuthCredential {
open var idToken: String
open var accessToken: String
open var secret: String
}
external interface AuthProvider {
var providerId: String
}
abstract external class AuthProviderWithCustomParameters : AuthProvider {
override var providerId: String = definedExternally
fun setCustomParameters(customOAuthParameters: Any): AuthProvider = definedExternally
}
abstract external class AuthProviderWithScopeAndCustomParameters : AuthProviderWithCustomParameters {
fun addScope(scope: String): AuthProvider = definedExternally
}
external interface ConfirmationResult {
fun confirm(verificationCode: String): Promise<UserCredential>
var verificationId: String
}
open external class EmailAuthProvider : EmailAuthProvider_Instance {
companion object {
var PROVIDER_ID: String
var EMAIL_PASSWORD_SIGN_IN_METHOD: String
var EMAIL_LINK_SIGN_IN_METHOD: String
fun credential(email: String, password: String): AuthCredential
fun credentialWithLink(email: String, emailLink: String): AuthCredential
}
}
open external class EmailAuthProvider_Instance : AuthProvider {
override var providerId: String
}
external interface Error {
var code: String
var message: String
}
external interface AuthError : Error {
var credential: AuthCredential? get() = definedExternally; set(value) = definedExternally
var email: String? get() = definedExternally; set(value) = definedExternally
var phoneNumber: String? get() = definedExternally; set(value) = definedExternally
var tenantId: String? get() = definedExternally; set(value) = definedExternally
}
open external class FacebookAuthProvider : FacebookAuthProvider_Instance {
companion object {
var PROVIDER_ID: String
var FACEBOOK_SIGN_IN_METHOD: String
fun credential(token: String): OAuthCredential
}
}
open external class FacebookAuthProvider_Instance : AuthProviderWithScopeAndCustomParameters
open external class GithubAuthProvider : GithubAuthProvider_Instance {
companion object {
var PROVIDER_ID: String
var GITHUB_SIGN_IN_METHOD: String
fun credential(token: String): OAuthCredential
}
}
open external class GithubAuthProvider_Instance : AuthProviderWithScopeAndCustomParameters
open external class GoogleAuthProvider : GoogleAuthProvider_Instance {
companion object {
var PROVIDER_ID: String
var GOOGLE_SIGN_IN_METHOD: String
fun credential(idToken: String? = definedExternally /* null */, accessToken: String? = definedExternally /* null */): OAuthCredential
}
}
open external class GoogleAuthProvider_Instance : AuthProviderWithScopeAndCustomParameters
open external class OAuthProvider(providerId: String) : AuthProviderWithScopeAndCustomParameters {
override var providerId: String
open fun credential(optionsOrIdToken: OAuthCredentialOptions, accessToken: String? = definedExternally /* null */): OAuthCredential
open fun credential(optionsOrIdToken: String, accessToken: String? = definedExternally /* null */): OAuthCredential
open fun credential(optionsOrIdToken: Nothing?, accessToken: String? = definedExternally /* null */): OAuthCredential
}
open external class SAMLAuthProvider : AuthProvider {
override var providerId: String
}
external interface IdTokenResult {
var token: String
var expirationTime: String
var authTime: String
var issuedAtTime: String
var signInProvider: String?
var claims: Json
}
external interface OAuthCredentialOptions {
var idToken: String? get() = definedExternally; set(value) = definedExternally
var accessToken: String? get() = definedExternally; set(value) = definedExternally
var rawNonce: String? get() = definedExternally; set(value) = definedExternally
}
open external class PhoneAuthProvider : PhoneAuthProvider_Instance {
companion object {
var PROVIDER_ID: String
var PHONE_SIGN_IN_METHOD: String
fun credential(verificationId: String, verificationCode: String): AuthCredential
}
}
open external class PhoneAuthProvider_Instance(auth: Auth? = definedExternally /* null */) : AuthProvider {
override var providerId: String
open fun verifyPhoneNumber(phoneNumber: String, applicationVerifier: ApplicationVerifier): Promise<String>
}
open external class RecaptchaVerifier : RecaptchaVerifier_Instance
open external class RecaptchaVerifier_Instance : ApplicationVerifier {
constructor(container: Any, parameters: Any?, app: App?)
constructor(container: String, parameters: Any?, app: App?)
open fun clear()
open fun render(): Promise<Number>
override var type: String
override fun verify(): Promise<String>
}
open external class TwitterAuthProvider : TwitterAuthProvider_Instance {
companion object {
var PROVIDER_ID: String
var TWITTER_SIGN_IN_METHOD: String
fun credential(token: String, secret: String): OAuthCredential
}
}
open external class TwitterAuthProvider_Instance : AuthProviderWithCustomParameters
external interface UserCredential {
var additionalUserInfo: AdditionalUserInfo? get() = definedExternally; set(value) = definedExternally
var credential: AuthCredential?
var operationType: String? get() = definedExternally; set(value) = definedExternally
var user: User?
}
external interface UserMetadata {
var creationTime: String? get() = definedExternally; set(value) = definedExternally
var lastSignInTime: String? get() = definedExternally; set(value) = definedExternally
} | apache-2.0 | 6412f32c0165a1dc16aa939c746c63b8 | 45.902655 | 193 | 0.752335 | 4.776476 | false | false | false | false |
xfournet/intellij-community | platform/vcs-log/impl/test/com/intellij/vcs/log/visible/VisiblePackBuilderTest.kt | 1 | 9166 | /*
* 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.vcs.log.visible
import com.intellij.mock.MockVirtualFile
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Consumer
import com.intellij.util.Function
import com.intellij.vcs.log.*
import com.intellij.vcs.log.data.*
import com.intellij.vcs.log.graph.GraphCommit
import com.intellij.vcs.log.graph.GraphCommitImpl
import com.intellij.vcs.log.graph.PermanentGraph
import com.intellij.vcs.log.graph.VisibleGraph
import com.intellij.vcs.log.impl.*
import com.intellij.vcs.log.impl.TestVcsLogProvider.BRANCH_TYPE
import com.intellij.vcs.log.impl.TestVcsLogProvider.DEFAULT_USER
import com.intellij.vcs.log.impl.VcsLogFilterCollectionImpl.VcsLogFilterCollectionBuilder
import org.junit.Test
import java.util.*
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class VisiblePackBuilderTest {
@Test fun `no filters`() {
val graph = graph {
1(2) *"master"
2(3)
3(4)
4()
}
val visiblePack = graph.build(noFilters())
assertEquals(4, visiblePack.visibleGraph.visibleCommitCount)
}
@Test fun `branch filter`() {
val graph = graph {
1(3) *"master"
2(3) *"feature"
3(4)
4()
}
val visiblePack = graph.build(filters(branch = listOf("master")))
val visibleGraph = visiblePack.visibleGraph
assertEquals(3, visibleGraph.visibleCommitCount)
assertDoesNotContain(visibleGraph, 2)
}
@Test fun `filter by user in memory`() {
val graph = graph {
1(2) *"master"
2(3)
3(4) +"bob.doe"
4(5)
5(6)
6(7)
7()
}
val visiblePack = graph.build(filters(user = DEFAULT_USER))
val visibleGraph = visiblePack.visibleGraph
assertEquals(6, visibleGraph.visibleCommitCount)
assertDoesNotContain(visibleGraph, 3)
}
@Test fun `filter by branch deny`() {
val graph = graph {
1(3) *"master"
2(3) *"feature"
3(4)
4()
}
val visiblePack = graph.build(filters(VcsLogBranchFilterImpl.fromTextPresentation(setOf("-master"), setOf("master"))))
val visibleGraph = visiblePack.visibleGraph
assertEquals(3, visibleGraph.visibleCommitCount)
assertDoesNotContain(visibleGraph, 1)
}
@Test fun `filter by branch deny works with extra results from vcs provider`() {
val graph = graph {
1(3) *"master" +null
2(3) *"feature" +null
3(4) +null
4() +null
}
val func = Function<VcsLogFilterCollection, MutableList<TimedVcsCommit>> {
ArrayList(listOf(2, 3, 4).map {
val id = it
val commit = graph.commits.firstOrNull {
it.id == id
}
commit!!.toVcsCommit(graph.hashMap)
})
}
graph.providers.entries.iterator().next().value.setFilteredCommitsProvider(func)
val visiblePack = graph.build(filters(VcsLogBranchFilterImpl.fromTextPresentation(setOf("-master"), setOf("master")), userFilter(DEFAULT_USER)))
val visibleGraph = visiblePack.visibleGraph
assertEquals(3, visibleGraph.visibleCommitCount)
assertDoesNotContain(visibleGraph, 1)
}
private fun GraphCommit<Int>.toVcsCommit(storage: VcsLogStorage) = TimedVcsCommitImpl(storage.getCommitId(this.id)!!.hash, storage.getHashes(this.parents), 1)
fun assertDoesNotContain(graph: VisibleGraph<Int>, id: Int) {
assertTrue(null == (1..graph.visibleCommitCount).firstOrNull { graph.getRowInfo(it - 1).commit == id })
}
data class Ref(val name: String, val commit: Int)
data class Data(val user: VcsUser? = DEFAULT_USER, val subject: String = "default commit message")
inner class Graph(val commits: List<GraphCommit<Int>>,
val refs: Set<Ref>,
val data: HashMap<GraphCommit<Int>, Data>) {
val root: VirtualFile = MockVirtualFile("root")
val providers: Map<VirtualFile, TestVcsLogProvider> = mapOf(root to TestVcsLogProvider(root))
val hashMap = generateHashMap(commits.maxBy { it.id }!!.id, refs, root)
fun build(filters: VcsLogFilterCollection): VisiblePack {
val dataPack = DataPack.build(commits, mapOf(root to hashMap.refsReversed.keys).mapValues { CompressedRefs(it.value, hashMap) }, providers, hashMap, true)
val detailsCache = TopCommitsCache(hashMap)
detailsCache.storeDetails(ArrayList(data.entries.mapNotNull {
val hash = hashMap.getCommitId(it.key.id).hash
if (it.value.user == null)
null
else VcsCommitMetadataImpl(hash, hashMap.getHashes(it.key.parents), 1L, root, it.value.subject,
it.value.user!!, it.value.subject, it.value.user!!, 1L)
}))
val commitDetailsGetter = object : DataGetter<VcsFullCommitDetails> {
override fun getCommitData(row: Int, neighbourHashes: MutableIterable<Int>): VcsFullCommitDetails {
throw UnsupportedOperationException()
}
override fun loadCommitsData(hashes: MutableList<Int>, consumer: Consumer<MutableList<VcsFullCommitDetails>>, indicator: ProgressIndicator?) {
}
override fun getCommitDataIfAvailable(hash: Int): VcsFullCommitDetails? {
return null
}
}
val builder = VcsLogFilterer(providers, hashMap, detailsCache, commitDetailsGetter, EmptyIndex())
return builder.filter(dataPack, PermanentGraph.SortType.Normal, filters, CommitCountStage.INITIAL).first
}
fun generateHashMap(num: Int, refs: Set<Ref>, root: VirtualFile): ConstantVcsLogStorage {
val hashes = HashMap<Int, Hash>()
for (i in 1..num) {
hashes.put(i, HashImpl.build(i.toString()))
}
val vcsRefs = refs.mapTo(ArrayList<VcsRef>(), {
VcsRefImpl(hashes[it.commit]!!, it.name, BRANCH_TYPE, root)
})
return ConstantVcsLogStorage(hashes, vcsRefs.indices.map { Pair(it, vcsRefs[it]) }.toMap(), root)
}
}
fun VcsLogStorage.getHashes(ids: List<Int>) = ids.map { getCommitId(it)!!.hash }
fun noFilters(): VcsLogFilterCollection = VcsLogFilterCollectionBuilder().build()
fun filters(branch: VcsLogBranchFilter? = null, user: VcsLogUserFilter? = null)
= VcsLogFilterCollectionBuilder(branch, user).build()
fun filters(branch: List<String>? = null, user: VcsUser? = null)
= VcsLogFilterCollectionBuilder(branchFilter(branch), userFilter(user)).build()
fun branchFilter(branch: List<String>?): VcsLogBranchFilterImpl? {
return if (branch != null) VcsLogBranchFilterImpl.fromTextPresentation(branch, branch.toHashSet()) else null
}
fun userFilter(user: VcsUser?): VcsLogUserFilter? {
return if (user != null) VcsLogUserFilterImpl(listOf(user.name), emptyMap(), setOf(user)) else null
}
fun graph(f: GraphBuilder.() -> Unit): Graph {
val builder = GraphBuilder()
builder.f()
return builder.done()
}
inner class GraphBuilder {
val commits = ArrayList<GraphCommit<Int>>()
val refs = HashSet<Ref>()
val data = HashMap<GraphCommit<Int>, Data>()
operator fun Int.invoke(vararg id: Int): GraphCommit<Int> {
val commit = GraphCommitImpl.createCommit(this, id.toList(), this.toLong())
commits.add(commit)
data[commit] = Data()
return commit
}
operator fun GraphCommit<Int>.times(name: String): GraphCommit<Int> {
refs.add(Ref(name, this.id))
return this
}
operator fun GraphCommit<Int>.plus(name: String): GraphCommit<Int> {
data[this] = Data(VcsUserImpl(name, name + "@example.com"))
return this
}
operator fun GraphCommit<Int>.plus(user: VcsUser?): GraphCommit<Int> {
data[this] = Data(user)
return this
}
fun done() = Graph(commits, refs, data)
}
class ConstantVcsLogStorage(private val hashes: Map<Int, Hash>, val refs: Map<Int, VcsRef>, val root: VirtualFile) : VcsLogStorage {
private val hashesReversed = hashes.entries.map { Pair(it.value, it.key) }.toMap()
val refsReversed = refs.entries.map { Pair(it.value, it.key) }.toMap()
override fun getCommitIndex(hash: Hash, root: VirtualFile) = hashesReversed[hash]!!
override fun getCommitId(commitIndex: Int) = CommitId(hashes[commitIndex]!!, root)
override fun containsCommit(id: CommitId): Boolean = root == id.root && hashesReversed.containsKey(id.hash)
override fun getVcsRef(refIndex: Int): VcsRef = refs[refIndex]!!
override fun getRefIndex(ref: VcsRef): Int = refsReversed[ref]!!
override fun iterateCommits(consumer: Function<CommitId, Boolean>) = throw UnsupportedOperationException()
override fun flush() {
}
}
}
| apache-2.0 | b70eee0f1335beaac0fe8d15632301a4 | 35.811245 | 160 | 0.690596 | 4.177758 | false | true | false | false |
Kotlin/dokka | plugins/base/src/test/kotlin/model/annotations/JavaAnnotationsTest.kt | 1 | 7938 | package model.annotations
import org.jetbrains.dokka.base.testApi.testRunner.BaseAbstractTest
import org.jetbrains.dokka.model.*
import org.junit.jupiter.api.Test
import translators.findClasslike
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class JavaAnnotationsTest : BaseAbstractTest() {
val configuration = dokkaConfiguration {
sourceSets {
sourceSet {
sourceRoots = listOf("src/main/java")
}
}
}
@Test // see https://github.com/Kotlin/dokka/issues/2350
fun `should hande array used as annotation param value`() {
testInline(
"""
|/src/main/java/annotation/TestClass.java
|package annotation;
|public class TestClass {
| @SimpleAnnotation(clazz = String[].class)
| public boolean simpleAnnotation() {
| return false;
| }
|}
|
|/src/main/java/annotation/SimpleAnnotation.java
|package annotation;
|@Retention(RetentionPolicy.RUNTIME)
|@Target(ElementType.METHOD)
|public @interface SimpleAnnotation {
| Class<?> clazz();
|}
""".trimIndent(),
configuration
) {
documentablesTransformationStage = { module ->
val testClass = module.findClasslike("annotation", "TestClass") as DClass
assertNotNull(testClass)
val annotatedFunction = testClass.functions.single { it.name == "simpleAnnotation" }
val annotation =
annotatedFunction.extra[Annotations]?.directAnnotations?.entries?.single()?.value?.single()
assertNotNull(annotation) { "Expected to find an annotation on simpleAnnotation function, found none" }
assertEquals("annotation", annotation.dri.packageName)
assertEquals("SimpleAnnotation", annotation.dri.classNames)
assertEquals(1, annotation.params.size)
val param = annotation.params.values.single()
assertTrue(param is ClassValue)
// should probably be Array instead
// String matches parsing of Kotlin sources as of now
assertEquals("String", param.className)
assertEquals("java.lang", param.classDRI.packageName)
assertEquals("String", param.classDRI.classNames)
}
}
}
@Test // see https://github.com/Kotlin/dokka/issues/2551
fun `should hande annotation used within annotation params with class param value`() {
testInline(
"""
|/src/main/java/annotation/TestClass.java
|package annotation;
|public class TestClass {
| @XmlElementRefs({
| @XmlElementRef(name = "NotOffered", namespace = "http://www.gaeb.de/GAEB_DA_XML/DA86/3.3", type = JAXBElement.class, required = false)
| })
| public List<JAXBElement<Object>> content;
|}
|
|/src/main/java/annotation/XmlElementRefs.java
|package annotation;
|public @interface XmlElementRefs {
| XmlElementRef[] value();
|}
|
|/src/main/java/annotation/XmlElementRef.java
|package annotation;
|public @interface XmlElementRef {
| String name();
|
| String namespace();
|
| boolean required();
|
| Class<JAXBElement> type();
|}
|
|/src/main/java/annotation/JAXBElement.java
|package annotation;
|public class JAXBElement<T> {
|}
""".trimIndent(),
configuration
) {
documentablesTransformationStage = { module ->
val testClass = module.findClasslike("annotation", "TestClass") as DClass
assertNotNull(testClass)
val contentField = testClass.properties.find { it.name == "content" }
assertNotNull(contentField)
val annotation = contentField.extra[Annotations]?.directAnnotations?.entries?.single()?.value?.single()
assertNotNull(annotation) { "Expected to find an annotation on content field, found none" }
assertEquals("XmlElementRefs", annotation.dri.classNames)
assertEquals(1, annotation.params.size)
val arrayParam = annotation.params.values.single()
assertTrue(arrayParam is ArrayValue, "Expected single annotation param to be array")
assertEquals(1, arrayParam.value.size)
val arrayParamValue = arrayParam.value.single()
assertTrue(arrayParamValue is AnnotationValue)
val arrayParamAnnotationValue = arrayParamValue.annotation
assertEquals(4, arrayParamAnnotationValue.params.size)
assertEquals("XmlElementRef", arrayParamAnnotationValue.dri.classNames)
val annotationParams = arrayParamAnnotationValue.params.values.toList()
val nameParam = annotationParams[0]
assertTrue(nameParam is StringValue)
assertEquals("NotOffered", nameParam.value)
val namespaceParam = annotationParams[1]
assertTrue(namespaceParam is StringValue)
assertEquals("http://www.gaeb.de/GAEB_DA_XML/DA86/3.3", namespaceParam.value)
val typeParam = annotationParams[2]
assertTrue(typeParam is ClassValue)
assertEquals("JAXBElement", typeParam.className)
assertEquals("annotation", typeParam.classDRI.packageName)
assertEquals("JAXBElement", typeParam.classDRI.classNames)
val requiredParam = annotationParams[3]
assertTrue(requiredParam is BooleanValue)
assertFalse(requiredParam.value)
}
}
}
@Test // see https://github.com/Kotlin/dokka/issues/2509
fun `should handle generic class in annotation`() {
testInline(
"""
|/src/main/java/annotation/Breaking.java
|package annotation;
|public class Breaking<Y> {
|}
|
|/src/main/java/annotation/TestAnnotate.java
|package annotation;
|public @interface TestAnnotate {
| Class<?> value();
|}
|
|/src/main/java/annotation/TestClass.java
|package annotation;
|@TestAnnotate(Breaking.class)
|public class TestClass {
|}
""".trimIndent(),
configuration
) {
documentablesTransformationStage = { module ->
val testClass = module.findClasslike("annotation", "TestClass") as DClass
assertNotNull(testClass)
val annotation = testClass.extra[Annotations]?.directAnnotations?.entries?.single()?.value?.single()
assertNotNull(annotation) { "Expected to find an annotation on TestClass, found none" }
assertEquals("TestAnnotate", annotation.dri.classNames)
assertEquals(1, annotation.params.size)
val valueParameter = annotation.params.values.single()
assertTrue(valueParameter is ClassValue)
assertEquals("Breaking", valueParameter.className)
assertEquals("annotation", valueParameter.classDRI.packageName)
assertEquals("Breaking", valueParameter.classDRI.classNames)
}
}
}
}
| apache-2.0 | 9b5d9326ed75cdd47081746c869f40b5 | 39.707692 | 159 | 0.577979 | 5.359892 | false | true | false | false |
Kotlin/dokka | plugins/base/src/main/kotlin/renderers/html/NavigationDataProvider.kt | 1 | 5017 | package org.jetbrains.dokka.base.renderers.html
import org.jetbrains.dokka.base.renderers.sourceSets
import org.jetbrains.dokka.base.signatures.KotlinSignatureUtils.annotations
import org.jetbrains.dokka.base.transformers.documentables.isDeprecated
import org.jetbrains.dokka.base.transformers.documentables.isException
import org.jetbrains.dokka.base.translators.documentables.DocumentableLanguage
import org.jetbrains.dokka.base.translators.documentables.documentableLanguage
import org.jetbrains.dokka.model.*
import org.jetbrains.dokka.pages.*
abstract class NavigationDataProvider {
open fun navigableChildren(input: RootPageNode): NavigationNode = input.withDescendants()
.first { it is ModulePage || it is MultimoduleRootPage }.let { visit(it as ContentPage) }
open fun visit(page: ContentPage): NavigationNode =
NavigationNode(
name = page.displayableName(),
dri = page.dri.first(),
sourceSets = page.sourceSets(),
icon = chooseNavigationIcon(page),
styles = chooseStyles(page),
children = page.navigableChildren()
)
/**
* Parenthesis is applied in 1 case:
* - page only contains functions (therefore documentable from this page is [DFunction])
*/
private fun ContentPage.displayableName(): String =
if (this is WithDocumentables && documentables.all { it is DFunction }) {
"$name()"
} else {
name
}
private fun chooseNavigationIcon(contentPage: ContentPage): NavigationNodeIcon? =
if (contentPage is WithDocumentables) {
val documentable = contentPage.documentables.firstOrNull()
val isJava = documentable?.hasAnyJavaSources() ?: false
when (documentable) {
is DClass -> when {
documentable.isException -> NavigationNodeIcon.EXCEPTION
documentable.isAbstract() -> {
if (isJava) NavigationNodeIcon.ABSTRACT_CLASS else NavigationNodeIcon.ABSTRACT_CLASS_KT
}
else -> if (isJava) NavigationNodeIcon.CLASS else NavigationNodeIcon.CLASS_KT
}
is DFunction -> NavigationNodeIcon.FUNCTION
is DProperty -> {
val isVar = documentable.extra[IsVar] != null
if (isVar) NavigationNodeIcon.VAR else NavigationNodeIcon.VAL
}
is DInterface -> if (isJava) NavigationNodeIcon.INTERFACE else NavigationNodeIcon.INTERFACE_KT
is DEnum,
is DEnumEntry -> if (isJava) NavigationNodeIcon.ENUM_CLASS else NavigationNodeIcon.ENUM_CLASS_KT
is DAnnotation -> {
if (isJava) NavigationNodeIcon.ANNOTATION_CLASS else NavigationNodeIcon.ANNOTATION_CLASS_KT
}
is DObject -> NavigationNodeIcon.OBJECT
else -> null
}
} else {
null
}
private fun Documentable.hasAnyJavaSources(): Boolean {
val withSources = this as? WithSources ?: return false
return this.sourceSets.any { withSources.documentableLanguage(it) == DocumentableLanguage.JAVA }
}
private fun DClass.isAbstract() =
modifier.values.all { it is KotlinModifier.Abstract || it is JavaModifier.Abstract }
private fun chooseStyles(page: ContentPage): Set<Style> =
if (page.containsOnlyDeprecatedDocumentables()) setOf(TextStyle.Strikethrough) else emptySet()
private fun ContentPage.containsOnlyDeprecatedDocumentables(): Boolean {
if (this !is WithDocumentables) {
return false
}
return this.documentables.isNotEmpty() && this.documentables.all { it.isDeprecatedForAllSourceSets() }
}
private fun Documentable.isDeprecatedForAllSourceSets(): Boolean {
val sourceSetAnnotations = this.annotations()
return sourceSetAnnotations.isNotEmpty() && sourceSetAnnotations.all { (_, annotations) ->
annotations.any { it.isDeprecated() }
}
}
private fun ContentPage.navigableChildren() =
if (this is ClasslikePage) {
this.navigableChildren()
} else {
children
.filterIsInstance<ContentPage>()
.map { visit(it) }
.sortedBy { it.name.toLowerCase() }
}
private fun ClasslikePage.navigableChildren(): List<NavigationNode> {
// Classlikes should only have other classlikes as navigable children
val navigableChildren = children
.filterIsInstance<ClasslikePage>()
.map { visit(it) }
val isEnumPage = documentables.any { it is DEnum }
return if (isEnumPage) {
// no sorting for enum entries, should be the same order as in source code
navigableChildren
} else {
navigableChildren.sortedBy { it.name.toLowerCase() }
}
}
}
| apache-2.0 | a54815354db883fa505b207b386abb4b | 41.880342 | 112 | 0.639426 | 5.067677 | false | false | false | false |
spinnaker/keiko | keiko-redis/src/main/kotlin/com/netflix/spinnaker/q/redis/RedisClusterQueue.kt | 3 | 12941 | package com.netflix.spinnaker.q.redis
import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.databind.ObjectMapper
import com.netflix.spinnaker.KotlinOpen
import com.netflix.spinnaker.q.AttemptsAttribute
import com.netflix.spinnaker.q.DeadMessageCallback
import com.netflix.spinnaker.q.MaxAttemptsAttribute
import com.netflix.spinnaker.q.Message
import com.netflix.spinnaker.q.Queue
import com.netflix.spinnaker.q.QueueCallback
import com.netflix.spinnaker.q.metrics.EventPublisher
import com.netflix.spinnaker.q.metrics.LockFailed
import com.netflix.spinnaker.q.metrics.MessageAcknowledged
import com.netflix.spinnaker.q.metrics.MessageDead
import com.netflix.spinnaker.q.metrics.MessageDuplicate
import com.netflix.spinnaker.q.metrics.MessageNotFound
import com.netflix.spinnaker.q.metrics.MessageProcessing
import com.netflix.spinnaker.q.metrics.MessagePushed
import com.netflix.spinnaker.q.metrics.MessageRescheduled
import com.netflix.spinnaker.q.metrics.MessageRetried
import com.netflix.spinnaker.q.metrics.QueuePolled
import com.netflix.spinnaker.q.metrics.QueueState
import com.netflix.spinnaker.q.metrics.RetryPolled
import com.netflix.spinnaker.q.migration.SerializationMigrator
import java.io.IOException
import java.time.Clock
import java.time.Duration
import java.time.Instant
import java.time.temporal.TemporalAmount
import java.util.Locale
import java.util.Optional
import org.funktionale.partials.partially1
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import redis.clients.jedis.JedisCluster
import redis.clients.jedis.Transaction
import redis.clients.jedis.exceptions.JedisDataException
import redis.clients.jedis.params.ZAddParams.zAddParams
import redis.clients.jedis.util.JedisClusterCRC16
@KotlinOpen
class RedisClusterQueue(
private val queueName: String,
private val jedisCluster: JedisCluster,
private val clock: Clock,
private val lockTtlSeconds: Int = 10,
private val mapper: ObjectMapper,
private val serializationMigrator: Optional<SerializationMigrator>,
override val ackTimeout: TemporalAmount = Duration.ofMinutes(1),
override val deadMessageHandlers: List<DeadMessageCallback>,
override val canPollMany: Boolean = false,
override val publisher: EventPublisher
) : AbstractRedisQueue(
clock,
lockTtlSeconds,
mapper,
serializationMigrator,
ackTimeout,
deadMessageHandlers,
canPollMany,
publisher
) {
final override val log: Logger = LoggerFactory.getLogger(javaClass)
override val queueKey = "{$queueName}.queue"
override val unackedKey = "{$queueName}.unacked"
override val messagesKey = "{$queueName}.messages"
override val locksKey = "{$queueName}.locks"
override val attemptsKey = "{$queueName}.attempts"
override lateinit var readMessageWithLockScriptSha: String
init {
cacheScript()
log.info("Configured $javaClass queue: $queueName")
}
final override fun cacheScript() {
readMessageWithLockScriptSha = jedisCluster.scriptLoad(READ_MESSAGE_WITH_LOCK_SRC, queueKey)
}
override fun poll(callback: (Message, () -> Unit) -> Unit) {
jedisCluster.readMessageWithLock()
?.also { (fingerprint, scheduledTime, json) ->
val ack = this::ackMessage.partially1(fingerprint)
jedisCluster.readMessage(fingerprint, json) { message ->
val attempts = message.getAttribute<AttemptsAttribute>()?.attempts
?: 0
val maxAttempts = message.getAttribute<MaxAttemptsAttribute>()?.maxAttempts
?: 0
if (maxAttempts > 0 && attempts > maxAttempts) {
log.warn("Message $fingerprint with payload $message exceeded $maxAttempts retries")
handleDeadMessage(message)
jedisCluster.removeMessage(fingerprint)
fire(MessageDead)
} else {
fire(MessageProcessing(message, scheduledTime, clock.instant()))
callback(message, ack)
}
}
}
fire(QueuePolled)
}
override fun poll(maxMessages: Int, callback: QueueCallback) {
poll(callback)
}
override fun push(message: Message, delay: TemporalAmount) {
jedisCluster.firstFingerprint(queueKey, message.fingerprint()).also { fingerprint ->
if (fingerprint != null) {
log.info(
"Re-prioritizing message as an identical one is already on the queue: " +
"$fingerprint, message: $message"
)
jedisCluster.zadd(queueKey, score(delay), fingerprint, zAddParams().xx())
fire(MessageDuplicate(message))
} else {
jedisCluster.queueMessage(message, delay)
fire(MessagePushed(message))
}
}
}
override fun reschedule(message: Message, delay: TemporalAmount) {
val fingerprint = message.fingerprint().latest
log.debug("Re-scheduling message: $message, fingerprint: $fingerprint to deliver in $delay")
val status: Long = jedisCluster.zadd(queueKey, score(delay), fingerprint, zAddParams().xx())
if (status.toInt() == 1) {
fire(MessageRescheduled(message))
} else {
fire(MessageNotFound(message))
}
}
override fun ensure(message: Message, delay: TemporalAmount) {
val fingerprint = message.fingerprint()
if (!jedisCluster.anyZismember(queueKey, fingerprint.all) &&
!jedisCluster.anyZismember(unackedKey, fingerprint.all)
) {
log.debug(
"Pushing ensured message onto queue as it does not exist in queue or unacked sets"
)
push(message, delay)
}
}
@Scheduled(fixedDelayString = "\${queue.retry.frequency.ms:10000}")
override fun retry() {
jedisCluster
.zrangeByScore(unackedKey, 0.0, score())
.let { fingerprints ->
if (fingerprints.size > 0) {
fingerprints
.map { "$locksKey:$it" }
.let { jedisCluster.del(*it.toTypedArray()) }
}
fingerprints.forEach { fingerprint ->
val attempts = jedisCluster.hgetInt(attemptsKey, fingerprint)
jedisCluster.readMessageWithoutLock(fingerprint) { message ->
val maxAttempts = message.getAttribute<MaxAttemptsAttribute>()?.maxAttempts ?: 0
/* If maxAttempts attribute is set, let poll() handle max retry logic.
If not, check for attempts >= Queue.maxRetries - 1, as attemptsKey is now
only incremented when retrying unacked messages vs. by readMessage*() */
if (maxAttempts == 0 && attempts >= Queue.maxRetries - 1) {
log.warn("Message $fingerprint with payload $message exceeded max retries")
handleDeadMessage(message)
jedisCluster.removeMessage(fingerprint)
fire(MessageDead)
} else {
if (jedisCluster.zismember(queueKey, fingerprint)) {
jedisCluster
.multi {
zrem(unackedKey, fingerprint)
zadd(queueKey, score(), fingerprint)
hincrBy(attemptsKey, fingerprint, 1L)
}
log.info(
"Not retrying message $fingerprint because an identical message " +
"is already on the queue"
)
fire(MessageDuplicate(message))
} else {
log.warn("Retrying message $fingerprint after $attempts attempts")
jedisCluster.hincrBy(attemptsKey, fingerprint, 1L)
jedisCluster.requeueMessage(fingerprint)
fire(MessageRetried)
}
}
}
}
}
.also {
fire(RetryPolled)
}
}
override fun readState(): QueueState =
jedisCluster.multi {
zcard(queueKey)
zcount(queueKey, 0.0, score())
zcard(unackedKey)
hlen(messagesKey)
}
.map { (it as Long).toInt() }
.let { (queued, ready, processing, messages) ->
return QueueState(
depth = queued,
ready = ready,
unacked = processing,
orphaned = messages - (queued + processing)
)
}
override fun containsMessage(predicate: (Message) -> Boolean): Boolean {
var found = false
var cursor = "0"
while (!found) {
jedisCluster.hscan(messagesKey, cursor).apply {
found = result
.map { mapper.readValue<Message>(it.value) }
.any(predicate)
cursor = getCursor()
}
if (cursor == "0") break
}
return found
}
internal fun JedisCluster.queueMessage(
message: Message,
delay: TemporalAmount = Duration.ZERO
) {
val fingerprint = message.fingerprint().latest
// ensure the message has the attempts tracking attribute
message.setAttribute(
message.getAttribute() ?: AttemptsAttribute()
)
multi {
hset(messagesKey, fingerprint, mapper.writeValueAsString(message))
zadd(queueKey, score(delay), fingerprint)
}
}
internal fun JedisCluster.requeueMessage(fingerprint: String) {
multi {
zrem(unackedKey, fingerprint)
zadd(queueKey, score(), fingerprint)
}
}
internal fun JedisCluster.removeMessage(fingerprint: String) {
multi {
zrem(queueKey, fingerprint)
zrem(unackedKey, fingerprint)
hdel(messagesKey, fingerprint)
del("$locksKey:$fingerprint")
hdel(attemptsKey, fingerprint)
}
}
internal fun JedisCluster.readMessageWithoutLock(
fingerprint: String,
block: (Message) -> Unit
) {
try {
hget(messagesKey, fingerprint)
.let {
val message = mapper.readValue<Message>(runSerializationMigration(it))
block.invoke(message)
}
} catch (e: IOException) {
log.error("Failed to read unacked message $fingerprint, requeuing...", e)
hincrBy(attemptsKey, fingerprint, 1L)
requeueMessage(fingerprint)
} catch (e: JsonParseException) {
log.error("Payload for unacked message $fingerprint is missing or corrupt", e)
removeMessage(fingerprint)
}
}
internal fun JedisCluster.readMessageWithLock(): Triple<String, Instant, String?>? {
try {
val response = evalsha(
readMessageWithLockScriptSha,
listOf(
queueKey,
unackedKey,
locksKey,
messagesKey
),
listOf(
score().toString(),
10.toString(), // TODO rz - make this configurable.
lockTtlSeconds.toString(),
java.lang.String.format(Locale.US, "%f", score(ackTimeout)),
java.lang.String.format(Locale.US, "%f", score())
)
)
if (response is List<*>) {
return Triple(
response[0].toString(), // fingerprint
Instant.ofEpochMilli(response[1].toString().toLong()), // fingerprintScore
response[2]?.toString() // message
)
}
if (response == "ReadLockFailed") {
// This isn't a "bad" thing, but means there's more work than keiko can process in a cycle
// in this case, but may be a signal to tune `peekFingerprintCount`
fire(LockFailed)
}
} catch (e: JedisDataException) {
if ((e.message ?: "").startsWith("NOSCRIPT")) {
cacheScript()
return readMessageWithLock()
} else {
throw e
}
}
return null
}
internal fun JedisCluster.readMessage(
fingerprint: String,
json: String?,
block: (Message) -> Unit
) {
if (json == null) {
log.error("Payload for message $fingerprint is missing")
// clean up what is essentially an unrecoverable message
removeMessage(fingerprint)
} else {
try {
val message = mapper.readValue<Message>(runSerializationMigration(json))
.apply {
val currentAttempts = (getAttribute() ?: AttemptsAttribute())
.run { copy(attempts = attempts + 1) }
setAttribute(currentAttempts)
}
hset(messagesKey, fingerprint, mapper.writeValueAsString(message))
block.invoke(message)
} catch (e: IOException) {
log.error("Failed to read message $fingerprint, requeuing...", e)
hincrBy(attemptsKey, fingerprint, 1L)
requeueMessage(fingerprint)
}
}
}
fun JedisCluster.multi(block: Transaction.() -> Unit) =
getConnectionFromSlot(JedisClusterCRC16.getSlot(queueKey))
.use { c ->
c.multi()
.let { tx ->
tx.block()
tx.exec()
}
}
private fun ackMessage(fingerprint: String) {
if (jedisCluster.zismember(queueKey, fingerprint)) {
// only remove this message from the unacked queue as a matching one has
// been put on the main queue
jedisCluster.multi {
zrem(unackedKey, fingerprint)
del("$locksKey:$fingerprint")
}
} else {
jedisCluster.removeMessage(fingerprint)
}
fire(MessageAcknowledged)
}
}
| apache-2.0 | ba7129d337fc1c86a20ab57570b55dde | 32.788512 | 98 | 0.655204 | 4.409199 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/psi/text/MdPlainTextElementImpl.kt | 1 | 10104 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.psi.text
import com.intellij.ide.util.PsiNavigationSupport
import com.intellij.lang.ASTNode
import com.intellij.lang.Language
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiReference
import com.intellij.psi.impl.FakePsiElement
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import com.vladsch.md.nav.MdLanguage
import com.vladsch.md.nav.psi.MdPlainText
/**
* Implements FakePsiElement for text based references to other elements
*/
class MdPlainTextElementImpl(parent: MdPlainText<*>, startOffset: Int, endOffset: Int, referenceableOffsetInParent: Int) : FakePsiElement() {
private val myParent = parent
private val myParentNode: ASTNode get() = myParent.node
private val myReferenceableOffsetInParent = referenceableOffsetInParent
private val myStartOffset = startOffset
private val myEndOffset = endOffset
private val myFileStartOffset: Int get() = myStartOffset + myParent.node.startOffset
private val myFileEndOffset: Int get() = myEndOffset + myParent.node.startOffset
private val myASTNode: ASTNode = MyAstNode()
// private val myTextLength:Int get() = myEndOffset - myStartOffset
override fun getParent(): PsiElement {
return myParent
}
override fun getText(): String {
return myParentNode.text.substring(myFileStartOffset, myFileEndOffset)
}
override fun getStartOffsetInParent(): Int {
return myReferenceableOffsetInParent
}
override fun getLanguage(): Language {
return MdLanguage.INSTANCE
}
override fun getTextRange(): TextRange {
return TextRange(myFileStartOffset, myFileEndOffset)
}
override fun canNavigate(): Boolean {
return true
}
override fun getContainingFile(): PsiFile {
return myParent.containingFile
}
override fun getContext(): PsiElement? {
return myParent
}
override fun isValid(): Boolean {
return myParent.isValid && myParent.node == myParentNode && myParentNode.startOffset <= myFileStartOffset && myParentNode.startOffset + myParentNode.textLength >= myFileEndOffset
}
override fun replace(newElement: PsiElement): PsiElement {
if (newElement is MdPlainTextElementImpl) {
val newParent = myParent.replace(newElement.myParent)
if (newParent != myParent) {
return newElement
}
return this
}
return super.replace(newElement)
}
override fun getTextLength(): Int {
return myEndOffset - myStartOffset
}
override fun getTextOffset(): Int {
return myFileStartOffset
}
override fun isPhysical(): Boolean {
return myParent.isPhysical
}
override fun getNode(): ASTNode? {
return myASTNode
}
override fun delete() {
name = ""
}
override fun setName(name: String): MdPlainTextElementImpl {
// change the file text and find element at offset
val newParent = myParent.replaceReferenceableText(name, myStartOffset, myEndOffset)
if (newParent !== myParent && newParent is MdPlainText<*>) {
// create a new us
return MdPlainTextElementImpl(newParent, myStartOffset, myStartOffset + name.length, myReferenceableOffsetInParent)
}
return this
}
override fun textContains(c: Char): Boolean {
return myASTNode.chars.contains(c)
}
override fun getReferences(): Array<out PsiReference> {
return PsiReference.EMPTY_ARRAY
}
override fun getNavigationElement(): PsiElement {
return this
}
override fun getReference(): PsiReference? {
return null
}
override fun getName(): String {
return text
}
override fun isWritable(): Boolean {
return myParent.isWritable
}
override fun navigate(requestFocus: Boolean) {
PsiNavigationSupport.getInstance().createNavigatable(project, containingFile.virtualFile, myFileStartOffset).navigate(requestFocus)
}
// ASTNode
inner class MyAstNode : ASTNode {
override fun getTextLength(): Int {
return [email protected]
}
override fun getText(): String {
return [email protected]
}
override fun <T : Any?> putUserData(key: Key<T>, value: T?) {
[email protected](key, value)
}
override fun <T : Any?> getUserData(key: Key<T>): T? {
return [email protected](key)
}
override fun textContains(c: Char): Boolean {
return [email protected](c)
}
override fun getTextRange(): TextRange {
return [email protected]
}
override fun <T : Any?> getCopyableUserData(key: Key<T>): T? {
return [email protected](key)
}
override fun <T : Any?> putCopyableUserData(key: Key<T>, value: T) {
return [email protected](key, value)
}
override fun getChildren(filter: TokenSet?): Array<out ASTNode> {
return EMPTY_NODES
}
override fun addLeaf(leafType: IElementType, leafText: CharSequence, anchorBefore: ASTNode?) {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getLastChildNode(): ASTNode? {
return null
}
override fun getElementType(): IElementType {
return myParentNode.elementType
}
override fun getTreeParent(): ASTNode {
return myParent.node
}
override fun getChars(): CharSequence {
return myParent.node.chars.subSequence(myFileStartOffset, myFileEndOffset)
}
override fun removeRange(firstNodeToRemove: ASTNode, firstNodeToKeep: ASTNode?) {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun replaceAllChildrenToChildrenOf(anotherParent: ASTNode) {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun findLeafElementAt(offset: Int): ASTNode? {
return null
}
override fun getStartOffset(): Int {
return myFileStartOffset
}
override fun getTreeNext(): ASTNode? {
return null
}
override fun replaceChild(oldChild: ASTNode, newChild: ASTNode) {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun clone(): Any {
val newParentNode = myParent.node.clone() as ASTNode
val newParent = newParentNode.psi
return MdPlainTextElementImpl(newParent as MdPlainText<*>, myStartOffset, myEndOffset, myReferenceableOffsetInParent)
}
override fun copyElement(): ASTNode {
val newParentNode = myParent.node.copyElement()
val newParent = newParentNode.psi
return MdPlainTextElementImpl(newParent as MdPlainText<*>, myStartOffset, myEndOffset, myReferenceableOffsetInParent).myASTNode
}
override fun addChildren(firstChild: ASTNode, firstChildToNotAdd: ASTNode?, anchorBefore: ASTNode?) {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun findChildByType(type: IElementType): ASTNode? {
return null
}
override fun findChildByType(type: IElementType, anchor: ASTNode?): ASTNode? {
return null
}
override fun findChildByType(typesSet: TokenSet): ASTNode? {
return null
}
override fun findChildByType(typesSet: TokenSet, anchor: ASTNode?): ASTNode? {
return null
}
override fun getFirstChildNode(): ASTNode? {
return null
}
override fun removeChild(child: ASTNode) {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getPsi(): PsiElement {
return this@MdPlainTextElementImpl
}
override fun <T : PsiElement?> getPsi(clazz: Class<T>): T {
LOG.assertTrue(clazz.isInstance(myParent), "unexpected psi class. expected: " + clazz + " got: " + myParent.javaClass)
@Suppress("UNCHECKED_CAST")
return myParent as T
}
override fun addChild(child: ASTNode) {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun addChild(child: ASTNode, anchorBefore: ASTNode?) {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getTreePrev(): ASTNode? {
return null
}
}
companion object {
private val LOG = Logger.getInstance("com.vladsch.md.nav.psi.impl.text")
@Suppress("CAST_NEVER_SUCCEEDS", "RemoveExplicitTypeArguments")
@JvmField
val EMPTY_NODES = Array<ASTNode>(0, { null as ASTNode })
}
}
| apache-2.0 | ae216ef4b2aefb35cf17375ddf819fc8 | 33.484642 | 186 | 0.662906 | 5.134146 | false | false | false | false |
lkolek/rstore | rstore-core/src/main/java/pl/geostreaming/rstore/core/channels/channels.kt | 1 | 5125 | package pl.geostreaming.rstore.core.channels
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.channels.Channel
import kotlinx.coroutines.experimental.channels.ReceiveChannel
import kotlinx.coroutines.experimental.channels.SendChannel
import kotlinx.coroutines.experimental.channels.consumeEach
import kotlinx.coroutines.experimental.future.await
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.newSingleThreadContext
import pl.geostreaming.rstore.core.model.IdList
import pl.geostreaming.rstore.core.model.NewId
import pl.geostreaming.rstore.core.model.ObjId
import pl.geostreaming.rstore.core.msg.*
import pl.geostreaming.rstore.core.node.RelicaOpLog
import pl.geostreaming.rstore.core.node.ReplicaManager
import java.util.concurrent.CompletableFuture
import kotlin.coroutines.experimental.CoroutineContext
/**
* Created by lkolek on 30.06.2017.
*/
class ChanneledReplica<T:Any>(
val repl:ReplicaManager,
val context: CoroutineContext = newSingleThreadContext("Chann r${repl.replId}"),
val concurrency:Int = 5
){
private val chIn= Channel<Pair<RsOpReq,T>>(10)
private val chOut= Channel<Pair<RsOpResp,T>>(10)
val inbox: SendChannel<Pair<RsOpReq,T>> = chIn;
val outbox: ReceiveChannel<Pair<RsOpResp,T>> = chOut;
init{
(1..concurrency).forEach {
launch(context){
chIn.consumeEach{(ev,t) ->
val resp = process(ev,t)
chOut.send(Pair(resp,t))
}
}
}
}
private suspend fun process(ev: RsOp, t:T ): RsOpResp = when (ev) {
is RsOpReq_queryIds -> RsOpRes_queryIds(ev.opid, repl.queryIds(ev.afertSeqId, ev.cnt))
is RsOpReq_put -> RsOpRes_put(ev.opid, repl.put(ev.obj))
is RsOpReq_get -> RsOpRes_get(ev.opid, repl.get(ev.oid))
is RsOpReq_has -> RsOpRes_has(ev.opid, repl.has(ev.oid))
is RsOpReq_listenNewIds -> {
launch(context){
repl.listenNewIds().consumeEach{id -> chOut.send( Pair(RsOpRes_listenNewIds_send(ev.opid, id), t))}
}
RsOpRes_listenNewIds(ev.opid)
}
else -> RsOpRes_bad(ev.opid, "op not supported")
}
}
open class ChanneledRemote(
override val replId:Int,
val inboxRemote: SendChannel<RsOpReq>,
val outboxRemote: ReceiveChannel<RsOpResp>,
val context: CoroutineContext = newSingleThreadContext("remote Chann r${replId}")
): RelicaOpLog
{
private var opseq:Long = 0L
get() {field++; return field}
private val handlers = HashMap<Long,suspend (RsOpResp) ->Unit >()
init{
launch(context){
outboxRemote.consumeEach { x ->
try {
// if(x.opid % 1000L == 0L){
// println("consume ${x.opid} handlers=${handlers.size}")
// }
val hh = handlers.get(x.opid)
if(hh != null){
hh.invoke(x)
} else {
println("no handler for: ${x.opid}, ${x.javaClass.name}")
}
}catch(ex:Exception){
println("rec remote ex:${ex.message}")
ex.printStackTrace()
}
}
}
}
private suspend fun <R> RsOpReq.sendAnd(block: suspend (RsOpResp) -> R ):R{
val cc = CompletableFuture<RsOpResp>()
handlers.put(this.opid){ x-> cc.complete(x); handlers.remove(this.opid) }
inboxRemote.send(this);
val xx1 = cc.await();
val ret = block.invoke(xx1)
return ret;
}
override suspend fun queryIds(afterSeqId:Long, cnt:Int): IdList =run(context){
val q = RsOpReq_queryIds(opseq, afterSeqId, cnt);
q.sendAnd { r-> (r as? RsOpRes_queryIds ?: throw RuntimeException("bad response")).ret }
}
override suspend fun put(obj:ByteArray):ObjId =run(context){
val q = RsOpReq_put(opseq, obj.copyOf());
q.sendAnd { r-> (r as? RsOpRes_put ?: throw RuntimeException("bad response")).ret }
}
override suspend fun get(oid:ObjId):ByteArray? =run(context){
val q = RsOpReq_get(opseq, oid);
q.sendAnd { r-> (r as? RsOpRes_get ?: throw RuntimeException("bad response")).ret }
}
override suspend fun has(oid:ObjId):Boolean =run(context){
val q = RsOpReq_has(opseq, oid);
q.sendAnd { r-> (r as? RsOpRes_has ?: throw RuntimeException("bad response")).ret }
}
override suspend fun listenNewIds():Channel<NewId> =run(context){
val q = RsOpReq_listenNewIds(opseq);
val ret = Channel<NewId>(100); // TODO: problem?
println("listenNewIds opid=${q.opid}")
handlers.put(q.opid, { r ->
when(r){
is RsOpRes_listenNewIds_send -> ret.send(r.ret)
is RsOpRes_listenNewIds -> println("listenNewIds installed")
else -> println("bad listenNewIds")
}
})
inboxRemote.send(q);
ret;
}
} | apache-2.0 | 522dfac9ea63832188decbdd426669dc | 32.94702 | 115 | 0.60722 | 3.67911 | false | false | false | false |
SimpleTimeTracking/StandaloneClient | src/test/kotlin/org/stt/text/JiraExpansionProviderTest.kt | 1 | 1834 | package org.stt.text
import net.rcarz.jiraclient.Issue
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.mockito.BDDMockito.given
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.stt.connector.jira.JiraConnector
import java.util.*
class JiraExpansionProviderTest {
@Mock
internal lateinit var jiraConnector: JiraConnector
@Mock
internal lateinit var issue: Issue
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
given(jiraConnector.getIssue("JRA-7")).willReturn(issue)
given(issue.summary).willReturn("Testing Issue")
}
@After
fun tearDown() {
}
@Test
fun testGetPossibleExpansions() {
// GIVEN
val sut = JiraExpansionProvider(jiraConnector, Optional.empty())
// WHEN
val matches = sut.getPossibleExpansions("JRA-7")
// THEN
assertThat(1).isEqualTo(matches.size.toLong())
assertThat(matches[0]).isEqualTo(": Testing Issue")
}
@Test
fun testGetPossibleExpansionsShouldHandleSubstring() {
// GIVEN
val sut = JiraExpansionProvider(jiraConnector, Optional.empty())
// WHEN
val matches = sut.getPossibleExpansions("Test JRA-7")
// THEN
assertThat(1).isEqualTo(matches.size.toLong())
assertThat(matches[0]).isEqualTo(": Testing Issue")
}
@Test
fun testGetPossibleExpansionsShouldHandleSpace() {
// GIVEN
val sut = JiraExpansionProvider(jiraConnector, Optional.empty())
// WHEN
val matches = sut.getPossibleExpansions(" JRA-7 ")
// THEN
assertThat(1).isEqualTo(matches.size.toLong())
assertThat(matches[0]).isEqualTo(": Testing Issue")
}
}
| gpl-3.0 | 1889baaa142ebdf06f45f0e17cce65e8 | 22.818182 | 72 | 0.664122 | 4.419277 | false | true | false | false |
xiaopansky/AssemblyAdapter | sample/src/main/java/me/panpf/adapter/sample/bean/Game.kt | 1 | 551 | package me.panpf.adapter.sample.bean
import me.panpf.adapter.paged.Diffable
class Game: Diffable<Game> {
var iconResId: Int = 0
var name: String? = null
var like: String? = null
override fun areItemsTheSame(other: Game): Boolean = this.name == other.name
override fun areContentsTheSame(other: Game): Boolean {
if (this === other) return true
if (iconResId != other.iconResId) return false
if (name != other.name) return false
if (like != other.like) return false
return true
}
}
| apache-2.0 | d6bd3ee5b85fa47ba75b0c8754c4df97 | 24.045455 | 80 | 0.649728 | 4.051471 | false | false | false | false |
Vakosta/Chapper | app/src/main/java/org/chapper/chapper/data/model/Device.kt | 1 | 614 | package org.chapper.chapper.data.model
class Device {
var bluetoothName = ""
var bluetoothAddress = ""
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Device
if (bluetoothName != other.bluetoothName) return false
if (bluetoothAddress != other.bluetoothAddress) return false
return true
}
override fun hashCode(): Int {
var result = bluetoothName.hashCode()
result = 31 * result + bluetoothAddress.hashCode()
return result
}
} | gpl-2.0 | 747e2b17fee97f1c395092ab4df6aeb3 | 22.653846 | 68 | 0.630293 | 4.75969 | false | false | false | false |
http4k/http4k | http4k-security/oauth/src/test/kotlin/org/http4k/security/oauth/client/OAuthRefreshTokenTest.kt | 1 | 1770 | package org.http4k.security.oauth.client
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.http4k.core.Credentials
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status
import org.http4k.core.then
import org.http4k.filter.ClientFilters
import org.http4k.security.oauth.core.RefreshToken
import org.junit.jupiter.api.Test
class OAuthRefreshTokenTest {
@Test
fun `auths with correct form`() {
val app = ClientFilters.OAuthRefreshToken(
Credentials("hello", "world"),
RefreshToken("goodbye"),
scopes = listOf("someactivity.read", "someactivity.write")
).then { req: Request -> Response(Status.OK).body(req.bodyString()) }
assertThat(
app(Request(Method.POST, "")).bodyString(),
equalTo(
"grant_type=refresh_token" +
"&client_id=hello" +
"&client_secret=world" +
"&refresh_token=goodbye" +
"&scope=someactivity.read+someactivity.write"
)
)
}
@Test
fun `omits scope if not provided`() {
val app = ClientFilters.OAuthRefreshToken(
Credentials("hello", "world"),
RefreshToken("goodbye"),
scopes = emptyList()
).then { req: Request -> Response(Status.OK).body(req.bodyString()) }
assertThat(
app(Request(Method.POST, "")).bodyString(),
equalTo(
"grant_type=refresh_token" +
"&client_id=hello" +
"&client_secret=world" +
"&refresh_token=goodbye"
)
)
}
}
| apache-2.0 | cdda74440870e48f7b22e38a061357e8 | 32.396226 | 77 | 0.584181 | 4.224344 | false | true | false | false |
dexbleeker/hamersapp | hamersapp/src/main/java/nl/ecci/hamers/models/Event.kt | 1 | 988 | package nl.ecci.hamers.models
import com.google.gson.annotations.SerializedName
import nl.ecci.hamers.utils.Utils
import java.util.*
data class Event(val id: Int = Utils.notFound,
val title: String = Utils.unknown,
@SerializedName("beschrijving")
val description: String = Utils.unknown,
val location: String = Utils.unknown,
@SerializedName("user_id")
val userID: Int = Utils.notFound,
val date: Date = Date(),
@SerializedName("end_time")
val endDate: Date = Date(),
val deadline: Date = Date(),
@SerializedName("signups")
val signUps: ArrayList<SignUp> = ArrayList(),
@SerializedName("created_at")
val createdAt: Date = Date(),
val attendance: Boolean = false) {
companion object {
const val EVENT = "EVENT"
}
}
| gpl-3.0 | 6887387e3953dd5fc038f300585ba700 | 35.592593 | 62 | 0.539474 | 4.891089 | false | false | false | false |
Ingwersaft/James | integrationstests/src/test/kotlin/com/mkring/james/integration/rocketchat/RocketChatRestClient.kt | 1 | 3336 | package com.mkring.james.integration.rocketchat
import com.google.gson.Gson
import com.google.gson.JsonObject
import org.apache.http.HttpEntity
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
class RocketChatRestClient(val baseUrl: String, val adminUser: String, val adminPw: String) {
private val client = HttpClients.createDefault()
private val gson = Gson()
lateinit var userId: String
lateinit var authToken: String
lateinit var generalChannelId: String
fun login() {
val loginResponse =
send("/api/v1/login", "{ \"user\": \"$adminUser\", \"password\": \"$adminPw\" }")
userId = loginResponse.get("data").asJsonObject.get("userId").asString
authToken = loginResponse.get("data").asJsonObject.get("authToken").asString
println("userId=$userId authToken=$authToken")
}
fun getGeneralChannelId() {
val generalId = send(
"/api/v1/channels.info?roomName=general",
null,
authToken = authToken,
userId = userId
).get("channel").asJsonObject.get("_id").asString
println("generalId=$generalId")
generalChannelId = generalId
}
fun postMessageToChannel(text: String): Boolean {
val postSuccess = send(
"/api/v1/chat.postMessage",
"{ \"roomId\": \"$generalChannelId\", \"text\": \"$text\" }",
authToken = authToken,
userId = userId
).also { println("$it") }.let { it["success"].asBoolean }
println("postSuccess=$postSuccess")
return postSuccess
}
fun createBotUser(botUser: String, botPassword: String) {
val user = botUser
val pw = botPassword
val createSuccess = send(
"/api/v1/users.create",
"""{"name": "$user", "email": "[email protected]", "password": "$pw", "username": "$user",
|"active": true, "joinDefaultChannels": true, "requirePasswordChange": false, "sendWelcomeEmail": false }""".trimMargin(),
authToken = authToken,
userId = userId
).also { println("users.create response: $it") }.let { it["success"].asBoolean }
if (createSuccess.not()) {
throw IllegalStateException("couldn't create bot user for test!")
}
}
private fun send(
resource: String,
payload: String?,
authToken: String? = null,
userId: String? = null
): JsonObject {
val request = if (payload == null) {
HttpGet("http://$baseUrl$resource")
} else {
HttpPost("http://$baseUrl$resource").apply {
entity = StringEntity(payload)
}
}
return request.apply {
addHeader("Content-type", "application/json")
authToken?.also { addHeader("X-Auth-Token", it) }
userId?.also { addHeader("X-User-Id", it) }
}.let { client.execute(it).entity.asString() }.parse(gson)
}
private fun HttpEntity.asString(): String = EntityUtils.toString(this)
private fun String.parse(gson: Gson): JsonObject = gson.fromJson(this, JsonObject::class.java)
}
| gpl-3.0 | ddb1ce5485f5d2e6498819a4283b3c90 | 37.344828 | 138 | 0.61211 | 4.372215 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/web/PreferenceBackedHostNum.kt | 1 | 2652 | /*
Copyright (c) 2020 David Allison <[email protected]>
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.web
import android.content.SharedPreferences
import androidx.annotation.CheckResult
import androidx.core.content.edit
import com.ichi2.libanki.sync.HostNum
import timber.log.Timber
class PreferenceBackedHostNum(hostNum: Int?, private val preferences: SharedPreferences) : HostNum(hostNum) {
/** Clearing hostNum whenever on log out/changes the server URL should avoid any problems with malicious servers */
override fun reset() {
hostNum = getDefaultHostNum()
}
override var hostNum: Int?
get() = getHostNum(preferences)
set(value) {
Timber.d("Setting hostnum to %s", value)
val prefValue = convertToPreferenceValue(value)
preferences.edit { putString("hostNum", prefValue) }
super.hostNum = value
}
@CheckResult
private fun convertToPreferenceValue(newHostNum: Int?): String? {
return newHostNum?.toString()
}
companion object {
fun fromPreferences(preferences: SharedPreferences): PreferenceBackedHostNum {
val hostNum = getHostNum(preferences)
return PreferenceBackedHostNum(hostNum, preferences)
}
private fun getHostNum(preferences: SharedPreferences): Int? {
return try {
val hostNum = preferences.getString("hostNum", null)
Timber.v("Obtained hostNum: %s", hostNum)
convertFromPreferenceValue(hostNum)
} catch (e: Exception) {
Timber.e(e, "Failed to get hostNum")
getDefaultHostNum()
}
}
private fun convertFromPreferenceValue(hostNum: String?): Int? {
return if (hostNum == null) {
getDefaultHostNum()
} else try {
hostNum.toInt()
} catch (e: Exception) {
Timber.w(e)
getDefaultHostNum()
}
}
}
}
| gpl-3.0 | 42783a248beb2c85396aec59c0924263 | 35.328767 | 119 | 0.654223 | 4.628272 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/libanki/template/NegatedConditional.kt | 1 | 2574 | /****************************************************************************************
* Copyright (c) 2020 Arthur Milchior <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.libanki.template
import com.ichi2.utils.KotlinCleanup
@KotlinCleanup("fix hashCode related @Suppress")
@Suppress("EqualsOrHashCode")
class NegatedConditional(private val key: String, private val child: ParsedNode) : ParsedNode() {
override fun template_is_empty(nonempty_fields: Set<String>): Boolean {
return nonempty_fields.contains(key) || child.template_is_empty(nonempty_fields)
}
@Throws(TemplateError::class)
override fun render_into(
fields: Map<String, String>,
nonempty_fields: Set<String>,
builder: StringBuilder
) {
if (!nonempty_fields.contains(key)) {
child.render_into(fields, nonempty_fields, builder)
}
}
@KotlinCleanup("fix parameter name issue")
@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE")
override fun equals(obj: Any?): Boolean {
if (obj !is NegatedConditional) {
return false
}
val other = obj
return other.key == key && other.child == child
}
override fun toString(): String {
@KotlinCleanup("this seems like java")
return "new NegatedConditional(\"" + key.replace("\\", "\\\\") + "," + child + "\")"
}
}
| gpl-3.0 | 51ff2ccb86ee0a166b5d62e6eb495d88 | 48.5 | 97 | 0.508547 | 5.263804 | false | false | false | false |
rock3r/detekt | detekt-api/src/test/kotlin/io/gitlab/arturbosch/detekt/api/AnnotationExcluderSpec.kt | 1 | 2362 | package io.gitlab.arturbosch.detekt.api
import io.gitlab.arturbosch.detekt.test.KtTestCompiler
import io.gitlab.arturbosch.detekt.test.compileContentForTest
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class AnnotationExcluderSpec : Spek({
val psiFactory = KtTestCompiler.createPsiFactory()
describe("a kt file with some imports") {
val jvmFieldAnnotation = psiFactory.createAnnotationEntry("@JvmField")
val fullyQualifiedJvmFieldAnnotation = psiFactory.createAnnotationEntry("@kotlin.jvm.JvmField")
val sinceKotlinAnnotation = psiFactory.createAnnotationEntry("@SinceKotlin")
val file = compileContentForTest("""
package foo
import kotlin.jvm.JvmField
""".trimIndent())
it("should exclude when the annotation was found") {
val excluder = AnnotationExcluder(file, listOf("JvmField"))
assertThat(excluder.shouldExclude(listOf(jvmFieldAnnotation))).isTrue()
}
it("should not exclude when the annotation was not found") {
val excluder = AnnotationExcluder(file, listOf("Jvm Field"))
assertThat(excluder.shouldExclude(listOf(jvmFieldAnnotation))).isFalse()
}
it("should not exclude when no annotations should be excluded") {
val excluder = AnnotationExcluder(file, listOf())
assertThat(excluder.shouldExclude(listOf(jvmFieldAnnotation))).isFalse()
}
it("should exclude when the annotation was found with its fully qualified name") {
val excluder = AnnotationExcluder(file, listOf("JvmField"))
assertThat(excluder.shouldExclude(listOf(fullyQualifiedJvmFieldAnnotation))).isTrue()
}
it("should also exclude an annotation that is not imported") {
val excluder = AnnotationExcluder(file, listOf("SinceKotlin"))
assertThat(excluder.shouldExclude(listOf(sinceKotlinAnnotation))).isTrue()
}
it("should exclude when the annotation was found with SplitPattern") {
@Suppress("Deprecation")
val excluder = AnnotationExcluder(file, SplitPattern("JvmField"))
assertThat(excluder.shouldExclude(listOf(jvmFieldAnnotation))).isTrue()
}
}
})
| apache-2.0 | c5e8a189839337ae8adb52404d78f287 | 41.945455 | 103 | 0.69475 | 5.16849 | false | true | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/manager/BalanceManager.kt | 1 | 10400 | /*
* Copyright (c) 2017. Toshi Inc
*
* 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.toshi.manager
import com.toshi.crypto.HDWallet
import com.toshi.crypto.util.TypeConverter
import com.toshi.extensions.getTimeoutSingle
import com.toshi.manager.ethRegistration.EthGcmRegistration
import com.toshi.manager.network.CurrencyInterface
import com.toshi.manager.network.CurrencyService
import com.toshi.manager.network.EthereumService
import com.toshi.manager.network.EthereumServiceInterface
import com.toshi.model.local.network.Network
import com.toshi.model.network.Balance
import com.toshi.model.network.Currencies
import com.toshi.model.network.ERC721TokenWrapper
import com.toshi.model.network.ExchangeRate
import com.toshi.model.network.token.CustomERCToken
import com.toshi.model.network.token.ERC20Tokens
import com.toshi.model.network.token.ERC721Tokens
import com.toshi.model.network.token.ERCToken
import com.toshi.model.sofa.payment.Payment
import com.toshi.util.CurrencyUtil
import com.toshi.util.EthUtil
import com.toshi.util.EthUtil.BIG_DECIMAL_SCALE
import com.toshi.util.logging.LogUtil
import com.toshi.util.sharedPrefs.AppPrefs
import com.toshi.util.sharedPrefs.AppPrefsInterface
import com.toshi.util.sharedPrefs.BalancePrefs
import com.toshi.util.sharedPrefs.BalancePrefsInterface
import com.toshi.view.BaseApplication
import rx.Completable
import rx.Observable
import rx.Scheduler
import rx.Single
import rx.Subscription
import rx.schedulers.Schedulers
import rx.subjects.BehaviorSubject
import java.math.BigDecimal
import java.math.RoundingMode
class BalanceManager(
private val ethService: EthereumServiceInterface = EthereumService,
private val currencyService: CurrencyInterface = CurrencyService.getApi(),
private val balancePrefs: BalancePrefsInterface = BalancePrefs(),
private val appPrefs: AppPrefsInterface = AppPrefs,
private val baseApplication: BaseApplication = BaseApplication.get(),
private val walletObservable: Observable<HDWallet>,
private val ethGcmRegistration: EthGcmRegistration = EthGcmRegistration(
ethService = ethService,
walletObservable = walletObservable
),
private val scheduler: Scheduler = Schedulers.io()
) {
private var connectivitySub: Subscription? = null
val balanceObservable: BehaviorSubject<Balance> = BehaviorSubject.create<Balance>()
fun init(): Completable {
initCachedBalance()
return registerEthGcm()
.onErrorComplete()
.doOnCompleted { attachConnectivityObserver() }
}
private fun initCachedBalance() {
readLastKnownBalance()
.map { Balance(it) }
.flatMapCompletable { handleNewBalance(it) }
.subscribe(
{},
{ LogUtil.exception("Error while reading last known balance $it") }
)
}
private fun attachConnectivityObserver() {
clearConnectivitySubscription()
connectivitySub = baseApplication
.isConnectedSubject
.subscribeOn(scheduler)
.filter { isConnected -> isConnected }
.subscribe(
{ handleConnectivity() },
{ LogUtil.exception("Error checking connection state", it) }
)
}
private fun handleConnectivity() {
refreshBalance()
registerEthGcm()
.subscribeOn(scheduler)
.subscribe(
{ },
{ LogUtil.exception("Error while registering eth gcm", it) }
)
}
fun registerEthGcm(): Completable = ethGcmRegistration.forceRegisterEthGcm()
fun refreshBalance() {
getBalance()
.observeOn(scheduler)
.flatMapCompletable { handleNewBalance(it) }
.doOnError { updateBalanceWithLastKnownBalance() }
.subscribe(
{},
{ LogUtil.exception("Error while fetching balance", it) }
)
}
private fun updateBalanceWithLastKnownBalance() {
readLastKnownBalance()
.map { Balance(it) }
.subscribe(
{ balanceObservable.onNext(it) },
{ LogUtil.exception("Error while updating balance with last known balance", it) }
)
}
private fun getBalance(): Single<Balance> {
return getWallet()
.flatMap { ethService.get().getBalance(it.paymentAddress) }
.subscribeOn(scheduler)
}
fun getERC20Tokens(): Single<ERC20Tokens> {
return getWallet()
.flatMap { ethService.get().getTokens(it.paymentAddress) }
.subscribeOn(scheduler)
}
fun getERC20Token(contractAddress: String): Single<ERCToken> {
return getWallet()
.flatMap { ethService.get().getToken(it.paymentAddress, contractAddress) }
.subscribeOn(scheduler)
}
fun getERC721Tokens(): Single<ERC721Tokens> {
return getWallet()
.flatMap { ethService.get().getCollectibles(it.paymentAddress) }
.subscribeOn(scheduler)
}
fun getERC721Token(contactAddress: String): Single<ERC721TokenWrapper> {
return getWallet()
.flatMap { ethService.get().getCollectible(it.paymentAddress, contactAddress) }
.subscribeOn(scheduler)
}
fun addCustomToken(customERCToken: CustomERCToken): Completable {
return ethService
.get()
.timestamp
.flatMapCompletable { ethService.get().addCustomToken(it.get(), customERCToken) }
.subscribeOn(scheduler)
}
private fun getWallet(): Single<HDWallet> {
return walletObservable
.getTimeoutSingle()
.subscribeOn(scheduler)
}
private fun handleNewBalance(balance: Balance): Completable {
return writeLastKnownBalance(balance)
.doOnCompleted { balanceObservable.onNext(balance) }
}
fun generateLocalPrice(payment: Payment): Single<Payment> {
val weiAmount = TypeConverter.StringHexToBigInteger(payment.value)
val ethAmount = EthUtil.weiToEth(weiAmount)
return getLocalCurrencyExchangeRate()
.map { toLocalCurrencyString(it, ethAmount) }
.map(payment::setLocalPrice)
}
fun getLocalCurrencyExchangeRate(): Single<ExchangeRate> {
return getLocalCurrency()
.flatMap { fetchLatestExchangeRate(it) }
.subscribeOn(scheduler)
}
private fun fetchLatestExchangeRate(code: String): Single<ExchangeRate> = currencyService.getRates(code)
fun getCurrencies(): Single<Currencies> {
return currencyService
.currencies
.subscribeOn(scheduler)
}
fun convertEthToLocalCurrencyString(ethAmount: BigDecimal): Single<String> {
return getLocalCurrencyExchangeRate()
.map { toLocalCurrencyString(it, ethAmount) }
}
fun toLocalCurrencyString(exchangeRate: ExchangeRate, ethAmount: BigDecimal): String {
val marketRate = exchangeRate.rate
val localAmount = marketRate.multiply(ethAmount)
val numberFormat = CurrencyUtil.getNumberFormat()
numberFormat.isGroupingUsed = true
numberFormat.maximumFractionDigits = 2
numberFormat.minimumFractionDigits = 2
val amount = numberFormat.format(localAmount)
val currencyCode = CurrencyUtil.getCode(exchangeRate.to)
val currencySymbol = CurrencyUtil.getSymbol(exchangeRate.to)
return String.format("%s%s %s", currencySymbol, amount, currencyCode)
}
private fun getLocalCurrency(): Single<String> = Single.fromCallable { appPrefs.getCurrency() }
fun convertLocalCurrencyToEth(localAmount: BigDecimal): Single<BigDecimal> {
return getLocalCurrencyExchangeRate()
.flatMap { mapToEth(it, localAmount) }
}
private fun mapToEth(exchangeRate: ExchangeRate,
localAmount: BigDecimal): Single<BigDecimal> {
return Single.fromCallable {
if (localAmount.compareTo(BigDecimal.ZERO) == 0) BigDecimal.ZERO
val marketRate = exchangeRate.rate
if (marketRate.compareTo(BigDecimal.ZERO) == 0) BigDecimal.ZERO
return@fromCallable localAmount.divide(marketRate, BIG_DECIMAL_SCALE, RoundingMode.HALF_DOWN)
}
}
fun getTransactionStatus(transactionHash: String): Single<Payment> {
return EthereumService.getStatusOfTransaction(transactionHash)
}
private fun readLastKnownBalance(): Single<String> {
return walletObservable.getTimeoutSingle()
.subscribeOn(scheduler)
.map { balancePrefs.readLastKnownBalance(it.getCurrentWalletIndex()) }
}
private fun writeLastKnownBalance(balance: Balance): Completable {
return walletObservable.getTimeoutSingle()
.subscribeOn(scheduler)
.doOnSuccess { balancePrefs.writeLastKnownBalance(it.getCurrentWalletIndex(), balance) }
.toCompletable()
}
fun changeNetwork(network: Network) = ethGcmRegistration.changeNetwork(network)
fun unregisterFromEthGcm(token: String) = ethGcmRegistration.unregisterFromEthGcm(token)
fun clear() {
clearConnectivitySubscription()
balancePrefs.clear()
ethGcmRegistration.clear()
}
private fun clearConnectivitySubscription() = connectivitySub?.unsubscribe()
} | gpl-3.0 | 309af94f9aa0ed9756b551b7e9d9bbb1 | 37.380074 | 108 | 0.663462 | 4.942966 | false | false | false | false |
rafaelwkerr/duplicate-user | app/src/main/java/ninenine/com/duplicateuser/repository/local/LocalUserRepository.kt | 1 | 1185 | package ninenine.com.duplicateuser.repository.local
import android.content.Context
import android.util.Log
import com.squareup.moshi.Moshi
import ninenine.com.duplicateuser.domain.User
import ninenine.com.duplicateuser.functions.loadJSONFromAsset
import ninenine.com.duplicateuser.repository.UserRepository
import javax.inject.Inject
class LocalUserRepository @Inject constructor(private val context: Context,
private val moshi: Moshi) : UserRepository {
private val TAG = LocalUserRepository::class.java.simpleName
override fun getUsersWithSet(): Set<User>? =
convertJsonStringToUsers()?.toSet()
override fun getUsersWithList(): List<User>? =
convertJsonStringToUsers()?.distinct()
fun convertJsonStringToUsers(): Array<User>? {
val usersFromJsonFile = loadJSONFromAsset(context)
val jsonAdapter = moshi.adapter<Array<User>>(Array<User>::class.java)
var users: Array<User>? = null
try {
users = jsonAdapter.fromJson(usersFromJsonFile)
} catch (e: Exception) {
Log.e(TAG, "error=" + e)
}
return users
}
} | mit | 1f92048cae437f88b5e00fdcfead513e | 33.882353 | 94 | 0.6827 | 4.759036 | false | false | false | false |
kunny/RxFirebase | firebase-auth-kotlin/src/main/kotlin/com/androidhuman/rxfirebase2/auth/RxFirebaseAuth.kt | 1 | 3151 | @file:Suppress("NOTHING_TO_INLINE", "UNUSED")
package com.androidhuman.rxfirebase2.auth
import com.google.firebase.auth.AuthCredential
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.Single
inline fun FirebaseAuth.authStateChanges()
: Observable<FirebaseAuth>
= RxFirebaseAuth.authStateChanges(this)
inline fun FirebaseAuth.rxCreateUserWithEmailAndPassword(email: String, password: String)
: Single<FirebaseUser>
= RxFirebaseAuth.createUserWithEmailAndPassword(this, email, password)
@Deprecated(message = "Use rxFetchSignMethodsForEmail() instead.")
inline fun FirebaseAuth.rxFetchProvidersForEmail(email: String)
: Maybe<List<String>>
= RxFirebaseAuth.fetchProvidersForEmail(this, email)
inline fun FirebaseAuth.rxFetchSignInMethodsForEmail(email: String)
: Maybe<List<String>>
= RxFirebaseAuth.fetchSignInMethodsForEmail(this, email)
inline fun FirebaseAuth.rxGetCurrentUser()
: Maybe<FirebaseUser>
= RxFirebaseAuth.getCurrentUser(this)
inline fun FirebaseAuth.rxSendPasswordResetEmail(email: String)
: Completable
= RxFirebaseAuth.sendPasswordResetEmail(this, email)
inline fun FirebaseAuth.rxSignInAnonymously()
: Single<FirebaseUser>
= RxFirebaseAuth.signInAnonymously(this)
inline fun FirebaseAuth.rxSignInWithCredential(credential: AuthCredential)
: Single<FirebaseUser>
= RxFirebaseAuth.signInWithCredential(this, credential)
inline fun FirebaseAuth.rxSignInWithCustomToken(token: String)
: Single<FirebaseUser>
= RxFirebaseAuth.signInWithCustomToken(this, token)
inline fun FirebaseAuth.rxSignInWithEmailAndPassword(email: String, password: String)
: Single<AuthResult>
= RxFirebaseAuth.signInWithEmailAndPasswordAuthResult(this, email, password)
inline fun FirebaseAuth.rxSignInAnonymouslyAuthResult()
: Single<AuthResult>
= RxFirebaseAuth.signInAnonymouslyAuthResult(this)
inline fun FirebaseAuth.rxSignInWithCredentialAuthResult(credential: AuthCredential)
: Single<AuthResult>
= RxFirebaseAuth.signInWithCredentialAuthResult(this, credential)
inline fun FirebaseAuth.rxSignInWithCustomTokenAuthResult(token: String)
: Single<AuthResult>
= RxFirebaseAuth.signInWithCustomTokenAuthResult(this, token)
inline fun FirebaseAuth.rxSignInWithEmailAndPasswordAuthResult(email: String, password: String)
: Single<FirebaseUser>
= RxFirebaseAuth.signInWithEmailAndPassword(this, email, password)
inline fun FirebaseAuth.rxSignInWithEmailLink(email: String, emailLink: String)
: Single<AuthResult>
= RxFirebaseAuth.signInWithEmailLink(this, email, emailLink)
inline fun FirebaseAuth.rxUpdateCurrentUser(user: FirebaseUser)
: Completable
= RxFirebaseAuth.updateCurrentUser(this, user)
inline fun FirebaseAuth.rxSignOut()
: Completable
= RxFirebaseAuth.signOut(this) | apache-2.0 | f522fb33408b4043b265c025f18a6a43 | 37.91358 | 95 | 0.771184 | 4.640648 | false | false | false | false |
kropp/intellij-makefile | src/main/kotlin/name/kropp/intellij/makefile/MakefileRunConfiguration.kt | 1 | 4005 | package name.kropp.intellij.makefile
import com.intellij.execution.*
import com.intellij.execution.configuration.*
import com.intellij.execution.configurations.*
import com.intellij.execution.process.*
import com.intellij.execution.runners.*
import com.intellij.openapi.components.*
import com.intellij.openapi.project.*
import com.intellij.util.*
import org.jdom.*
import org.jetbrains.plugins.terminal.*
import java.io.*
class MakefileRunConfiguration(project: Project, factory: MakefileRunConfigurationFactory, name: String) : LocatableConfigurationBase<RunProfileState>(project, factory, name) {
var filename = ""
var target = ""
var workingDirectory = ""
var environmentVariables: EnvironmentVariablesData = EnvironmentVariablesData.DEFAULT
var arguments = ""
private companion object {
const val MAKEFILE = "makefile"
const val FILENAME = "filename"
const val TARGET = "target"
const val WORKING_DIRECTORY = "workingDirectory"
const val ARGUMENTS = "arguments"
}
override fun checkConfiguration() {
}
override fun getConfigurationEditor() = MakefileRunConfigurationEditor(project)
override fun writeExternal(element: Element) {
super.writeExternal(element)
val child = element.getOrCreate(MAKEFILE)
child.setAttribute(FILENAME, filename)
child.setAttribute(TARGET, target)
child.setAttribute(WORKING_DIRECTORY, workingDirectory)
child.setAttribute(ARGUMENTS, arguments)
environmentVariables.writeExternal(child)
}
override fun readExternal(element: Element) {
super.readExternal(element)
val child = element.getChild(MAKEFILE)
if (child != null) {
filename = child.getAttributeValue(FILENAME) ?: ""
target = child.getAttributeValue(TARGET) ?: ""
workingDirectory = child.getAttributeValue(WORKING_DIRECTORY) ?: ""
arguments = child.getAttributeValue(ARGUMENTS) ?: ""
environmentVariables = EnvironmentVariablesData.readExternal(child)
}
}
override fun getState(executor: Executor, executionEnvironment: ExecutionEnvironment): RunProfileState? {
val makeSettings = ServiceManager.getService(project, MakefileProjectSettings::class.java).settings
val makePath = makeSettings?.path ?: DEFAULT_MAKE_PATH
return object : CommandLineState(executionEnvironment) {
override fun startProcess(): ProcessHandler {
val params = ParametersList()
params.addParametersString(arguments)
val macroManager = PathMacroManager.getInstance(project)
val path = macroManager.expandPath(filename)
params.addAll("-f", path)
if (target.isNotEmpty()) {
params.addParametersString(target)
}
val workDirectory = if (workingDirectory.isNotEmpty()) macroManager.expandPath(workingDirectory) else File(path).parent
val parentEnvs = if (environmentVariables.isPassParentEnvs) EnvironmentUtil.getEnvironmentMap() else emptyMap<String,String>()
val envs = parentEnvs + environmentVariables.envs.toMutableMap()
var command = arrayOf(makePath) + params.array
try {
for (customizer in LocalTerminalCustomizer.EP_NAME.extensions) {
try {
command = customizer.customizeCommandAndEnvironment(project, command, envs)
} catch (e: Throwable) {
}
}
} catch (e: Throwable) {
// optional dependency
}
val cmd = PtyCommandLine()
.withUseCygwinLaunch(makeSettings?.useCygwin ?: false)
.withExePath(command[0])
.withWorkDirectory(workDirectory)
.withEnvironment(envs)
.withParentEnvironmentType(GeneralCommandLine.ParentEnvironmentType.NONE)
.withParameters(command.slice(1 until command.size))
val processHandler = ColoredProcessHandler(cmd)
processHandler.setShouldKillProcessSoftly(true)
ProcessTerminatedListener.attach(processHandler)
return processHandler
}
}
}
} | mit | 45cb54cef63896744340f7af5603d0fa | 38.27451 | 176 | 0.715855 | 5.037736 | false | true | false | false |
panpanini/KotlinWithDatabinding | app/src/main/java/nz/co/panpanini/kotlindatabinding/ui/repo/RepoAdapter.kt | 1 | 1242 | package nz.co.panpanini.kotlindatabinding.ui.repo
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import nz.co.panpanini.kotlindatabinding.databinding.ViewRepoBinding
import nz.co.panpanini.kotlindatabinding.model.Repo
import java.util.*
/**
* Created by matthewvern on 2017/01/30.
*/
class RepoAdapter : RecyclerView.Adapter<RepoViewHolder>(){
val items = ArrayList<Repo>()
override fun onBindViewHolder(holder: RepoViewHolder?, position: Int) {
val repo = items[position]
holder?.bind(repo)
}
override fun getItemCount(): Int = items.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RepoViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ViewRepoBinding.inflate(inflater, parent, false)
// we do have to use return in a function (I dunno why ¯\_(ツ)_/¯ )
return RepoViewHolder(binding)
}
fun add(repo: Repo) {
items.add(repo)
notifyItemInserted(items.size)
}
fun remove(repo: Repo) {
val position = items.indexOf(repo)
items.removeAt(position)
notifyItemRemoved(position)
}
} | unlicense | 2c0be1fba477ce39206ad3c5dc966013 | 27.159091 | 87 | 0.694669 | 4.072368 | false | false | false | false |
huclengyue/StateLayoutWithKotlin | stateLayout/src/main/java/com/apkdv/statelayout/helper/LayoutHelper.kt | 1 | 7775 | package com.apkdv.statelayout.helper
import android.content.Context
import android.text.TextUtils
import android.view.LayoutInflater
import android.util.AttributeSet
import android.view.View
import com.apkdv.KotlinDemo.holder.*
import com.apkdv.KotlinDemo.bean.LoadingItem
import com.apkdv.KotlinDemo.bean.LoginItem
import com.apkdv.KotlinDemo.bean.NoNetworkItem
import com.apkdv.KotlinDemo.bean.EmptyItem
import com.apkdv.KotlinDemo.bean.TimeOutItem
import com.apkdv.KotlinDemo.bean.ErrorItem
import android.support.annotation.DrawableRes
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import com.apkdv.KotlinDemo.pagestate.StateLayout
import com.apkdv.statelayout.R
/**
* Created by LengYue on 2017/5/19.
*/
class LayoutHelper {
companion object {
/**
* 解析布局中的可选参数
* @param context
* *
* @param attrs
* *
* @param stateLayout
*/
fun parseAttr(context: Context, attrs: AttributeSet, stateLayout: StateLayout) {
val a = context.theme.obtainStyledAttributes(attrs, R.styleable.StateLayout, 0, 0)
try {
val errorImg = a.getResourceId(R.styleable.StateLayout_errorImg, -1)
val errorText = a.getString(R.styleable.StateLayout_errorText)
stateLayout.errorItem = ErrorItem(errorImg, errorText)
val timeOutImg = a.getResourceId(R.styleable.StateLayout_timeOutImg, -1)
val timeOutText = a.getString(R.styleable.StateLayout_timeOutText)
stateLayout.timeOutItem = TimeOutItem(timeOutImg, timeOutText)
val emptyImg = a.getResourceId(R.styleable.StateLayout_emptyImg, -1)
val emptyText = a.getString(R.styleable.StateLayout_emptyText)
stateLayout.emptyItem = EmptyItem(emptyImg, emptyText)
val noNetworkImg = a.getResourceId(R.styleable.StateLayout_noNetworkImg, -1)
val noNetworkText = a.getString(R.styleable.StateLayout_noNetworkText)
stateLayout.noNetworkItem = NoNetworkItem(noNetworkImg, noNetworkText)
val loginImg = a.getResourceId(R.styleable.StateLayout_loginImg, -1)
val loginText = a.getString(R.styleable.StateLayout_loginText)
stateLayout.loginItem = LoginItem(loginImg, loginText)
val loadingText = a.getString(R.styleable.StateLayout_loadingText)
stateLayout.loadingItem = LoadingItem(loadingText)
} finally {
a.recycle()
}
}
/**
* 获取初始的错误View
* @param layoutInflater 布局填充器
* *
* @param item 错误bean
* *
* @param layout 容器
* *
* @return 错误View
*/
fun getErrorView(layoutInflater: LayoutInflater, item: ErrorItem?,
layout: StateLayout): View {
val view = layoutInflater.inflate(R.layout.layout_error, null)
if (item != null) {
val holder = ErrorViewHolder(view)
view.tag = holder
setImageAndText(item.tip, item.resId, holder.textTip, holder.ivImg)
view.setOnClickListener {
layout.mListener?.refreshClick()
}
}
return view
}
/**
* 获取初始的没有网络View
* @param layoutInflater 布局填充器
* *
* @param item 没有网络bean
* *
* @param layout 容器
* *
* @return 没有网络View
*/
fun getNoNetworkView(layoutInflater: LayoutInflater, item: NoNetworkItem?,
layout: StateLayout): View {
val view = layoutInflater.inflate(R.layout.layout_no_network, null)
if (item != null) {
val holder = NoNetworkViewHolder(view)
view.tag = holder
setImageAndText(item.tip, item.resId, holder.textTip, holder.ivImg)
view.setOnClickListener { layout.mListener?.refreshClick() }
}
return view
}
/**
* 获取初始的加载View
* @param layoutInflater 布局填充器
* *
* @param item 加载bean
* *
* @return 加载View
*/
fun getLoadingView(layoutInflater: LayoutInflater, item: LoadingItem?): View {
val view = layoutInflater.inflate(R.layout.layout_loading, null)
if (item != null) {
val holder = LoadingViewHolder(view)
view.tag = holder
val progressBar = ProgressBar(view.context)
progressBar.indeterminateDrawable = view.resources.getDrawable(R.drawable.bg_loading)
holder.frameLayout?.addView(progressBar)
if (!TextUtils.isEmpty(item.tip)) {
holder.textTip?.text = item.tip
}
}
return view
}
/**
* 获取初始的超时View
* @param layoutInflater 布局填充器
* *
* @param item 超时bean
* *
* @param layout 容器
* *
* @return 超时View
*/
fun getTimeOutView(layoutInflater: LayoutInflater, item: TimeOutItem?,
layout: StateLayout): View {
val view = layoutInflater.inflate(R.layout.layout_time_out, null)
if (item != null) {
val holder = TimeOutViewHolder(view)
view.tag = holder
setImageAndText(item.tip, item.resId, holder.textTip, holder.ivImg)
view.setOnClickListener { layout.mListener?.refreshClick() }
}
return view
}
/**
* 获取初始的空数据View
* @param layoutInflater 布局填充器
* *
* @param item 空数据bean
* *
* @return 空数据View
*/
fun getEmptyView(layoutInflater: LayoutInflater, item: EmptyItem?): View {
val view = layoutInflater.inflate(R.layout.layout_empty, null)
if (item != null) {
val holder = EmptyViewHolder(view)
view.tag = holder
setImageAndText(item.tip, item.resId, holder.textTip, holder.ivImg)
}
return view
}
/**
* 获取初始的空数据View
* @param layoutInflater 布局填充器
* *
* @param item 空数据bean
* *
* @return 空数据View
*/
fun getLoginView(layoutInflater: LayoutInflater, item: LoginItem?,
layout: StateLayout): View {
val view = layoutInflater.inflate(R.layout.layout_login, null)
if (item != null) {
val holder = LoginViewHolder(view)
view.tag = holder
setImageAndText(item.tip, item.resId, holder.textTip, holder.ivImg)
holder.btnLogin?.setOnClickListener { layout.mListener?.loginClick() }
}
return view
}
/**
* 设置文字图片
*/
private fun setImageAndText(tips: String, @DrawableRes resId: Int, textTips: TextView?, imageview: ImageView?) {
if (!TextUtils.isEmpty(tips)) {
textTips?.text = tips
}
if (resId > 0) {
imageview?.setImageResource(resId)
}
}
}
} | apache-2.0 | 41a87376eaf253a729e11bd6a68a03c1 | 32.553571 | 120 | 0.556354 | 4.516226 | false | false | false | false |
bravelocation/yeltzland-android | app/src/main/java/com/bravelocation/yeltzlandnew/dataproviders/GameScoreDataProvider.kt | 1 | 9025 | package com.bravelocation.yeltzlandnew.dataproviders
import android.content.Context
import android.util.Log
import com.bravelocation.yeltzlandnew.dataproviders.FixtureListDataProvider.getNextFixtures
import com.bravelocation.yeltzlandnew.dataproviders.TimelineManager.Companion.instance
import com.bravelocation.yeltzlandnew.models.FixtureListDataItem
import okhttp3.*
import org.json.JSONObject
import java.io.*
import java.text.SimpleDateFormat
import java.util.*
object GameScoreDataProvider {
private const val localFileName = "gamescore.json"
var latestScore: FixtureListDataItem? = null
private set
private val nextFixture: FixtureListDataItem?
get() {
val nextGames = getNextFixtures(1)
return if (nextGames.isNotEmpty()) {
nextGames[0]
} else null
}
fun isGameScoreForLatestGame(): Boolean {
if (latestScore == null) {
return false
}
val nextGame = nextFixture
return nextGame != null && nextGame.isSameGame(latestScore!!)
}
fun updateGameScore(context: Context, completion: Runnable?) {
// Copy bundled matches to cache
moveBundleFileToAppDirectory(context)
// Load data from cached JSON file
loadDataFromCachedJson(context, completion)
// Refresh data from server
refreshFixturesFromServer(context, completion)
// Update timeline on data refreshed
instance.loadLatestData()
}
private fun moveBundleFileToAppDirectory(context: Context) {
var inputStream: InputStream? = null
var outputStream: OutputStream? = null
try {
// Does the file already exist?
val cacheFile = File(context.getExternalFilesDir(null), localFileName)
if (cacheFile.exists()) {
Log.d("GameScoreDataProvider", "Asset file already exists in file cache")
return
}
val assetManager = context.assets
inputStream = assetManager.open(localFileName)
outputStream = FileOutputStream(cacheFile)
val buffer = ByteArray(1024)
var read: Int
while (inputStream.read(buffer).also { read = it } != -1) {
outputStream.write(buffer, 0, read)
}
Log.d("GameScoreDataProvider", "Asset file copied to file cache")
} catch (e: Exception) {
Log.e("GameScoreDataProvider", "Error copying asset to cache:$e")
} finally {
if (inputStream != null) {
try {
inputStream.close()
} catch (e: IOException) {
// Ignore cleanup error
}
}
if (outputStream != null) {
try {
outputStream.flush()
outputStream.close()
} catch (e: IOException) {
// Ignore cleanup error
}
}
}
}
private fun loadDataFromCachedJson(context: Context, completion: Runnable?) {
var fileInputStream: FileInputStream? = null
try {
// Load the JSON data
val cacheFile = File(context.getExternalFilesDir(null), localFileName)
fileInputStream = FileInputStream(cacheFile)
val size = fileInputStream.available()
val buffer = ByteArray(size)
fileInputStream.read(buffer)
parseJSON(String(buffer, Charsets.UTF_8), completion)
} catch (e: Exception) {
Log.e("GameScoreDataProvider", "Error parsing JSON:$e")
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close()
} catch (e: IOException) {
// Ignore cleanup error
}
}
}
}
private fun parseJSON(input: String, completion: Runnable?): Boolean {
return try {
if (input.isEmpty()) {
return false
}
val parsedJson = JSONObject(input)
val match = parsedJson.getJSONObject("match")
// Pulling items from the match
val matchDateTime = match.getString("MatchDateTime")
val opponent = match.getString("Opponent")
val home = match.getString("Home")
// Pull latest score
val teamScore = parsedJson.getString("yeltzScore")
val opponentScore = parsedJson.getString("opponentScore")
val dateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.UK)
dateFormat.timeZone = TimeZone.getTimeZone("Europe/London")
val convertedMatchDate = dateFormat.parse(matchDateTime)
if (convertedMatchDate == null) {
Log.d("GameScoreDataProvider", "Unexpected date: $matchDateTime")
return false
}
var nextFixture: FixtureListDataItem? = null
val latestScore: FixtureListDataItem =
if (teamScore == "null" || opponentScore == "null") {
FixtureListDataItem(convertedMatchDate, opponent, home == "1")
} else {
FixtureListDataItem(convertedMatchDate,
opponent,
home == "1",
Integer.valueOf(teamScore),
Integer.valueOf(opponentScore))
}
val nextFixtures = getNextFixtures(1)
if (nextFixtures.isNotEmpty()) {
nextFixture = nextFixtures[0]
}
// Is the game in progress
if (nextFixture != null) {
// If same game
if (latestScore.isSameGame(nextFixture)) {
GameScoreDataProvider.latestScore = latestScore
} else {
// Are we after kickoff?
val now = Date()
if (now.after(nextFixture.fixtureDate)) {
// If so, we are in progress with no score yet
GameScoreDataProvider.latestScore = nextFixture
} else {
// Get last result
val lastResult = FixtureListDataProvider.lastResult
GameScoreDataProvider.latestScore = lastResult
}
}
}
Log.d("GameScoreDataProvider", "Game score updated")
if (completion != null) {
Log.d("GameScoreDataProvider", "Running completion after game score update")
completion.run()
}
true
} catch (e: Exception) {
Log.e("GameScoreDataProvider", "Error parsing JSON:$e")
false
}
}
fun refreshFixturesFromServer(context: Context, completion: Runnable?) {
val client = OkHttpClient()
val request: Request = Request.Builder()
.url("https://bravelocation.com/automation/feeds/gamescore.json")
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
if (!response.isSuccessful) {
Log.d("GameScoreDataProvider", "Unexpected code $response")
} else {
val result = response.body?.string()
if (result == null) {
Log.d("GameScoreDataProvider", "Unexpected response")
return
}
// Check it's valid JSON, and if so, replace cache
if (parseJSON(result, completion)) {
var out: FileOutputStream? = null
val cacheFile = File(context.getExternalFilesDir(null), localFileName)
try {
out = FileOutputStream(cacheFile)
out.write(result.toByteArray())
Log.d("GameScoreDataProvider",
"Written server game score data to cache")
} finally {
if (out != null) {
try {
out.flush()
out.close()
} catch (e: IOException) {
// Ignore cleanup error
}
}
}
} else {
Log.d("GameScoreDataProvider", "No game score found in server data")
}
}
}
})
}
} | mit | ac009dbbc9f207e03ac955314e9a3c7c | 36.92437 | 94 | 0.521551 | 5.570988 | false | true | false | false |
ansman/okhttp | mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/PushPromise.kt | 2 | 1669 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.mockwebserver
import okhttp3.Headers
class PushPromise(
@get:JvmName("method") val method: String,
@get:JvmName("path") val path: String,
@get:JvmName("headers") val headers: Headers,
@get:JvmName("response") val response: MockResponse
) {
@JvmName("-deprecated_method")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "method"),
level = DeprecationLevel.ERROR)
fun method() = method
@JvmName("-deprecated_path")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "path"),
level = DeprecationLevel.ERROR)
fun path() = path
@JvmName("-deprecated_headers")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "headers"),
level = DeprecationLevel.ERROR)
fun headers() = headers
@JvmName("-deprecated_response")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "response"),
level = DeprecationLevel.ERROR)
fun response() = response
}
| apache-2.0 | 11fd80aa7cfcd59c0bcd1e915e461b38 | 29.907407 | 75 | 0.692031 | 4.246819 | false | false | false | false |
daugeldauge/NeePlayer | app/src/main/java/com/neeplayer/ui/common/BindingUtils.kt | 1 | 862 | package com.neeplayer.ui.common
import android.graphics.drawable.Drawable
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import java.util.concurrent.TimeUnit
@BindingAdapter("imageUri")
fun loadImage(view: ImageView, uri: String?) = Glide.with(view.context).run {
if (uri != null) {
load(uri).into(view)
} else {
clear(view)
}
}
@BindingAdapter("drawable")
fun setDrawable(view: ImageView, drawable: Drawable) = view.setImageDrawable(drawable)
@BindingAdapter("duration")
fun setFormattedDuration(view: TextView, duration: Int) {
val min = TimeUnit.MILLISECONDS.toMinutes(duration.toLong())
val sec = TimeUnit.MILLISECONDS.toSeconds(duration.toLong()) - TimeUnit.MINUTES.toSeconds(min)
view.text = "%d:%02d".format(min, sec)
}
| mit | 02409b93dfb474cc984bb7881980b246 | 30.925926 | 98 | 0.74594 | 3.882883 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/widget/WidgetClickActivity.kt | 1 | 3999 | package org.tasks.widget
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import com.todoroo.astrid.dao.TaskDao
import com.todoroo.astrid.data.Task
import com.todoroo.astrid.service.TaskCompleter
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.launch
import org.tasks.LocalBroadcastManager
import org.tasks.R
import org.tasks.dialogs.BaseDateTimePicker.OnDismissHandler
import org.tasks.dialogs.DateTimePicker.Companion.newDateTimePicker
import org.tasks.injection.InjectingAppCompatActivity
import org.tasks.intents.TaskIntents
import org.tasks.preferences.Preferences
import javax.inject.Inject
@AndroidEntryPoint
class WidgetClickActivity : InjectingAppCompatActivity(), OnDismissHandler {
@Inject lateinit var taskCompleter: TaskCompleter
@Inject lateinit var taskDao: TaskDao
@Inject lateinit var localBroadcastManager: LocalBroadcastManager
@Inject lateinit var preferences: Preferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val intent = intent
val action = intent.action
if (action.isNullOrEmpty()) {
return
}
when (action) {
COMPLETE_TASK -> {
lifecycleScope.launch(NonCancellable) {
taskCompleter.setComplete(task, !task.isCompleted)
}
finish()
}
EDIT_TASK -> {
startActivity(
TaskIntents.getEditTaskIntent(
this,
intent.getParcelableExtra(EXTRA_FILTER),
intent.getParcelableExtra(EXTRA_TASK)))
finish()
}
TOGGLE_SUBTASKS -> {
lifecycleScope.launch(NonCancellable) {
taskDao.setCollapsed(task.id, intent.getBooleanExtra(EXTRA_COLLAPSED, false))
}
finish()
}
RESCHEDULE_TASK -> {
val fragmentManager = supportFragmentManager
if (fragmentManager.findFragmentByTag(FRAG_TAG_DATE_TIME_PICKER) == null) {
newDateTimePicker(
preferences.getBoolean(R.string.p_auto_dismiss_datetime_widget, false),
task)
.show(fragmentManager, FRAG_TAG_DATE_TIME_PICKER)
}
}
TOGGLE_GROUP -> {
val widgetPreferences = WidgetPreferences(
applicationContext,
preferences,
intent.getIntExtra(EXTRA_WIDGET, -1)
)
val collapsed = widgetPreferences.collapsed
val group = intent.getLongExtra(EXTRA_GROUP, -1)
if (intent.getBooleanExtra(EXTRA_COLLAPSED, false)) {
collapsed.add(group)
} else {
collapsed.remove(group)
}
widgetPreferences.setCollapsed(collapsed)
localBroadcastManager.broadcastRefresh()
finish()
}
}
}
val task: Task
get() = intent.getParcelableExtra(EXTRA_TASK)!!
override fun onDismiss() {
finish()
}
companion object {
const val COMPLETE_TASK = "COMPLETE_TASK"
const val EDIT_TASK = "EDIT_TASK"
const val TOGGLE_SUBTASKS = "TOGGLE_SUBTASKS"
const val RESCHEDULE_TASK = "RESCHEDULE_TASK"
const val TOGGLE_GROUP = "TOGGLE_GROUP"
const val EXTRA_FILTER = "extra_filter"
const val EXTRA_TASK = "extra_task" // $NON-NLS-1$
const val EXTRA_COLLAPSED = "extra_collapsed"
const val EXTRA_GROUP = "extra_group"
const val EXTRA_WIDGET = "extra_widget"
private const val FRAG_TAG_DATE_TIME_PICKER = "frag_tag_date_time_picker"
}
} | gpl-3.0 | 51ee7c2b9756621311e993c8fa6b3496 | 37.461538 | 99 | 0.594149 | 5.234293 | false | false | false | false |
jereksel/LibreSubstratum | app/src/main/kotlin/com/jereksel/libresubstratum/domain/overlayService/nougat/InterfacerOverlayService.kt | 1 | 7039 | /*
* 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.domain.overlayService.nougat
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.om.IOverlayManager
import android.content.pm.PackageManager
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.support.v4.content.ContextCompat
import arrow.core.Option
import arrow.core.Option.Companion.empty
import arrow.core.Some
import com.google.common.util.concurrent.ThreadFactoryBuilder
import com.jereksel.libresubstratum.domain.OverlayInfo
import com.jereksel.libresubstratum.domain.OverlayService
import com.jereksel.libresubstratum.extensions.getLogger
import com.jereksel.omslib.OMSLib
import io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.BehaviorSubject.createDefault
import projekt.substratum.IInterfacerInterface
import kotlinx.coroutines.experimental.asCoroutineDispatcher
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.guava.asListenableFuture
import kotlinx.coroutines.experimental.guava.await
import kotlinx.coroutines.experimental.rx2.await
import java.io.File
import java.util.concurrent.Executors
abstract class InterfacerOverlayService(val context: Context): OverlayService {
private val log = getLogger()
private val interfacerBS: BehaviorSubject<Option<IInterfacerInterface>> = createDefault(empty())
private val interfacerRx: Observable<IInterfacerInterface> = interfacerBS.filter { it.isDefined() }.map { it.get() }
private val oms: IOverlayManager = OMSLib.getOMS()
val threadFactory = ThreadFactoryBuilder().setNameFormat("nougat-interfacer-overlay-service-thread-%d").build()
val dispatcher = Executors.newFixedThreadPool(2, threadFactory).asCoroutineDispatcher()
val INTERFACER_PACKAGE = "projekt.interfacer"
val INTERFACER_SERVICE = "$INTERFACER_PACKAGE.services.JobService"
val INTERFACER_BINDED = "$INTERFACER_PACKAGE.INITIALIZE"
val STATUS_CHANGED = "$INTERFACER_PACKAGE.STATUS_CHANGED"
private val interfacerServiceConnection = object: ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
log.debug("Interfacer connected")
interfacerBS.onNext(Some(IInterfacerInterface.Stub.asInterface(service)))
}
override fun onServiceDisconnected(name: ComponentName?) {
log.debug("Interfacer disconnected")
interfacerBS.onNext(empty())
}
}
private fun initInterfacer() {
val intent = Intent(INTERFACER_BINDED)
intent.`package` = INTERFACER_PACKAGE
// binding to remote service
context.bindService(intent, interfacerServiceConnection, Context.BIND_AUTO_CREATE);
}
init {
Handler(Looper.getMainLooper()).post {
initInterfacer()
}
}
override fun enableOverlay(id: String) = async(dispatcher) {
enableOverlay0(id)
}.asListenableFuture()
private suspend fun enableOverlay0(id: String) {
val interfacer = interfacerRx.firstOrError().await()
interfacer.enableOverlay(listOf(id), false)
}
override fun disableOverlay(id: String) = async(dispatcher) {
disableOverlay0(id)
}.asListenableFuture()
private suspend fun disableOverlay0(id: String) {
val interfacer = interfacerRx.firstOrError().await()
interfacer.disableOverlay(listOf(id), false)
}
//When we use CommonPool on everything we have possibility of deadlock
//enableExclusive is only method that uses other async methods
override fun enableExclusive(id: String) = async(dispatcher) {
val overlayInfo = getOverlayInfo0(id) ?: return@async
getAllOverlaysForApk0(overlayInfo.targetId)
.filter { it.enabled }
.forEach { disableOverlay0(it.overlayId) }
enableOverlay0(id)
}.asListenableFuture()
override fun getOverlayInfo(id: String) = async(dispatcher) {
getOverlayInfo0(id)
}.asListenableFuture()
private fun getOverlayInfo0(id: String): OverlayInfo? {
val info = oms.getOverlayInfo(id, 0)
return if (info != null) {
OverlayInfo(id, info.targetPackageName, info.isEnabled)
} else {
null
}
}
override fun getAllOverlaysForApk(appId: String) = async(dispatcher) {
getAllOverlaysForApk0(appId)
}.asListenableFuture()
private fun getAllOverlaysForApk0(appId: String): List<OverlayInfo> {
@Suppress("UNCHECKED_CAST")
val map = oms.getOverlayInfosForTarget(appId, 0) as List<android.content.om.OverlayInfo>
return map.map { OverlayInfo(it.packageName, it.targetPackageName, it.isEnabled) }
}
override fun getOverlaysPrioritiesForTarget(targetAppId: String) = async(dispatcher) {
@Suppress("UNCHECKED_CAST")
val list = oms.getOverlayInfosForTarget(targetAppId, 0) as List<android.content.om.OverlayInfo>
list.map { OverlayInfo(it.packageName, it.targetPackageName, it.isEnabled) }.reversed()
}.asListenableFuture()
override fun updatePriorities(overlayIds: List<String>) = async(dispatcher) {
val interfacer = interfacerRx.firstOrError().await()
interfacer.changePriority(overlayIds.reversed(), false)
}.asListenableFuture()
override fun restartSystemUI() = async(dispatcher) {
val interfacer = interfacerRx.firstOrError().await()
interfacer.restartSystemUI()
}.asListenableFuture()
override fun installApk(apk: File) = async(dispatcher) {
val interfacer = interfacerRx.firstOrError().await()
interfacer.installPackage(listOf(apk.absolutePath))
}.asListenableFuture()
override fun uninstallApk(appId: String) = async(dispatcher) {
val interfacer = interfacerRx.firstOrError().await()
interfacer.uninstallPackage(listOf(appId), false)
}.asListenableFuture()
override final fun requiredPermissions(): List<String> {
return allPermissions()
.filter { ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_DENIED }
}
abstract fun allPermissions(): List<String>
} | mit | f5ea1d6498b4b401b0ad66ae9ed173a7 | 38.111111 | 120 | 0.730644 | 4.355817 | false | false | false | false |
bozaro/git-as-svn | src/main/kotlin/svnserver/auth/cache/CacheUserDB.kt | 1 | 3288 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.auth.cache
import com.google.common.cache.Cache
import org.apache.commons.codec.binary.Hex
import org.tmatesoft.svn.core.SVNException
import svnserver.HashHelper
import svnserver.UserType
import svnserver.auth.Authenticator
import svnserver.auth.PlainAuthenticator
import svnserver.auth.User
import svnserver.auth.UserDB
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.util.concurrent.ExecutionException
/**
* Caching user authentication result for reduce external API usage.
*
* @author Artem V. Navrotskiy
*/
class CacheUserDB(private val userDB: UserDB, private val cache: Cache<String?, User>) : UserDB {
private val authenticators: Collection<Authenticator> = setOf(PlainAuthenticator(this))
override fun authenticators(): Collection<Authenticator> {
return authenticators
}
@Throws(SVNException::class)
override fun check(username: String, password: String): User? {
return cached("c." + hash(username, password)) { db: UserDB -> db.check(username, password) }
}
@Throws(SVNException::class)
override fun lookupByUserName(username: String): User? {
return cached("l.$username") { db: UserDB -> db.lookupByUserName(username) }
}
@Throws(SVNException::class)
override fun lookupByExternal(external: String): User? {
return cached("e.$external") { db: UserDB -> db.lookupByExternal(external) }
}
@Throws(SVNException::class)
private fun cached(key: String, callback: CachedCallback): User? {
return try {
val cachedUser = cache[key, {
val authUser = callback.exec(userDB)
authUser ?: invalidUser
}]
if (cachedUser !== invalidUser) cachedUser else null
} catch (e: ExecutionException) {
if (e.cause is SVNException) {
throw (e.cause as SVNException?)!!
}
throw IllegalStateException(e)
}
}
private fun hash(username: String, password: String): String {
val digest = HashHelper.sha256()
hashPacket(digest, username.toByteArray(StandardCharsets.UTF_8))
hashPacket(digest, password.toByteArray(StandardCharsets.UTF_8))
return Hex.encodeHexString(digest.digest())
}
private fun hashPacket(digest: MessageDigest, packet: ByteArray) {
var length = packet.size
while (true) {
digest.update((length and 0xFF).toByte())
if (length == 0) {
break
}
length = length shr 8 and 0xFFFFFF
}
digest.update(packet)
}
private fun interface CachedCallback {
@Throws(SVNException::class)
fun exec(userDB: UserDB): User?
}
companion object {
private val invalidUser: User = User.create("invalid", "invalid", null, null, UserType.Local, null)
}
}
| gpl-2.0 | f0b83374f877d7161836f8bc76f35e7c | 34.73913 | 107 | 0.669404 | 4.326316 | false | false | false | false |
thomcz/kotlin-todo-app | app/src/main/java/thomcz/kotlintodo/adapter/RecyclerViewAdapter.kt | 1 | 2338 | package thomcz.kotlintodo.adapter
import android.graphics.Paint
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import thomcz.kotlintodo.R
import thomcz.kotlintodo.data.Item
/**
* Copyright (c) 2017
* Created by Thomas Czogalik on 28.09.2017
*/
class RecyclerViewAdapter(private var items: List<Item>, private var changedListener: View.OnClickListener) : RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder>() {
override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {
val item = items[position]
holder.itemTitleView.text = item.title
holder.itemDescView.text = item.description
holder.itemCheckButton.isChecked = item.checked
setStrikeThrough(holder.itemCheckButton.isChecked, holder.itemTitleView, holder.itemDescView)
holder.itemCheckButton.setOnClickListener(changedListener)
holder.itemView.tag = item
}
override fun getItemCount(): Int = items.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
return RecyclerViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.todo_list_item, parent, false))
}
fun addItems(items : List<Item>) {
this.items = items
notifyDataSetChanged()
}
inner class RecyclerViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val itemTitleView: TextView = view.findViewById(R.id.todo_item_title)
val itemDescView: TextView = view.findViewById(R.id.todo_item_desc)
val itemCheckButton: CheckBox = view.findViewById(R.id.todo_check)
}
companion object {
fun setStrikeThrough(isChecked: Boolean, title: TextView, desc: TextView) {
if (isChecked) {
setStrikeThroughFlag(title, title.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG)
setStrikeThroughFlag(desc, desc.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG)
} else {
setStrikeThroughFlag(title, 0)
setStrikeThroughFlag(desc, 0)
}
}
private fun setStrikeThroughFlag(textView: TextView, flag: Int) {
textView.paintFlags = flag
}
}
} | mit | 8e94441704203434dd19ea0a80eb0ea2 | 35.546875 | 174 | 0.707015 | 4.305709 | false | false | false | false |
StoneMain/Shortranks | ShortranksCommon/src/main/kotlin/eu/mikroskeem/shortranks/common/commands/MainCommand.kt | 1 | 3913 | /*
* This file is part of project Shortranks, licensed under the MIT License (MIT).
*
* Copyright (c) 2017-2019 Mark Vainomaa <[email protected]>
* Copyright (c) Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package eu.mikroskeem.shortranks.common.commands
import co.aikar.commands.BaseCommand
import co.aikar.commands.annotation.CommandAlias
import co.aikar.commands.annotation.CommandCompletion
import co.aikar.commands.annotation.CommandPermission
import co.aikar.commands.annotation.Default
import co.aikar.commands.annotation.Subcommand
import eu.mikroskeem.shortranks.api.ShortranksPlugin
import eu.mikroskeem.shortranks.common.getSubcommands
/**
* Shortranks main command
*
* @author Mark Vainomaa
*/
@CommandAlias("shortranks")
@CommandPermission("shortranks.use")
class MainCommand(private val plugin: ShortranksPlugin<*, *>): BaseCommand() {
@Default
fun mainCommand() {
currentCommandIssuer.sendMessage("Usage: /shortranks ${getSubcommands()}")
}
@Subcommand("version")
fun versionCommand() = currentCommandIssuer.sendMessage("Shortranks version " +
"${plugin.info.version} running on ${plugin.info.platform} made by ${plugin.info.authors}")
@Subcommand("reload")
fun reloadCommand() {
plugin.reloadConfiguration()
currentCommandIssuer.sendMessage("Plugin reloaded!")
}
@Subcommand("resetTeams")
fun resetTeamsCommand() {
plugin.api.scoreboardManager.resetTeams()
currentCommandIssuer.sendMessage("Teams reset!")
}
@Subcommand("dumpTeams")
fun dumpTeamsCommand() {
currentCommandIssuer.sendMessage("Dumping ${plugin.api.scoreboardManager.teams.size} teams:")
plugin.api.scoreboardManager.teams.forEach { team ->
currentCommandIssuer.sendMessage("§r${plugin.findOnlinePlayer(team.teamOwnerPlayer)!!.name} -> $team")
}
}
@Subcommand("showHooks")
fun showHooksCommand() {
currentCommandIssuer.sendMessage("Enabled hooks:")
plugin.api.hookManager.registeredHooks.forEach {
currentCommandIssuer.sendMessage("» §r${it.name} - ${it.description} " +
"(Authors: ${it.authors.joinToString(separator = ", ")})")
}
}
@Subcommand("reloadhook")
@CommandCompletion("@hooks")
fun reloadHookCommand(hookName: String) {
val hook = plugin.api.hookManager.getHookByName(hookName)
if(hook == null) {
currentCommandIssuer.sendMessage("No such hook: $hookName")
} else {
if(!hook.javaClass.getMethod("reload").isDefault) {
hook.reload()
currentCommandIssuer.sendMessage("Hook '$hookName' reloaded")
} else {
currentCommandIssuer.sendMessage("Hook '$hookName' does not support reloading!")
}
}
}
} | mit | 0c8926df8a12292d4ad8dbf0bf740013 | 38.908163 | 114 | 0.704859 | 4.535963 | false | false | false | false |
panpf/sketch | sketch-gif-koral/src/androidTest/java/com/github/panpf/sketch/gif/koral/test/GifInfoHandlerHelperTest.kt | 1 | 7735 | /*
* 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.gif.koral.test
import android.net.Uri
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.github.panpf.sketch.Sketch
import com.github.panpf.sketch.datasource.AssetDataSource
import com.github.panpf.sketch.datasource.ByteArrayDataSource
import com.github.panpf.sketch.datasource.ContentDataSource
import com.github.panpf.sketch.datasource.DataFrom
import com.github.panpf.sketch.datasource.DataFrom.LOCAL
import com.github.panpf.sketch.datasource.DataFrom.NETWORK
import com.github.panpf.sketch.datasource.DiskCacheDataSource
import com.github.panpf.sketch.datasource.FileDataSource
import com.github.panpf.sketch.datasource.ResourceDataSource
import com.github.panpf.sketch.datasource.UnavailableDataSource
import com.github.panpf.sketch.fetch.newAssetUri
import com.github.panpf.sketch.fetch.newResourceUri
import com.github.panpf.sketch.request.ImageRequest
import com.github.panpf.sketch.request.LoadRequest
import com.github.panpf.sketch.sketch
import com.github.panpf.tools4j.test.ktx.assertThrow
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import pl.droidsonroids.gif.GifInfoHandleHelper
import pl.droidsonroids.gif.GifOptions
import java.io.InputStream
@RunWith(AndroidJUnit4::class)
class GifInfoHandlerHelperTest {
@Test
fun test() {
val context = InstrumentationRegistry.getInstrumentation().context
val sketch = context.sketch
AssetDataSource(
sketch = sketch,
request = LoadRequest(context, newAssetUri("sample_anim.gif")),
assetFileName = "sample_anim.gif"
).file()
val snapshot = sketch.resultCache[newAssetUri("sample_anim.gif") + "_data_source"]!!
GifInfoHandleHelper(
ByteArrayDataSource(
sketch = sketch,
request = LoadRequest(context, "http://sample.com/sample.gif"),
dataFrom = NETWORK,
data = snapshot.file.readBytes()
)
).apply {
Assert.assertEquals(480, width)
Assert.assertEquals(480, height)
Assert.assertEquals(500, duration)
Assert.assertEquals(5, numberOfFrames)
setOptions(GifOptions().apply {
setInSampleSize(2)
})
Assert.assertEquals(240, width)
Assert.assertEquals(240, height)
Assert.assertNotNull(createGifDrawable().apply { recycle() })
}
GifInfoHandleHelper(
DiskCacheDataSource(
sketch = sketch,
request = LoadRequest(context, newAssetUri("sample_anim.gif")),
dataFrom = LOCAL,
snapshot = snapshot
)
).apply {
Assert.assertEquals(480, width)
Assert.assertEquals(480, height)
Assert.assertEquals(500, duration)
Assert.assertEquals(5, numberOfFrames)
setOptions(GifOptions().apply {
setInSampleSize(2)
})
Assert.assertEquals(240, width)
Assert.assertEquals(240, height)
Assert.assertNotNull(createGifDrawable().apply { recycle() })
}
GifInfoHandleHelper(
ResourceDataSource(
sketch = sketch,
request = LoadRequest(context, newResourceUri(R.drawable.sample_anim)),
packageName = context.packageName,
resources = context.resources,
drawableId = R.drawable.sample_anim
)
).apply {
Assert.assertEquals(480, width)
Assert.assertEquals(480, height)
Assert.assertEquals(500, duration)
Assert.assertEquals(5, numberOfFrames)
setOptions(GifOptions().apply {
setInSampleSize(2)
})
Assert.assertEquals(240, width)
Assert.assertEquals(240, height)
Assert.assertNotNull(createGifDrawable().apply { recycle() })
}
GifInfoHandleHelper(
ContentDataSource(
sketch = sketch,
request = LoadRequest(context, Uri.fromFile(snapshot.file).toString()),
contentUri = Uri.fromFile(snapshot.file),
)
).apply {
Assert.assertEquals(480, width)
Assert.assertEquals(480, height)
Assert.assertEquals(500, duration)
Assert.assertEquals(5, numberOfFrames)
setOptions(GifOptions().apply {
setInSampleSize(2)
})
Assert.assertEquals(240, width)
Assert.assertEquals(240, height)
Assert.assertNotNull(createGifDrawable().apply { recycle() })
}
GifInfoHandleHelper(
FileDataSource(
sketch = sketch,
request = LoadRequest(context, Uri.fromFile(snapshot.file).toString()),
file = snapshot.file,
)
).apply {
Assert.assertEquals(480, width)
Assert.assertEquals(480, height)
Assert.assertEquals(500, duration)
Assert.assertEquals(5, numberOfFrames)
setOptions(GifOptions().apply {
setInSampleSize(2)
})
Assert.assertEquals(240, width)
Assert.assertEquals(240, height)
Assert.assertNotNull(createGifDrawable().apply { recycle() })
}
GifInfoHandleHelper(
AssetDataSource(
sketch = sketch,
request = LoadRequest(context, newAssetUri("sample_anim.gif")),
assetFileName = "sample_anim.gif"
)
).apply {
Assert.assertEquals(480, width)
Assert.assertEquals(480, height)
Assert.assertEquals(500, duration)
Assert.assertEquals(5, numberOfFrames)
setOptions(GifOptions().apply {
setInSampleSize(2)
})
Assert.assertEquals(240, width)
Assert.assertEquals(240, height)
Assert.assertNotNull(createGifDrawable().apply { recycle() })
}
assertThrow(Exception::class) {
GifInfoHandleHelper(
object : UnavailableDataSource {
override val sketch: Sketch
get() = throw UnsupportedOperationException()
override val request: ImageRequest
get() = throw UnsupportedOperationException()
override val dataFrom: DataFrom
get() = throw UnsupportedOperationException()
override fun length(): Long {
throw UnsupportedOperationException()
}
override fun newInputStream(): InputStream {
throw UnsupportedOperationException()
}
}
).apply {
Assert.assertEquals(480, width)
}
}
}
} | apache-2.0 | 6ab29f167ec6c1e05e5bd5255130fe9b | 37.487562 | 92 | 0.609308 | 5.098879 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/feed/suggestededits/SuggestedEditsFeedClient.kt | 1 | 13239 | package org.wikipedia.feed.suggestededits
import android.content.Context
import android.os.Parcelable
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.parcelize.Parcelize
import org.wikipedia.Constants
import org.wikipedia.WikipediaApp
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.mwapi.MwQueryPage
import org.wikipedia.descriptions.DescriptionEditActivity
import org.wikipedia.feed.FeedCoordinator
import org.wikipedia.feed.dataclient.FeedClient
import org.wikipedia.page.Namespace
import org.wikipedia.page.PageTitle
import org.wikipedia.suggestededits.PageSummaryForEdit
import org.wikipedia.suggestededits.provider.EditingSuggestionsProvider
import org.wikipedia.usercontrib.UserContribStats
import org.wikipedia.util.StringUtil
import org.wikipedia.util.log.L
import java.util.*
class SuggestedEditsFeedClient : FeedClient {
fun interface ClientCallback {
fun onComplete(suggestedEditsSummary: SuggestedEditsSummary?, imageTagPage: MwQueryPage?)
}
interface Callback {
fun onReceiveSource(pageSummaryForEdit: PageSummaryForEdit)
fun onReceiveTarget(pageSummaryForEdit: PageSummaryForEdit)
fun onReceiveImageTag(imageTagPage: MwQueryPage)
}
private lateinit var cb: FeedClient.Callback
private var age: Int = 0
private val disposables = CompositeDisposable()
private var appLanguages = WikipediaApp.instance.languageState.appLanguageCodes
override fun request(context: Context, wiki: WikiSite, age: Int, cb: FeedClient.Callback) {
this.age = age
this.cb = cb
if (age == 0) {
// In the background, fetch the user's latest contribution stats, so that we can update whether the
// Suggested Edits feature is paused or disabled, the next time the feed is refreshed.
UserContribStats.updateStatsInBackground()
}
if (UserContribStats.isDisabled() || UserContribStats.maybePauseAndGetEndDate() != null) {
FeedCoordinator.postCardsToCallback(cb, Collections.emptyList())
return
}
// Request three different SE cards
getCardTypeAndData(DescriptionEditActivity.Action.ADD_DESCRIPTION) { descriptionSummary, _ ->
getCardTypeAndData(DescriptionEditActivity.Action.ADD_CAPTION) { captionSummary, _ ->
getCardTypeAndData(DescriptionEditActivity.Action.ADD_IMAGE_TAGS) { _, imageTagsPage ->
FeedCoordinator.postCardsToCallback(cb,
listOf(
SuggestedEditsCard(
listOf(descriptionSummary!!, captionSummary!!),
imageTagsPage,
wiki,
age
)
)
)
cancel()
}
}
}
}
override fun cancel() {
disposables.clear()
}
private fun getCardTypeAndData(cardActionType: DescriptionEditActivity.Action, clientCallback: ClientCallback) {
val suggestedEditsCard = SuggestedEditsSummary(cardActionType)
val langFromCode = appLanguages.first()
val targetLanguage = appLanguages.getOrElse(age % appLanguages.size) { langFromCode }
if (appLanguages.size > 1) {
if (cardActionType == DescriptionEditActivity.Action.ADD_DESCRIPTION && targetLanguage != langFromCode)
suggestedEditsCard.cardActionType = DescriptionEditActivity.Action.TRANSLATE_DESCRIPTION
if (cardActionType == DescriptionEditActivity.Action.ADD_CAPTION && targetLanguage != langFromCode)
suggestedEditsCard.cardActionType = DescriptionEditActivity.Action.TRANSLATE_CAPTION
}
when (suggestedEditsCard.cardActionType) {
DescriptionEditActivity.Action.ADD_DESCRIPTION -> addDescription(langFromCode, actionCallback(suggestedEditsCard, clientCallback))
DescriptionEditActivity.Action.TRANSLATE_DESCRIPTION -> translateDescription(langFromCode, targetLanguage, actionCallback(suggestedEditsCard, clientCallback))
DescriptionEditActivity.Action.ADD_CAPTION -> addCaption(langFromCode, actionCallback(suggestedEditsCard, clientCallback))
DescriptionEditActivity.Action.TRANSLATE_CAPTION -> translateCaption(langFromCode, targetLanguage, actionCallback(suggestedEditsCard, clientCallback))
DescriptionEditActivity.Action.ADD_IMAGE_TAGS -> addImageTags(actionCallback(suggestedEditsCard, clientCallback))
}
}
private fun actionCallback(suggestedEditsCard: SuggestedEditsSummary, clientCallback: ClientCallback): Callback {
return object : Callback {
override fun onReceiveSource(pageSummaryForEdit: PageSummaryForEdit) {
suggestedEditsCard.sourceSummaryForEdit = pageSummaryForEdit
clientCallback.onComplete(suggestedEditsCard, null)
}
override fun onReceiveTarget(pageSummaryForEdit: PageSummaryForEdit) {
suggestedEditsCard.targetSummaryForEdit = pageSummaryForEdit
clientCallback.onComplete(suggestedEditsCard, null)
}
override fun onReceiveImageTag(imageTagPage: MwQueryPage) {
clientCallback.onComplete(null, imageTagPage)
}
}
}
private fun addDescription(langFromCode: String, callback: Callback) {
disposables.add(EditingSuggestionsProvider.getNextArticleWithMissingDescription(WikiSite.forLanguageCode(langFromCode),
SuggestedEditsCardItemFragment.MAX_RETRY_LIMIT)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ pageSummary ->
callback.onReceiveSource(
PageSummaryForEdit(
pageSummary.apiTitle,
langFromCode,
pageSummary.getPageTitle(WikiSite.forLanguageCode(langFromCode)),
pageSummary.displayTitle,
pageSummary.description,
pageSummary.thumbnailUrl,
pageSummary.extract,
pageSummary.extractHtml
)
)
}, {
L.e(it)
cb.error(it)
}))
}
private fun translateDescription(langFromCode: String, targetLanguage: String, callback: Callback) {
disposables.add(
EditingSuggestionsProvider
.getNextArticleWithMissingDescription(WikiSite.forLanguageCode(langFromCode), targetLanguage, true,
SuggestedEditsCardItemFragment.MAX_RETRY_LIMIT
)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ pair ->
val source = pair.first
val target = pair.second
callback.onReceiveSource(
PageSummaryForEdit(
source.apiTitle,
langFromCode,
source.getPageTitle(WikiSite.forLanguageCode(langFromCode)),
source.displayTitle,
source.description,
source.thumbnailUrl,
source.extract,
source.extractHtml
)
)
callback.onReceiveTarget(
PageSummaryForEdit(
target.apiTitle,
targetLanguage,
target.getPageTitle(WikiSite.forLanguageCode(targetLanguage)),
target.displayTitle,
target.description,
target.thumbnailUrl,
target.extract,
target.extractHtml
)
)
}, {
L.e(it)
cb.error(it)
}))
}
private fun addCaption(langFromCode: String, callback: Callback) {
disposables.add(
EditingSuggestionsProvider.getNextImageWithMissingCaption(langFromCode,
SuggestedEditsCardItemFragment.MAX_RETRY_LIMIT
)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap { title ->
ServiceFactory.get(Constants.commonsWikiSite).getImageInfo(title, langFromCode)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
.subscribe({ response ->
val page = response.query?.firstPage()!!
page.imageInfo()?.let {
callback.onReceiveSource(
PageSummaryForEdit(
page.title, langFromCode,
PageTitle(
Namespace.FILE.name,
StringUtil.removeNamespace(page.title),
null,
it.thumbUrl,
WikiSite.forLanguageCode(langFromCode)),
StringUtil.removeHTMLTags(page.title),
it.metadata!!.imageDescription(),
it.thumbUrl,
null,
null,
it.timestamp,
it.user,
it.metadata
)
)
}
}, {
L.e(it)
cb.error(it)
}))
}
private fun translateCaption(langFromCode: String, targetLanguage: String, callback: Callback) {
var fileCaption: String? = null
disposables.add(
EditingSuggestionsProvider.getNextImageWithMissingCaption(langFromCode, targetLanguage,
SuggestedEditsCardItemFragment.MAX_RETRY_LIMIT
)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap { pair ->
fileCaption = pair.first
ServiceFactory.get(Constants.commonsWikiSite).getImageInfo(pair.second, langFromCode)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
.subscribe({ response ->
val page = response.query?.firstPage()!!
page.imageInfo()?.let {
val sourceSummaryForEdit = PageSummaryForEdit(
page.title,
langFromCode,
PageTitle(
Namespace.FILE.name,
StringUtil.removeNamespace(page.title),
null,
it.thumbUrl,
WikiSite.forLanguageCode(langFromCode)
),
StringUtil.removeHTMLTags(page.title),
fileCaption,
it.thumbUrl,
null,
null,
it.timestamp,
it.user,
it.metadata
)
callback.onReceiveSource(sourceSummaryForEdit)
callback.onReceiveTarget(
sourceSummaryForEdit.copy(
description = null,
lang = targetLanguage,
pageTitle = PageTitle(
Namespace.FILE.name,
StringUtil.removeNamespace(page.title),
null,
it.thumbUrl,
WikiSite.forLanguageCode(targetLanguage)
)
)
)
}
}, {
L.e(it)
cb.error(it)
}))
}
private fun addImageTags(callback: Callback) {
disposables.add(
EditingSuggestionsProvider
.getNextImageWithMissingTags(SuggestedEditsCardItemFragment.MAX_RETRY_LIMIT)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ page ->
callback.onReceiveImageTag(page)
}, {
L.e(it)
cb.error(it)
}))
}
@Suppress("unused")
@Parcelize
data class SuggestedEditsSummary(
var cardActionType: DescriptionEditActivity.Action,
var sourceSummaryForEdit: PageSummaryForEdit? = null,
var targetSummaryForEdit: PageSummaryForEdit? = null
) : Parcelable
}
| apache-2.0 | e75942b68c3e5418eacac5dd9fa0f864 | 42.264706 | 170 | 0.567339 | 6.250708 | false | false | false | false |
UnknownJoe796/ponderize | app/src/main/java/com/ivieleague/ponderize/ConfigActivity.kt | 1 | 1620 | package com.ivieleague.ponderize
import android.app.Activity
import android.appwidget.AppWidgetManager
import android.content.Intent
import android.os.Bundle
import com.ivieleague.ponderize.vc.MainVC
import com.lightningkite.kotlincomponents.viewcontroller.containers.VCStack
import com.lightningkite.kotlincomponents.viewcontroller.implementations.VCActivity
import org.jetbrains.anko.defaultSharedPreferences
import java.util.*
class ConfigActivity : VCActivity() {
var appWidgetId: Int = AppWidgetManager.INVALID_APPWIDGET_ID
companion object {
val stacks: HashMap<Int, VCStack> = HashMap()
fun getStack(id: Int): VCStack {
return stacks[id] ?: VCStack().apply {
push(MainVC(this, id))
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
appWidgetId = defaultSharedPreferences.getInt("widget_id", AppWidgetManager.INVALID_APPWIDGET_ID)
appWidgetId = intent?.extras?.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) ?: appWidgetId
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
defaultSharedPreferences.edit().putInt("widget_id", appWidgetId).commit()
}
val stack = getStack(appWidgetId)
stack.onEmptyListener = {
finish()
}
attach(stack)
}
override fun finish() {
val resultValue = Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
setResult(Activity.RESULT_OK, resultValue);
super.finish()
}
}
| mit | dc1727ff7a64b6047cbda78f1fef31ee | 33.468085 | 109 | 0.696914 | 4.778761 | false | false | false | false |
stripe/stripe-android | identity/src/main/java/com/stripe/android/identity/ui/ErrorScreen.kt | 1 | 5136 | package com.stripe.android.identity.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.OutlinedButton
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.google.android.material.composethemeadapter.MdcTheme
import com.stripe.android.identity.R
@Composable
internal fun ErrorScreen(
title: String,
modifier: Modifier = Modifier,
message1: String? = null,
message2: String? = null,
topButton: ErrorScreenButton? = null,
bottomButton: ErrorScreenButton? = null,
) {
MdcTheme {
Column(
modifier = modifier
.fillMaxSize()
.padding(
vertical = dimensionResource(id = R.dimen.page_vertical_margin),
horizontal = dimensionResource(id = R.dimen.page_horizontal_margin)
)
) {
val scrollState = rememberScrollState()
Column(
modifier = Modifier
.weight(1f)
.verticalScroll(scrollState)
) {
Spacer(modifier = Modifier.height(180.dp))
Image(
painter = painterResource(id = R.drawable.ic_exclamation),
modifier = Modifier
.size(92.dp)
.align(Alignment.CenterHorizontally),
contentDescription = stringResource(id = R.string.description_exclamation)
)
Spacer(modifier = Modifier.height(26.dp))
Text(
text = title,
modifier = Modifier
.fillMaxWidth()
.padding(
top = dimensionResource(id = R.dimen.item_vertical_margin),
bottom = 12.dp
)
.testTag(ErrorTitleTag),
fontSize = dimensionResource(id = R.dimen.camera_permission_title_text_size).value.sp,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
message1?.let {
Text(
text = it,
modifier = Modifier
.fillMaxWidth()
.padding(
bottom = dimensionResource(id = R.dimen.item_vertical_margin)
)
.testTag(ErrorMessage1Tag),
textAlign = TextAlign.Center
)
}
message2?.let {
Text(
text = it,
modifier = Modifier
.fillMaxWidth()
.testTag(ErrorMessage2Tag),
textAlign = TextAlign.Center
)
}
}
topButton?.let { (buttonText, onClick) ->
OutlinedButton(
onClick = onClick,
modifier = Modifier
.fillMaxWidth()
.testTag(
ErrorTopButtonTag
)
) {
Text(text = buttonText.uppercase())
}
}
bottomButton?.let { (buttonText, onClick) ->
Button(
onClick = onClick,
modifier = Modifier
.fillMaxWidth()
.testTag(
ErrorBottomButtonTag
)
) {
Text(text = buttonText.uppercase())
}
}
}
}
}
internal data class ErrorScreenButton(
val buttonText: String,
val onButtonClick: () -> Unit
)
internal const val ErrorTitleTag = "ConfirmationTitle"
internal const val ErrorMessage1Tag = "Message1"
internal const val ErrorMessage2Tag = "Message2"
internal const val ErrorTopButtonTag = "TopButton"
internal const val ErrorBottomButtonTag = "BottomButton"
| mit | 064f3b4926d8d65c40a83bec387c61a9 | 36.217391 | 106 | 0.538941 | 5.594771 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/annotator/RsLiteralAnnotatorTest.kt | 3 | 1658 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator
class RsLiteralAnnotatorTest : RsAnnotatorTestBase(RsLiteralAnnotator::class) {
fun `test char literal length`() = checkErrors("""
fn main() {
let ch1 = <error descr="empty char literal">''</error>;
let ch2 = <error descr="too many characters in char literal">'abrakadabra'</error>;
let ch3 = <error descr="too many characters in byte literal">b'abrakadabra'</error>;
let ch4 = 'a';
let ch5 = b'a';
}
""")
fun `test literal suffixes`() = checkErrors("""
fn main() {
let lit1 = <error descr="string literal with a suffix is invalid">"test"u8</error>;
let lit2 = <error descr="char literal with a suffix is invalid">'c'u8</error>;
let lit3 = <error descr="invalid suffix 'u8' for float literal; the suffix must be one of: 'f32', 'f64'">1.2u8</error>;
let lit4 = <error descr="invalid suffix 'f34' for float literal; the suffix must be one of: 'f32', 'f64'">1f34</error>;
let lit4 = <error descr="invalid suffix 'u96' for integer literal; the suffix must be one of: 'u8', 'i8', 'u16', 'i16', 'u32', 'i32', 'u64', 'i64', 'u128', 'i128', 'isize', 'usize'">1u96</error>;
let lit5 = 1e30f64;
}
""")
fun `test literal unclosed quotes`() = checkErrors("""
fn main() {
let ch1 = <error descr="unclosed char literal">'1</error>;
let ch2 = <error descr="unclosed byte literal">b'1</error>;
}
""")
}
| mit | 5a3a52ba85cd05f3c05722c19982d958 | 43.810811 | 207 | 0.584439 | 3.573276 | false | true | false | false |
foreverigor/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/barrierfree/model/BarrierfreeContact.kt | 1 | 795 | package de.tum.`in`.tumcampusapp.component.ui.barrierfree.model
import de.tum.`in`.tumcampusapp.component.other.generic.adapter.SimpleStickyListHeadersAdapter
/**
* The model used to display contact infromation in barrier free page
*/
data class BarrierfreeContact(var name: String = "",
var telephone: String = "",
var email: String = "",
var faculty: String = "",
var tumID: String = "") :
SimpleStickyListHeadersAdapter.SimpleStickyListItem {
val isValid: Boolean
get() = name != ""
val hasTumID: Boolean
get() = !(tumID == "null" || tumID == "")
override fun getHeadName() = faculty
override fun getHeaderId() = faculty
}
| gpl-3.0 | cd38f8eac7530517a0210fed8eab5bde | 30.8 | 94 | 0.579874 | 4.649123 | false | false | false | false |
foreverigor/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/chat/ChatMessagesCardViewHolder.kt | 1 | 1622 | package de.tum.`in`.tumcampusapp.component.ui.chat
import android.view.View
import android.widget.TextView
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.ui.chat.model.ChatMessage
import de.tum.`in`.tumcampusapp.component.ui.overview.card.CardViewHolder
import kotlinx.android.synthetic.main.card_chat_messages.view.*
class ChatMessagesCardViewHolder(itemView: View) : CardViewHolder(itemView) {
fun bind(roomName: String, roomId: Int, roomIdStr: String, unreadMessages: List<ChatMessage>) {
with(itemView) {
chatRoomNameTextView.text = if (unreadMessages.size > 5) {
context.getString(R.string.card_message_title, roomName, unreadMessages.size)
} else {
roomName
}
if (contentContainerLayout.childCount == 0) {
// We have not yet inflated the chat messages
unreadMessages.asSequence()
.map { message ->
val memberName = message.member.displayName
context.getString(R.string.card_message_line, memberName, message.text)
}
.map { messageText ->
TextView(context, null, R.style.CardBody).apply {
text = messageText
}
}
.toList()
.forEach { textView ->
contentContainerLayout.addView(textView)
}
}
}
}
} | gpl-3.0 | 775f5fb26599c0df6888431d7be9ab8b | 39.575 | 99 | 0.545006 | 5.198718 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/skikoMain/kotlin/androidx/compose/ui/platform/OutlineCache.skiko.kt | 3 | 2157 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.platform
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.toSize
/**
* Class for storing outline. Recalculates outline when [size] or [shape] is changed.
* It' s needed so we don't have to recreate it every time we use it for rendering
* (it can be expensive to create outline every frame).
*/
internal class OutlineCache(
density: Density,
size: IntSize,
shape: Shape,
layoutDirection: LayoutDirection
) {
var density = density
set(value) {
if (value != field) {
field = value
outline = createOutline()
}
}
var size = size
set(value) {
if (value != field) {
field = value
outline = createOutline()
}
}
var shape = shape
set(value) {
if (value != field) {
field = value
outline = createOutline()
}
}
var layoutDirection = layoutDirection
set(value) {
if (value != field) {
field = value
outline = createOutline()
}
}
var outline: Outline = createOutline()
private set
private fun createOutline() =
shape.createOutline(size.toSize(), layoutDirection, density)
} | apache-2.0 | 5d2e9638cee173d8ac2ad5a2a157eac5 | 28.162162 | 85 | 0.625406 | 4.541053 | false | false | false | false |
androidx/androidx | navigation/integration-tests/testapp/src/main/java/androidx/navigation/testapp/HelpActivity.kt | 3 | 3821 | /*
* 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.navigation.testapp
import android.os.Build
import android.os.Bundle
import android.transition.Fade
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.graphics.drawable.DrawerArrowDrawable
import androidx.appcompat.widget.Toolbar
import androidx.navigation.ActivityNavigator
import androidx.navigation.NavController
import androidx.navigation.createGraph
import androidx.navigation.ui.setupWithNavController
import androidx.testutils.TestNavigator
import androidx.testutils.test
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.android.material.navigation.NavigationView
/**
* Simple 'Help' activity that shows the data URI passed to it. In a real world app, it would
* load the chosen help article, etc.
*/
class HelpActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_help)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val fade = Fade()
fade.excludeTarget(android.R.id.statusBarBackground, true)
fade.excludeTarget(android.R.id.navigationBarBackground, true)
window.exitTransition = fade
window.enterTransition = fade
}
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
findViewById<TextView>(R.id.data).text = intent.data?.toString()
val bottomToolbar = findViewById<Toolbar>(R.id.bottom_toolbar)
bottomToolbar.navigationIcon = DrawerArrowDrawable(this)
bottomToolbar.setNavigationOnClickListener {
BottomSheetNavigationView().show(supportFragmentManager, "bottom")
}
}
override fun onSupportNavigateUp(): Boolean {
finish()
ActivityNavigator.applyPopAnimationsToPendingTransition(this)
return true
}
@Suppress("DEPRECATION")
override fun onBackPressed() {
super.onBackPressed()
ActivityNavigator.applyPopAnimationsToPendingTransition(this)
}
}
class BottomSheetNavigationView : BottomSheetDialogFragment() {
@Suppress("DEPRECATION")
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val navigationView = requireActivity().layoutInflater
.inflate(R.layout.bottom_bar_menu, container, false) as NavigationView
// Add a fake Navigation Graph just to test out the behavior but not
// actually navigate anywhere
navigationView.setupWithNavController(
NavController(requireContext()).apply {
navigatorProvider.addNavigator(TestNavigator())
graph = createGraph(startDestination = R.id.launcher_home) {
test(R.id.launcher_home)
test(R.id.android)
}
}
)
return navigationView
}
}
| apache-2.0 | 0db0bfc5aab1736b9822ec0ae82cf08b | 35.740385 | 93 | 0.714996 | 4.988251 | false | true | false | false |
androidx/androidx | compose/ui/ui-test-junit4/src/androidAndroidTest/kotlin/androidx/compose/ui/test/junit4/CustomActivityTest.kt | 3 | 2707 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.test.junit4
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.testutils.expectError
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.runAndroidComposeUiTest
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import org.junit.Test
import org.junit.runner.RunWith
class CustomActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
Box {
Button(onClick = {}) {
Text("Hello")
}
}
}
}
}
}
/**
* Tests that we can launch custom activities via [createAndroidComposeRule].
*/
@LargeTest
@RunWith(AndroidJUnit4::class)
@OptIn(ExperimentalTestApi::class)
class CustomActivityTest {
private companion object {
const val ContentAlreadySetError = "androidx\\.compose\\.ui\\.test\\.junit4\\." +
"CustomActivity@[0-9A-Fa-f]* has already set content\\. If you have populated the " +
"Activity with a ComposeView, make sure to call setContent on that ComposeView " +
"instead of on the test rule; and make sure that that call to `setContent \\{\\}` " +
"is done after the ComposeTestRule has run"
}
@Test
fun launchCustomActivity() = runAndroidComposeUiTest<CustomActivity> {
onNodeWithText("Hello").assertExists()
}
@Test
fun setContentOnActivityWithContent() = runAndroidComposeUiTest<CustomActivity> {
expectError<IllegalStateException>(expectedMessage = ContentAlreadySetError) {
setContent { Text("Hello") }
}
}
}
| apache-2.0 | f0d3502c3d65ad36c66b554278c4105c | 33.705128 | 97 | 0.703362 | 4.595925 | false | true | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-core/src/org/jetbrains/kotlin/core/KotlinClasspathContainer.kt | 1 | 3431 | /*******************************************************************************
* 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 org.jetbrains.kotlin.core
import org.eclipse.core.runtime.IPath
import org.eclipse.core.runtime.Path
import org.eclipse.jdt.core.IClasspathContainer
import org.eclipse.jdt.core.IClasspathEntry
import org.eclipse.jdt.core.IJavaProject
import org.eclipse.jdt.core.JavaCore
import org.jetbrains.kotlin.core.model.KotlinJavaManager
import org.jetbrains.kotlin.core.utils.ProjectUtils
import java.util.ArrayList
import kotlin.jvm.JvmStatic
val runtimeContainerId: IPath = Path("org.jetbrains.kotlin.core.KOTLIN_CONTAINER")
fun newExportedLibraryEntry(path: IPath): IClasspathEntry = JavaCore.newLibraryEntry(path, null, null, true)
public class KotlinClasspathContainer(val javaProject: IJavaProject) : IClasspathContainer {
companion object {
val CONTAINER_ENTRY: IClasspathEntry = JavaCore.newContainerEntry(runtimeContainerId)
val LIB_RUNTIME_NAME = "kotlin-stdlib"
val LIB_RUNTIME_SRC_NAME = "kotlin-stdlib-sources"
val LIB_REFLECT_NAME = "kotlin-reflect"
val LIB_SCRIPT_RUNTIME_NAME = "kotlin-script-runtime"
@JvmStatic
public fun getPathToLightClassesFolder(javaProject: IJavaProject): IPath {
return Path(javaProject.getProject().getName()).append(KotlinJavaManager.KOTLIN_BIN_FOLDER).makeAbsolute()
}
}
override public fun getClasspathEntries() : Array<IClasspathEntry> {
val entries = ArrayList<IClasspathEntry>()
val kotlinBinFolderEntry = newExportedLibraryEntry(getPathToLightClassesFolder(javaProject))
entries.add(kotlinBinFolderEntry)
val project = javaProject.getProject()
if (!ProjectUtils.isMavenProject(project) && !ProjectUtils.isGradleProject(project)) {
val kotlinRuntimeEntry = JavaCore.newLibraryEntry(
LIB_RUNTIME_NAME.buildLibPath(),
LIB_RUNTIME_SRC_NAME.buildLibPath(),
null,
true)
val kotlinReflectEntry = newExportedLibraryEntry(LIB_REFLECT_NAME.buildLibPath())
val kotlinScriptRuntime = newExportedLibraryEntry(LIB_SCRIPT_RUNTIME_NAME.buildLibPath())
entries.add(kotlinRuntimeEntry)
entries.add(kotlinReflectEntry)
entries.add(kotlinScriptRuntime)
}
return entries.toTypedArray()
}
override public fun getDescription() : String = "Kotlin Runtime Library"
override public fun getKind() : Int = IClasspathContainer.K_APPLICATION
override public fun getPath() : IPath = runtimeContainerId
}
fun String.buildLibPath(): Path = Path(ProjectUtils.buildLibPath(this)) | apache-2.0 | dac8a6628a622ea6a6417bc04f529fdb | 42.443038 | 118 | 0.681725 | 4.611559 | false | false | false | false |
edsilfer/sticky-index | demo/src/main/java/br/com/stickyindex/sample/presentation/view/ContactsView.kt | 1 | 3105 | package br.com.stickyindex.sample.presentation.view
import android.content.Context
import android.databinding.DataBindingUtil.inflate
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import br.com.stickyindex.sample.R
import br.com.stickyindex.sample.databinding.ContactsViewBinding
import br.com.stickyindex.sample.domain.model.Contact
import br.com.stickyindex.sample.presentation.presenter.ContactsPresenter
import br.com.stickyindex.sample.presentation.view.adapter.ContactsAdapter
import dagger.android.support.AndroidSupportInjection.inject
import kotlinx.android.synthetic.main.contacts_view.*
import javax.inject.Inject
/**
* Displays {@link Contact} information in the shape of an interactive list
*/
class ContactsView : Fragment() {
@Inject
lateinit var presenter: ContactsPresenter
@Inject
lateinit var adapter: ContactsAdapter
/**
* {@inheritDoc}
*/
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = inflate<ContactsViewBinding>(
inflater,
R.layout.contacts_view,
container,
false
)
binding.presenter = presenter
return binding.root
}
/**
* {@inheritDoc}
*/
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
assemblyContactList()
}
/**
* {@inheritDoc}
*/
override fun onAttach(context: Context?) {
inject(this)
super.onAttach(context)
}
private fun assemblyContactList() {
recyclerView.layoutManager = LinearLayoutManager(activity!!.applicationContext)
recyclerView.adapter = adapter
assemblyStickyIndexAndFastScroller()
}
private fun assemblyStickyIndexAndFastScroller() {
stickyIndex.bindRecyclerView(recyclerView)
fastScroller.bindRecyclerView(recyclerView)
}
/**
* Maps the RecyclerView content to a {@link CharArray} to be used as sticky-indexes
*/
private fun convertToIndexList(list: List<Contact>) = list.map { contact -> contact.name.toUpperCase()[0] }
.toCollection(ArrayList())
.toCharArray()
/**
* Load the given contacts in the list
*/
fun loadContacts(contacts: List<Contact>) {
adapter.refresh(contacts)
stickyIndex.refresh(convertToIndexList(contacts))
}
/**
* Scroll the list to the contact with the given name
*/
fun scrollToContact(name: String) {
recyclerView.layoutManager.smoothScrollToPosition(
recyclerView,
null,
adapter.getIndexByContactName(name)
)
}
/**
* Proxys contact click event to presenter
*/
fun onContactClicked() = adapter.addOnClickListener()
}
| apache-2.0 | e697bcba448b2fe84ea58d730b3baeb9 | 28.018692 | 111 | 0.676006 | 4.905213 | false | false | false | false |
takke/DataStats | app/src/main/java/jp/takke/datastats/MainActivity.kt | 1 | 17695 | package jp.takke.datastats
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.RemoteException
import android.provider.Settings
import android.view.Menu
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.CheckBox
import android.widget.ImageButton
import android.widget.SeekBar
import android.widget.Spinner
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceManager
import jp.takke.util.MyLog
import jp.takke.util.TkConfig
class MainActivity : AppCompatActivity() {
private var mPreparingConfigArea = false
private var mServiceIF: ILayerService? = null
private val mServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
MyLog.d("onServiceConnected[$name]")
mServiceIF = ILayerService.Stub.asInterface(service)
}
override fun onServiceDisconnected(name: ComponentName) {
MyLog.d("onServiceDisconnected[$name]")
mServiceIF = null
}
}
private val overlayPermissionLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (OverlayUtil.checkOverlayPermission(this)) {
MyLog.i("MainActivity: overlay permission OK")
// restart service
doStopService()
doRestartService()
} else {
MyLog.i("MainActivity: overlay permission NG")
finish()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MyLog.d("MainActivity.onCreate")
prepareConfigArea()
preparePreviewArea()
// M以降の権限対応
if (!OverlayUtil.checkOverlayPermission(this)) {
requestOverlayPermission()
} else {
doBindService()
}
// 外部ストレージのログファイルを削除する
MyLog.deleteBigExternalLogFile()
}
private fun doBindService() {
val serviceIntent = Intent(this, LayerService::class.java)
// start
MyLog.d("MainActivity: startService of LayerService")
if (Build.VERSION.SDK_INT >= 26) {
startForegroundService(serviceIntent)
} else {
startService(serviceIntent)
}
// bind
MyLog.d("MainActivity: bindService of LayerService")
bindService(serviceIntent, mServiceConnection, Context.BIND_AUTO_CREATE)
}
private fun requestOverlayPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName"))
overlayPermissionLauncher.launch(intent)
}
}
override fun onPause() {
// プレビュー状態の解除
if (mServiceIF != null) {
// restart
try {
mServiceIF!!.restart()
} catch (e: RemoteException) {
MyLog.e(e)
}
}
super.onPause()
}
override fun onDestroy() {
if (mServiceIF != null) {
unbindService(mServiceConnection)
}
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// start
run {
val item = menu.add(R.string.config_start)
item.setOnMenuItemClickListener {
doRestartService()
true
}
}
// stop
run {
val item = menu.add(R.string.config_stop)
item.setOnMenuItemClickListener {
doStopService()
true
}
}
// restart
run {
val item = menu.add(R.string.config_restart)
item.setOnMenuItemClickListener {
doStopService()
doRestartService()
true
}
}
// debug
run {
val item = menu.add(R.string.config_debug_mode)
item.setOnMenuItemClickListener { item1 ->
TkConfig.debugMode = !TkConfig.debugMode
item1.isChecked = TkConfig.debugMode
// save
val pref = PreferenceManager.getDefaultSharedPreferences(this@MainActivity)
val edit = pref.edit()
edit.putBoolean(C.PREF_KEY_DEBUG_MODE, TkConfig.debugMode)
edit.apply()
true
}
item.isCheckable = true
item.setChecked(TkConfig.debugMode)
}
return true
}
private fun doStopService() {
if (mServiceIF != null) {
try {
mServiceIF!!.stop()
} catch (e: RemoteException) {
MyLog.e(e)
}
unbindService(mServiceConnection)
mServiceIF = null
}
}
private fun doRestartService() {
if (mPreparingConfigArea) {
MyLog.d("MainActivity.doRestartService -> cancel (preparing)")
return
}
MyLog.d("MainActivity.doRestartService")
if (mServiceIF != null) {
// restart
try {
mServiceIF!!.restart()
} catch (e: RemoteException) {
MyLog.e(e)
}
} else {
// rebind
doBindService()
}
val kbText = findViewById<TextView>(R.id.preview_kb_text)
kbText.text = "-"
}
@SuppressLint("SetTextI18n")
private fun prepareConfigArea() {
mPreparingConfigArea = true
Config.loadPreferences(this)
// auto start
val autoStartOnBoot = findViewById<CheckBox>(R.id.autoStartOnBoot)
autoStartOnBoot.setOnCheckedChangeListener { _, isChecked ->
val pref = PreferenceManager.getDefaultSharedPreferences(this@MainActivity)
val editor = pref.edit()
editor.putBoolean(C.PREF_KEY_START_ON_BOOT, isChecked)
editor.apply()
}
val pref = PreferenceManager.getDefaultSharedPreferences(this)
val startOnBoot = pref.getBoolean(C.PREF_KEY_START_ON_BOOT, true)
autoStartOnBoot.isChecked = startOnBoot
// hide when in fullscreen
val hideCheckbox = findViewById<CheckBox>(R.id.hideWhenInFullscreen)
hideCheckbox.setOnCheckedChangeListener { _, isChecked ->
val pref1 = PreferenceManager.getDefaultSharedPreferences(this@MainActivity)
val editor = pref1.edit()
editor.putBoolean(C.PREF_KEY_HIDE_WHEN_IN_FULLSCREEN, isChecked)
editor.apply()
}
hideCheckbox.isChecked = Config.hideWhenInFullscreen
// Logarithm bar
val logCheckbox = findViewById<CheckBox>(R.id.logarithmCheckbox)
logCheckbox.setOnCheckedChangeListener { _, isChecked ->
val pref12 = PreferenceManager.getDefaultSharedPreferences(this@MainActivity)
val editor = pref12.edit()
editor.putBoolean(C.PREF_KEY_LOGARITHM_BAR, isChecked)
editor.apply()
// restart
doRestartService()
// 補間モードは logMode on の場合のみ有効
val interpolateCheckBox = findViewById<CheckBox>(R.id.interpolateCheckBox)
interpolateCheckBox.isEnabled = isChecked
}
logCheckbox.isChecked = Config.logBar
// Interpolate mode
val interpolateCheckBox = findViewById<CheckBox>(R.id.interpolateCheckBox)
interpolateCheckBox.setOnCheckedChangeListener { _, isChecked ->
val pref13 = PreferenceManager.getDefaultSharedPreferences(this@MainActivity)
val editor = pref13.edit()
editor.putBoolean(C.PREF_KEY_INTERPOLATE_MODE, isChecked)
editor.apply()
// kill surface
doStopService()
// restart
doRestartService()
}
interpolateCheckBox.isChecked = Config.interpolateMode
// 補間モードは logMode on の場合のみ有効
interpolateCheckBox.isEnabled = Config.logBar
// text size
val plusButton = findViewById<ImageButton>(R.id.plusButton)
plusButton.setOnClickListener {
updateTextSize(true)
}
val minusButton = findViewById<ImageButton>(R.id.minusButton)
minusButton.setOnClickListener {
updateTextSize(false)
}
val textSizeValue = findViewById<TextView>(R.id.text_size_value)
textSizeValue.text = Config.textSizeSp.toString() + "sp"
// pos
val seekBar = findViewById<SeekBar>(R.id.posSeekBar)
seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
val textView = findViewById<TextView>(R.id.pos_text)
textView.text = "$progress%"
val editor = pref.edit()
editor.putInt(C.PREF_KEY_X_POS, progress)
editor.apply()
// restart
doRestartService()
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
})
seekBar.progress = Config.xPos
// Interval Spinner
run {
val adapter = ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item)
val intervals = intArrayOf(500, 1000, 1500, 2000)
for (interval in intervals) {
adapter.add("" + interval / 1000 + "." + interval % 1000 / 100 + "sec")
}
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
val spinner = findViewById<Spinner>(R.id.intervalSpinner)
spinner.adapter = adapter
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
if (mPreparingConfigArea) {
return
}
MyLog.d("onItemSelected: [$position]")
val interval = intervals[position]
val editor = pref.edit()
editor.putInt(C.PREF_KEY_INTERVAL_MSEC, interval)
editor.apply()
// restart
doRestartService()
}
override fun onNothingSelected(parent: AdapterView<*>) {
}
}
val currentIntervalMsec = pref.getInt(C.PREF_KEY_INTERVAL_MSEC, 1000)
for (i in intervals.indices) {
if (currentIntervalMsec == intervals[i]) {
spinner.setSelection(i)
break
}
}
}
// Max Speed[KB] Spinner (Bar)
run {
val adapter = ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item)
val speeds = intArrayOf(10, 50, 100, 500, 1024, 2048, 5120, 10240)
for (s in speeds) {
if (s >= 1024) {
adapter.add("" + s / 1024 + "MB/s")
} else {
adapter.add("" + s + "KB/s")
}
}
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
val spinner = findViewById<Spinner>(R.id.maxSpeedSpinner)
spinner.adapter = adapter
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
if (mPreparingConfigArea) {
return
}
MyLog.d("onItemSelected: [$position]")
val speed = speeds[position]
val editor = pref.edit()
editor.putInt(C.PREF_KEY_BAR_MAX_SPEED_KB, speed)
editor.apply()
// restart
doRestartService()
}
override fun onNothingSelected(parent: AdapterView<*>) {
}
}
val currentSpeed = pref.getInt(C.PREF_KEY_BAR_MAX_SPEED_KB, 10240)
for (i in speeds.indices) {
if (currentSpeed == speeds[i]) {
spinner.setSelection(i)
break
}
}
}
// 通信速度の単位
run {
val adapter = ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item)
adapter.add("KB/s")
adapter.add("Kbps")
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
val spinner = findViewById<Spinner>(R.id.unitTypeSpinner)
spinner.adapter = adapter
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
if (mPreparingConfigArea) {
return
}
MyLog.d("unitTypeSpinner onItemSelected: [$position]")
val unitTypeBps = position == 1
val editor = pref.edit()
editor.putBoolean(C.PREF_KEY_UNIT_TYPE_BPS, unitTypeBps)
editor.apply()
// restart
doRestartService()
}
override fun onNothingSelected(parent: AdapterView<*>) {
}
}
val unitTypeBps = pref.getBoolean(C.PREF_KEY_UNIT_TYPE_BPS, false)
spinner.setSelection(if (unitTypeBps) 1 else 0)
}
mPreparingConfigArea = false
}
@SuppressLint("SetTextI18n")
private fun updateTextSize(isZoomIn: Boolean) {
if (isZoomIn) {
if (Config.textSizeSp >= 24) {
return
}
Config.textSizeSp++
} else {
if (Config.textSizeSp <= 6) {
return
}
Config.textSizeSp--
}
val textSizeValue = findViewById<TextView>(R.id.text_size_value)
textSizeValue.text = Config.textSizeSp.toString() + "sp"
val pref = PreferenceManager.getDefaultSharedPreferences(this@MainActivity)
val editor = pref.edit()
editor.putInt(C.PREF_KEY_TEXT_SIZE_SP, Config.textSizeSp)
editor.apply()
// restart
Config.loadPreferences(this)
MySurfaceView.sForceRedraw = true
startSnapshot(1)
MySurfaceView.sForceRedraw = false
Handler(Looper.getMainLooper()).postDelayed({
MySurfaceView.sForceRedraw = true
startSnapshot(1)
MySurfaceView.sForceRedraw = false
doRestartService()
}, 1)
}
private fun preparePreviewArea() {
val seekBar = findViewById<SeekBar>(R.id.seekBar)
seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
@SuppressLint("SetTextI18n")
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
val kbText = findViewById<TextView>(R.id.preview_kb_text)
kbText.text = "" + progress / 10 + "." + progress % 10 + "KB"
restartWithPreview((progress / 10).toLong(), (progress % 10).toLong())
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
})
val sampleButtonIds = intArrayOf(R.id.sample_1kb_button, R.id.sample_20kb_button, R.id.sample_50kb_button, R.id.sample_80kb_button, R.id.sample_100kb_button)
val samples = intArrayOf(1, 20, 50, 80, 100)
for (i in sampleButtonIds.indices) {
val button = findViewById<Button>(sampleButtonIds[i])
val kb = samples[i]
button.setOnClickListener {
restartWithPreview(kb.toLong(), 0)
}
}
}
@SuppressLint("SetTextI18n")
private fun restartWithPreview(kb: Long, kbd1: Long) {
startSnapshot(kb * 1024 + kbd1 * 100)
val seekBar = findViewById<SeekBar>(R.id.seekBar)
seekBar.progress = (kb * 10 + kbd1).toInt()
val kbText = findViewById<TextView>(R.id.preview_kb_text)
kbText.text = kb.toString() + "." + kbd1 + "KB"
}
private fun startSnapshot(previewBytes: Long) {
if (mServiceIF != null) {
// preview
try {
mServiceIF!!.startSnapshot(previewBytes)
} catch (e: RemoteException) {
MyLog.e(e)
}
}
}
}
| apache-2.0 | 51dc24bf178ae00adc5f775482acd46b | 29.801754 | 165 | 0.570769 | 4.975064 | false | true | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xslt/main/uk/co/reecedunn/intellij/plugin/xslt/lang/ValueTemplate.kt | 1 | 2469 | /*
* Copyright (C) 2020-2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xslt.lang
import com.intellij.lang.Language
import com.intellij.lang.PsiParser
import com.intellij.lexer.Lexer
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.IFileElementType
import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathParserDefinition
import uk.co.reecedunn.intellij.plugin.xslt.lang.fileTypes.XsltSchemaTypeFileType
import uk.co.reecedunn.intellij.plugin.xslt.lexer.XsltValueTemplateLexer
import uk.co.reecedunn.intellij.plugin.xslt.parser.XsltSchemaTypesParser
import uk.co.reecedunn.intellij.plugin.xslt.psi.impl.schema.XsltSchemaTypePsiImpl
import xqt.platform.intellij.xpath.XPath
object ValueTemplate : Language(XPath, "xsl:value-template") {
// region Language
val FileType: LanguageFileType = XsltSchemaTypeFileType(this)
override fun getAssociatedFileType(): LanguageFileType = FileType
// endregion
// region Tokens
val VALUE_CONTENTS: IElementType = IElementType("XSLT_VALUE_CONTENTS_TOKEN", this)
val ESCAPED_CHARACTER: IElementType = IElementType("XSLT_ESCAPED_CHARACTER_TOKEN", this)
// endregion
// region ParserDefinition
val FileElementType: IFileElementType = IFileElementType(this)
class ParserDefinition : XPathParserDefinition() {
override fun createLexer(project: Project): Lexer = XsltValueTemplateLexer()
override fun createParser(project: Project): PsiParser = XsltSchemaTypesParser(ValueTemplate)
override fun getFileNodeType(): IFileElementType = FileElementType
override fun createFile(viewProvider: FileViewProvider): PsiFile = XsltSchemaTypePsiImpl(viewProvider, FileType)
}
// endregion
}
| apache-2.0 | 431bac35aef25758782c9af04720479f | 38.190476 | 120 | 0.782503 | 4.440647 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/GuidelinesActivity.kt | 1 | 2026 | package com.habitrpg.android.habitica.ui.activities
import android.os.Bundle
import android.view.MenuItem
import android.widget.TextView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.common.habitica.helpers.setMarkdown
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
class GuidelinesActivity : BaseActivity() {
override fun getLayoutResId(): Int = R.layout.activity_guidelines
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupToolbar(findViewById(R.id.toolbar))
val client = OkHttpClient()
val request = Request.Builder().url("https://s3.amazonaws.com/habitica-assets/mobileApp/endpoint/community-guidelines.md").build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
ExceptionHandler.reportError(e)
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
val `in` = response.body?.byteStream()
val reader = BufferedReader(InputStreamReader(`in`))
val text = reader.readText()
response.body?.close()
findViewById<TextView>(R.id.text_view).post {
findViewById<TextView>(R.id.text_view).setMarkdown(text)
}
}
})
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return if (item.itemId == android.R.id.home) {
onBackPressed()
true
} else super.onOptionsItemSelected(item)
}
}
| gpl-3.0 | d279731298654995d8a4b84b7a5e9859 | 34.54386 | 138 | 0.679171 | 4.722611 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/existence/CheckExistence.kt | 1 | 4520 | package de.westnordost.streetcomplete.quests.existence
import de.westnordost.osmapi.map.MapDataWithGeometry
import de.westnordost.osmapi.map.data.Element
import de.westnordost.osmfeatures.FeatureDictionary
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression
import de.westnordost.streetcomplete.data.meta.LAST_CHECK_DATE_KEYS
import de.westnordost.streetcomplete.data.meta.SURVEY_MARK_KEY
import de.westnordost.streetcomplete.data.meta.toCheckDateString
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.osmquest.OsmElementQuestType
import de.westnordost.streetcomplete.ktx.arrayOfNotNull
import de.westnordost.streetcomplete.ktx.containsAnyKey
import java.util.*
import java.util.concurrent.FutureTask
class CheckExistence(
private val featureDictionaryFuture: FutureTask<FeatureDictionary>
) : OsmElementQuestType<Unit> {
private val nodesFilter by lazy { """
nodes with ((
(
amenity = atm
or amenity = telephone
or amenity = vending_machine and vending !~ fuel|parking_tickets|public_transport_tickets
or amenity = public_bookcase
or birds_nest = stork
)
and (${lastChecked(2.0)})
) or (
(
amenity = clock
or amenity = bench
or amenity = waste_basket
or amenity = post_box
or amenity = grit_bin
or leisure = picnic_table
or leisure = firepit
or amenity = vending_machine and vending ~ parking_tickets|public_transport_tickets
or tourism = information and information ~ board|terminal|map
or advertising ~ column|board|poster_box
or traffic_calming ~ bump|hump|island|cushion|choker|rumble_strip|chicane|dip
or traffic_calming = table and !highway and !crossing
)
and (${lastChecked(4.0)})
)) and access !~ no|private
""".toElementFilterExpression()
}
// traffic_calming = table is often used as a property of a crossing: we don't want the app
// to delete the crossing if the table is not there anymore, so exclude that
// postboxes are in 4 years category so that postbox collection times is asked instead more often
private val nodesWaysFilter by lazy { """
nodes, ways with (
leisure = pitch and sport = table_tennis
)
and access !~ no|private
and (${lastChecked(4.0)})
""".toElementFilterExpression() }
/* not including bicycle parkings, motorcycle parkings because their capacity is asked every
* few years already, so if it's gone now, it will be noticed that way. */
override val commitMessage = "Check if element still exists"
override val wikiLink: String? = null
override val icon = R.drawable.ic_quest_check
override fun getTitle(tags: Map<String, String>): Int =
if (tags.containsAnyKey("name", "brand", "operator"))
R.string.quest_existence_name_title
else
R.string.quest_existence_title
override fun getTitleArgs(tags: Map<String, String>, featureName: Lazy<String?>): Array<String> {
val name = tags["name"] ?: tags["brand"] ?: tags["operator"]
return arrayOfNotNull(name, featureName.value)
}
override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> =
mapData.filter { isApplicableTo(it) }
override fun isApplicableTo(element: Element) =
(nodesFilter.matches(element) || nodesWaysFilter.matches(element))
&& hasAnyName(element.tags)
override fun createForm() = CheckExistenceForm()
override fun applyAnswerTo(answer: Unit, changes: StringMapChangesBuilder) {
changes.addOrModify(SURVEY_MARK_KEY, Date().toCheckDateString())
val otherCheckDateKeys = LAST_CHECK_DATE_KEYS.filterNot { it == SURVEY_MARK_KEY }
for (otherCheckDateKey in otherCheckDateKeys) {
changes.deleteIfExists(otherCheckDateKey)
}
}
private fun lastChecked(yearsAgo: Double): String = """
older today -$yearsAgo years
or ${LAST_CHECK_DATE_KEYS.joinToString(" or ") { "$it < today -$yearsAgo years" }}
""".trimIndent()
private fun hasAnyName(tags: Map<String, String>?): Boolean =
tags?.let { featureDictionaryFuture.get().byTags(it).find().isNotEmpty() } ?: false
}
| gpl-3.0 | 9e6d243374a7a0da9e634f89f14c8b73 | 42.047619 | 101 | 0.682965 | 4.470821 | false | false | false | false |
dhleong/ideavim | src/com/maddyhome/idea/vim/action/motion/leftright/MotionShiftHomeAction.kt | 1 | 2230 | /*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2019 The IdeaVim authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.maddyhome.idea.vim.action.motion.leftright
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.action.VimCommandAction
import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.command.MappingMode
import com.maddyhome.idea.vim.group.MotionGroup
import com.maddyhome.idea.vim.handler.ShiftedSpecialKeyHandler
import com.maddyhome.idea.vim.handler.VimActionHandler
import com.maddyhome.idea.vim.helper.enumSetOf
import com.maddyhome.idea.vim.helper.vimForEachCaret
import java.util.*
import javax.swing.KeyStroke
/**
* @author Alex Plate
*/
class MotionShiftHomeAction : VimCommandAction() {
override fun makeActionHandler(): VimActionHandler = object : ShiftedSpecialKeyHandler() {
override fun motion(editor: Editor, context: DataContext, cmd: Command) {
editor.vimForEachCaret { caret ->
val newOffset = VimPlugin.getMotion().moveCaretToLineStart(editor, caret)
MotionGroup.moveCaret(editor, caret, newOffset)
}
}
}
override val mappingModes: MutableSet<MappingMode> = MappingMode.NVS
override val keyStrokesSet: Set<List<KeyStroke>> = parseKeysSet("<S-Home>")
override val type: Command.Type = Command.Type.OTHER_READONLY
override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_MOT_EXCLUSIVE)
} | gpl-2.0 | f9fcfc989cd013633b2ffbf950175961 | 38.839286 | 92 | 0.776233 | 4.207547 | false | false | false | false |
GLodi/GitNav | app/src/main/java/giuliolodi/gitnav/ui/forklist/ForkListActivity.kt | 1 | 1828 | /*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.forklist
import android.content.Context
import android.content.Intent
import android.os.Bundle
import giuliolodi.gitnav.R
import giuliolodi.gitnav.ui.base.BaseActivity
/**
* Created by giulio on 19/09/2017.
*/
class ForkListActivity : BaseActivity() {
private val FORK_LIST_FRAGMENT_TAG = "FORK_LIST_FRAGMENT_TAG"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.fork_list_activity)
var forkListFragment: ForkListFragment? = supportFragmentManager.findFragmentByTag(FORK_LIST_FRAGMENT_TAG) as ForkListFragment?
if (forkListFragment == null) {
forkListFragment = ForkListFragment()
supportFragmentManager
.beginTransaction()
.replace(R.id.fork_list_activity_frame, forkListFragment, FORK_LIST_FRAGMENT_TAG)
.commit()
}
}
override fun onBackPressed() {
super.onBackPressed()
overridePendingTransition(0,0)
}
companion object {
fun getIntent(context: Context): Intent {
return Intent(context, ForkListActivity::class.java)
}
}
} | apache-2.0 | d24ef4aa7ef9e3a31cc96ea59171a85d | 31.087719 | 135 | 0.68709 | 4.502463 | false | false | false | false |
MrSugarCaney/DirtyArrows | src/main/kotlin/nl/sugcube/dirtyarrows/util/BukkitExtensions.kt | 1 | 2478 | package nl.sugcube.dirtyarrows.util
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.World
import org.bukkit.configuration.MemorySection
import org.bukkit.entity.Entity
import org.bukkit.entity.HumanEntity
import org.bukkit.entity.Item
import org.bukkit.inventory.ItemStack
import org.bukkit.plugin.java.JavaPlugin
import org.bukkit.util.Vector
import kotlin.reflect.KClass
/**
* Schedules a delayed task.
*
* @param delayTicks
* The amount of ticks to wait before executing the task.
* @param task
* The task to execute.
*/
fun JavaPlugin.scheduleDelayed(delayTicks: Long, task: Runnable) {
Bukkit.getScheduler().scheduleSyncDelayedTask(this, task, delayTicks)
}
/**
* Reads a float from the configuration.
*/
fun MemorySection.getFloat(node: String) = getDouble(node).toFloat()
/**
* Spawns an entity at this location.
*/
fun <T : Entity> Location.spawn(entity: Class<T>): T? = world?.spawn(this, entity)
/**
* Spawns an entity at this location.
*/
fun <T : Entity> Location.spawn(entity: KClass<T>): T? = world?.spawn(this, entity.java)
/**
* Drops the given item on this location.
*/
fun Location.dropItem(item: ItemStack): Item? = world?.dropItem(this, item)
/**
* Creates an explosion at this location.
*/
fun Location.createExplosion(
power: Float,
setFire: Boolean = false,
breakBlocks: Boolean = false
) {
if (breakBlocks.not()) {
world?.createExplosion(x, y, z, power, setFire, breakBlocks)
}
else world?.createExplosion(this, power, setFire)
}
/**
* Makes a copy of this location.
*/
fun Location.copyOf(
world: World? = this.world,
x: Double = this.x,
y: Double = this.y,
z: Double = this.z,
yaw: Float = this.yaw,
pitch: Float = this.pitch
): Location {
return Location(world, x, y, z, yaw, pitch)
}
/**
* Makes a copy of this vector.
*/
fun Vector.copyOf(
x: Number = this.x,
y: Number = this.y,
z: Number = this.z
): Vector {
return Vector(x.toDouble(), y.toDouble(), z.toDouble())
}
/**
* @see org.bukkit.inventory.PlayerInventory.getItemInMainHand
*/
val HumanEntity.itemInMainHand: ItemStack
get() = inventory.itemInMainHand
/**
* @see org.bukkit.inventory.PlayerInventory.getItemInOffHand
*/
val HumanEntity.itemInOffHand: ItemStack
get() = inventory.itemInOffHand
/**
* The display name of the item.
*/
val ItemStack.itemName: String?
get() = itemMeta?.displayName | gpl-3.0 | e465a80493107a8c0438ca39da26b513 | 23.303922 | 88 | 0.686037 | 3.54 | false | false | false | false |
apollostack/apollo-android | apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo3/gradle/internal/DefaultService.kt | 1 | 5291 | package com.apollographql.apollo3.gradle.internal
import com.apollographql.apollo3.compiler.OperationIdGenerator
import com.apollographql.apollo3.compiler.OperationOutputGenerator
import com.apollographql.apollo3.gradle.api.Introspection
import com.apollographql.apollo3.gradle.api.Registry
import com.apollographql.apollo3.gradle.api.Service
import com.apollographql.apollo3.gradle.internal.DefaultApolloExtension.Companion.MIN_GRADLE_VERSION
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.file.Directory
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFile
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.MapProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.provider.SetProperty
import org.gradle.util.GradleVersion
import javax.inject.Inject
abstract class DefaultService @Inject constructor(val objects: ObjectFactory, override val name: String)
: Service {
init {
if (GradleVersion.current().compareTo(GradleVersion.version("6.2")) >= 0) {
// This allows users to call customScalarsMapping.put("Date", "java.util.Date")
// see https://github.com/gradle/gradle/issues/7485
customScalarsMapping.convention(null as Map<String, String>?)
include.convention(null as List<String>?)
exclude.convention(null as List<String>?)
alwaysGenerateTypesMatching.convention(null as Set<String>?)
} else {
customScalarsMapping.set(null as Map<String, String>?)
include.set(null as List<String>?)
exclude.set(null as List<String>?)
alwaysGenerateTypesMatching.set(null as Set<String>?)
}
}
abstract override val sourceFolder: Property<String>
abstract override val exclude: ListProperty<String>
abstract override val include: ListProperty<String>
abstract override val schemaFile: RegularFileProperty
abstract override val debugDir: DirectoryProperty
abstract override val warnOnDeprecatedUsages: Property<Boolean>
abstract override val failOnWarnings: Property<Boolean>
abstract override val customScalarsMapping: MapProperty<String, String>
abstract override val operationIdGenerator: Property<OperationIdGenerator>
abstract override val operationOutputGenerator: Property<OperationOutputGenerator>
abstract override val useSemanticNaming: Property<Boolean>
abstract override val rootPackageName: Property<String>
abstract override val generateAsInternal: Property<Boolean>
abstract override val generateApolloMetadata: Property<Boolean>
abstract override val alwaysGenerateTypesMatching: SetProperty<String>
abstract override val generateFragmentImplementations: Property<Boolean>
abstract override val generateFragmentsAsInterfaces: Property<Boolean>
val graphqlSourceDirectorySet = objects.sourceDirectorySet("graphql", "graphql")
override fun addGraphqlDirectory(directory: Any) {
graphqlSourceDirectorySet.srcDir(directory)
}
var introspection: DefaultIntrospection? = null
override fun introspection(configure: Action<in Introspection>) {
val introspection = objects.newInstance(DefaultIntrospection::class.java)
if (this.introspection != null) {
throw IllegalArgumentException("there must be only one introspection block")
}
configure.execute(introspection)
if (!introspection.endpointUrl.isPresent) {
throw IllegalArgumentException("introspection must have a url")
}
this.introspection = introspection
}
var registry: DefaultRegistry? = null
override fun registry(configure: Action<in Registry>) {
val registry = objects.newInstance(DefaultRegistry::class.java)
if (this.registry != null) {
throw IllegalArgumentException("there must be only one registry block")
}
configure.execute(registry)
if (!registry.graph.isPresent) {
throw IllegalArgumentException("registry must have a graph")
}
if (!registry.key.isPresent) {
throw IllegalArgumentException("registry must have a key")
}
this.registry = registry
}
var operationOutputAction: Action<in Service.OperationOutputWire>? = null
override fun withOperationOutput(action: Action<in Service.OperationOutputWire>) {
this.operationOutputAction = action
}
var outputDirAction: Action<in Service.OutputDirWire>? = null
override fun withOutputDir(action: Action<in Service.OutputDirWire>) {
this.outputDirAction = action
}
fun resolvedSchemaProvider(project: Project): Provider<RegularFile> {
return schemaFile.orElse(project.layout.file(project.provider {
val candidates = graphqlSourceDirectorySet.srcDirs.flatMap { srcDir ->
srcDir.walkTopDown().filter { it.name == "schema.json" || it.name == "schema.sdl" || it.name == "schema.graphqls"}.toList()
}
check(candidates.size <= 1) {
"""
Multiple schemas found:
${candidates.joinToString(separator = "\n")}
Multiple schemas are not supported. You can either define multiple services or specify the schema you want to use explicitely with `schemaFile`
""".trimIndent()
}
candidates.firstOrNull()
}))
}
}
| mit | 2c8a65f655036865da4efaa8751bed1e | 34.039735 | 143 | 0.767341 | 4.690603 | false | false | false | false |
Heiner1/AndroidAPS | automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputWeekDay.kt | 1 | 2660 | package info.nightscout.androidaps.plugins.general.automation.elements
import android.widget.LinearLayout
import androidx.annotation.StringRes
import info.nightscout.androidaps.automation.R
import info.nightscout.androidaps.utils.ui.WeekdayPicker
import java.util.*
class InputWeekDay : Element() {
enum class DayOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
fun toCalendarInt(): Int {
return calendarInts[ordinal]
}
@get:StringRes val shortName: Int
get() = shortNames[ordinal]
companion object {
private val calendarInts = intArrayOf(
Calendar.MONDAY,
Calendar.TUESDAY,
Calendar.WEDNESDAY,
Calendar.THURSDAY,
Calendar.FRIDAY,
Calendar.SATURDAY,
Calendar.SUNDAY
)
private val shortNames = intArrayOf(
R.string.weekday_monday_short,
R.string.weekday_tuesday_short,
R.string.weekday_wednesday_short,
R.string.weekday_thursday_short,
R.string.weekday_friday_short,
R.string.weekday_saturday_short,
R.string.weekday_sunday_short
)
fun fromCalendarInt(day: Int): DayOfWeek {
for (i in calendarInts.indices) {
if (calendarInts[i] == day) return values()[i]
}
throw IllegalStateException("Invalid day")
}
}
}
val weekdays = BooleanArray(DayOfWeek.values().size)
init {
for (day in DayOfWeek.values()) set(day, false)
}
fun setAll(value: Boolean) {
for (day in DayOfWeek.values()) set(day, value)
}
operator fun set(day: DayOfWeek, value: Boolean): InputWeekDay {
weekdays[day.ordinal] = value
return this
}
fun isSet(day: DayOfWeek): Boolean = weekdays[day.ordinal]
fun getSelectedDays(): List<Int> {
val selectedDays: MutableList<Int> = ArrayList()
for (i in weekdays.indices) {
val day = DayOfWeek.values()[i]
val selected = weekdays[i]
if (selected) selectedDays.add(day.toCalendarInt())
}
return selectedDays
}
override fun addToLayout(root: LinearLayout) {
root.addView(
WeekdayPicker(root.context).apply {
setSelectedDays(getSelectedDays())
setOnWeekdaysChangeListener { i: Int, selected: Boolean -> set(DayOfWeek.fromCalendarInt(i), selected) }
}
)
}
}
| agpl-3.0 | 883dd8382f7d496e7a82fbdf134a6218 | 29.930233 | 120 | 0.580451 | 4.767025 | false | false | false | false |
geeteshk/Hyper | app/src/main/java/io/geeteshk/hyper/util/net/NetworkUtils.kt | 1 | 2082 | /*
* Copyright 2016 Geetesh Kalakoti <[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 io.geeteshk.hyper.util.net
import android.util.Log
import eu.bitwalker.useragentutils.UserAgent
import timber.log.Timber
import java.net.Inet4Address
import java.net.InetAddress
import java.net.NetworkInterface
import java.net.SocketException
import java.util.*
object NetworkUtils {
var server: HyperServer? = null
val ipAddress: String?
get() {
try {
val en = NetworkInterface.getNetworkInterfaces()
while (en.hasMoreElements()) {
val intf = en.nextElement() as NetworkInterface
val enumIpAddr = intf.inetAddresses
while (enumIpAddr.hasMoreElements()) {
val inetAddress = enumIpAddr.nextElement() as InetAddress
if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
return inetAddress.getHostAddress()
}
}
}
} catch (e: SocketException) {
Timber.e(e)
}
return null
}
fun parseUA(ua: String): String {
val agent = UserAgent.parseUserAgentString(ua)
return agent.operatingSystem.getName() + " / " + agent.browser.getName() + " " + agent.browserVersion.version
}
fun parseUAList(uaList: LinkedList<String>): LinkedList<String> =
uaList.mapTo(LinkedList()) { parseUA(it) }
}
| apache-2.0 | 30d4cd4e6ea1f77f285b553fba131ff7 | 33.7 | 117 | 0.631124 | 4.565789 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/behavior/Movable.kt | 1 | 1546 | package org.hexworks.zircon.api.behavior
import org.hexworks.cobalt.databinding.api.value.ObservableValue
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Rect
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.internal.behavior.impl.DefaultMovable
import kotlin.jvm.JvmStatic
/**
* A [Movable] is a [Boundable] object which can change its position.
*/
interface Movable : Boundable {
/**
* Observable value that can be used to observe the changes of [rect].
*/
val rectValue: ObservableValue<Rect>
/**
* Sets the position of this [Movable].
* @return `true` if the operation was successful, `false` if not
*/
fun moveTo(position: Position): Boolean
/**
* Moves this [Movable] relative to its current position by the given
* [position]. Eg.: if its current position is (3, 2) and it is moved by
* (-1, 2), its new position will be (2, 4).
*/
fun moveBy(position: Position) = moveTo(this.position + position)
fun moveRightBy(delta: Int) = moveTo(position.withRelativeX(delta))
fun moveLeftBy(delta: Int) = moveTo(position.withRelativeX(-delta))
fun moveUpBy(delta: Int) = moveTo(position.withRelativeY(-delta))
fun moveDownBy(delta: Int) = moveTo(position.withRelativeY(delta))
companion object {
@Suppress("JVM_STATIC_IN_INTERFACE_1_6")
@JvmStatic
fun create(size: Size, position: Position = Position.zero()): Movable =
DefaultMovable(size, position)
}
}
| apache-2.0 | a6897f29b511398817f7b9d9d45cf77f | 31.208333 | 79 | 0.689521 | 3.874687 | false | false | false | false |
Hexworks/zircon | zircon.jvm.swing/src/main/kotlin/org/hexworks/zircon/internal/tileset/transformer/Java2DTextureColorizer.kt | 1 | 1764 | package org.hexworks.zircon.internal.tileset.transformer
import org.hexworks.zircon.api.color.TileColor
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.tileset.TileTexture
import org.hexworks.zircon.api.tileset.transformer.Java2DTextureTransformer
import java.awt.Color
import java.awt.image.BufferedImage
class Java2DTextureColorizer : Java2DTextureTransformer() {
override fun transform(texture: TileTexture<BufferedImage>, tile: Tile): TileTexture<BufferedImage> {
val r = tile.foregroundColor.red.toFloat() / 255
val g = tile.foregroundColor.green.toFloat() / 255
val b = tile.foregroundColor.blue.toFloat() / 255
val backend = texture.texture
(0 until backend.width).forEach { x ->
(0 until backend.height).forEach { y ->
val ax = backend.colorModel.getAlpha(backend.raster.getDataElements(x, y, null))
var rx = backend.colorModel.getRed(backend.raster.getDataElements(x, y, null))
var gx = backend.colorModel.getGreen(backend.raster.getDataElements(x, y, null))
var bx = backend.colorModel.getBlue(backend.raster.getDataElements(x, y, null))
rx = (rx * r).toInt()
gx = (gx * g).toInt()
bx = (bx * b).toInt()
if (ax < 50) {
backend.setRGB(x, y, tile.backgroundColor.toAWTColor().rgb)
} else {
backend.setRGB(x, y, (ax shl 24) or (rx shl 16) or (gx shl 8) or (bx shl 0))
}
}
}
return texture
}
}
/**
* Extension for easy conversion between [TileColor] and awt [Color].
*/
fun TileColor.toAWTColor(): Color = Color(red, green, blue, alpha)
| apache-2.0 | fe7d1dc1947f7a2a34a0f9e97b28e329 | 40.023256 | 105 | 0.628685 | 3.972973 | false | false | false | false |
fengzhizi715/SAF-Kotlin-Utils | saf-kotlin-ext/src/main/java/com/safframework/ext/Number+Extension.kt | 1 | 2263 | package com.safframework.ext
import java.math.BigDecimal
import java.math.RoundingMode
import java.text.DecimalFormat
/**
* @Author zhiqiang
* @Date 2019-06-19
* @Description
*/
/**
* 默认保留小数点后10位
*/
const val DEFAULT_DECIMAL_NUMBER = 2
/**
* 默认分隔符为千分位
*/
const val DEFAULT_SEPARATE_NUMBER = 3
/**
* @param addComma 是否需要添加逗号,默认不加
* @param modeFloor 是否使用去尾法,默认true 1.5->1 2.8->2
* @param decimalNum 小数点后位数
*/
fun Number.formatNumber(
addComma: Boolean = false,
modeFloor: Boolean = true,
decimalNum: Int? = DEFAULT_DECIMAL_NUMBER
): String {
var decimal = decimalNum
if (decimal == null) {
decimal = DEFAULT_DECIMAL_NUMBER
}
val decimalFormat = DecimalFormat()
decimalFormat.maximumFractionDigits = decimal
decimalFormat.groupingSize = if (addComma) DEFAULT_SEPARATE_NUMBER else 0
if (modeFloor) decimalFormat.roundingMode = RoundingMode.FLOOR
return decimalFormat.format(this)
}
/**
* @param addComma 是否需要添加逗号,默认不加
* @param modeFloor 是否使用去尾法,默认true 1.5->1 2.8->2
* @param decimalNum 小数点后位数
*/
fun String.formatNumber(
addComma: Boolean = false, modeFloor: Boolean = true,
decimalNum: Int? = DEFAULT_DECIMAL_NUMBER
): String =
this.toBigDecimalWithNull().formatNumber(addComma, modeFloor, decimalNum)
fun String?.toBigDecimalWithNull(default: BigDecimal = BigDecimal.ZERO) = isNullOrBlank().not().then({
try {
this!!.toBigDecimal()
} catch (e: NumberFormatException) {
default
}
}, default)
fun String?.toIntWithNull(default: Int = 0) = isNullOrBlank().not().then({
try {
this!!.toInt()
} catch (e: NumberFormatException) {
default
}
}, default)
fun String?.toFloatWithNull(default: Float = 0F) = isNullOrBlank().not().then({
try {
this!!.toFloat()
} catch (e: NumberFormatException) {
default
}
}, default)
fun String?.toDoubleWithNull(default: Double = 0.toDouble()) = isNullOrBlank().not().then({
try {
this!!.toDouble()
} catch (e: NumberFormatException) {
default
}
}, default) | apache-2.0 | 87fc1223d912ea454066df63795139d0 | 23.55814 | 102 | 0.660351 | 3.614726 | false | false | false | false |
mdaniel/intellij-community | java/compiler/impl/src/com/intellij/packaging/impl/artifacts/workspacemodel/BridgeUtils.kt | 2 | 6127 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.packaging.impl.artifacts.workspacemodel
import com.intellij.configurationStore.serialize
import com.intellij.openapi.compiler.JavaCompilerBundle
import com.intellij.openapi.module.ProjectLoadingErrorsNotifier
import com.intellij.openapi.project.Project
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.UnknownFeaturesCollector
import com.intellij.openapi.util.JDOMUtil
import com.intellij.packaging.artifacts.ArtifactProperties
import com.intellij.packaging.artifacts.ArtifactPropertiesProvider
import com.intellij.packaging.artifacts.ArtifactType
import com.intellij.packaging.elements.CompositePackagingElement
import com.intellij.packaging.elements.PackagingElement
import com.intellij.packaging.elements.PackagingElementFactory
import com.intellij.packaging.elements.PackagingElementType
import com.intellij.packaging.impl.artifacts.ArtifactLoadingErrorDescription
import com.intellij.packaging.impl.artifacts.workspacemodel.ArtifactManagerBridge.Companion.FEATURE_TYPE
import com.intellij.packaging.impl.artifacts.workspacemodel.ArtifactManagerBridge.Companion.mutableArtifactsMap
import com.intellij.packaging.impl.elements.*
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.VersionedEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.api.*
import org.jetbrains.annotations.Nls
internal fun addBridgesToDiff(newBridges: List<ArtifactBridge>, builder: MutableEntityStorage) {
for (newBridge in newBridges) {
val artifactEntity = builder.resolve(newBridge.artifactId) ?: continue
builder.mutableArtifactsMap.addMapping(artifactEntity, newBridge)
}
}
internal fun createArtifactBridge(it: ArtifactEntity, entityStorage: VersionedEntityStorage, project: Project): ArtifactBridge {
if (ArtifactType.findById(it.artifactType) == null) {
return createInvalidArtifact(it, entityStorage, project, JavaCompilerBundle.message("unknown.artifact.type.0", it.artifactType))
}
fun findMissingArtifactType(element: PackagingElementEntity): String? {
if (element is CustomPackagingElementEntity) {
if (PackagingElementFactory.getInstance().findElementType(element.typeId) == null) {
return element.typeId
}
}
if (element is CompositePackagingElementEntity) {
element.children.forEach { child ->
val artifactType = findMissingArtifactType(child)
if (artifactType != null) return artifactType
}
}
return null
}
val missingArtifactType = findMissingArtifactType(it.rootElement!!)
if (missingArtifactType != null) {
return createInvalidArtifact(it, entityStorage, project, JavaCompilerBundle.message("unknown.element.0", missingArtifactType))
}
val unknownProperty = it.customProperties.firstOrNull { ArtifactPropertiesProvider.findById(it.providerType) == null }
if (unknownProperty != null) {
return createInvalidArtifact(it, entityStorage, project,
JavaCompilerBundle.message("unknown.artifact.properties.0", unknownProperty))
}
return ArtifactBridge(it.persistentId, entityStorage, project, null, null)
}
private fun createInvalidArtifact(it: ArtifactEntity,
entityStorage: VersionedEntityStorage,
project: Project,
@Nls message: String): InvalidArtifactBridge {
val invalidArtifactBridge = InvalidArtifactBridge(it.persistentId, entityStorage, project, null, message)
ProjectLoadingErrorsNotifier.getInstance(project).registerError(ArtifactLoadingErrorDescription(project, invalidArtifactBridge));
UnknownFeaturesCollector.getInstance(project).registerUnknownFeature(FEATURE_TYPE, it.artifactType, JavaCompilerBundle.message("plugins.advertiser.feature.artifact"));
return invalidArtifactBridge
}
fun PackagingElement<*>.forThisAndFullTree(action: (PackagingElement<*>) -> Unit) {
action(this)
if (this is CompositePackagingElement<*>) {
this.children.forEach {
if (it is CompositePackagingElement<*>) {
it.forThisAndFullTree(action)
}
else {
action(it)
}
}
}
}
fun EntityStorage.get(id: ArtifactId): ArtifactEntity = this.resolve(id) ?: error("Cannot find artifact by id: ${id.name}")
internal fun PackagingElementEntity.sameTypeWith(type: PackagingElementType<out PackagingElement<*>>): Boolean {
return when (this) {
is ModuleOutputPackagingElementEntity -> type == ProductionModuleOutputElementType.ELEMENT_TYPE
is ModuleTestOutputPackagingElementEntity -> type == TestModuleOutputElementType.ELEMENT_TYPE
is ModuleSourcePackagingElementEntity -> type == ProductionModuleSourceElementType.ELEMENT_TYPE
is ArtifactOutputPackagingElementEntity -> type == PackagingElementFactoryImpl.ARCHIVE_ELEMENT_TYPE
is ExtractedDirectoryPackagingElementEntity -> type == PackagingElementFactoryImpl.EXTRACTED_DIRECTORY_ELEMENT_TYPE
is FileCopyPackagingElementEntity -> type == PackagingElementFactoryImpl.FILE_COPY_ELEMENT_TYPE
is DirectoryCopyPackagingElementEntity -> type == PackagingElementFactoryImpl.DIRECTORY_COPY_ELEMENT_TYPE
is DirectoryPackagingElementEntity -> type == PackagingElementFactoryImpl.DIRECTORY_ELEMENT_TYPE
is ArchivePackagingElementEntity -> type == PackagingElementFactoryImpl.ARCHIVE_ELEMENT_TYPE
is ArtifactRootElementEntity -> type == PackagingElementFactoryImpl.ARTIFACT_ROOT_ELEMENT_TYPE
is LibraryFilesPackagingElementEntity -> type == LibraryElementType.LIBRARY_ELEMENT_TYPE
is CustomPackagingElementEntity -> this.typeId == type.id
else -> error("Unexpected branch. $this")
}
}
internal fun ArtifactProperties<*>.propertiesTag(): String? {
val state = state
return if (state != null) {
val element = serialize(state) ?: return null
element.name = "options"
JDOMUtil.write(element)
}
else null
}
| apache-2.0 | 41ead8f05e19c2ba389a23e9c5a15a60 | 49.636364 | 169 | 0.784071 | 5.105833 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/challenge/preset/PresetChallengeViewState.kt | 1 | 9234 | package io.ipoli.android.challenge.preset
import io.ipoli.android.challenge.entity.Challenge
import io.ipoli.android.challenge.preset.PresetChallengeViewState.StateType.*
import io.ipoli.android.challenge.usecase.CreateChallengeFromPresetUseCase
import io.ipoli.android.common.AppState
import io.ipoli.android.common.BaseViewStateReducer
import io.ipoli.android.common.DataLoadedAction
import io.ipoli.android.common.datetime.*
import io.ipoli.android.common.redux.Action
import io.ipoli.android.common.redux.BaseViewState
import io.ipoli.android.tag.Tag
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 9/29/18.
*/
sealed class PresetChallengeAction : Action {
data class Load(val challenge: PresetChallenge) : PresetChallengeAction() {
override fun toMap() = mapOf(
"id" to challenge.id,
"name" to challenge.name,
"isPaid" to (challenge.gemPrice > 0),
"gemPrice" to challenge.gemPrice
)
}
data class Accept(
val challenge: PresetChallenge,
val tags: List<Tag>,
val startTime: Time?,
val schedule: PresetChallenge.Schedule,
val physicalCharacteristics: CreateChallengeFromPresetUseCase.PhysicalCharacteristics?
) : PresetChallengeAction() {
override fun toMap() = mapOf(
"id" to challenge.id,
"name" to challenge.name,
"tags" to tags.joinToString(",") { it.name },
"startTime" to startTime,
"isPaid" to (challenge.gemPrice > 0),
"gemPrice" to challenge.gemPrice
)
}
data class ChangeStartTime(val time: Time?) : PresetChallengeAction()
data class AddTag(val tag: Tag) : PresetChallengeAction()
data class RemoveTag(val tag: Tag) : PresetChallengeAction()
data class ToggleSelectedHabit(val habitName: String, val isSelected: Boolean) :
PresetChallengeAction()
object Validate : PresetChallengeAction()
object Unlocked : PresetChallengeAction()
object ChallengeTooExpensive : PresetChallengeAction()
object ChallengeAlreadyAccepted : PresetChallengeAction()
data class Unlock(val challenge: PresetChallenge) : PresetChallengeAction()
data class PhysicalCharacteristicsPicked(
val physicalCharacteristics: CreateChallengeFromPresetUseCase.PhysicalCharacteristics?
) : PresetChallengeAction()
data class Accepted(val challengeId: String) : PresetChallengeAction()
}
object PresetChallengeReducer : BaseViewStateReducer<PresetChallengeViewState>() {
override val stateKey = key<PresetChallengeViewState>()
override fun reduce(
state: AppState,
subState: PresetChallengeViewState,
action: Action
) = when (action) {
is PresetChallengeAction.Load -> {
val c = action.challenge
subState.copy(
type = DATA_CHANGED,
name = c.name,
duration = c.duration,
busynessPerWeek = c.busynessPerWeek.asMinutes,
difficulty = c.difficulty,
level = c.level,
description = c.description,
requirements = c.requirements,
expectedResults = c.expectedResults,
showStartTime = c.config.defaultStartTime != null,
startTime = c.config.defaultStartTime,
schedule = c.schedule,
challenge = c,
showAddTag = true,
challengeTags = emptyList(),
tags = state.dataState.tags,
gemPrice = c.gemPrice,
isUnlocked = c.gemPrice == 0 || state.dataState.player!!.hasChallenge(c),
author = c.author,
participantCount = c.participantCount
)
}
is DataLoadedAction.PlayerChanged -> {
if (subState.challenge != null) {
val challenge = subState.challenge
subState.copy(
type = DATA_CHANGED,
isUnlocked = challenge.gemPrice == 0 || action.player.hasChallenge(challenge)
)
} else {
subState.copy(
type = LOADING
)
}
}
is PresetChallengeAction.ChangeStartTime ->
subState.copy(
type = START_TIME_CHANGED,
startTime = action.time
)
is DataLoadedAction.TagsChanged ->
subState.copy(
type = TAGS_CHANGED,
tags = action.tags
)
is PresetChallengeAction.AddTag -> {
val challengeTags = subState.challengeTags!! + action.tag
subState.copy(
type = TAGS_CHANGED,
showAddTag = challengeTags.size < 3,
challengeTags = challengeTags
)
}
is PresetChallengeAction.RemoveTag -> {
val challengeTags = subState.challengeTags!! - action.tag
subState.copy(
type = TAGS_CHANGED,
showAddTag = challengeTags.size < 3,
challengeTags = challengeTags
)
}
is PresetChallengeAction.Validate -> {
val newType = if (subState.challengeTags!!.isEmpty())
EMPTY_TAGS
else if (subState.schedule!!.quests.isEmpty() && subState.schedule.habits.none { it.isSelected })
EMPTY_SCHEDULE
else if (subState.challenge!!.config.nutritionMacros != null)
SHOW_CHARACTERISTICS_PICKER
else
CHALLENGE_VALID
subState.copy(
type = newType
)
}
is PresetChallengeAction.ToggleSelectedHabit -> {
val schedule = subState.schedule!!
subState.copy(
type = HABITS_CHANGED,
schedule = schedule.copy(
habits = schedule.habits.map {
if (it.name == action.habitName) {
it.copy(
isSelected = action.isSelected
)
} else it
}
)
)
}
is PresetChallengeAction.Unlocked ->
subState.copy(
type = UNLOCKED
)
is PresetChallengeAction.ChallengeTooExpensive ->
subState.copy(
type = TOO_EXPENSIVE
)
is PresetChallengeAction.PhysicalCharacteristicsPicked ->
subState.copy(
type = if (action.physicalCharacteristics == null) CHARACTERISTICS_PICKER_CANCELED else CHALLENGE_VALID,
physicalCharacteristics = action.physicalCharacteristics
)
is PresetChallengeAction.ChallengeAlreadyAccepted ->
subState.copy(
type = ALREADY_ACCEPTED
)
is PresetChallengeAction.Accept ->
subState.copy(
type = LOADING
)
is PresetChallengeAction.Accepted ->
subState.copy(
type = ACCEPTED,
challengeId = action.challengeId
)
else -> subState
}
override fun defaultState() = PresetChallengeViewState(
type = LOADING,
name = "",
duration = 0.days,
busynessPerWeek = 0.minutes,
difficulty = Challenge.Difficulty.EASY,
level = null,
description = "",
requirements = emptyList(),
expectedResults = emptyList(),
showStartTime = null,
startTime = null,
schedule = null,
challenge = null,
showAddTag = null,
challengeTags = emptyList(),
tags = null,
gemPrice = null,
isUnlocked = false,
physicalCharacteristics = null,
challengeId = null,
author = null,
participantCount = 0
)
}
data class PresetChallengeViewState(
val type: StateType,
val name: String,
val duration: Duration<Day>,
val busynessPerWeek: Duration<Minute>,
val difficulty: Challenge.Difficulty,
val level: Int?,
val description: String,
val requirements: List<String>,
val expectedResults: List<String>,
val showStartTime: Boolean?,
val startTime: Time?,
val schedule: PresetChallenge.Schedule?,
val challenge: PresetChallenge?,
val showAddTag: Boolean?,
val challengeTags: List<Tag>?,
val tags: List<Tag>?,
val gemPrice: Int?,
val isUnlocked: Boolean?,
val physicalCharacteristics: CreateChallengeFromPresetUseCase.PhysicalCharacteristics?,
val challengeId: String?,
val author: PresetChallenge.Author?,
val participantCount: Int
) : BaseViewState(
) {
enum class StateType {
LOADING,
DATA_CHANGED,
START_TIME_CHANGED,
TAGS_CHANGED,
CHALLENGE_VALID,
EMPTY_TAGS,
EMPTY_SCHEDULE,
HABITS_CHANGED,
UNLOCKED,
TOO_EXPENSIVE,
SHOW_CHARACTERISTICS_PICKER,
CHARACTERISTICS_PICKER_CANCELED,
ALREADY_ACCEPTED,
ACCEPTED
}
} | gpl-3.0 | 3068e1b5906c61f810c08781c8585332 | 32.33935 | 120 | 0.583279 | 5.237663 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinUMethodWithFakeLightDelegate.kt | 4 | 1444 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.kotlin
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.psi.*
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.psi.UastFakeLightMethod
@ApiStatus.Internal
class KotlinUMethodWithFakeLightDelegate(
val original: KtFunction,
fakePsi: UastFakeLightMethod,
givenParent: UElement?
) : KotlinUMethod(fakePsi, original, givenParent) {
constructor(original: KtFunction, containingLightClass: PsiClass, givenParent: UElement?)
: this(original, UastFakeLightMethod(original, containingLightClass), givenParent)
override val uAnnotations: List<UAnnotation> by lz {
original.annotationEntries.map {
baseResolveProviderService.baseKotlinConverter.convertAnnotation(it, this)
}
}
override fun getTextRange(): TextRange {
return original.textRange
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as KotlinUMethodWithFakeLightDelegate
if (original != other.original) return false
return true
}
override fun hashCode(): Int = original.hashCode()
}
| apache-2.0 | bed22e30c44523362f47c994af263b56 | 34.219512 | 158 | 0.732687 | 4.765677 | false | false | false | false |
GunoH/intellij-community | platform/execution-impl/src/com/intellij/execution/ui/RunContentManagerImpl.kt | 1 | 30984 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplacePutWithAssignment")
package com.intellij.execution.ui
import com.intellij.execution.ExecutionBundle
import com.intellij.execution.Executor
import com.intellij.execution.KillableProcess
import com.intellij.execution.RunnerAndConfigurationSettings
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.execution.dashboard.RunDashboardManager
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.ExecutionUtil
import com.intellij.execution.ui.layout.impl.DockableGridContainerFactory
import com.intellij.ide.plugins.DynamicPluginListener
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.options.advanced.AdvancedSettings
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.ScalableIcon
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.RegisterToolWindowTask
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.openapi.wm.impl.content.SingleContentSupplier
import com.intellij.openapi.wm.impl.content.ToolWindowContentUi
import com.intellij.toolWindow.InternalDecoratorImpl
import com.intellij.ui.AppUIUtil
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.IconManager
import com.intellij.ui.content.*
import com.intellij.ui.content.Content.CLOSE_LISTENER_KEY
import com.intellij.ui.content.impl.ContentManagerImpl
import com.intellij.ui.docking.DockManager
import com.intellij.util.ObjectUtils
import com.intellij.util.SmartList
import com.intellij.util.ui.EmptyIcon
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.ApiStatus
import java.awt.KeyboardFocusManager
import java.util.concurrent.ConcurrentLinkedDeque
import java.util.function.Predicate
import javax.swing.Icon
private val EXECUTOR_KEY: Key<Executor> = Key.create("Executor")
class RunContentManagerImpl(private val project: Project) : RunContentManager {
private val toolWindowIdToBaseIcon: MutableMap<String, Icon> = HashMap()
private val toolWindowIdZBuffer = ConcurrentLinkedDeque<String>()
init {
val containerFactory = DockableGridContainerFactory()
DockManager.getInstance(project).register(DockableGridContainerFactory.TYPE, containerFactory, project)
AppUIExecutor.onUiThread().expireWith(project).submit { init() }
}
companion object {
@JvmField
val ALWAYS_USE_DEFAULT_STOPPING_BEHAVIOUR_KEY = Key.create<Boolean>("ALWAYS_USE_DEFAULT_STOPPING_BEHAVIOUR_KEY")
@ApiStatus.Internal
@JvmField
val TEMPORARY_CONFIGURATION_KEY = Key.create<RunnerAndConfigurationSettings>("TemporaryConfiguration")
@JvmStatic
fun copyContentAndBehavior(descriptor: RunContentDescriptor, contentToReuse: RunContentDescriptor?) {
if (contentToReuse != null) {
val attachedContent = contentToReuse.attachedContent
if (attachedContent != null && attachedContent.isValid) {
descriptor.setAttachedContent(attachedContent)
}
if (contentToReuse.isReuseToolWindowActivation) {
descriptor.isActivateToolWindowWhenAdded = contentToReuse.isActivateToolWindowWhenAdded
}
if (descriptor.processHandler?.getUserData(RunContentDescriptor.CONTENT_TOOL_WINDOW_ID_KEY) == null) {
descriptor.contentToolWindowId = contentToReuse.contentToolWindowId
}
descriptor.isSelectContentWhenAdded = contentToReuse.isSelectContentWhenAdded
}
}
@JvmStatic
fun isTerminated(content: Content): Boolean {
val processHandler = getRunContentDescriptorByContent(content)?.processHandler ?: return true
return processHandler.isProcessTerminated
}
@JvmStatic
fun getRunContentDescriptorByContent(content: Content): RunContentDescriptor? {
return content.getUserData(RunContentDescriptor.DESCRIPTOR_KEY)
}
@JvmStatic
fun getExecutorByContent(content: Content): Executor? = content.getUserData(EXECUTOR_KEY)
@JvmStatic
fun getLiveIndicator(icon: Icon?): Icon = when (ExperimentalUI.isNewUI()) {
true -> IconManager.getInstance().withIconBadge(icon ?: EmptyIcon.ICON_13, JBUI.CurrentTheme.IconBadge.SUCCESS)
else -> ExecutionUtil.getLiveIndicator(icon)
}
}
// must be called on EDT
private fun init() {
val messageBusConnection = project.messageBus.connect()
messageBusConnection.subscribe(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener {
override fun stateChanged(toolWindowManager: ToolWindowManager) {
toolWindowIdZBuffer.retainAll(toolWindowManager.toolWindowIdSet)
val activeToolWindowId = toolWindowManager.activeToolWindowId
if (activeToolWindowId != null && toolWindowIdZBuffer.remove(activeToolWindowId)) {
toolWindowIdZBuffer.addFirst(activeToolWindowId)
}
}
})
messageBusConnection.subscribe(DynamicPluginListener.TOPIC, object : DynamicPluginListener {
override fun beforePluginUnload(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) {
processToolWindowContentManagers { _, contentManager ->
val contents = contentManager.contents
for (content in contents) {
val runContentDescriptor = getRunContentDescriptorByContent(content) ?: continue
if (runContentDescriptor.processHandler?.isProcessTerminated == true) {
contentManager.removeContent(content, true)
}
}
}
}
})
}
@ApiStatus.Internal
fun registerToolWindow(executor: Executor): ContentManager {
val toolWindowManager = getToolWindowManager()
val toolWindowId = executor.toolWindowId
var toolWindow = toolWindowManager.getToolWindow(toolWindowId)
if (toolWindow != null) {
return toolWindow.contentManager
}
toolWindow = toolWindowManager.registerToolWindow(RegisterToolWindowTask(
id = toolWindowId,
icon = executor.toolWindowIcon,
stripeTitle = executor::getActionName
))
toolWindow.setToHideOnEmptyContent(true)
if (DefaultRunExecutor.EXECUTOR_ID == executor.id || Registry.`is`("debugger.new.tool.window.layout.dnd", false)) {
toolWindow.component.putClientProperty(ToolWindowContentUi.ALLOW_DND_FOR_TABS, true)
}
val contentManager = toolWindow.contentManager
contentManager.addDataProvider(object : DataProvider {
override fun getData(dataId: String): Any? {
if (PlatformCoreDataKeys.HELP_ID.`is`(dataId)) {
return executor.helpId
}
return null
}
})
initToolWindow(executor, toolWindowId, executor.toolWindowIcon, contentManager)
return contentManager
}
private fun initToolWindow(executor: Executor?, toolWindowId: String, toolWindowIcon: Icon, contentManager: ContentManager) {
toolWindowIdToBaseIcon.put(toolWindowId, toolWindowIcon)
contentManager.addContentManagerListener(object : ContentManagerListener {
override fun selectionChanged(event: ContentManagerEvent) {
if (event.operation != ContentManagerEvent.ContentOperation.add) {
return
}
val content = event.content
// Content manager contains contents related with different executors.
// Try to get executor from content.
// Must contain this user data since all content is added by this class.
val contentExecutor = executor ?: getExecutorByContent(content)!!
syncPublisher.contentSelected(getRunContentDescriptorByContent(content), contentExecutor)
content.helpId = contentExecutor.helpId
}
})
Disposer.register(contentManager, Disposable {
contentManager.removeAllContents(true)
toolWindowIdZBuffer.remove(toolWindowId)
toolWindowIdToBaseIcon.remove(toolWindowId)
})
toolWindowIdZBuffer.addLast(toolWindowId)
}
private val syncPublisher: RunContentWithExecutorListener
get() = project.messageBus.syncPublisher(RunContentManager.TOPIC)
override fun toFrontRunContent(requestor: Executor, handler: ProcessHandler) {
val descriptor = getDescriptorBy(handler, requestor) ?: return
toFrontRunContent(requestor, descriptor)
}
override fun toFrontRunContent(requestor: Executor, descriptor: RunContentDescriptor) {
ApplicationManager.getApplication().invokeLater(Runnable {
val contentManager = getContentManagerForRunner(requestor, descriptor)
val content = getRunContentByDescriptor(contentManager, descriptor)
if (content != null) {
contentManager.setSelectedContent(content)
getToolWindowManager().getToolWindow(getToolWindowIdForRunner(requestor, descriptor))!!.show(null)
}
}, project.disposed)
}
override fun hideRunContent(executor: Executor, descriptor: RunContentDescriptor) {
ApplicationManager.getApplication().invokeLater(Runnable {
val toolWindow = getToolWindowManager().getToolWindow(getToolWindowIdForRunner(executor, descriptor))
toolWindow?.hide(null)
}, project.disposed)
}
override fun getSelectedContent(): RunContentDescriptor? {
for (activeWindow in toolWindowIdZBuffer) {
val contentManager = getContentManagerByToolWindowId(activeWindow) ?: continue
val selectedContent = contentManager.selectedContent
?: if (contentManager.contentCount == 0) {
// continue to the next window if the content manager is empty
continue
}
else {
// stop iteration over windows because there is some content in the window and the window is the last used one
break
}
// here we have selected content
return getRunContentDescriptorByContent(selectedContent)
}
return null
}
override fun removeRunContent(executor: Executor, descriptor: RunContentDescriptor): Boolean {
val contentManager = getContentManagerForRunner(executor, descriptor)
val content = getRunContentByDescriptor(contentManager, descriptor)
return content != null && contentManager.removeContent(content, true)
}
override fun showRunContent(executor: Executor, descriptor: RunContentDescriptor) {
showRunContent(executor, descriptor, descriptor.executionId)
}
private fun showRunContent(executor: Executor, descriptor: RunContentDescriptor, executionId: Long) {
if (ApplicationManager.getApplication().isUnitTestMode) {
return
}
val contentManager = getContentManagerForRunner(executor, descriptor)
val toolWindowId = getToolWindowIdForRunner(executor, descriptor)
val oldDescriptor = chooseReuseContentForDescriptor(contentManager, descriptor, executionId, descriptor.displayName, getReuseCondition(toolWindowId))
val content: Content?
if (oldDescriptor == null) {
content = createNewContent(descriptor, executor)
}
else {
content = oldDescriptor.attachedContent!!
SingleContentSupplier.removeSubContentsOfContent(content, rightNow = true)
syncPublisher.contentRemoved(oldDescriptor, executor)
Disposer.dispose(oldDescriptor) // is of the same category, can be reused
}
content.executionId = executionId
content.component = descriptor.component
content.setPreferredFocusedComponent(descriptor.preferredFocusComputable)
content.putUserData(RunContentDescriptor.DESCRIPTOR_KEY, descriptor)
content.putUserData(EXECUTOR_KEY, executor)
content.displayName = descriptor.displayName
descriptor.setAttachedContent(content)
val toolWindow = getToolWindowManager().getToolWindow(toolWindowId)
val processHandler = descriptor.processHandler
if (processHandler != null) {
val processAdapter = object : ProcessAdapter() {
override fun startNotified(event: ProcessEvent) {
UIUtil.invokeLaterIfNeeded {
content.icon = getLiveIndicator(descriptor.icon)
var icon = toolWindowIdToBaseIcon[toolWindowId]
if (ExperimentalUI.isNewUI() && icon is ScalableIcon) {
icon = IconLoader.loadCustomVersionOrScale(icon, 20)
}
toolWindow!!.setIcon(getLiveIndicator(icon))
}
}
override fun processTerminated(event: ProcessEvent) {
AppUIUtil.invokeLaterIfProjectAlive(project) {
val manager = getContentManagerByToolWindowId(toolWindowId) ?: return@invokeLaterIfProjectAlive
val alive = isAlive(manager)
setToolWindowIcon(alive, toolWindow!!)
val icon = descriptor.icon
content.icon = if (icon == null) executor.disabledIcon else IconLoader.getTransparentIcon(icon)
}
}
}
processHandler.addProcessListener(processAdapter)
val disposer = content.disposer
if (disposer != null) {
Disposer.register(disposer, Disposable { processHandler.removeProcessListener(processAdapter) })
}
}
addRunnerContentListener(descriptor)
if (oldDescriptor == null) {
contentManager.addContent(content)
content.putUserData(CLOSE_LISTENER_KEY, CloseListener(content, executor))
}
if (descriptor.isSelectContentWhenAdded /* also update selection when reused content is already selected */
|| oldDescriptor != null && content.manager!!.isSelected(content)) {
content.manager!!.setSelectedContent(content)
}
if (!descriptor.isActivateToolWindowWhenAdded) {
return
}
ApplicationManager.getApplication().invokeLater(Runnable {
// let's activate tool window, but don't move focus
//
// window.show() isn't valid here, because it will not
// mark the window as "last activated" windows and thus
// some action like navigation up/down in stacktrace wont
// work correctly
var focus = descriptor.isAutoFocusContent
if (KeyboardFocusManager.getCurrentKeyboardFocusManager().focusOwner == null) {
// This is to cover the case, when the focus was in Run tool window already,
// and it was reset due to us replacing tool window content.
// We're restoring focus in the tool window in this case.
// It shouldn't harm in any case - having no focused component isn't useful at all.
focus = true
}
getToolWindowManager().getToolWindow(toolWindowId)!!.activate(descriptor.activationCallback, focus, focus)
}, project.disposed)
}
private fun getContentManagerByToolWindowId(toolWindowId: String): ContentManager? {
project.serviceIfCreated<RunDashboardManager>()?.let {
if (it.toolWindowId == toolWindowId) {
return if (toolWindowIdToBaseIcon.contains(toolWindowId)) it.dashboardContentManager else null
}
}
return getToolWindowManager().getToolWindow(toolWindowId)?.contentManagerIfCreated
}
private fun addRunnerContentListener(descriptor: RunContentDescriptor) {
val runContentManager = descriptor.runnerLayoutUi?.contentManager
val mainContent = descriptor.attachedContent
if (runContentManager != null && mainContent != null) {
runContentManager.addContentManagerListener(object : ContentManagerListener {
// remove the toolwindow tab that is moved outside via drag and drop
// if corresponding run/debug tab was hidden in debugger layout settings
override fun contentRemoved(event: ContentManagerEvent) {
val toolWindowContentManager = InternalDecoratorImpl.findTopLevelDecorator(mainContent.component)?.contentManager ?: return
val allContents = if (toolWindowContentManager is ContentManagerImpl)
toolWindowContentManager.contentsRecursively else toolWindowContentManager.contents.toList()
val removedContent = event.content
val movedContent = allContents.find { it.displayName == removedContent.displayName }
if (movedContent != null) {
movedContent.manager?.removeContent(movedContent, false)
}
}
})
}
}
override fun getReuseContent(executionEnvironment: ExecutionEnvironment): RunContentDescriptor? {
if (ApplicationManager.getApplication().isUnitTestMode) {
return null
}
val contentToReuse = executionEnvironment.contentToReuse
if (contentToReuse != null) {
return contentToReuse
}
val toolWindowId = getContentDescriptorToolWindowId(executionEnvironment)
val reuseCondition: Predicate<Content>?
val contentManager: ContentManager
if (toolWindowId == null) {
contentManager = getContentManagerForRunner(executionEnvironment.executor, null)
reuseCondition = null
}
else {
contentManager = getOrCreateContentManagerForToolWindow(toolWindowId, executionEnvironment.executor)
reuseCondition = getReuseCondition(toolWindowId)
}
return chooseReuseContentForDescriptor(contentManager, null, executionEnvironment.executionId, executionEnvironment.toString(), reuseCondition)
}
private fun getReuseCondition(toolWindowId: String): Predicate<Content>? {
val runDashboardManager = RunDashboardManager.getInstance(project)
return if (runDashboardManager.toolWindowId == toolWindowId) runDashboardManager.reuseCondition else null
}
override fun findContentDescriptor(requestor: Executor, handler: ProcessHandler): RunContentDescriptor? {
return getDescriptorBy(handler, requestor)
}
override fun showRunContent(info: Executor, descriptor: RunContentDescriptor, contentToReuse: RunContentDescriptor?) {
copyContentAndBehavior(descriptor, contentToReuse)
showRunContent(info, descriptor, descriptor.executionId)
}
private fun getContentManagerForRunner(executor: Executor, descriptor: RunContentDescriptor?): ContentManager {
return descriptor?.attachedContent?.manager ?: getOrCreateContentManagerForToolWindow(getToolWindowIdForRunner(executor, descriptor), executor)
}
private fun getOrCreateContentManagerForToolWindow(id: String, executor: Executor): ContentManager {
val contentManager = getContentManagerByToolWindowId(id)
if (contentManager != null) {
updateToolWindowDecoration(id, executor)
return contentManager
}
val dashboardManager = RunDashboardManager.getInstance(project)
if (dashboardManager.toolWindowId == id) {
initToolWindow(null, dashboardManager.toolWindowId, dashboardManager.toolWindowIcon, dashboardManager.dashboardContentManager)
return dashboardManager.dashboardContentManager
}
else {
return registerToolWindow(executor)
}
}
override fun getToolWindowByDescriptor(descriptor: RunContentDescriptor): ToolWindow? {
descriptor.contentToolWindowId?.let {
return getToolWindowManager().getToolWindow(it)
}
processToolWindowContentManagers { toolWindow, contentManager ->
if (getRunContentByDescriptor(contentManager, descriptor) != null) {
return toolWindow
}
}
return null
}
private fun updateToolWindowDecoration(id: String, executor: Executor) {
if (project.serviceIfCreated<RunDashboardManager>()?.toolWindowId == id) {
return
}
getToolWindowManager().getToolWindow(id)?.apply {
stripeTitle = executor.actionName
setIcon(executor.toolWindowIcon)
toolWindowIdToBaseIcon[id] = executor.toolWindowIcon
}
}
private inline fun processToolWindowContentManagers(processor: (ToolWindow, ContentManager) -> Unit) {
val toolWindowManager = getToolWindowManager()
for (executor in Executor.EXECUTOR_EXTENSION_NAME.extensionList) {
val toolWindow = toolWindowManager.getToolWindow(executor.id) ?: continue
processor(toolWindow, toolWindow.contentManagerIfCreated ?: continue)
}
project.serviceIfCreated<RunDashboardManager>()?.let {
val toolWindowId = it.toolWindowId
if (toolWindowIdToBaseIcon.contains(toolWindowId)) {
processor(toolWindowManager.getToolWindow(toolWindowId) ?: return, it.dashboardContentManager)
}
}
}
override fun getAllDescriptors(): List<RunContentDescriptor> {
val descriptors: MutableList<RunContentDescriptor> = SmartList()
processToolWindowContentManagers { _, contentManager ->
for (content in contentManager.contents) {
getRunContentDescriptorByContent(content)?.let {
descriptors.add(it)
}
}
}
return descriptors
}
override fun selectRunContent(descriptor: RunContentDescriptor) {
processToolWindowContentManagers { _, contentManager ->
val content = getRunContentByDescriptor(contentManager, descriptor) ?: return@processToolWindowContentManagers
contentManager.setSelectedContent(content)
return
}
}
private fun getToolWindowManager() = ToolWindowManager.getInstance(project)
override fun getContentDescriptorToolWindowId(configuration: RunConfiguration?): String? {
if (configuration != null) {
val runDashboardManager = RunDashboardManager.getInstance(project)
if (runDashboardManager.isShowInDashboard(configuration)) {
return runDashboardManager.toolWindowId
}
}
return null
}
override fun getToolWindowIdByEnvironment(executionEnvironment: ExecutionEnvironment): String {
// Also there are some places where ToolWindowId.RUN or ToolWindowId.DEBUG are used directly.
// For example, HotSwapProgressImpl.NOTIFICATION_GROUP. All notifications for this group is shown in Debug tool window,
// however such notifications should be shown in Run Dashboard tool window, if run content is redirected to Run Dashboard tool window.
val toolWindowId = getContentDescriptorToolWindowId(executionEnvironment)
return toolWindowId ?: executionEnvironment.executor.toolWindowId
}
private fun getDescriptorBy(handler: ProcessHandler, runnerInfo: Executor): RunContentDescriptor? {
fun find(manager: ContentManager?): RunContentDescriptor? {
if (manager == null) return null
val contents =
if (manager is ContentManagerImpl) {
manager.contentsRecursively
} else {
manager.contents.toList()
}
for (content in contents) {
val runContentDescriptor = getRunContentDescriptorByContent(content)
if (runContentDescriptor?.processHandler === handler) {
return runContentDescriptor
}
}
return null
}
find(getContentManagerForRunner(runnerInfo, null))?.let {
return it
}
find(getContentManagerByToolWindowId(project.serviceIfCreated<RunDashboardManager>()?.toolWindowId ?: return null) ?: return null)?.let {
return it
}
return null
}
fun moveContent(executor: Executor, descriptor: RunContentDescriptor) {
val content = descriptor.attachedContent ?: return
val oldContentManager = content.manager
val newContentManager = getOrCreateContentManagerForToolWindow(getToolWindowIdForRunner(executor, descriptor), executor)
if (oldContentManager == null || oldContentManager === newContentManager) return
val listener = content.getUserData(CLOSE_LISTENER_KEY)
if (listener != null) {
oldContentManager.removeContentManagerListener(listener)
}
oldContentManager.removeContent(content, false)
if (isAlive(descriptor)) {
if (!isAlive(oldContentManager)) {
updateToolWindowIcon(oldContentManager, false)
}
if (!isAlive(newContentManager)) {
updateToolWindowIcon(newContentManager, true)
}
}
newContentManager.addContent(content)
// Close listener is added to new content manager by propertyChangeListener in BaseContentCloseListener.
}
private fun updateToolWindowIcon(contentManagerToUpdate: ContentManager, alive: Boolean) {
processToolWindowContentManagers { toolWindow, contentManager ->
if (contentManagerToUpdate == contentManager) {
setToolWindowIcon(alive, toolWindow)
return
}
}
}
private fun setToolWindowIcon(alive: Boolean, toolWindow: ToolWindow) {
val base = toolWindowIdToBaseIcon.get(toolWindow.id)
toolWindow.setIcon(if (alive) getLiveIndicator(base) else ObjectUtils.notNull(base, EmptyIcon.ICON_13))
}
private inner class CloseListener(content: Content, private val myExecutor: Executor) : BaseContentCloseListener(content, project) {
override fun disposeContent(content: Content) {
try {
val descriptor = getRunContentDescriptorByContent(content)
syncPublisher.contentRemoved(descriptor, myExecutor)
if (descriptor != null) {
Disposer.dispose(descriptor)
}
}
finally {
content.release()
}
}
override fun closeQuery(content: Content, projectClosing: Boolean): Boolean {
val descriptor = getRunContentDescriptorByContent(content) ?: return true
if (Content.TEMPORARY_REMOVED_KEY.get(content, false)) return true
val processHandler = descriptor.processHandler
if (processHandler == null || processHandler.isProcessTerminated) {
return true
}
val sessionName = descriptor.displayName
val killable = processHandler is KillableProcess && (processHandler as KillableProcess).canKillProcess()
val task = object : WaitForProcessTask(processHandler, sessionName, projectClosing, project) {
override fun onCancel() {
if (killable && !processHandler.isProcessTerminated) {
(processHandler as KillableProcess).killProcess()
}
}
}
if (killable) {
val cancelText = ExecutionBundle.message("terminating.process.progress.kill")
task.cancelText = cancelText
task.cancelTooltipText = cancelText
}
return askUserAndWait(processHandler, sessionName, task)
}
}
}
private fun chooseReuseContentForDescriptor(contentManager: ContentManager,
descriptor: RunContentDescriptor?,
executionId: Long,
preferredName: String?,
reuseCondition: Predicate<in Content>?): RunContentDescriptor? {
var content: Content? = null
if (descriptor != null) {
//Stage one: some specific descriptors (like AnalyzeStacktrace) cannot be reused at all
if (descriptor.isContentReuseProhibited) {
return null
}
// stage two: try to get content from descriptor itself
val attachedContent = descriptor.attachedContent
if (attachedContent != null && attachedContent.isValid
&& (descriptor.displayName == attachedContent.displayName || !attachedContent.isPinned)) {
val contents =
if (contentManager is ContentManagerImpl) {
contentManager.contentsRecursively
} else {
contentManager.contents.toList()
}
if (contents.contains(attachedContent)) {
content = attachedContent
}
}
}
// stage three: choose the content with name we prefer
if (content == null) {
content = getContentFromManager(contentManager, preferredName, executionId, reuseCondition)
}
if (content == null || !RunContentManagerImpl.isTerminated(content) || content.executionId == executionId && executionId != 0L) {
return null
}
val oldDescriptor = RunContentManagerImpl.getRunContentDescriptorByContent(content) ?: return null
if (oldDescriptor.isContentReuseProhibited) {
return null
}
if (descriptor == null || oldDescriptor.reusePolicy.canBeReusedBy(descriptor)) {
return oldDescriptor
}
return null
}
private fun getContentFromManager(contentManager: ContentManager,
preferredName: String?,
executionId: Long,
reuseCondition: Predicate<in Content>?): Content? {
val contents =
if (contentManager is ContentManagerImpl) {
contentManager.contentsRecursively
} else {
contentManager.contents.toMutableList()
}
val first = contentManager.selectedContent
if (first != null && contents.remove(first)) {
//selected content should be checked first
contents.add(0, first)
}
if (preferredName != null) {
// try to match content with specified preferred name
for (c in contents) {
if (canReuseContent(c, executionId) && preferredName == c.displayName) {
return c
}
}
}
// return first "good" content
return contents.firstOrNull {
canReuseContent(it, executionId) && (reuseCondition == null || reuseCondition.test(it))
}
}
private fun canReuseContent(c: Content, executionId: Long): Boolean {
return !c.isPinned && RunContentManagerImpl.isTerminated(c) && !(c.executionId == executionId && executionId != 0L)
}
private fun getToolWindowIdForRunner(executor: Executor, descriptor: RunContentDescriptor?): String {
return descriptor?.contentToolWindowId ?: executor.toolWindowId
}
private fun createNewContent(descriptor: RunContentDescriptor, executor: Executor): Content {
val content = ContentFactory.getInstance().createContent(descriptor.component, descriptor.displayName, true)
content.putUserData(ToolWindow.SHOW_CONTENT_ICON, java.lang.Boolean.TRUE)
if (AdvancedSettings.getBoolean("start.run.configurations.pinned")) content.isPinned = true
content.icon = descriptor.icon ?: executor.toolWindowIcon
return content
}
private fun getRunContentByDescriptor(contentManager: ContentManager, descriptor: RunContentDescriptor): Content? {
return contentManager.contents.firstOrNull {
descriptor == RunContentManagerImpl.getRunContentDescriptorByContent(it)
}
}
private fun isAlive(contentManager: ContentManager): Boolean {
return contentManager.contents.any {
val descriptor = RunContentManagerImpl.getRunContentDescriptorByContent(it)
descriptor != null && isAlive(descriptor)
}
}
private fun isAlive(descriptor: RunContentDescriptor): Boolean {
val handler = descriptor.processHandler
return handler != null && !handler.isProcessTerminated
} | apache-2.0 | 61d03aa0d43d95878ef3b3e252c66efe | 41.737931 | 153 | 0.733895 | 5.320969 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/notifications/profiles/EditNotificationProfileFragment.kt | 1 | 8340 | package org.thoughtcrime.securesms.components.settings.app.notifications.profiles
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.dd.CircularProgressButton
import com.google.android.material.textfield.TextInputLayout
import io.reactivex.rxjava3.kotlin.subscribeBy
import org.signal.core.util.BreakIteratorCompat
import org.signal.core.util.EditTextUtil
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.emoji.EmojiUtil
import org.thoughtcrime.securesms.components.settings.DSLSettingsAdapter
import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment
import org.thoughtcrime.securesms.components.settings.app.notifications.profiles.EditNotificationProfileViewModel.SaveNotificationProfileResult
import org.thoughtcrime.securesms.components.settings.app.notifications.profiles.models.NotificationProfileNamePreset
import org.thoughtcrime.securesms.reactions.any.ReactWithAnyEmojiBottomSheetDialogFragment
import org.thoughtcrime.securesms.util.BottomSheetUtil
import org.thoughtcrime.securesms.util.CircularProgressButtonUtil
import org.thoughtcrime.securesms.util.LifecycleDisposable
import org.thoughtcrime.securesms.util.ViewUtil
import org.thoughtcrime.securesms.util.navigation.safeNavigate
import org.thoughtcrime.securesms.util.text.AfterTextChanged
/**
* Dual use Edit/Create notification profile fragment. Use to create in the create profile flow,
* and then to edit from profile details. Responsible for naming and emoji.
*/
class EditNotificationProfileFragment : DSLSettingsFragment(layoutId = R.layout.fragment_edit_notification_profile), ReactWithAnyEmojiBottomSheetDialogFragment.Callback {
private val viewModel: EditNotificationProfileViewModel by viewModels(factoryProducer = this::createFactory)
private val lifecycleDisposable = LifecycleDisposable()
private var emojiView: ImageView? = null
private var nameView: EditText? = null
private fun createFactory(): ViewModelProvider.Factory {
val profileId = EditNotificationProfileFragmentArgs.fromBundle(requireArguments()).profileId
return EditNotificationProfileViewModel.Factory(profileId)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val toolbar: Toolbar = view.findViewById(R.id.toolbar)
toolbar.setNavigationOnClickListener {
ViewUtil.hideKeyboard(requireContext(), requireView())
requireActivity().onBackPressed()
}
val title: TextView = view.findViewById(R.id.edit_notification_profile_title)
val countView: TextView = view.findViewById(R.id.edit_notification_profile_count)
val saveButton: CircularProgressButton = view.findViewById(R.id.edit_notification_profile_save)
val emojiView: ImageView = view.findViewById(R.id.edit_notification_profile_emoji)
val nameView: EditText = view.findViewById(R.id.edit_notification_profile_name)
val nameTextWrapper: TextInputLayout = view.findViewById(R.id.edit_notification_profile_name_wrapper)
EditTextUtil.addGraphemeClusterLimitFilter(nameView, NOTIFICATION_PROFILE_NAME_MAX_GLYPHS)
nameView.addTextChangedListener(
AfterTextChanged { editable: Editable ->
presentCount(countView, editable.toString())
nameTextWrapper.error = null
}
)
emojiView.setOnClickListener {
ReactWithAnyEmojiBottomSheetDialogFragment.createForAboutSelection()
.show(childFragmentManager, BottomSheetUtil.STANDARD_BOTTOM_SHEET_FRAGMENT_TAG)
}
view.findViewById<View>(R.id.edit_notification_profile_clear).setOnClickListener {
nameView.setText("")
onEmojiSelectedInternal("")
}
lifecycleDisposable.bindTo(viewLifecycleOwner.lifecycle)
saveButton.setOnClickListener {
if (TextUtils.isEmpty(nameView.text)) {
nameTextWrapper.error = getString(R.string.EditNotificationProfileFragment__profile_must_have_a_name)
return@setOnClickListener
}
lifecycleDisposable += viewModel.save(nameView.text.toString())
.doOnSubscribe { CircularProgressButtonUtil.setSpinning(saveButton) }
.doAfterTerminate { CircularProgressButtonUtil.cancelSpinning(saveButton) }
.subscribeBy(
onSuccess = { saveResult ->
when (saveResult) {
is SaveNotificationProfileResult.Success -> {
ViewUtil.hideKeyboard(requireContext(), nameView)
if (saveResult.createMode) {
findNavController().safeNavigate(EditNotificationProfileFragmentDirections.actionEditNotificationProfileFragmentToAddAllowedMembersFragment(saveResult.profile.id))
} else {
findNavController().navigateUp()
}
}
SaveNotificationProfileResult.DuplicateNameFailure -> {
nameTextWrapper.error = getString(R.string.EditNotificationProfileFragment__a_profile_with_this_name_already_exists)
}
}
}
)
}
lifecycleDisposable += viewModel.getInitialState()
.subscribeBy(
onSuccess = { initial ->
if (initial.createMode) {
saveButton.text = getString(R.string.EditNotificationProfileFragment__create)
title.setText(R.string.EditNotificationProfileFragment__name_your_profile)
} else {
saveButton.text = getString(R.string.EditNotificationProfileFragment__save)
title.setText(R.string.EditNotificationProfileFragment__edit_this_profile)
}
nameView.setText(initial.name)
onEmojiSelectedInternal(initial.emoji)
ViewUtil.focusAndMoveCursorToEndAndOpenKeyboard(nameView)
}
)
this.nameView = nameView
this.emojiView = emojiView
}
override fun bindAdapter(adapter: DSLSettingsAdapter) {
NotificationProfileNamePreset.register(adapter)
val onClick = { preset: NotificationProfileNamePreset.Model ->
nameView?.apply {
setText(preset.bodyResource)
setSelection(length(), length())
}
onEmojiSelectedInternal(preset.emoji)
}
adapter.submitList(
listOf(
NotificationProfileNamePreset.Model("\uD83D\uDCAA", R.string.EditNotificationProfileFragment__work, onClick),
NotificationProfileNamePreset.Model("\uD83D\uDE34", R.string.EditNotificationProfileFragment__sleep, onClick),
NotificationProfileNamePreset.Model("\uD83D\uDE97", R.string.EditNotificationProfileFragment__driving, onClick),
NotificationProfileNamePreset.Model("\uD83D\uDE0A", R.string.EditNotificationProfileFragment__downtime, onClick),
NotificationProfileNamePreset.Model("\uD83D\uDCA1", R.string.EditNotificationProfileFragment__focus, onClick),
)
)
}
override fun onReactWithAnyEmojiSelected(emoji: String) {
onEmojiSelectedInternal(emoji)
}
override fun onReactWithAnyEmojiDialogDismissed() = Unit
private fun presentCount(countView: TextView, profileName: String) {
val breakIterator = BreakIteratorCompat.getInstance()
breakIterator.setText(profileName)
val glyphCount = breakIterator.countBreaks()
if (glyphCount >= NOTIFICATION_PROFILE_NAME_LIMIT_DISPLAY_THRESHOLD) {
countView.visibility = View.VISIBLE
countView.text = resources.getString(R.string.EditNotificationProfileFragment__count, glyphCount, NOTIFICATION_PROFILE_NAME_MAX_GLYPHS)
} else {
countView.visibility = View.GONE
}
}
private fun onEmojiSelectedInternal(emoji: String) {
val drawable = EmojiUtil.convertToDrawable(requireContext(), emoji)
if (drawable != null) {
emojiView?.setImageDrawable(drawable)
viewModel.onEmojiSelected(emoji)
} else {
emojiView?.setImageResource(R.drawable.ic_add_emoji)
viewModel.onEmojiSelected("")
}
}
companion object {
private const val NOTIFICATION_PROFILE_NAME_MAX_GLYPHS = 32
private const val NOTIFICATION_PROFILE_NAME_LIMIT_DISPLAY_THRESHOLD = 22
}
}
| gpl-3.0 | b988146a08633241b63e8351cf977355 | 42.664921 | 181 | 0.757674 | 4.888628 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/HttpTimeout.kt | 1 | 10599 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.plugins
import io.ktor.client.*
import io.ktor.client.engine.*
import io.ktor.client.network.sockets.*
import io.ktor.client.request.*
import io.ktor.client.utils.*
import io.ktor.http.*
import io.ktor.util.*
import io.ktor.utils.io.errors.*
import kotlinx.coroutines.*
/**
* A plugin that allows you to configure the following timeouts:
* - __request timeout__ — a time period required to process an HTTP call: from sending a request to receiving a response.
* - __connection timeout__ — a time period in which a client should establish a connection with a server.
* - __socket timeout__ — a maximum time of inactivity between two data packets when exchanging data with a server.
*
* You can learn more from [Timeout](https://ktor.io/docs/timeout.html).
*/
public class HttpTimeout private constructor(
private val requestTimeoutMillis: Long?,
private val connectTimeoutMillis: Long?,
private val socketTimeoutMillis: Long?
) {
/**
* An [HttpTimeout] extension configuration that is used during installation.
*/
@KtorDsl
public class HttpTimeoutCapabilityConfiguration {
private var _requestTimeoutMillis: Long? = 0
private var _connectTimeoutMillis: Long? = 0
private var _socketTimeoutMillis: Long? = 0
/**
* Creates a new instance of [HttpTimeoutCapabilityConfiguration].
*/
public constructor(
requestTimeoutMillis: Long? = null,
connectTimeoutMillis: Long? = null,
socketTimeoutMillis: Long? = null
) {
this.requestTimeoutMillis = requestTimeoutMillis
this.connectTimeoutMillis = connectTimeoutMillis
this.socketTimeoutMillis = socketTimeoutMillis
}
/**
* Specifies a request timeout in milliseconds.
* The request timeout is the time period required to process an HTTP call: from sending a request to receiving a response.
*/
public var requestTimeoutMillis: Long?
get() = _requestTimeoutMillis
set(value) {
_requestTimeoutMillis = checkTimeoutValue(value)
}
/**
* Specifies a connection timeout in milliseconds.
* The connection timeout is the time period in which a client should establish a connection with a server.
*/
public var connectTimeoutMillis: Long?
get() = _connectTimeoutMillis
set(value) {
_connectTimeoutMillis = checkTimeoutValue(value)
}
/**
* Specifies a socket timeout (read and write) in milliseconds.
* The socket timeout is the maximum time of inactivity between two data packets when exchanging data with a server.
*/
public var socketTimeoutMillis: Long?
get() = _socketTimeoutMillis
set(value) {
_socketTimeoutMillis = checkTimeoutValue(value)
}
internal fun build(): HttpTimeout = HttpTimeout(requestTimeoutMillis, connectTimeoutMillis, socketTimeoutMillis)
private fun checkTimeoutValue(value: Long?): Long? {
require(value == null || value > 0) {
"Only positive timeout values are allowed, for infinite timeout use HttpTimeout.INFINITE_TIMEOUT_MS"
}
return value
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as HttpTimeoutCapabilityConfiguration
if (_requestTimeoutMillis != other._requestTimeoutMillis) return false
if (_connectTimeoutMillis != other._connectTimeoutMillis) return false
if (_socketTimeoutMillis != other._socketTimeoutMillis) return false
return true
}
override fun hashCode(): Int {
var result = _requestTimeoutMillis?.hashCode() ?: 0
result = 31 * result + (_connectTimeoutMillis?.hashCode() ?: 0)
result = 31 * result + (_socketTimeoutMillis?.hashCode() ?: 0)
return result
}
public companion object {
public val key: AttributeKey<HttpTimeoutCapabilityConfiguration> = AttributeKey("TimeoutConfiguration")
}
}
/**
* Utils method that return `true` if at least one timeout is configured (has not null value).
*/
private fun hasNotNullTimeouts() =
requestTimeoutMillis != null || connectTimeoutMillis != null || socketTimeoutMillis != null
/**
* A companion object for a plugin installation.
*/
public companion object Plugin :
HttpClientPlugin<HttpTimeoutCapabilityConfiguration, HttpTimeout>,
HttpClientEngineCapability<HttpTimeoutCapabilityConfiguration> {
override val key: AttributeKey<HttpTimeout> = AttributeKey("TimeoutPlugin")
/**
* An infinite timeout in milliseconds.
*/
public const val INFINITE_TIMEOUT_MS: Long = Long.MAX_VALUE
override fun prepare(block: HttpTimeoutCapabilityConfiguration.() -> Unit): HttpTimeout =
HttpTimeoutCapabilityConfiguration().apply(block).build()
@OptIn(InternalAPI::class)
override fun install(plugin: HttpTimeout, scope: HttpClient) {
scope.plugin(HttpSend).intercept { request ->
val isWebSocket = request.url.protocol.isWebsocket()
if (isWebSocket || request.body is ClientUpgradeContent) return@intercept execute(request)
var configuration = request.getCapabilityOrNull(HttpTimeout)
if (configuration == null && plugin.hasNotNullTimeouts()) {
configuration = HttpTimeoutCapabilityConfiguration()
request.setCapability(HttpTimeout, configuration)
}
configuration?.apply {
connectTimeoutMillis = connectTimeoutMillis ?: plugin.connectTimeoutMillis
socketTimeoutMillis = socketTimeoutMillis ?: plugin.socketTimeoutMillis
requestTimeoutMillis = requestTimeoutMillis ?: plugin.requestTimeoutMillis
val requestTimeout = requestTimeoutMillis ?: plugin.requestTimeoutMillis
if (requestTimeout == null || requestTimeout == INFINITE_TIMEOUT_MS) return@apply
val executionContext = request.executionContext
val killer = scope.launch {
delay(requestTimeout)
val cause = HttpRequestTimeoutException(request)
executionContext.cancel(cause.message!!, cause)
}
request.executionContext.invokeOnCompletion {
killer.cancel()
}
}
execute(request)
}
}
}
}
/**
* Adds timeout boundaries to the request. Requires the [HttpTimeout] plugin to be installed.
*/
public fun HttpRequestBuilder.timeout(block: HttpTimeout.HttpTimeoutCapabilityConfiguration.() -> Unit): Unit =
setCapability(HttpTimeout, HttpTimeout.HttpTimeoutCapabilityConfiguration().apply(block))
/**
* This exception is thrown in case the request timeout is exceeded.
* The request timeout is the time period required to process an HTTP call: from sending a request to receiving a response.
*/
public class HttpRequestTimeoutException(
url: String,
timeoutMillis: Long?
) : IOException("Request timeout has expired [url=$url, request_timeout=${timeoutMillis ?: "unknown"} ms]") {
public constructor(request: HttpRequestBuilder) : this(
request.url.buildString(),
request.getCapabilityOrNull(HttpTimeout)?.requestTimeoutMillis
)
public constructor(request: HttpRequestData) : this(
request.url.toString(),
request.getCapabilityOrNull(HttpTimeout)?.requestTimeoutMillis
)
}
/**
* This exception is thrown in case the connection timeout is exceeded.
* It indicates the client took too long to establish a connection with a server.
*/
public fun ConnectTimeoutException(
request: HttpRequestData,
cause: Throwable? = null
): ConnectTimeoutException = ConnectTimeoutException(
"Connect timeout has expired [url=${request.url}, " +
"connect_timeout=${request.getCapabilityOrNull(HttpTimeout)?.connectTimeoutMillis ?: "unknown"} ms]",
cause
)
/**
* This exception is thrown in case the connection timeout is exceeded.
* It indicates the client took too long to establish a connection with a server.
*/
public fun ConnectTimeoutException(
url: String,
timeout: Long?,
cause: Throwable? = null
): ConnectTimeoutException = ConnectTimeoutException(
"Connect timeout has expired [url=$url, connect_timeout=${timeout ?: "unknown"} ms]",
cause
)
/**
* This exception is thrown in case the socket timeout (read or write) is exceeded.
* It indicates the time between two data packets when exchanging data with a server was too long.
*/
public fun SocketTimeoutException(
request: HttpRequestData,
cause: Throwable? = null
): SocketTimeoutException = SocketTimeoutException(
"Socket timeout has expired [url=${request.url}, " +
"socket_timeout=${request.getCapabilityOrNull(HttpTimeout)?.socketTimeoutMillis ?: "unknown"}] ms",
cause
)
/**
* Converts a long timeout in milliseconds to int value. To do that, we need to consider [HttpTimeout.INFINITE_TIMEOUT_MS]
* as zero and convert timeout value to [Int].
*/
@InternalAPI
public fun convertLongTimeoutToIntWithInfiniteAsZero(timeout: Long): Int = when {
timeout == HttpTimeout.INFINITE_TIMEOUT_MS -> 0
timeout < Int.MIN_VALUE -> Int.MIN_VALUE
timeout > Int.MAX_VALUE -> Int.MAX_VALUE
else -> timeout.toInt()
}
/**
* Converts long timeout in milliseconds to long value. To do that, we need to consider [HttpTimeout.INFINITE_TIMEOUT_MS]
* as zero and convert timeout value to [Int].
*/
@InternalAPI
public fun convertLongTimeoutToLongWithInfiniteAsZero(timeout: Long): Long = when (timeout) {
HttpTimeout.INFINITE_TIMEOUT_MS -> 0L
else -> timeout
}
@PublishedApi
internal inline fun <T> unwrapRequestTimeoutException(block: () -> T): T {
try {
return block()
} catch (cause: CancellationException) {
throw cause.unwrapCancellationException()
}
}
| apache-2.0 | 164e2a517e42f313ec8ab06aaaf29ddb | 38.233333 | 131 | 0.663079 | 5.139738 | false | true | false | false |
ktorio/ktor | ktor-client/ktor-client-android/jvm/src/io/ktor/client/engine/android/AndroidURLConnectionUtils.kt | 1 | 3242 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine.android
import io.ktor.client.network.sockets.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.util.*
import io.ktor.util.cio.*
import io.ktor.utils.io.*
import io.ktor.utils.io.jvm.javaio.*
import kotlinx.coroutines.*
import java.io.*
import java.net.*
import kotlin.coroutines.*
/**
* Setup [HttpURLConnection] timeout configuration using [HttpTimeout.HttpTimeoutCapabilityConfiguration] as a source.
*/
@OptIn(InternalAPI::class)
internal fun HttpURLConnection.setupTimeoutAttributes(requestData: HttpRequestData) {
requestData.getCapabilityOrNull(HttpTimeout)?.let { timeoutAttributes ->
timeoutAttributes.connectTimeoutMillis?.let { connectTimeout = convertLongTimeoutToIntWithInfiniteAsZero(it) }
timeoutAttributes.socketTimeoutMillis?.let { readTimeout = convertLongTimeoutToIntWithInfiniteAsZero(it) }
setupRequestTimeoutAttributes(timeoutAttributes)
}
}
/**
* Update [HttpURLConnection] timeout configuration to support request timeout. Required to support blocking
* [HttpURLConnection.connect] call.
*/
@OptIn(InternalAPI::class)
private fun HttpURLConnection.setupRequestTimeoutAttributes(
timeoutAttributes: HttpTimeout.HttpTimeoutCapabilityConfiguration
) {
// Android performs blocking connect call, so we need to add an upper bound on the call time.
timeoutAttributes.requestTimeoutMillis?.let { requestTimeout ->
if (requestTimeout == HttpTimeout.INFINITE_TIMEOUT_MS) return@let
if (connectTimeout == 0 || connectTimeout > requestTimeout) {
connectTimeout = convertLongTimeoutToIntWithInfiniteAsZero(requestTimeout)
}
}
}
/**
* Executes [block] catching [java.net.SocketTimeoutException] and returning [SocketTimeoutException] instead
* of it. If request timeout happens earlier [HttpRequestTimeoutException] will be thrown.
*/
internal suspend fun <T> HttpURLConnection.timeoutAwareConnection(
request: HttpRequestData,
block: (HttpURLConnection) -> T
): T {
try {
return block(this)
} catch (cause: Throwable) {
// Allow to throw request timeout cancellation exception instead of connect timeout exception if needed.
yield()
throw when {
cause.isTimeoutException() -> ConnectTimeoutException(request, cause)
else -> cause
}
}
}
/**
* Establish connection and return correspondent [ByteReadChannel].
*/
@OptIn(InternalAPI::class)
internal fun HttpURLConnection.content(callContext: CoroutineContext, request: HttpRequestData): ByteReadChannel = try {
inputStream?.buffered()
} catch (_: IOException) {
errorStream?.buffered()
}?.toByteReadChannel(
context = callContext,
pool = KtorDefaultPool
)?.let { CoroutineScope(callContext).mapEngineExceptions(it, request) } ?: ByteReadChannel.Empty
/**
* Checks the exception and identifies timeout exception by it.
*/
private fun Throwable.isTimeoutException(): Boolean =
this is java.net.SocketTimeoutException || (this is ConnectException && message?.contains("timed out") ?: false)
| apache-2.0 | 4f7a6a8c10210e7e1c251ed2e281d910 | 37.141176 | 120 | 0.746761 | 4.624822 | false | false | false | false |
cfieber/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/ResumeStageHandlerTest.kt | 1 | 2746 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.ExecutionStatus.*
import com.netflix.spinnaker.orca.fixture.pipeline
import com.netflix.spinnaker.orca.fixture.stage
import com.netflix.spinnaker.orca.fixture.task
import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.ResumeStage
import com.netflix.spinnaker.orca.q.ResumeTask
import com.netflix.spinnaker.q.Queue
import com.nhaarman.mockito_kotlin.*
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP
import org.jetbrains.spek.subject.SubjectSpek
object ResumeStageHandlerTest : SubjectSpek<ResumeStageHandler>({
val queue: Queue = mock()
val repository: ExecutionRepository = mock()
subject(GROUP) {
ResumeStageHandler(queue, repository)
}
fun resetMocks() = reset(queue, repository)
describe("resuming a paused execution") {
val pipeline = pipeline {
application = "spinnaker"
status = RUNNING
stage {
refId = "1"
status = PAUSED
task {
id = "1"
status = SUCCEEDED
}
task {
id = "2"
status = PAUSED
}
task {
id = "3"
status = NOT_STARTED
}
}
}
val message = ResumeStage(pipeline.type, pipeline.id, pipeline.application, pipeline.stages.first().id)
beforeGroup {
whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline
}
afterGroup(::resetMocks)
action("the handler receives a message") {
subject.handle(message)
}
it("sets the stage status to running") {
verify(repository).storeStage(check {
assertThat(it.id).isEqualTo(message.stageId)
assertThat(it.status).isEqualTo(RUNNING)
})
}
it("resumes all paused tasks") {
verify(queue).push(ResumeTask(message, "2"))
verifyNoMoreInteractions(queue)
}
}
})
| apache-2.0 | 55edf3a4a0d7d72dad226e4eaa59edb9 | 29.175824 | 107 | 0.701748 | 4.16692 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderPresenter.kt | 2 | 28931 | package eu.kanade.tachiyomi.ui.reader
import android.app.Application
import android.os.Bundle
import com.jakewharton.rxrelay.BehaviorRelay
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.cache.CoverCache
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.data.download.DownloadManager
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.data.track.job.DelayedTrackingStore
import eu.kanade.tachiyomi.data.track.job.DelayedTrackingUpdateJob
import eu.kanade.tachiyomi.source.LocalSource
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import eu.kanade.tachiyomi.ui.reader.loader.ChapterLoader
import eu.kanade.tachiyomi.ui.reader.model.InsertPage
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
import eu.kanade.tachiyomi.ui.reader.model.ViewerChapters
import eu.kanade.tachiyomi.ui.reader.setting.OrientationType
import eu.kanade.tachiyomi.ui.reader.setting.ReadingModeType
import eu.kanade.tachiyomi.util.chapter.getChapterSort
import eu.kanade.tachiyomi.util.isLocal
import eu.kanade.tachiyomi.util.lang.byteSize
import eu.kanade.tachiyomi.util.lang.launchIO
import eu.kanade.tachiyomi.util.lang.takeBytes
import eu.kanade.tachiyomi.util.storage.DiskUtil
import eu.kanade.tachiyomi.util.storage.getPicturesDir
import eu.kanade.tachiyomi.util.storage.getTempShareDir
import eu.kanade.tachiyomi.util.system.ImageUtil
import eu.kanade.tachiyomi.util.system.isOnline
import eu.kanade.tachiyomi.util.system.logcat
import eu.kanade.tachiyomi.util.updateCoverLastModified
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import logcat.LogPriority
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.io.File
import java.util.Date
import java.util.concurrent.TimeUnit
/**
* Presenter used by the activity to perform background operations.
*/
class ReaderPresenter(
private val db: DatabaseHelper = Injekt.get(),
private val sourceManager: SourceManager = Injekt.get(),
private val downloadManager: DownloadManager = Injekt.get(),
private val coverCache: CoverCache = Injekt.get(),
private val preferences: PreferencesHelper = Injekt.get(),
private val delayedTrackingStore: DelayedTrackingStore = Injekt.get(),
) : BasePresenter<ReaderActivity>() {
/**
* The manga loaded in the reader. It can be null when instantiated for a short time.
*/
var manga: Manga? = null
private set
/**
* The chapter id of the currently loaded chapter. Used to restore from process kill.
*/
private var chapterId = -1L
/**
* The chapter loader for the loaded manga. It'll be null until [manga] is set.
*/
private var loader: ChapterLoader? = null
/**
* Subscription to prevent setting chapters as active from multiple threads.
*/
private var activeChapterSubscription: Subscription? = null
/**
* Relay for currently active viewer chapters.
*/
private val viewerChaptersRelay = BehaviorRelay.create<ViewerChapters>()
/**
* Relay used when loading prev/next chapter needed to lock the UI (with a dialog).
*/
private val isLoadingAdjacentChapterRelay = BehaviorRelay.create<Boolean>()
/**
* Chapter list for the active manga. It's retrieved lazily and should be accessed for the first
* time in a background thread to avoid blocking the UI.
*/
private val chapterList by lazy {
val manga = manga!!
val dbChapters = db.getChapters(manga).executeAsBlocking()
val selectedChapter = dbChapters.find { it.id == chapterId }
?: error("Requested chapter of id $chapterId not found in chapter list")
val chaptersForReader = when {
(preferences.skipRead() || preferences.skipFiltered()) -> {
val filteredChapters = dbChapters.filterNot {
when {
preferences.skipRead() && it.read -> true
preferences.skipFiltered() -> {
(manga.readFilter == Manga.CHAPTER_SHOW_READ && !it.read) ||
(manga.readFilter == Manga.CHAPTER_SHOW_UNREAD && it.read) ||
(manga.downloadedFilter == Manga.CHAPTER_SHOW_DOWNLOADED && !downloadManager.isChapterDownloaded(it, manga)) ||
(manga.downloadedFilter == Manga.CHAPTER_SHOW_NOT_DOWNLOADED && downloadManager.isChapterDownloaded(it, manga)) ||
(manga.bookmarkedFilter == Manga.CHAPTER_SHOW_BOOKMARKED && !it.bookmark) ||
(manga.bookmarkedFilter == Manga.CHAPTER_SHOW_NOT_BOOKMARKED && it.bookmark)
}
else -> false
}
}
if (filteredChapters.any { it.id == chapterId }) {
filteredChapters
} else {
filteredChapters + listOf(selectedChapter)
}
}
else -> dbChapters
}
chaptersForReader
.sortedWith(getChapterSort(manga, sortDescending = false))
.map(::ReaderChapter)
}
private var hasTrackers: Boolean = false
private val checkTrackers: (Manga) -> Unit = { manga ->
val tracks = db.getTracks(manga).executeAsBlocking()
hasTrackers = tracks.size > 0
}
private val incognitoMode = preferences.incognitoMode().get()
/**
* Called when the presenter is created. It retrieves the saved active chapter if the process
* was restored.
*/
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
if (savedState != null) {
chapterId = savedState.getLong(::chapterId.name, -1)
}
}
/**
* Called when the presenter is destroyed. It saves the current progress and cleans up
* references on the currently active chapters.
*/
override fun onDestroy() {
super.onDestroy()
val currentChapters = viewerChaptersRelay.value
if (currentChapters != null) {
currentChapters.unref()
saveChapterProgress(currentChapters.currChapter)
saveChapterHistory(currentChapters.currChapter)
}
}
/**
* Called when the presenter instance is being saved. It saves the currently active chapter
* id and the last page read.
*/
override fun onSave(state: Bundle) {
super.onSave(state)
val currentChapter = getCurrentChapter()
if (currentChapter != null) {
currentChapter.requestedPage = currentChapter.chapter.last_page_read
state.putLong(::chapterId.name, currentChapter.chapter.id!!)
}
}
/**
* Called when the user pressed the back button and is going to leave the reader. Used to
* trigger deletion of the downloaded chapters.
*/
fun onBackPressed() {
deletePendingChapters()
}
/**
* Called when the activity is saved and not changing configurations. It updates the database
* to persist the current progress of the active chapter.
*/
fun onSaveInstanceStateNonConfigurationChange() {
val currentChapter = getCurrentChapter() ?: return
saveChapterProgress(currentChapter)
}
/**
* Whether this presenter is initialized yet.
*/
fun needsInit(): Boolean {
return manga == null
}
/**
* Initializes this presenter with the given [mangaId] and [initialChapterId]. This method will
* fetch the manga from the database and initialize the initial chapter.
*/
fun init(mangaId: Long, initialChapterId: Long) {
if (!needsInit()) return
db.getManga(mangaId).asRxObservable()
.first()
.observeOn(AndroidSchedulers.mainThread())
.doOnNext { init(it, initialChapterId) }
.subscribeFirst(
{ _, _ ->
// Ignore onNext event
},
ReaderActivity::setInitialChapterError
)
}
/**
* Initializes this presenter with the given [manga] and [initialChapterId]. This method will
* set the chapter loader, view subscriptions and trigger an initial load.
*/
private fun init(manga: Manga, initialChapterId: Long) {
if (!needsInit()) return
this.manga = manga
if (chapterId == -1L) chapterId = initialChapterId
checkTrackers(manga)
val context = Injekt.get<Application>()
val source = sourceManager.getOrStub(manga.source)
loader = ChapterLoader(context, downloadManager, manga, source)
Observable.just(manga).subscribeLatestCache(ReaderActivity::setManga)
viewerChaptersRelay.subscribeLatestCache(ReaderActivity::setChapters)
isLoadingAdjacentChapterRelay.subscribeLatestCache(ReaderActivity::setProgressDialog)
// Read chapterList from an io thread because it's retrieved lazily and would block main.
activeChapterSubscription?.unsubscribe()
activeChapterSubscription = Observable
.fromCallable { chapterList.first { chapterId == it.chapter.id } }
.flatMap { getLoadObservable(loader!!, it) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeFirst(
{ _, _ ->
// Ignore onNext event
},
ReaderActivity::setInitialChapterError
)
}
/**
* Returns an observable that loads the given [chapter] with this [loader]. This observable
* handles main thread synchronization and updating the currently active chapters on
* [viewerChaptersRelay], however callers must ensure there won't be more than one
* subscription active by unsubscribing any existing [activeChapterSubscription] before.
* Callers must also handle the onError event.
*/
private fun getLoadObservable(
loader: ChapterLoader,
chapter: ReaderChapter
): Observable<ViewerChapters> {
return loader.loadChapter(chapter)
.andThen(
Observable.fromCallable {
val chapterPos = chapterList.indexOf(chapter)
ViewerChapters(
chapter,
chapterList.getOrNull(chapterPos - 1),
chapterList.getOrNull(chapterPos + 1)
)
}
)
.observeOn(AndroidSchedulers.mainThread())
.doOnNext { newChapters ->
val oldChapters = viewerChaptersRelay.value
// Add new references first to avoid unnecessary recycling
newChapters.ref()
oldChapters?.unref()
viewerChaptersRelay.call(newChapters)
}
}
/**
* Called when the user changed to the given [chapter] when changing pages from the viewer.
* It's used only to set this chapter as active.
*/
private fun loadNewChapter(chapter: ReaderChapter) {
val loader = loader ?: return
logcat { "Loading ${chapter.chapter.url}" }
activeChapterSubscription?.unsubscribe()
activeChapterSubscription = getLoadObservable(loader, chapter)
.toCompletable()
.onErrorComplete()
.subscribe()
.also(::add)
}
/**
* Called when the user is going to load the prev/next chapter through the menu button. It
* sets the [isLoadingAdjacentChapterRelay] that the view uses to prevent any further
* interaction until the chapter is loaded.
*/
private fun loadAdjacent(chapter: ReaderChapter) {
val loader = loader ?: return
logcat { "Loading adjacent ${chapter.chapter.url}" }
activeChapterSubscription?.unsubscribe()
activeChapterSubscription = getLoadObservable(loader, chapter)
.doOnSubscribe { isLoadingAdjacentChapterRelay.call(true) }
.doOnUnsubscribe { isLoadingAdjacentChapterRelay.call(false) }
.subscribeFirst(
{ view, _ ->
view.moveToPageIndex(0)
},
{ _, _ ->
// Ignore onError event, viewers handle that state
}
)
}
/**
* Called when the viewers decide it's a good time to preload a [chapter] and improve the UX so
* that the user doesn't have to wait too long to continue reading.
*/
private fun preload(chapter: ReaderChapter) {
if (chapter.state != ReaderChapter.State.Wait && chapter.state !is ReaderChapter.State.Error) {
return
}
logcat { "Preloading ${chapter.chapter.url}" }
val loader = loader ?: return
loader.loadChapter(chapter)
.observeOn(AndroidSchedulers.mainThread())
// Update current chapters whenever a chapter is preloaded
.doOnCompleted { viewerChaptersRelay.value?.let(viewerChaptersRelay::call) }
.onErrorComplete()
.subscribe()
.also(::add)
}
/**
* Called every time a page changes on the reader. Used to mark the flag of chapters being
* read, update tracking services, enqueue downloaded chapter deletion, and updating the active chapter if this
* [page]'s chapter is different from the currently active.
*/
fun onPageSelected(page: ReaderPage) {
val currentChapters = viewerChaptersRelay.value ?: return
val selectedChapter = page.chapter
// Insert page doesn't change page progress
if (page is InsertPage) {
return
}
// Save last page read and mark as read if needed
selectedChapter.chapter.last_page_read = page.index
val shouldTrack = !incognitoMode || hasTrackers
if (selectedChapter.pages?.lastIndex == page.index && shouldTrack) {
selectedChapter.chapter.read = true
updateTrackChapterRead(selectedChapter)
deleteChapterIfNeeded(selectedChapter)
deleteChapterFromDownloadQueue(currentChapters.currChapter)
}
if (selectedChapter != currentChapters.currChapter) {
logcat { "Setting ${selectedChapter.chapter.url} as active" }
onChapterChanged(currentChapters.currChapter)
loadNewChapter(selectedChapter)
}
}
/**
* Removes [currentChapter] from download queue
* if setting is enabled and [currentChapter] is queued for download
*/
private fun deleteChapterFromDownloadQueue(currentChapter: ReaderChapter) {
downloadManager.getChapterDownloadOrNull(currentChapter.chapter)?.let { download ->
downloadManager.deletePendingDownload(download)
}
}
/**
* Determines if deleting option is enabled and nth to last chapter actually exists.
* If both conditions are satisfied enqueues chapter for delete
* @param currentChapter current chapter, which is going to be marked as read.
*/
private fun deleteChapterIfNeeded(currentChapter: ReaderChapter) {
// Determine which chapter should be deleted and enqueue
val currentChapterPosition = chapterList.indexOf(currentChapter)
val removeAfterReadSlots = preferences.removeAfterReadSlots()
val chapterToDelete = chapterList.getOrNull(currentChapterPosition - removeAfterReadSlots)
// Check if deleting option is enabled and chapter exists
if (removeAfterReadSlots != -1 && chapterToDelete != null) {
enqueueDeleteReadChapters(chapterToDelete)
}
}
/**
* Called when a chapter changed from [fromChapter] to [toChapter]. It updates [fromChapter]
* on the database.
*/
private fun onChapterChanged(fromChapter: ReaderChapter) {
saveChapterProgress(fromChapter)
saveChapterHistory(fromChapter)
}
/**
* Saves this [chapter] progress (last read page and whether it's read).
* If incognito mode isn't on or has at least 1 tracker
*/
private fun saveChapterProgress(chapter: ReaderChapter) {
if (!incognitoMode || hasTrackers) {
db.updateChapterProgress(chapter.chapter).asRxCompletable()
.onErrorComplete()
.subscribeOn(Schedulers.io())
.subscribe()
}
}
/**
* Saves this [chapter] last read history if incognito mode isn't on.
*/
private fun saveChapterHistory(chapter: ReaderChapter) {
if (!incognitoMode) {
val history = History.create(chapter.chapter).apply { last_read = Date().time }
db.updateHistoryLastRead(history).asRxCompletable()
.onErrorComplete()
.subscribeOn(Schedulers.io())
.subscribe()
}
}
/**
* Called from the activity to preload the given [chapter].
*/
fun preloadChapter(chapter: ReaderChapter) {
preload(chapter)
}
/**
* Called from the activity to load and set the next chapter as active.
*/
fun loadNextChapter() {
val nextChapter = viewerChaptersRelay.value?.nextChapter ?: return
loadAdjacent(nextChapter)
}
/**
* Called from the activity to load and set the previous chapter as active.
*/
fun loadPreviousChapter() {
val prevChapter = viewerChaptersRelay.value?.prevChapter ?: return
loadAdjacent(prevChapter)
}
/**
* Returns the currently active chapter.
*/
fun getCurrentChapter(): ReaderChapter? {
return viewerChaptersRelay.value?.currChapter
}
/**
* Bookmarks the currently active chapter.
*/
fun bookmarkCurrentChapter(bookmarked: Boolean) {
if (getCurrentChapter()?.chapter == null) {
return
}
val chapter = getCurrentChapter()?.chapter!!
chapter.bookmark = bookmarked
db.updateChapterProgress(chapter).executeAsBlocking()
}
/**
* Returns the viewer position used by this manga or the default one.
*/
fun getMangaReadingMode(resolveDefault: Boolean = true): Int {
val default = preferences.defaultReadingMode()
val readingMode = ReadingModeType.fromPreference(manga?.readingModeType)
return when {
resolveDefault && readingMode == ReadingModeType.DEFAULT -> default
else -> manga?.readingModeType ?: default
}
}
/**
* Updates the viewer position for the open manga.
*/
fun setMangaReadingMode(readingModeType: Int) {
val manga = manga ?: return
manga.readingModeType = readingModeType
db.updateViewerFlags(manga).executeAsBlocking()
Observable.timer(250, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.subscribeFirst({ view, _ ->
val currChapters = viewerChaptersRelay.value
if (currChapters != null) {
// Save current page
val currChapter = currChapters.currChapter
currChapter.requestedPage = currChapter.chapter.last_page_read
// Emit manga and chapters to the new viewer
view.setManga(manga)
view.setChapters(currChapters)
}
})
}
/**
* Returns the orientation type used by this manga or the default one.
*/
fun getMangaOrientationType(resolveDefault: Boolean = true): Int {
val default = preferences.defaultOrientationType()
val orientation = OrientationType.fromPreference(manga?.orientationType)
return when {
resolveDefault && orientation == OrientationType.DEFAULT -> default
else -> manga?.orientationType ?: default
}
}
/**
* Updates the orientation type for the open manga.
*/
fun setMangaOrientationType(rotationType: Int) {
val manga = manga ?: return
manga.orientationType = rotationType
db.updateViewerFlags(manga).executeAsBlocking()
logcat(LogPriority.INFO) { "Manga orientation is ${manga.orientationType}" }
Observable.timer(250, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.subscribeFirst({ view, _ ->
val currChapters = viewerChaptersRelay.value
if (currChapters != null) {
view.setOrientation(getMangaOrientationType())
}
})
}
/**
* Saves the image of this [page] in the given [directory] and returns the file location.
*/
private fun saveImage(page: ReaderPage, directory: File, manga: Manga): File {
val stream = page.stream!!
val type = ImageUtil.findImageType(stream) ?: throw Exception("Not an image")
directory.mkdirs()
val chapter = page.chapter.chapter
// Build destination file.
val filenameSuffix = " - ${page.number}.${type.extension}"
val filename = DiskUtil.buildValidFilename(
"${manga.title} - ${chapter.name}".takeBytes(MAX_FILE_NAME_BYTES - filenameSuffix.byteSize())
) + filenameSuffix
val destFile = File(directory, filename)
stream().use { input ->
destFile.outputStream().use { output ->
input.copyTo(output)
}
}
return destFile
}
/**
* Saves the image of this [page] on the pictures directory and notifies the UI of the result.
* There's also a notification to allow sharing the image somewhere else or deleting it.
*/
fun saveImage(page: ReaderPage) {
if (page.status != Page.READY) return
val manga = manga ?: return
val context = Injekt.get<Application>()
val notifier = SaveImageNotifier(context)
notifier.onClear()
// Pictures directory.
val baseDir = getPicturesDir(context).absolutePath
val destDir = if (preferences.folderPerManga()) {
File(baseDir + File.separator + DiskUtil.buildValidFilename(manga.title))
} else {
File(baseDir)
}
// Copy file in background.
Observable.fromCallable { saveImage(page, destDir, manga) }
.doOnNext { file ->
DiskUtil.scanMedia(context, file)
notifier.onComplete(file)
}
.doOnError { notifier.onError(it.message) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeFirst(
{ view, file -> view.onSaveImageResult(SaveImageResult.Success(file)) },
{ view, error -> view.onSaveImageResult(SaveImageResult.Error(error)) }
)
}
/**
* Shares the image of this [page] and notifies the UI with the path of the file to share.
* The image must be first copied to the internal partition because there are many possible
* formats it can come from, like a zipped chapter, in which case it's not possible to directly
* get a path to the file and it has to be decompresssed somewhere first. Only the last shared
* image will be kept so it won't be taking lots of internal disk space.
*/
fun shareImage(page: ReaderPage) {
if (page.status != Page.READY) return
val manga = manga ?: return
val context = Injekt.get<Application>()
val destDir = getTempShareDir(context)
Observable.fromCallable { destDir.deleteRecursively() } // Keep only the last shared file
.map { saveImage(page, destDir, manga) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeFirst(
{ view, file -> view.onShareImageResult(file, page) },
{ _, _ -> /* Empty */ }
)
}
/**
* Sets the image of this [page] as cover and notifies the UI of the result.
*/
fun setAsCover(page: ReaderPage) {
if (page.status != Page.READY) return
val manga = manga ?: return
val stream = page.stream ?: return
Observable
.fromCallable {
if (manga.isLocal()) {
val context = Injekt.get<Application>()
LocalSource.updateCover(context, manga, stream())
manga.updateCoverLastModified(db)
R.string.cover_updated
SetAsCoverResult.Success
} else {
if (manga.favorite) {
coverCache.setCustomCoverToCache(manga, stream())
manga.updateCoverLastModified(db)
coverCache.clearMemoryCache()
SetAsCoverResult.Success
} else {
SetAsCoverResult.AddToLibraryFirst
}
}
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeFirst(
{ view, result -> view.onSetAsCoverResult(result) },
{ view, _ -> view.onSetAsCoverResult(SetAsCoverResult.Error) }
)
}
/**
* Results of the set as cover feature.
*/
enum class SetAsCoverResult {
Success, AddToLibraryFirst, Error
}
/**
* Results of the save image feature.
*/
sealed class SaveImageResult {
class Success(val file: File) : SaveImageResult()
class Error(val error: Throwable) : SaveImageResult()
}
/**
* Starts the service that updates the last chapter read in sync services. This operation
* will run in a background thread and errors are ignored.
*/
private fun updateTrackChapterRead(readerChapter: ReaderChapter) {
if (!preferences.autoUpdateTrack()) return
val manga = manga ?: return
val chapterRead = readerChapter.chapter.chapter_number
val trackManager = Injekt.get<TrackManager>()
val context = Injekt.get<Application>()
launchIO {
db.getTracks(manga).executeAsBlocking()
.mapNotNull { track ->
val service = trackManager.getService(track.sync_id)
if (service != null && service.isLogged && chapterRead > track.last_chapter_read) {
track.last_chapter_read = chapterRead
// We want these to execute even if the presenter is destroyed and leaks
// for a while. The view can still be garbage collected.
async {
runCatching {
if (context.isOnline()) {
service.update(track, true)
db.insertTrack(track).executeAsBlocking()
} else {
delayedTrackingStore.addItem(track)
DelayedTrackingUpdateJob.setupTask(context)
}
}
}
} else {
null
}
}
.awaitAll()
.mapNotNull { it.exceptionOrNull() }
.forEach { logcat(LogPriority.INFO, it) }
}
}
/**
* Enqueues this [chapter] to be deleted when [deletePendingChapters] is called. The download
* manager handles persisting it across process deaths.
*/
private fun enqueueDeleteReadChapters(chapter: ReaderChapter) {
if (!chapter.chapter.read) return
val manga = manga ?: return
launchIO {
downloadManager.enqueueDeleteChapters(listOf(chapter.chapter), manga)
}
}
/**
* Deletes all the pending chapters. This operation will run in a background thread and errors
* are ignored.
*/
private fun deletePendingChapters() {
launchIO {
downloadManager.deletePendingChapters()
}
}
companion object {
// Safe theoretical max filename size is 255 bytes and 1 char = 2-4 bytes (UTF-8)
private const val MAX_FILE_NAME_BYTES = 250
}
}
| apache-2.0 | dcbe9d07baa5fa7bbdae7d7758ed97f8 | 36.670573 | 146 | 0.620131 | 5.071166 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/BangumiApi.kt | 2 | 7600 | package eu.kanade.tachiyomi.data.track.bangumi
import android.net.Uri
import androidx.core.net.toUri
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.data.track.model.TrackSearch
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.POST
import eu.kanade.tachiyomi.network.await
import eu.kanade.tachiyomi.network.parseAs
import eu.kanade.tachiyomi.util.lang.withIOContext
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.int
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import okhttp3.CacheControl
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import uy.kohesive.injekt.injectLazy
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
class BangumiApi(private val client: OkHttpClient, interceptor: BangumiInterceptor) {
private val json: Json by injectLazy()
private val authClient = client.newBuilder().addInterceptor(interceptor).build()
suspend fun addLibManga(track: Track): Track {
return withIOContext {
val body = FormBody.Builder()
.add("rating", track.score.toInt().toString())
.add("status", track.toBangumiStatus())
.build()
authClient.newCall(POST("$apiUrl/collection/${track.media_id}/update", body = body))
.await()
track
}
}
suspend fun updateLibManga(track: Track): Track {
return withIOContext {
// read status update
val sbody = FormBody.Builder()
.add("rating", track.score.toInt().toString())
.add("status", track.toBangumiStatus())
.build()
authClient.newCall(POST("$apiUrl/collection/${track.media_id}/update", body = sbody))
.await()
// chapter update
val body = FormBody.Builder()
.add("watched_eps", track.last_chapter_read.toInt().toString())
.build()
authClient.newCall(
POST(
"$apiUrl/subject/${track.media_id}/update/watched_eps",
body = body
)
).await()
track
}
}
suspend fun search(search: String): List<TrackSearch> {
return withIOContext {
val url = "$apiUrl/search/subject/${URLEncoder.encode(search, StandardCharsets.UTF_8.name())}"
.toUri()
.buildUpon()
.appendQueryParameter("max_results", "20")
.build()
authClient.newCall(GET(url.toString()))
.await()
.use {
var responseBody = it.body?.string().orEmpty()
if (responseBody.isEmpty()) {
throw Exception("Null Response")
}
if (responseBody.contains("\"code\":404")) {
responseBody = "{\"results\":0,\"list\":[]}"
}
val response = json.decodeFromString<JsonObject>(responseBody)["list"]?.jsonArray
response?.filter { it.jsonObject["type"]?.jsonPrimitive?.int == 1 }
?.map { jsonToSearch(it.jsonObject) }.orEmpty()
}
}
}
private fun jsonToSearch(obj: JsonObject): TrackSearch {
val coverUrl = if (obj["images"] is JsonObject) {
obj["images"]?.jsonObject?.get("common")?.jsonPrimitive?.contentOrNull ?: ""
} else {
// Sometimes JsonNull
""
}
val totalChapters = if (obj["eps_count"] != null) {
obj["eps_count"]!!.jsonPrimitive.int
} else {
0
}
return TrackSearch.create(TrackManager.BANGUMI).apply {
media_id = obj["id"]!!.jsonPrimitive.int
title = obj["name_cn"]!!.jsonPrimitive.content
cover_url = coverUrl
summary = obj["name"]!!.jsonPrimitive.content
tracking_url = obj["url"]!!.jsonPrimitive.content
total_chapters = totalChapters
}
}
suspend fun findLibManga(track: Track): Track? {
return withIOContext {
authClient.newCall(GET("$apiUrl/subject/${track.media_id}"))
.await()
.parseAs<JsonObject>()
.let { jsonToSearch(it) }
}
}
suspend fun statusLibManga(track: Track): Track? {
return withIOContext {
val urlUserRead = "$apiUrl/collection/${track.media_id}"
val requestUserRead = Request.Builder()
.url(urlUserRead)
.cacheControl(CacheControl.FORCE_NETWORK)
.get()
.build()
// TODO: get user readed chapter here
var response = authClient.newCall(requestUserRead).await()
var responseBody = response.body?.string().orEmpty()
if (responseBody.isEmpty()) {
throw Exception("Null Response")
}
if (responseBody.contains("\"code\":400")) {
null
} else {
json.decodeFromString<Collection>(responseBody).let {
track.status = it.status?.id!!
track.last_chapter_read = it.ep_status!!.toFloat()
track.score = it.rating!!
track
}
}
}
}
suspend fun accessToken(code: String): OAuth {
return withIOContext {
client.newCall(accessTokenRequest(code))
.await()
.parseAs()
}
}
private fun accessTokenRequest(code: String) = POST(
oauthUrl,
body = FormBody.Builder()
.add("grant_type", "authorization_code")
.add("client_id", clientId)
.add("client_secret", clientSecret)
.add("code", code)
.add("redirect_uri", redirectUrl)
.build()
)
companion object {
private const val clientId = "bgm10555cda0762e80ca"
private const val clientSecret = "8fff394a8627b4c388cbf349ec865775"
private const val apiUrl = "https://api.bgm.tv"
private const val oauthUrl = "https://bgm.tv/oauth/access_token"
private const val loginUrl = "https://bgm.tv/oauth/authorize"
private const val redirectUrl = "tachiyomi://bangumi-auth"
private const val baseMangaUrl = "$apiUrl/mangas"
fun mangaUrl(remoteId: Int): String {
return "$baseMangaUrl/$remoteId"
}
fun authUrl(): Uri =
loginUrl.toUri().buildUpon()
.appendQueryParameter("client_id", clientId)
.appendQueryParameter("response_type", "code")
.appendQueryParameter("redirect_uri", redirectUrl)
.build()
fun refreshTokenRequest(token: String) = POST(
oauthUrl,
body = FormBody.Builder()
.add("grant_type", "refresh_token")
.add("client_id", clientId)
.add("client_secret", clientSecret)
.add("refresh_token", token)
.add("redirect_uri", redirectUrl)
.build()
)
}
}
| apache-2.0 | 326eabca31e10c035cc9e8ae4a38a39e | 35.714976 | 106 | 0.565395 | 4.78891 | false | false | false | false |
WilliamHester/Breadit-2 | app/app/src/main/java/me/williamhester/reddit/ui/text/SpoilerSpan.kt | 1 | 587 | package me.williamhester.reddit.ui.text
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.View
/** A [ClickableSpan] that hides the text until it is clicked. */
class SpoilerSpan : ClickableSpan() {
private var clicked = false
override fun onClick(view: View) {
val unpaint = TextPaint()
clicked = true
updateDrawState(unpaint)
view.invalidate()
}
override fun updateDrawState(ds: TextPaint) {
ds.isUnderlineText = true
if (!clicked) {
ds.bgColor = ds.color
} else {
ds.bgColor = 0
}
}
}
| apache-2.0 | 7bbc1a6906484f88f5af1547083810a7 | 20.740741 | 65 | 0.684838 | 3.966216 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/util/CommonColors.kt | 1 | 1558 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.util
import java.awt.Color
object CommonColors {
val DARK_RED = Color(0xAA0000)
val RED = Color(0xFF5555)
val GOLD = Color(0xFFAA00)
val YELLOW = Color(0xFFFF55)
val DARK_GREEN = Color(0x00AA00)
val GREEN = Color(0x55FF55)
val AQUA = Color(0x55FFFF)
val DARK_AQUA = Color(0x00AAAA)
val DARK_BLUE = Color(0x0000AA)
val BLUE = Color(0x5555FF)
val LIGHT_PURPLE = Color(0xFF55FF)
val DARK_PURPLE = Color(0xAA00AA)
val WHITE = Color(0xFFFFFF)
val GRAY = Color(0xAAAAAA)
val DARK_GRAY = Color(0x555555)
val BLACK = Color(0x000000)
fun applyStandardColors(map: MutableMap<String, Color>, prefix: String) {
map.apply {
put("$prefix.DARK_RED", DARK_RED)
put("$prefix.RED", RED)
put("$prefix.GOLD", GOLD)
put("$prefix.YELLOW", YELLOW)
put("$prefix.DARK_GREEN", DARK_GREEN)
put("$prefix.GREEN", GREEN)
put("$prefix.AQUA", AQUA)
put("$prefix.DARK_AQUA", DARK_AQUA)
put("$prefix.DARK_BLUE", DARK_BLUE)
put("$prefix.BLUE", BLUE)
put("$prefix.LIGHT_PURPLE", LIGHT_PURPLE)
put("$prefix.DARK_PURPLE", DARK_PURPLE)
put("$prefix.WHITE", WHITE)
put("$prefix.GRAY", GRAY)
put("$prefix.DARK_GRAY", DARK_GRAY)
put("$prefix.BLACK", BLACK)
}
}
}
| mit | b47c0ad1292af5baafb0006a1f22916a | 27.851852 | 77 | 0.584724 | 3.454545 | false | false | false | false |
dahlstrom-g/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/ide/ui/DocumentationToolWindowUpdater.kt | 7 | 3359 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.lang.documentation.ide.ui
import com.intellij.ide.DataManager
import com.intellij.ide.IdeEventQueue
import com.intellij.lang.documentation.ide.actions.DOCUMENTATION_TARGETS
import com.intellij.lang.documentation.ide.impl.DocumentationBrowser
import com.intellij.lang.documentation.impl.documentationRequest
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.impl.Utils
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.readAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.util.ui.EDT
import com.intellij.util.ui.update.Activatable
import kotlinx.coroutines.*
import java.lang.Runnable
import kotlin.coroutines.resume
internal class DocumentationToolWindowUpdater(
private val project: Project,
private val browser: DocumentationBrowser,
) : Activatable {
private val cs = CoroutineScope(CoroutineName("DocumentationPreviewToolWindowUI"))
override fun showNotify() {
toggleAutoUpdate(true)
}
override fun hideNotify() {
toggleAutoUpdate(false)
}
private var paused: Boolean = false
fun pause(): Disposable {
EDT.assertIsEdt()
paused = true
cs.coroutineContext.cancelChildren()
return Disposable {
EDT.assertIsEdt()
paused = false
}
}
private val autoUpdateRequest = Runnable(::requestAutoUpdate)
private var autoUpdateDisposable: Disposable? = null
private fun toggleAutoUpdate(state: Boolean) {
if (state) {
if (autoUpdateDisposable != null) {
return
}
val disposable = Disposer.newDisposable("documentation auto updater")
IdeEventQueue.getInstance().addActivityListener(autoUpdateRequest, disposable)
autoUpdateDisposable = disposable
}
else {
autoUpdateDisposable?.let(Disposer::dispose)
autoUpdateDisposable = null
}
}
private fun requestAutoUpdate() {
cs.coroutineContext.cancelChildren()
if (paused) {
return
}
cs.launch {
delay(DEFAULT_UI_RESPONSE_TIMEOUT)
autoUpdate()
}
}
private suspend fun autoUpdate() {
val dataContext = focusDataContext()
if (dataContext.getData(CommonDataKeys.PROJECT) != project) {
return
}
val request = readAction {
dataContext.getData(DOCUMENTATION_TARGETS)?.singleOrNull()?.documentationRequest()
}
if (request != null) {
browser.resetBrowser(request)
}
}
private suspend fun focusDataContext(): DataContext = suspendCancellableCoroutine {
// @formatter:off
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown({
@Suppress("DEPRECATION")
val dataContextFromFocusedComponent = DataManager.getInstance().dataContext
val uiSnapshot = Utils.wrapToAsyncDataContext(dataContextFromFocusedComponent)
val asyncDataContext = AnActionEvent.getInjectedDataContext(uiSnapshot)
it.resume(asyncDataContext)
}, ModalityState.any())
// @formatter:on
}
}
| apache-2.0 | 9bdee8984b79a837a15cbb12f0cb8a3c | 30.688679 | 120 | 0.7532 | 4.771307 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/leetcode/wildcard_matching/v2/WildcardMatching2.kt | 1 | 2110 | package katas.kotlin.leetcode.wildcard_matching.v2
import datsok.*
import org.junit.*
class WildcardMatching2 {
@Test fun `some examples`() {
match("", "") shouldEqual true
match("a", "") shouldEqual false
match("", "a") shouldEqual false
match("a", "a") shouldEqual true
match("a", "b") shouldEqual false
match("aa", "a") shouldEqual false
match("a", "aa") shouldEqual false
match("ab", "ab") shouldEqual true
match("", "?") shouldEqual false
match("a", "?") shouldEqual true
match("?", "a") shouldEqual false
match("?", "?") shouldEqual true
match("ab", "a?") shouldEqual true
match("ab", "??") shouldEqual true
match("ab", "???") shouldEqual false
match("abc", "??") shouldEqual false
match("", "*") shouldEqual true
match("abc", "*") shouldEqual true
match("abc", "ab*") shouldEqual true
match("abc", "a*c") shouldEqual true
match("abc", "*bc") shouldEqual true
match("abc", "a*") shouldEqual true
match("abc", "*c") shouldEqual true
match("abc", "*cc") shouldEqual false
match("abc", "aa*") shouldEqual false
match("abc", "**") shouldEqual true
}
}
private typealias Matcher = (input: String) -> List<String>
private fun char(c: Char): Matcher = { input: String ->
if (input.isEmpty() || input.first() != c) emptyList()
else listOf(input.drop(1))
}
private fun question(): Matcher = { input: String ->
if (input.isEmpty()) emptyList()
else listOf(input.drop(1))
}
private fun star(): Matcher = { input: String ->
if (input.isEmpty()) listOf(input)
else input.indices.map { i -> input.substring(i + 1, input.length) }
}
private fun match(s: String, pattern: String): Boolean {
val matchers = pattern.map {
when (it) {
'?' -> question()
'*' -> star()
else -> char(it)
}
}
return matchers
.fold(listOf(s)) { inputs, matcher -> inputs.flatMap(matcher) }
.any { it.isEmpty() }
} | unlicense | 12411acba8fa754154f06573829cac2e | 30.044118 | 72 | 0.563033 | 4.161736 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/features/main/MainActivity.kt | 1 | 8238 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.features.main
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.view.GravityCompat
import androidx.databinding.DataBindingUtil
import androidx.test.espresso.idling.CountingIdlingResource
import de.dreier.mytargets.R
import de.dreier.mytargets.base.navigation.NavigationController
import de.dreier.mytargets.databinding.ActivityMainBinding
import de.dreier.mytargets.features.arrows.EditArrowListFragment
import de.dreier.mytargets.features.bows.EditBowListFragment
import de.dreier.mytargets.features.settings.ESettingsScreens
import de.dreier.mytargets.features.settings.ESettingsScreens.MAIN
import de.dreier.mytargets.features.settings.SettingsManager
import de.dreier.mytargets.features.training.overview.TrainingsFragment
import de.dreier.mytargets.utils.Utils
import de.dreier.mytargets.utils.Utils.getCurrentLocale
import im.delight.android.languages.Language
/**
* Shows the apps main screen, which contains a bottom navigation for switching between trainings,
* bows and arrows, as well as an navigation drawer for hosting settings and the timer quick access.
*/
class MainActivity : AppCompatActivity() {
private lateinit var navigationController: NavigationController
internal lateinit var binding: ActivityMainBinding
private var drawerToggle: ActionBarDrawerToggle? = null
private var onDrawerClosePendingAction: Int? = null
/**
* Ensures that espresso is waiting until the launched intent is sent from the navigation drawer.
*/
val espressoIdlingResourceForMainActivity = CountingIdlingResource("delayed_activity")
private var countryCode: String? = null
public override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppTheme_CustomToolbar)
Language.setFromPreference(this, SettingsManager.KEY_LANGUAGE)
countryCode = getCountryCode()
super.onCreate(savedInstanceState)
navigationController = NavigationController(this)
if (SettingsManager.shouldShowIntroActivity) {
SettingsManager.shouldShowIntroActivity = false
val intent = Intent(this, IntroActivity::class.java)
startActivity(intent)
}
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
setSupportActionBar(binding.toolbar)
setupBottomNavigation()
setupNavigationDrawer()
if (savedInstanceState == null) {
supportFragmentManager
.beginTransaction()
.add(R.id.content_frame, TrainingsFragment())
.commit()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(KEY_LANGUAGE, countryCode)
}
private fun getCountryCode(): String {
return getCurrentLocale(this).toString()
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
countryCode = savedInstanceState.getString(KEY_LANGUAGE)
}
override fun onResume() {
super.onResume()
if (countryCode != null && getCountryCode() != countryCode) {
countryCode = getCountryCode()
recreate()
}
setupNavigationHeaderView()
}
private fun setupBottomNavigation() {
binding.bottomNavigation.setOnNavigationItemSelectedListener { item ->
val fragment = when (item.itemId) {
R.id.action_arrows -> EditArrowListFragment()
R.id.action_bows -> EditBowListFragment()
R.id.action_trainings -> TrainingsFragment()
else -> throw IllegalStateException("Illegal action id")
}
supportFragmentManager
.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit()
true
}
}
private fun setupNavigationDrawer() {
if (Utils.isLollipop) {
window.statusBarColor = Color.TRANSPARENT
}
binding.navigationView.setNavigationItemSelectedListener { menuItem ->
when (menuItem.itemId) {
R.id.nav_timer -> closeDrawerAndStart(menuItem.itemId)
R.id.nav_settings -> closeDrawerAndStart(menuItem.itemId)
R.id.nav_help_and_feedback -> closeDrawerAndStart(menuItem.itemId)
else -> {
}
}
false
}
drawerToggle = object : ActionBarDrawerToggle(
this,
binding.drawerLayout,
binding.toolbar,
R.string.drawer_open,
R.string.drawer_close
) {
override fun onDrawerClosed(drawerView: View) {
super.onDrawerClosed(drawerView)
if (onDrawerClosePendingAction != null) {
when (onDrawerClosePendingAction) {
R.id.nav_timer -> navigationController.navigateToTimer(false)
R.id.nav_settings -> navigationController.navigateToSettings(MAIN)
R.id.nav_help_and_feedback -> navigationController.navigateToHelp()
R.id.profile -> navigationController.navigateToSettings(ESettingsScreens.PROFILE)
}
onDrawerClosePendingAction = null
espressoIdlingResourceForMainActivity.decrement()
}
}
}
binding.drawerLayout.addDrawerListener(drawerToggle!!)
}
private fun setupNavigationHeaderView() {
val headerLayout = binding.navigationView.getHeaderView(0)
val userName = headerLayout.findViewById<TextView>(R.id.username)
val userDetails = headerLayout.findViewById<TextView>(R.id.user_details)
val profileFullName = SettingsManager.profileFullName
if (profileFullName.trim { it <= ' ' }.isEmpty()) {
userName.setText(R.string.click_to_enter_profile)
} else {
userName.text = profileFullName
}
userDetails.text = SettingsManager.profileClub
headerLayout.setOnClickListener { closeDrawerAndStart(R.id.profile) }
}
private fun closeDrawerAndStart(actionId: Int) {
onDrawerClosePendingAction = actionId
espressoIdlingResourceForMainActivity.increment()
binding.drawerLayout.closeDrawers()
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle!!.syncState()
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
// Pass any configuration change to the drawer toggles
drawerToggle!!.onConfigurationChanged(newConfig)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
binding.drawerLayout.openDrawer(GravityCompat.START)
true
}
else -> super.onOptionsItemSelected(item)
}
}
companion object {
const val KEY_LANGUAGE = "language"
init {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
}
}
}
| gpl-2.0 | c473a523567eed455002eec6f9d54af8 | 37.676056 | 105 | 0.678077 | 5.311412 | false | false | false | false |
paplorinc/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/EditCustomSettingsAction.kt | 2 | 6550 | // Copyright 2000-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 file.
package com.intellij.ide.actions
import com.intellij.CommonBundle
import com.intellij.diagnostic.VMOptions
import com.intellij.ide.IdeBundle
import com.intellij.ide.util.PsiNavigationSupport
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessExtension
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.project.DefaultProjectFactory
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.showOkCancelDialog
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.psi.PsiManager
import com.intellij.ui.EditorTextField
import com.intellij.util.LineSeparator
import java.io.File
import java.io.IOException
import javax.swing.JFrame
import javax.swing.ScrollPaneConstants
abstract class EditCustomSettingsAction : DumbAwareAction() {
protected abstract fun file(): File?
protected abstract fun template(): String
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = (e.project != null || WelcomeFrame.getInstance() != null) && file() != null
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project
val frame = WelcomeFrame.getInstance() as JFrame?
val file = file() ?: return
if (project != null) {
if (!file.exists()) {
val confirmation = IdeBundle.message("edit.custom.settings.confirm", FileUtil.getLocationRelativeToUserHome(file.path))
val result = showOkCancelDialog(title = e.presentation.text!!, message = confirmation,
okText = IdeBundle.message("button.create"), cancelText = IdeBundle.message("button.cancel"),
icon = Messages.getQuestionIcon(), project = project)
if (result == Messages.CANCEL) return
try {
FileUtil.writeToFile(file, StringUtil.convertLineSeparators(template(), LineSeparator.getSystemLineSeparator().separatorString))
}
catch (ex: IOException) {
Logger.getInstance(javaClass).warn(file.path, ex)
val message = IdeBundle.message("edit.custom.settings.failed", file, ex.message)
Messages.showErrorDialog(project, message, CommonBundle.message("title.error"))
return
}
}
val vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file)
if (vFile != null) {
vFile.refresh(false, false)
val psiFile = PsiManager.getInstance(project).findFile(vFile)
if (psiFile != null) {
PsiNavigationSupport.getInstance().createNavigatable(project, vFile, psiFile.textLength).navigate(true)
}
}
}
else if (frame != null) {
val text = StringUtil.convertLineSeparators(if (file.exists()) FileUtil.loadFile(file) else template())
object : DialogWrapper(frame, true) {
private val editor: EditorTextField
init {
title = FileUtil.getLocationRelativeToUserHome(file.path)
setOKButtonText(IdeBundle.message("button.save"))
val document = EditorFactory.getInstance().createDocument(text)
val defaultProject = DefaultProjectFactory.getInstance().defaultProject
val fileType = FileTypeManager.getInstance().getFileTypeByFileName(file.name)
editor = object : EditorTextField(document, defaultProject, fileType, false, false) {
override fun createEditor(): EditorEx {
val editor = super.createEditor()
editor.scrollPane.verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
editor.scrollPane.horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
return editor
}
}
init()
}
override fun createCenterPanel() = editor
override fun getPreferredFocusedComponent() = editor
override fun getDimensionServiceKey() = "ide.config.custom.settings"
override fun doOKAction() {
val toSave = StringUtil.convertLineSeparators(editor.text, LineSeparator.getSystemLineSeparator().separatorString)
try {
FileUtil.writeToFile(file, toSave)
close(OK_EXIT_CODE)
}
catch (ex: IOException) {
Logger.getInstance(javaClass).warn(file.path, ex)
val message = IdeBundle.message("edit.custom.settings.failed", file, ex.message)
Messages.showErrorDialog(this.window, message, CommonBundle.message("title.error"))
}
}
}.show()
}
}
}
class EditCustomPropertiesAction : EditCustomSettingsAction() {
private companion object {
val file = lazy {
val dir = PathManager.getCustomOptionsDirectory()
return@lazy if (dir != null) File(dir, PathManager.PROPERTIES_FILE_NAME) else null
}
}
override fun file(): File? = EditCustomPropertiesAction.file.value
override fun template(): String = "# custom ${ApplicationNamesInfo.getInstance().fullProductName} properties\n\n"
class AccessExtension : NonProjectFileWritingAccessExtension {
override fun isWritable(file: VirtualFile): Boolean = FileUtil.pathsEqual(file.path, EditCustomPropertiesAction.file.value?.path)
}
}
class EditCustomVmOptionsAction : EditCustomSettingsAction() {
private companion object {
val file = lazy { VMOptions.getWriteFile() }
}
override fun file(): File? = EditCustomVmOptionsAction.file.value
override fun template(): String = "# custom ${ApplicationNamesInfo.getInstance().fullProductName} VM options\n\n${VMOptions.read() ?: ""}"
fun isEnabled(): Boolean = file() != null
class AccessExtension : NonProjectFileWritingAccessExtension {
override fun isWritable(file: VirtualFile): Boolean = FileUtil.pathsEqual(file.path, EditCustomVmOptionsAction.file.value?.path)
}
} | apache-2.0 | ca3f6e9890850956bfc23459ce500847 | 42.673333 | 140 | 0.718473 | 4.877141 | false | false | false | false |
Werb/MoreType | library/src/main/kotlin/com/werb/library/MoreAdapter.kt | 1 | 10552 | package com.werb.library
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import com.werb.library.action.DataAction
import com.werb.library.action.MoreClickListener
import com.werb.library.exception.ViewHolderInitErrorException
import com.werb.library.extension.AlphaAnimation
import com.werb.library.extension.AnimExtension
import com.werb.library.extension.MoreAnimation
import com.werb.library.link.*
import java.lang.ref.SoftReference
/**
* [MoreAdapter] build viewHolder with data
* Created by wanbo on 2017/7/2.
*/
class MoreAdapter : Adapter<MoreViewHolder<Any>>(), MoreLink, AnimExtension, DataAction, MoreOperation {
val list: MutableList<Any> = mutableListOf()
private val linkManager: MoreLinkManager by lazy { MoreLinkManager() }
private var allValuesInHolder = mapOf<String, Any>()
private var animation: MoreAnimation? = null
private var animDuration = 250L
private var startAnimPosition = 0
private var firstShow = false
private var lastAnimPosition = -1
private var linearInterpolator = LinearInterpolator()
private var recyclerViewSoft: SoftReference<RecyclerView>? = null
@Suppress("UNCHECKED_CAST")
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MoreViewHolder<Any> {
val viewHolderClass = createViewHolder(viewType)
val con = viewHolderClass.getConstructor(MutableMap::class.java, View::class.java)
val view = LayoutInflater.from(parent.context).inflate(viewType, parent, false)
var moreViewHolder: MoreViewHolder<Any>? = null
try {
val map = allValuesInHolder.plus(linkManager.getinjectValueWithHolder(viewType))
moreViewHolder = con.newInstance(map, view) as MoreViewHolder<Any>
} catch (e: Exception) {
e.printStackTrace()
if (moreViewHolder == null) {
throw ViewHolderInitErrorException(viewHolderClass.simpleName)
}
}
return moreViewHolder!!
}
override fun onBindViewHolder(holder: MoreViewHolder<Any>, position: Int) {
val any = list[position]
holder.clickListener = bindClickListener(holder)
holder.bindData(any)
}
override fun onBindViewHolder(holder: MoreViewHolder<Any>, position: Int, payloads: MutableList<Any>) {
if (payloads.isNotEmpty()) {
val any = list[position]
holder.clickListener = bindClickListener(holder)
holder.bindData(any, payloads)
} else {
onBindViewHolder(holder, position)
}
}
@Suppress("UNCHECKED_CAST")
override fun onViewRecycled(holder: MoreViewHolder<Any>) {
holder.unBindData()
}
fun attachTo(view: androidx.recyclerview.widget.RecyclerView): MoreLink {
view.adapter = this
recyclerViewSoft = SoftReference(view)
return this
}
fun getRecyclerView(): androidx.recyclerview.widget.RecyclerView? = recyclerViewSoft?.get()
fun injectValueInAllHolder(values: Map<String, Any>) {
this.allValuesInHolder = values
}
/*-------------------Data Start--------------------*/
@Suppress("UNCHECKED_CAST")
override fun refresh(index: Int, newData: Any, diffUtilClazz: Class<out XDiffCallback>) {
val newList = mutableListOf<Any>()
val fixList = list.subList(0, index)
val diff = diffUtilClazz.getConstructor(List::class.java, List::class.java)
newList.addAll(fixList)
if (newData is List<*>) {
newList.addAll(newData as Collection<Any>)
} else {
newList.add(newData)
}
val diffCallback = diff.newInstance(list, newList)
val diffResult = DiffUtil.calculateDiff(diffCallback)
list.clear()
list.addAll(newList)
recyclerViewSoft?.get()?.apply {
val state = this.layoutManager?.onSaveInstanceState()
diffResult.dispatchUpdatesTo(this@MoreAdapter)
this.layoutManager?.onRestoreInstanceState(state)
} ?: run {
diffResult.dispatchUpdatesTo(this@MoreAdapter)
}
}
override fun getDataIndex(data: Any): Int = list.indexOf(data)
@Suppress("UNCHECKED_CAST")
override fun loadData(data: Any) {
if (data is List<*>) {
var position = 0
if (list.size > 0) {
position = list.size
}
list.addAll(position, data as Collection<Any>)
recyclerViewSoft?.get()?.apply {
val state = this.layoutManager?.onSaveInstanceState()
notifyItemRangeInserted(position, data.size)
this.layoutManager?.onRestoreInstanceState(state)
} ?: run {
notifyItemRangeInserted(position, data.size)
}
} else {
list.add(data)
recyclerViewSoft?.get()?.apply {
val state = this.layoutManager?.onSaveInstanceState()
notifyItemInserted(itemCount - 1)
this.layoutManager?.onRestoreInstanceState(state)
} ?: run {
notifyItemInserted(itemCount - 1)
}
}
}
@Suppress("UNCHECKED_CAST")
override fun loadData(index: Int, data: Any) {
if (data is List<*>) {
list.addAll(index, data as Collection<Any>)
recyclerViewSoft?.get()?.apply {
val state = this.layoutManager?.onSaveInstanceState()
notifyItemRangeInserted(index, data.size)
this.layoutManager?.onRestoreInstanceState(state)
} ?: run {
notifyItemRangeInserted(index, data.size)
}
} else {
list.add(index, data)
recyclerViewSoft?.get()?.apply {
val state = this.layoutManager?.onSaveInstanceState()
notifyItemInserted(index)
this.layoutManager?.onRestoreInstanceState(state)
} ?: run {
notifyItemInserted(index)
}
}
}
override fun getData(position: Int): Any = list[position]
override fun removeAllData() {
if (list.isNotEmpty()) {
list.clear()
notifyDataSetChanged()
}
}
override fun removeAllNotRefresh() {
list.clear()
}
override fun removeData(data: Any) {
val contains = list.contains(data)
if (contains) {
val index = list.indexOf(data)
removeData(index)
}
}
override fun removeData(position: Int) {
if (list.size == 0) {
return
}
if (position >= 0 && position <= list.size - 1) {
list.removeAt(position)
notifyItemRemoved(position)
}
}
override fun removeDataFromIndex(index: Int) {
val count = list.size
list.subList(index, list.size).clear()
notifyItemRangeRemoved(index, count)
}
override fun replaceData(position: Int, data: Any) {
list.removeAt(position)
list.add(position, data)
notifyItemChanged(position)
}
/*-------------------Data End--------------------*/
override fun getItemCount(): Int = list.size
override fun getItemViewType(position: Int): Int {
val any = list[position]
return attachViewTypeLayout(any)
}
override fun onViewAttachedToWindow(holder: MoreViewHolder<Any>) {
super.onViewAttachedToWindow(holder)
addAnimation(holder)
}
/** [renderWithAnimation] user default animation AlphaAnimation */
override fun renderWithAnimation(): MoreAdapter {
this.animation = AlphaAnimation()
return this
}
/** [renderWithAnimation] user custom animation */
override fun renderWithAnimation(animation: MoreAnimation): MoreAdapter {
this.animation = animation
return this
}
/** [addAnimation] addAnimation when view attached to windows */
override fun addAnimation(holder: MoreViewHolder<Any>) {
this.animation?.let {
if (holder.layoutPosition < startAnimPosition) {
return
}
if (!firstShow || holder.layoutPosition > lastAnimPosition) {
val animators = it.getItemAnimators(holder.itemView)
for (anim in animators) {
anim.setDuration(animDuration).start()
anim.interpolator = linearInterpolator
}
lastAnimPosition = holder.layoutPosition
}
}
}
/** [duration] set animation duration */
override fun duration(duration: Long): MoreAdapter {
this.animDuration = duration
return this
}
/** [firstShowAnim] set isShow animation when first display */
override fun firstShowAnim(firstShow: Boolean): MoreAdapter {
this.firstShow = firstShow
return this
}
/** [startAnimPosition] set animation start position */
override fun startAnimPosition(position: Int): MoreAdapter {
this.startAnimPosition = position
return this
}
/** [register] register viewType which single link with model */
override fun register(registerItem: RegisterItem) {
linkManager.register(registerItem)
}
override fun register(clazz: Class<out MoreViewHolder<*>>, clickListener: MoreClickListener?, injectValue: Map<String, Any>?) {
linkManager.register(clazz, clickListener, injectValue)
}
/** [multiRegister] multiRegister viewType like one2more case , user MultiLink to choose which one is we need */
override fun multiRegister(link: MultiLink<*>) {
linkManager.multiRegister(link)
}
/** [attachViewTypeLayout] find viewType layout by item of list */
override fun attachViewTypeLayout(any: Any): Int = linkManager.attachViewTypeLayout(any)
/** [createViewHolder] find viewType by layout */
override fun createViewHolder(type: Int): Class<out MoreViewHolder<*>> = linkManager.createViewHolder(type)
override fun bindClickListener(holder: MoreViewHolder<*>): MoreClickListener? = linkManager.bindClickListener(holder)
/** [userSoleRegister] register sole global viewType */
override fun userSoleRegister() = linkManager.userSoleRegister()
} | apache-2.0 | 551c821d8a51cfc607a8e8eddf6315e5 | 34.531987 | 131 | 0.636372 | 4.923938 | false | false | false | false |
JetBrains/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/ToggleAmendCommitOption.kt | 1 | 1561 | // 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 com.intellij.vcs.commit
import com.intellij.openapi.Disposable
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.ui.components.JBCheckBox
import com.intellij.vcs.commit.CommitSessionCounterUsagesCollector.CommitOption
import org.jetbrains.annotations.ApiStatus
import java.awt.event.KeyEvent
@ApiStatus.Internal
class ToggleAmendCommitOption(commitPanel: CheckinProjectPanel, parent: Disposable) : JBCheckBox(VcsBundle.message("commit.amend.commit")) {
private val project = commitPanel.project
private val amendCommitHandler = commitPanel.commitWorkflowHandler.amendCommitHandler
init {
mnemonic = KeyEvent.VK_M
toolTipText = VcsBundle.message("commit.tooltip.merge.this.commit.with.the.previous.one")
addActionListener {
amendCommitHandler.isAmendCommitMode = isSelected
CommitSessionCollector.getInstance(project).logCommitOptionToggled(CommitOption.AMEND, isSelected)
}
amendCommitHandler.addAmendCommitModeListener(object : AmendCommitModeListener {
override fun amendCommitModeToggled() {
isSelected = amendCommitHandler.isAmendCommitMode
}
}, parent)
}
companion object {
@JvmStatic
fun isAmendCommitOptionSupported(commitPanel: CheckinProjectPanel, amendAware: AmendCommitAware) =
!commitPanel.isNonModalCommit && amendAware.isAmendCommitSupported()
}
} | apache-2.0 | 93cfd8c2536b525576b0022b35e9279b | 41.216216 | 140 | 0.799488 | 4.847826 | false | false | false | false |
mikepenz/Android-Iconics | meteocons-typeface-library/src/main/java/com/mikepenz/iconics/typeface/library/meteoconcs/Meteoconcs.kt | 1 | 3650 | /*
* Copyright (c) 2020 Mike Penz
*
* 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.mikepenz.iconics.typeface.library.meteoconcs
import com.mikepenz.iconics.typeface.IIcon
import com.mikepenz.iconics.typeface.ITypeface
import java.util.LinkedList
@Suppress("EnumEntryName")
object Meteoconcs : ITypeface {
override val fontRes: Int
get() = R.font.meteocons_v1_1_1
override val characters: Map<String, Char> by lazy {
Icon.values().associate { it.name to it.character }
}
override val mappingPrefix: String
get() = "met"
override val fontName: String
get() = "Meteocons"
override val version: String
get() = "1.1.1"
override val iconCount: Int
get() = characters.size
override val icons: List<String>
get() = characters.keys.toCollection(LinkedList())
override val author: String
get() = "Alessio Atzeni"
override val url: String
get() = "http://www.alessioatzeni.com/meteocons/"
override val description: String
get() = "Meteocons is a set of weather icons, it containing 40+ icons available in PSD, " +
"CSH, EPS, SVG, Desktop font and Web font. All icon and updates are free and " +
"always will be."
override val license: String
get() = ""
override val licenseUrl: String
get() = ""
override fun getIcon(key: String): IIcon = Icon.valueOf(key)
enum class Icon constructor(override val character: Char) : IIcon {
met_windy_rain_inv('\ue800'),
met_snow_inv('\ue801'),
met_snow_heavy_inv('\ue802'),
met_hail_inv('\ue803'),
met_clouds_inv('\ue804'),
met_clouds_flash_inv('\ue805'),
met_temperature('\ue806'),
met_compass('\ue807'),
met_na('\ue808'),
met_celcius('\ue809'),
met_fahrenheit('\ue80a'),
met_clouds_flash_alt('\ue80b'),
met_sun_inv('\ue80c'),
met_moon_inv('\ue80d'),
met_cloud_sun_inv('\ue80e'),
met_cloud_moon_inv('\ue80f'),
met_cloud_inv('\ue810'),
met_cloud_flash_inv('\ue811'),
met_drizzle_inv('\ue812'),
met_rain_inv('\ue813'),
met_windy_inv('\ue814'),
met_sunrise('\ue815'),
met_sun('\ue816'),
met_moon('\ue817'),
met_eclipse('\ue818'),
met_mist('\ue819'),
met_wind('\ue81a'),
met_snowflake('\ue81b'),
met_cloud_sun('\ue81c'),
met_cloud_moon('\ue81d'),
met_fog_sun('\ue81e'),
met_fog_moon('\ue81f'),
met_fog_cloud('\ue820'),
met_fog('\ue821'),
met_cloud('\ue822'),
met_cloud_flash('\ue823'),
met_cloud_flash_alt('\ue824'),
met_drizzle('\ue825'),
met_rain('\ue826'),
met_windy('\ue827'),
met_windy_rain('\ue828'),
met_snow('\ue829'),
met_snow_alt('\ue82a'),
met_snow_heavy('\ue82b'),
met_hail('\ue82c'),
met_clouds('\ue82d'),
met_clouds_flash('\ue82e');
override val typeface: ITypeface by lazy { Meteoconcs }
}
}
| apache-2.0 | 2ee455289dd5a741513b22dda35a0e5a | 30.196581 | 99 | 0.592603 | 3.621032 | false | false | false | false |
allotria/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/integrate/AlienLocalChangeList.kt | 3 | 1113 | // Copyright 2000-2020 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.svn.integrate
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.LocalChangeList
import org.jetbrains.annotations.Nls
open class AlienLocalChangeList(private val myChanges: List<Change>, @Nls private var myName: String) : LocalChangeList() {
private var myComment: String? = ""
override fun getChanges(): Collection<Change> = myChanges
override fun getName(): String = myName
override fun setName(@Nls name: String) {
myName = name
}
override fun getComment(): String? = myComment
override fun setComment(comment: String?) {
myComment = comment
}
override fun isDefault(): Boolean = false
override fun isReadOnly(): Boolean = false
override fun setReadOnly(isReadOnly: Boolean) = throw UnsupportedOperationException()
override fun getData(): Any? = throw UnsupportedOperationException()
override fun copy(): LocalChangeList = throw UnsupportedOperationException()
}
| apache-2.0 | 588bf72b20cc1cb2759a87f6c208c166 | 34.903226 | 140 | 0.761006 | 4.676471 | false | false | false | false |
allotria/intellij-community | platform/platform-api/src/com/intellij/ide/util/PropertiesComponentEx.kt | 3 | 3466 | // 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 com.intellij.ide.util
import com.intellij.openapi.project.Project
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* @author yole
*/
private fun propComponent(project: Project?): PropertiesComponent {
return if (project == null) PropertiesComponent.getInstance() else PropertiesComponent.getInstance(project)
}
private fun propName(name: String?, thisRef: Any?, property: KProperty<*>): String {
return name
?: thisRef?.let { it::class.qualifiedName + "." + property.name }
?: error("Either name must be specified or the property must belong to a class")
}
private class PropertiesComponentIntProperty(
private val project: Project?,
private val name: String?,
private val defaultValue: Int
) : ReadWriteProperty<Any?, Int> {
override fun getValue(thisRef: Any?, property: KProperty<*>): Int {
return propComponent(project).getInt(propName(name, thisRef, property), defaultValue)
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) {
propComponent(project).setValue(propName(name, thisRef, property), value, defaultValue)
}
}
private class PropertiesComponentStringProperty(
private val project: Project?,
private val name: String?,
private val defaultValue: String
) : ReadWriteProperty<Any?, String> {
override fun getValue(thisRef: Any?, property: KProperty<*>): String {
return propComponent(project).getValue(propName(name, thisRef, property), defaultValue)
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
propComponent(project).setValue(propName(name, thisRef, property), value, defaultValue)
}
}
private class PropertiesComponentBooleanProperty(
private val project: Project?,
private val name: String?,
private val defaultValue: Boolean
) : ReadWriteProperty<Any?, Boolean> {
override fun getValue(thisRef: Any?, property: KProperty<*>): Boolean {
return propComponent(project).getBoolean(propName(name, thisRef, property), defaultValue)
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean) {
propComponent(project).setValue(propName(name, thisRef, property), value, defaultValue)
}
}
fun propComponentProperty(project: Project? = null, defaultValue: Int = 0): ReadWriteProperty<Any, Int> =
PropertiesComponentIntProperty(project, null, defaultValue)
fun propComponentProperty(project: Project? = null, name: String, defaultValue: Int = 0): ReadWriteProperty<Any?, Int> =
PropertiesComponentIntProperty(project, name, defaultValue)
fun propComponentProperty(project: Project? = null, defaultValue: String = ""): ReadWriteProperty<Any, String> =
PropertiesComponentStringProperty(project, null, defaultValue)
fun propComponentProperty(project: Project? = null, name: String, defaultValue: String = ""): ReadWriteProperty<Any?, String> =
PropertiesComponentStringProperty(project, name, defaultValue)
fun propComponentProperty(project: Project? = null, defaultValue: Boolean = false): ReadWriteProperty<Any, Boolean> =
PropertiesComponentBooleanProperty(project, null, defaultValue)
fun propComponentProperty(project: Project? = null, name: String, defaultValue: Boolean = false): ReadWriteProperty<Any?, Boolean> =
PropertiesComponentBooleanProperty(project, name, defaultValue)
| apache-2.0 | 400269cfb8bcefdb1f58f5513eb69efe | 41.268293 | 140 | 0.759088 | 4.621333 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/idea/IdeStarter.kt | 1 | 11327 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.idea
import com.intellij.diagnostic.*
import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector
import com.intellij.ide.*
import com.intellij.ide.customize.CommonCustomizeIDEWizardDialog
import com.intellij.ide.customize.CustomizeIDEWizardDialog
import com.intellij.ide.customize.CustomizeIDEWizardStepsProvider
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.lightEdit.LightEditService
import com.intellij.ide.plugins.DisabledPluginsState
import com.intellij.ide.plugins.PluginManagerConfigurable
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.PluginManagerMain
import com.intellij.ide.ui.customization.CustomActionsSchema
import com.intellij.notification.Notification
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.*
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.openapi.wm.impl.SystemDock
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.ui.AppUIUtil
import com.intellij.ui.mac.touchbar.TouchBarsManager
import com.intellij.util.PlatformUtils
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.concurrency.NonUrgentExecutor
import com.intellij.util.ui.accessibility.ScreenReader
import java.awt.EventQueue
import java.beans.PropertyChangeListener
import java.nio.file.Path
import javax.swing.JOptionPane
open class IdeStarter : ApplicationStarter {
companion object {
private var filesToLoad: List<Path> = emptyList()
private var wizardStepProvider: CustomizeIDEWizardStepsProvider? = null
@JvmStatic
fun openFilesOnLoading(value: List<Path>) {
filesToLoad = value
}
@JvmStatic
fun setWizardStepsProvider(provider: CustomizeIDEWizardStepsProvider) {
wizardStepProvider = provider
}
}
override fun isHeadless() = false
override fun getCommandName(): String? = null
final override fun getRequiredModality() = ApplicationStarter.NOT_IN_EDT
override fun main(args: List<String>) {
val app = ApplicationManagerEx.getApplicationEx()
assert(!app.isDispatchThread)
if (app.isLightEditMode && !app.isHeadlessEnvironment) {
// In a light mode UI is shown very quickly, tab layout requires ActionManager but it is forbidden to init ActionManager in EDT,
// so, preload
AppExecutorUtil.getAppExecutorService().execute {
ActionManager.getInstance()
}
}
val frameInitActivity = StartUpMeasurer.startMainActivity("frame initialization")
// Event queue should not be changed during initialization of application components.
// It also cannot be changed before initialization of application components because IdeEventQueue uses other
// application components. So it is proper to perform replacement only here.
// out of EDT
val windowManager = WindowManagerEx.getInstanceEx()
app.invokeLater {
runMainActivity("IdeEventQueue informing about WindowManager") {
IdeEventQueue.getInstance().setWindowManager(windowManager)
}
}
val lifecyclePublisher = app.messageBus.syncPublisher(AppLifecycleListener.TOPIC)
val isStandaloneLightEdit = PlatformUtils.getPlatformPrefix() == "LightEdit"
val needToOpenProject: Boolean
if (isStandaloneLightEdit) {
needToOpenProject = true
}
else {
frameInitActivity.runChild("app frame created callback") {
lifecyclePublisher.appFrameCreated(args)
}
// must be after appFrameCreated because some listeners can mutate state of RecentProjectsManager
if (app.isHeadlessEnvironment) {
needToOpenProject = false
}
else {
val willOpenProject = (args.isNotEmpty() || filesToLoad.isNotEmpty() || RecentProjectsManager.getInstance().willReopenProjectOnStart())
&& JetBrainsProtocolHandler.getCommand() == null
needToOpenProject = showWizardAndWelcomeFrame(lifecyclePublisher, willOpenProject)
}
frameInitActivity.end()
NonUrgentExecutor.getInstance().execute {
LifecycleUsageTriggerCollector.onIdeStart()
}
}
val project = when {
!needToOpenProject -> null
filesToLoad.isNotEmpty() -> ProjectUtil.tryOpenFiles(null, filesToLoad, "MacMenu")
args.isNotEmpty() -> loadProjectFromExternalCommandLine(args)
else -> null
}
lifecyclePublisher.appStarting(project)
if (needToOpenProject && project == null && !JetBrainsProtocolHandler.appStartedWithCommand()) {
val recentProjectManager = RecentProjectsManager.getInstance()
var openLightEditFrame = isStandaloneLightEdit
if (recentProjectManager.willReopenProjectOnStart()) {
if (recentProjectManager.reopenLastProjectsOnStart()) {
openLightEditFrame = false
}
else if (!isStandaloneLightEdit) {
WelcomeFrame.showIfNoProjectOpened()
}
}
if (openLightEditFrame) {
ApplicationManager.getApplication().invokeLater {
LightEditService.getInstance().showEditorWindow()
}
}
}
reportPluginErrors()
if (!app.isHeadlessEnvironment) {
postOpenUiTasks(app)
}
StartUpMeasurer.compareAndSetCurrentState(LoadingState.COMPONENTS_LOADED, LoadingState.APP_STARTED)
lifecyclePublisher.appStarted()
if (!app.isHeadlessEnvironment && PluginManagerCore.isRunningFromSources()) {
AppUIUtil.updateWindowIcon(JOptionPane.getRootFrame())
}
}
private fun showWizardAndWelcomeFrame(lifecyclePublisher: AppLifecycleListener, willOpenProject: Boolean): Boolean {
val doShowWelcomeFrame = if (willOpenProject) null else WelcomeFrame.prepareToShow()
// do not show Customize IDE Wizard [IDEA-249516]
val wizardStepProvider = wizardStepProvider
if (wizardStepProvider == null || System.getProperty("idea.show.customize.ide.wizard")?.toBoolean() != true) {
if (doShowWelcomeFrame == null) {
return true
}
ApplicationManager.getApplication().invokeLater {
doShowWelcomeFrame.run()
lifecyclePublisher.welcomeScreenDisplayed()
}
return false
}
// temporary until 211 release
val stepDialogName = System.getProperty("idea.temp.change.ide.wizard")
?: ApplicationInfoImpl.getShadowInstance().customizeIDEWizardDialog
ApplicationManager.getApplication().invokeLater {
val wizardDialog: CommonCustomizeIDEWizardDialog?
if (stepDialogName.isNullOrBlank()) {
wizardDialog = CustomizeIDEWizardDialog(wizardStepProvider, null, false, true)
}
else {
wizardDialog = try {
Class.forName(stepDialogName).getConstructor(StartupUtil.AppStarter::class.java)
.newInstance(null) as CommonCustomizeIDEWizardDialog
}
catch (e: Throwable) {
Main.showMessage(BootstrapBundle.message("bootstrap.error.title.configuration.wizard.failed"), e)
null
}
}
wizardDialog?.showIfNeeded()
if (doShowWelcomeFrame != null) {
doShowWelcomeFrame.run()
lifecyclePublisher.welcomeScreenDisplayed()
}
}
return false
}
}
private fun loadProjectFromExternalCommandLine(commandLineArgs: List<String>): Project? {
val currentDirectory = System.getenv(SocketLock.LAUNCHER_INITIAL_DIRECTORY_ENV_VAR)
@Suppress("SSBasedInspection")
Logger.getInstance("#com.intellij.idea.ApplicationLoader").info("ApplicationLoader.loadProject (cwd=${currentDirectory})")
val result = CommandLineProcessor.processExternalCommandLine(commandLineArgs, currentDirectory)
if (result.hasError) {
ApplicationManager.getApplication().invokeAndWait {
result.showErrorIfFailed()
ApplicationManager.getApplication().exit(true, true, false)
}
}
return result.project
}
private fun postOpenUiTasks(app: Application) {
if (SystemInfoRt.isMac) {
NonUrgentExecutor.getInstance().execute {
runActivity("mac touchbar on app init") {
TouchBarsManager.onApplicationInitialized()
if (TouchBarsManager.isTouchBarAvailable()) {
CustomActionsSchema.addSettingsGroup(IdeActions.GROUP_TOUCHBAR, IdeBundle.message("settings.menus.group.touch.bar"))
}
}
}
}
else if (SystemInfoRt.isXWindow && SystemInfo.isJetBrainsJvm) {
NonUrgentExecutor.getInstance().execute {
runActivity("input method disabling on Linux") {
disableInputMethodsIfPossible()
}
}
}
invokeLaterWithAnyModality("system dock menu") {
SystemDock.updateMenu()
}
invokeLaterWithAnyModality("ScreenReader") {
val generalSettings = GeneralSettings.getInstance()
generalSettings.addPropertyChangeListener(GeneralSettings.PROP_SUPPORT_SCREEN_READERS, app, PropertyChangeListener { e ->
ScreenReader.setActive(e.newValue as Boolean)
})
ScreenReader.setActive(generalSettings.isSupportScreenReaders)
}
}
private fun invokeLaterWithAnyModality(name: String, task: () -> Unit) {
EventQueue.invokeLater {
runActivity(name, task = task)
}
}
private fun reportPluginErrors() {
val pluginErrors = PluginManagerCore.getAndClearPluginLoadingErrors()
if (pluginErrors.isEmpty()) {
return
}
ApplicationManager.getApplication().invokeLater({
val title = IdeBundle.message("title.plugin.error")
val content = HtmlBuilder().appendWithSeparators(HtmlChunk.p(), pluginErrors).toString()
Notification(NotificationGroup.createIdWithTitle("Plugin Error", title), title, content, NotificationType.ERROR) { notification, event ->
notification.expire()
val description = event.description
if (PluginManagerCore.EDIT == description) {
PluginManagerConfigurable.showPluginConfigurable(
WindowManagerEx.getInstanceEx().findFrameFor(null)?.component,
null,
emptyList(),
)
return@Notification
}
if (PluginManagerCore.ourPluginsToDisable != null && PluginManagerCore.DISABLE == description) {
DisabledPluginsState.enablePluginsById(PluginManagerCore.ourPluginsToDisable, false)
}
else if (PluginManagerCore.ourPluginsToEnable != null && PluginManagerCore.ENABLE == description) {
DisabledPluginsState.enablePluginsById(PluginManagerCore.ourPluginsToEnable, true)
@Suppress("SSBasedInspection")
PluginManagerMain.notifyPluginsUpdated(null)
}
PluginManagerCore.ourPluginsToEnable = null
PluginManagerCore.ourPluginsToDisable = null
}.notify(null)
}, ModalityState.NON_MODAL)
} | apache-2.0 | 3bc266bf175079deb84be89d582a58de | 37.4 | 143 | 0.743357 | 5.00973 | false | false | false | false |
bitsydarel/DBWeather | app/src/main/java/com/dbeginc/dbweather/newspaperdetail/NewsPaperDetailActivity.kt | 1 | 5974 | /*
* Copyright (C) 2017 Darel Bitsy
* 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.dbeginc.dbweather.newspaperdetail
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.databinding.DataBindingUtil
import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import com.dbeginc.dbweather.R
import com.dbeginc.dbweather.base.BaseActivity
import com.dbeginc.dbweather.databinding.ActivityNewsPaperDetailBinding
import com.dbeginc.dbweather.utils.utility.NEWSPAPER_KEY
import com.dbeginc.dbweather.utils.utility.snack
import com.dbeginc.dbweathercommon.utils.RequestState
import com.dbeginc.dbweathercommon.view.MVMPVView
import com.dbeginc.dbweathernews.managenewspapers.ManageNewsPapersViewModel
import com.dbeginc.dbweathernews.newspaperdetail.NewsPaperDetailViewModel
import com.dbeginc.dbweathernews.viewmodels.NewsPaperModel
class NewsPaperDetailActivity : BaseActivity(), MVMPVView {
private lateinit var binding: ActivityNewsPaperDetailBinding
private var toolbarMenu: Menu? = null
private var newspaperStateBackup: NewsPaperModel? = null
private val viewModel: NewsPaperDetailViewModel by lazy {
return@lazy ViewModelProviders.of(this, factory.get())[NewsPaperDetailViewModel::class.java]
}
private val managerViewModel: ManageNewsPapersViewModel by lazy {
return@lazy ViewModelProviders.of(this, factory.get())[ManageNewsPapersViewModel::class.java]
}
override val stateObserver: Observer<RequestState> = Observer {
onStateChanged(state = it!!)
}
private val newsPaperDetailObserver: Observer<NewsPaperModel> = Observer { newData ->
newData?.let {
binding.newsPaper = it
toolbarMenu?.findItem(R.id.newsPaperSubscriptionStatus)?.setIcon(
if (it.subscribed) R.drawable.ic_follow_icon_red
else R.drawable.ic_un_follow_icon_black
)
binding.executePendingBindings()
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.activity_newspaper_detail_menu, menu)
toolbarMenu = menu
return true
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
binding.newsPaper?.let {
menu.findItem(R.id.newsPaperSubscriptionStatus)?.setIcon(
if (it.subscribed) R.drawable.ic_follow_icon_red
else R.drawable.ic_un_follow_icon_black
)
menu.findItem(R.id.newsPaperLanguage)?.title = it.language
}
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.newsPaperSubscriptionStatus -> {
newspaperStateBackup = binding.newsPaper?.copy()
binding.newsPaper?.run {
subscribed = !subscribed
managerViewModel.subscribeTo(this)
item.setIcon(if (subscribed) R.drawable.ic_follow_icon_red else R.drawable.ic_un_follow_icon_black)
}
}
}
return true
}
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_news_paper_detail)
binding.newsPaper = if (savedState == null) intent.getParcelableExtra(NEWSPAPER_KEY)
else savedState.getParcelable(NEWSPAPER_KEY)
setSupportActionBar(binding.newsPaperDetailToolbar)
}
override fun onStart() {
super.onStart()
viewModel.getRequestState().observe(this, stateObserver)
viewModel.getNewsPaperDetail().observe(this, newsPaperDetailObserver)
binding.newsPaperDetailToolbar.setNavigationOnClickListener {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) finishAfterTransition()
else finish()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putParcelable(NEWSPAPER_KEY, binding.newsPaper)
}
override fun setupView() {
binding.newsPaperDetailToolbar.setNavigationOnClickListener {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) finishAfterTransition()
else finish()
}
binding.newsPaper?.let {
viewModel.loadNewsPaperDetail(name = it.name)
}
}
override fun onStateChanged(state: RequestState) {
when (state) {
RequestState.LOADING -> return
RequestState.COMPLETED -> newspaperStateBackup = null
RequestState.ERROR -> {
newspaperStateBackup?.let { backup ->
if (backup != binding.newsPaper) revertSubscriptionStatus(previousStatus = backup.subscribed)
}
binding.newsPaperDetailLayout.snack(message = "Could complete your request, please retry")
}
}
}
private fun revertSubscriptionStatus(previousStatus: Boolean) {
binding.newsPaper?.subscribed = previousStatus
toolbarMenu?.findItem(R.id.newsPaperSubscriptionStatus)
?.setIcon(
if (previousStatus) R.drawable.ic_follow_icon_red
else R.drawable.ic_un_follow_icon_black
)
}
}
| gpl-3.0 | ae11ee7b5266b3a27153fb1b93f6d5e4 | 33.732558 | 119 | 0.67844 | 4.613127 | false | false | false | false |
zdary/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensions/maven/MavenProjectModuleProvider.kt | 1 | 2477 | package com.jetbrains.packagesearch.intellij.plugin.extensions.maven
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.jetbrains.packagesearch.intellij.plugin.extensibility.BuildSystemType.MAVEN
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleProvider
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
import org.jetbrains.idea.maven.navigator.MavenNavigationUtil
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.utils.MavenUtil
internal class MavenProjectModuleProvider : ProjectModuleProvider {
override fun obtainAllProjectModulesFor(project: Project): Sequence<ProjectModule> =
ModuleManager.getInstance(project).modules.asSequence()
.flatMap { obtainProjectModulesFor(project, it) }
.distinct()
private fun obtainProjectModulesFor(project: Project, module: Module): Sequence<ProjectModule> {
if (!MavenUtil.isMavenModule(module)) {
return emptySequence()
}
val mavenManager = MavenProjectsManager.getInstance(project)
val mavenProject = mavenManager.findProject(module) ?: return emptySequence()
return sequenceOf(
ProjectModule(
name = module.name,
nativeModule = module,
parent = null,
buildFile = mavenProject.file,
buildSystemType = MAVEN,
moduleType = MavenProjectModuleType
).apply {
getNavigatableDependency = createNavigatableDependencyCallback(project, mavenProject)
}
)
}
private fun createNavigatableDependencyCallback(project: Project, mavenProject: MavenProject) =
{ groupId: String, artifactId: String, _: PackageVersion ->
val dependencyElement = mavenProject.findDependencies(groupId, artifactId)
.firstOrNull()
if (dependencyElement != null) {
MavenNavigationUtil.createNavigatableForDependency(
project,
mavenProject.file,
dependencyElement
)
} else {
null
}
}
}
| apache-2.0 | ead2d3952b3ecf18b2377ee415c7a696 | 40.983051 | 101 | 0.687929 | 5.642369 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/secondaryConstructors/generics.kt | 5 | 598 | internal open class B<T>(val x: T, val y: T) {
constructor(x: T): this(x, x)
override fun toString() = "$x#$y"
}
internal class A : B<String> {
constructor(): super("default")
constructor(x: String): super(x, "default")
}
fun box(): String {
val b1 = B("1", "2").toString()
if (b1 != "1#2") return "fail1: $b1"
val b2 = B("abc").toString()
if (b2 != "abc#abc") return "fail2: $b2"
val a1 = A().toString()
if (a1 != "default#default") return "fail3: $a1"
val a2 = A("xyz").toString()
if (a2 != "xyz#default") return "fail4: $a2"
return "OK"
}
| apache-2.0 | 88fb5ef51529e33a3e55d69d364b947c | 25 | 52 | 0.548495 | 2.743119 | false | false | false | false |
mpcjanssen/simpletask-android | app/src/main/java/nl/mpcjanssen/simpletask/AddTaskBackground.kt | 1 | 5065 | /**
* This file is part of Simpletask.
* Copyright (c) 2009-2012 Todo.txt contributors (http://todotxt.com)
* Copyright (c) 2013- Mark Janssen
* LICENSE:
* Todo.txt Touch is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any
* later version.
* Todo.txt Touch 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 Todo.txt Touch. If not, see
* //www.gnu.org/licenses/>.
* @author Mark Janssen
* *
* @license http://www.gnu.org/licenses/gpl.html
* *
* @copyright 2009-2012 Todo.txt contributors (http://todotxt.com)
* *
* @copyright 2013- Mark Janssen
*/
package nl.mpcjanssen.simpletask
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import nl.mpcjanssen.simpletask.task.Task
import nl.mpcjanssen.simpletask.task.TodoList
import nl.mpcjanssen.simpletask.util.Config
import nl.mpcjanssen.simpletask.util.showToastShort
import nl.mpcjanssen.simpletask.util.todayAsString
import java.io.IOException
class AddTaskBackground : Activity() {
val TAG = "AddTaskBackground"
public override fun onCreate(instance: Bundle?) {
Log.d(TAG, "onCreate()")
super.onCreate(instance)
val intent = intent
val action = intent.action
val append_text = TodoApplication.config.shareAppendText
if (intent.type?.startsWith("text/") ?: false) {
if (Intent.ACTION_SEND == action) {
Log.d(TAG, "Share")
var share_text = ""
if (TodoApplication.atLeastAPI(21) && intent.hasExtra(Intent.EXTRA_STREAM)) {
val uri = intent.extras?.get(Intent.EXTRA_STREAM) as Uri?
uri?.let {
try {
contentResolver.openInputStream(uri)?.let {
share_text = it.reader().readText()
it.close()
}
} catch (e: IOException) {
e.printStackTrace()
}
}
} else if (intent.hasExtra(Intent.EXTRA_TEXT)) {
val text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)
if (text != null) {
share_text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT).toString()
}
}
addBackgroundTask(share_text, append_text)
} else if ("com.google.android.gm.action.AUTO_SEND" == action) {
// Called as note to self from google search/now
noteToSelf(intent, append_text)
} else if (Constants.INTENT_BACKGROUND_TASK == action) {
Log.d(TAG, "Adding background task")
if (intent.hasExtra(Constants.EXTRA_BACKGROUND_TASK)) {
addBackgroundTask(intent.getStringExtra(Constants.EXTRA_BACKGROUND_TASK) ?: "", append_text)
} else {
Log.w(TAG, "Task was not in extras")
}
}
} else {
val imageUri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
imageUri?.let {
Log.i(TAG, "Added link to content: $imageUri")
addBackgroundTask(imageUri.toString(), append_text)
}
}
}
private fun noteToSelf(intent: Intent, append_text: String) {
val task = intent.getStringExtra(Intent.EXTRA_TEXT) ?: ""
if (intent.hasExtra(Intent.EXTRA_STREAM)) {
Log.d(TAG, "Voice note added.")
}
addBackgroundTask(task, append_text)
}
private fun addBackgroundTask(sharedText: String, appendText: String) {
val todoList = TodoApplication.todoList
todoList.reload("Background add")
Log.d(TAG, "Adding background tasks to todolist $todoList")
val rawLines = sharedText.split("\r\n|\r|\n".toRegex()).filterNot(String::isBlank)
val lines = if (appendText.isBlank()) { rawLines } else {
rawLines.map { "$it $appendText" }
}
val tasks = lines.map { text ->
if (TodoApplication.config.hasPrependDate) { Task(text, todayAsString) } else { Task(text) }
}
todoList.add(tasks, TodoApplication.config.hasAppendAtEnd)
todoList.notifyTasklistChanged(TodoApplication.config.todoFile, save = true, refreshMainUI = true)
showToastShort(TodoApplication.app, R.string.task_added)
if (TodoApplication.config.hasShareTaskShowsEdit) {
todoList.editTasks(this, tasks, "")
}
finish()
}
}
| gpl-3.0 | a446af7280b618c14e0a9032c32d211d | 38.570313 | 119 | 0.603751 | 4.439089 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/arrays/kt7288.kt | 4 | 801 | fun test(b: Boolean): String {
val a = if (b) IntArray(5) else LongArray(5)
if (a is IntArray) {
val x = a.iterator()
var i = 0
while (x.hasNext()) {
if (a[i] != x.next()) return "Fail $i"
i++
}
return "OK"
} else if (a is LongArray) {
val x = a.iterator()
var i = 0
while (x.hasNext()) {
if (a[i] != x.next()) return "Fail $i"
i++
}
return "OK"
}
return "fail"
}
fun box(): String {
// Only run this test if primitive array `is` checks work (KT-17137)
if ((intArrayOf() as Any) is Array<*>) return "OK"
if (test(true) != "OK") return "fail 1: ${test(true)}"
if (test(false) != "OK") return "fail 1: ${test(false)}"
return "OK"
} | apache-2.0 | a918631419cbb0b8fd23df466b4ccb82 | 24.0625 | 72 | 0.47191 | 3.309917 | false | true | false | false |
peterLaurence/TrekAdvisor | app/src/main/java/com/peterlaurence/trekme/core/sensors/OrientationSensor.kt | 1 | 2628 | package com.peterlaurence.trekme.core.sensors
import android.app.Activity
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.view.Surface
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
class OrientationSensor(val activity: Activity) : SensorEventListener {
private val sensorManager: SensorManager = activity.getSystemService(Context.SENSOR_SERVICE) as SensorManager
private val rotationVectorReading = FloatArray(3)
private val rotationMatrix = FloatArray(9)
private val orientationAngles = FloatArray(3)
var isStarted: Boolean = false
private set
fun getAzimuthFlow(): Flow<Float> = flow {
while (true) {
delay(1)
updateOrientation()
val screenRotation: Int = activity.windowManager.defaultDisplay.rotation
var fix = 0
when (screenRotation) {
Surface.ROTATION_90 -> fix = 90
Surface.ROTATION_180 -> fix = 180
Surface.ROTATION_270 -> fix = 270
}
/* Get the azimuth value (orientation[0]) in degree */
val azimuth = (Math.toDegrees(orientationAngles[0].toDouble()) + 360 + fix).toFloat() % 360
emit(azimuth)
}
}.flowOn(Dispatchers.Default)
fun start() {
sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)?.also { sensor ->
sensorManager.registerListener(
this,
sensor,
SensorManager.SENSOR_DELAY_FASTEST
)
}
isStarted = true
}
fun stop() {
sensorManager.unregisterListener(this)
isStarted = false
}
fun toggle(): Boolean {
if (isStarted) stop() else start()
return isStarted
}
override fun onSensorChanged(event: SensorEvent) {
if (event.sensor.type == Sensor.TYPE_ROTATION_VECTOR) {
System.arraycopy(event.values, 0, rotationVectorReading, 0, rotationVectorReading.size)
}
}
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {
}
private fun updateOrientation() {
SensorManager.getRotationMatrixFromVector(rotationMatrix, rotationVectorReading)
/* Get the azimuth value (orientation[0]) in degree */
SensorManager.getOrientation(rotationMatrix, orientationAngles)
}
}
| gpl-3.0 | a49168c9ad7ab502d55f3f00028b5280 | 31.444444 | 113 | 0.661339 | 4.996198 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.