content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package aunmag.shooter.data
import aunmag.nightingale.audio.AudioSource
import aunmag.nightingale.utilities.UtilsAudio
val soundAmbiance = initializeSoundAmbiance()
val soundAtmosphere = initializeSoundAtmosphere()
val soundGameOver = initializeSoundGameOver()
private fun initializeSoundAmbiance(): AudioSource {
val sound = UtilsAudio.getOrCreateSoundOgg("sounds/ambiance/birds")
sound.setVolume(0.4f)
sound.setIsLooped(true)
return sound
}
private fun initializeSoundAtmosphere(): AudioSource {
val sound = UtilsAudio.getOrCreateSoundOgg("sounds/music/gameplay_atmosphere")
sound.setVolume(0.06f)
sound.setIsLooped(true)
return sound
}
private fun initializeSoundGameOver(): AudioSource {
val sound = UtilsAudio.getOrCreateSoundOgg("sounds/music/death")
sound.setVolume(0.6f)
return sound
}
| src/main/java/aunmag/shooter/data/Sounds.kt | 2735638386 |
/*
* 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.model.network.token
data class ERC20Tokens(
val tokens: List<ERCToken> = emptyList()
) | app/src/main/java/com/toshi/model/network/token/ERC20Tokens.kt | 2204452873 |
package com.fracturedskies.api.task
enum class TaskPriority {
LOWEST,
LOWER,
LOW,
BELOW_AVERAGE,
AVERAGE,
ABOVE_AVERAGE,
HIGH,
HIGHER,
HIGHEST
} | src/main/kotlin/com/fracturedskies/api/task/TaskPriority.kt | 2002065943 |
/*
* Copyright (c) 2017.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine.patterns
import nl.adaptivity.process.engine.*
import nl.adaptivity.process.processModel.configurableModel.activity
import nl.adaptivity.process.processModel.configurableModel.endNode
import nl.adaptivity.process.processModel.configurableModel.startNode
import org.junit.jupiter.api.DisplayName
@DisplayName("WASP4: Vertical modularisation (subprocesses)")
class WASP4: TraceTest(Companion) {
companion object : TraceTest.ConfigBase() {
override val modelData: ModelData = run {
val model = object : TestConfigurableModel("WASP4") {
val start1 by startNode
val ac1 by activity(start1)
val comp1 by object : ConfigurableCompositeActivity(ac1) {
val start2 by startNode
val ac2 by activity(start2)
val end2 by endNode(ac2)
}
val ac3 by activity(comp1)
val end by endNode(ac3)
}
val start2 = model.comp1.start2
val ac2 = model.comp1.ac2
val end2 = model.comp1.end2
val validTraces = with(model) {
trace {
(start1..ac1..start2..ac2) * (end2 % comp1)..ac3..end
}
}
val invalidTraces = with(model) {
trace {
ac1 or comp1 or start2 or ac2 or end2 or ac3 or end or
(start1..(comp1 or start2 or ac2 or end2 or ac3 or end or
((ac1..start2.opt) * (comp1 or end2 or ac3 or end or
(ac2..(comp1.opt % end2.opt)..end)))))
}
}
ModelData(model, validTraces, invalidTraces)
}
}
}
| ProcessEngine/core/src/jvmTest/kotlin/nl/adaptivity/process/engine/patterns/WASP4.kt | 2976904912 |
package de.westnordost.streetcomplete.quests.construction
import de.westnordost.streetcomplete.data.meta.ALL_ROADS
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.meta.SURVEY_MARK_KEY
import de.westnordost.streetcomplete.data.meta.toCheckDateString
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
import java.time.LocalDate
import java.util.*
class MarkCompletedConstructionMinorOrGeneric() : OsmFilterQuestType<Boolean>() {
override val elementFilter = """
ways with construction = yes or construction = minor
and (!opening_date or opening_date < today)
and older today -1 months
"""
override val commitMessage = "Determine whether construction is now completed"
override val wikiLink = "Tag:construction=yes"
override val icon = R.drawable.ic_quest_building_construction
override fun getTitle(tags: Map<String, String>): Int {
val isRoad = ALL_ROADS.contains(tags["construction"])
val isCycleway = tags["construction"] == "cycleway"
val isFootway = tags["construction"] == "footway"
val isBridge = tags["man_made"] == "bridge"
return when {
isRoad -> R.string.quest_construction_road_title
isCycleway -> R.string.quest_construction_cycleway_title
isFootway -> R.string.quest_construction_footway_title
isBridge -> R.string.quest_construction_bridge_title
else -> R.string.quest_construction_even_more_generic_title
}
}
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
if (answer) {
deleteTagsDescribingConstruction(changes) //includes deletion of construction=yes/minor
} else {
changes.addOrModify(SURVEY_MARK_KEY, LocalDate.now().toCheckDateString())
}
}
override val questTypeAchievements: List<QuestTypeAchievement>
get() = listOf()
}
| app/src/main/java/de/westnordost/streetcomplete/quests/construction/MarkCompletedConstructionMinorOrGeneric.kt | 431694131 |
/*
* (C) Copyright 2014 mjahnen <[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 me.jahnen.libaums.core.fs.fat32
import java.util.*
/**
* This class is responsible for generating valid 8.3 short names for any given
* long file name.
*
* @author mjahnen
* @see FatLfnDirectoryEntry
*
* @see FatDirectoryEntry
*/
internal object ShortNameGenerator {
/**
* See fatgen103.pdf from Microsoft for allowed characters.
*
* @param c
* The character to test.
* @return True if the character is allowed in an 8.3 short name.
*/
private fun isValidChar(c: Char): Boolean {
if (c in '0'..'9')
return true
return if (c in 'A'..'Z') true else c == '$' || c == '%' || c == '\'' || c == '-' || c == '_' || c == '@' || c == '~'
|| c == '`' || c == '!' || c == '(' || c == ')' || c == '{' || c == '}' || c == '^'
|| c == '#' || c == '&'
}
/**
*
* @param str
* The String to test.
* @return True if the String contains any invalid chars which are not
* allowed on 8.3 short names.
*/
private fun containsInvalidChars(str: String): Boolean {
val length = str.length
for (i in 0 until length) {
val c = str[i]
if (!isValidChar(c))
return true
}
return false
}
/**
* Replaces all invalid characters in an string with an underscore (_).
*
* @param str
* The string where invalid chars shall be replaced.
* @return The new string only containing valid chars.
*/
private fun replaceInvalidChars(str: String): String {
val length = str.length
val builder = StringBuilder(length)
for (i in 0 until length) {
val c = str[i]
if (isValidChar(c)) {
builder.append(c)
} else {
builder.append("_")
}
}
return builder.toString()
}
/**
* Generate the next possible hex part for using in SFN. We are using a
* similar approach as what Windows 2000 did.
*/
private fun getNextHexPart(hexPart: String, limit: Int): String? {
var hexValue = java.lang.Long.parseLong(hexPart, 16)
hexValue += 1
val tempHexString = java.lang.Long.toHexString(hexValue)
if (tempHexString.length <= limit) {
val sb = StringBuilder()
for (i in 0 until limit - tempHexString.length) {
sb.append("0")
}
return sb.toString() + tempHexString
}
return null
}
/**
* Generates an 8.3 short name for a given long file name. It creates a
* suffix at the end of the short name if there is already a existing entry
* in the directory with an equal short name.
*
* @param lfnName
* Long file name.
* @param existingShortNames
* The short names already existing in the directory.
* @return The generated short name.
*/
fun generateShortName(lfnName: String,
existingShortNames: Collection<ShortName>): ShortName {
var lfnName = lfnName
lfnName = lfnName.toUpperCase(Locale.ROOT).trim { it <= ' ' }
// remove leading periods
var i = 0
while (i < lfnName.length) {
if (lfnName[i] != '.')
break
i++
}
lfnName = lfnName.substring(i)
lfnName = lfnName.replace(" ", "")
var filenamePart: String
var extensionPart: String
val indexOfDot = lfnName.lastIndexOf(".")
if (indexOfDot == -1) {
// no extension
filenamePart = lfnName
extensionPart = ""
} else {
// has extension
filenamePart = lfnName.substring(0, indexOfDot)
extensionPart = lfnName.substring(indexOfDot + 1)
if (extensionPart.length > 3) {
extensionPart = extensionPart.substring(0, 3)
}
}
// remove invalid chars
if (containsInvalidChars(filenamePart)) {
filenamePart = replaceInvalidChars(filenamePart)
}
// remove invalid chars
if (containsInvalidChars(extensionPart)) {
extensionPart = replaceInvalidChars(extensionPart)
}
var filePrefix = filenamePart
when {
filenamePart.isEmpty() -> filePrefix = "__"
filenamePart.length == 1 -> filePrefix += "_"
filenamePart.length == 2 -> {
// Do nothing
}
filenamePart.length > 2 -> filePrefix = filenamePart.substring(0, 2)
}
var extSuffix = extensionPart
when {
extensionPart.isEmpty() -> extSuffix = "000"
extensionPart.length == 1 -> extSuffix = extensionPart + "00"
extensionPart.length == 2 -> extSuffix = extensionPart + "0"
}
var hexPart = "0000"
var tildeDigit = 0
var result = ShortName("$filePrefix$hexPart~$tildeDigit", extSuffix)
while (containShortName(existingShortNames, result)) {
val hexPartNullable = getNextHexPart(hexPart, 4)
if (hexPartNullable != null) {
hexPart = hexPartNullable
} else {
if (tildeDigit + 1 < 10) {
tildeDigit += 1
hexPart = "0000"
} else {
// This should not happen
break
}
}
result = ShortName("$filePrefix$hexPart~$tildeDigit", extSuffix)
}
return result
}
private fun containShortName(shortNames: Collection<ShortName>, shortName: ShortName): Boolean {
var contain = false
for (temp in shortNames) {
if (temp.string.equals(shortName.string, ignoreCase = true)) {
contain = true
break
}
}
return contain
}
}
| libaums/src/main/java/me/jahnen/libaums/core/fs/fat32/ShortNameGenerator.kt | 2548535984 |
package org.wordpress.android.fluxc.model.layouts
import com.wellsql.generated.GutenbergLayoutModelTable
import com.yarolegovich.wellsql.WellSql
import com.yarolegovich.wellsql.core.Identifiable
import com.yarolegovich.wellsql.core.annotation.Column
import com.yarolegovich.wellsql.core.annotation.PrimaryKey
import com.yarolegovich.wellsql.core.annotation.Table
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.network.rest.wpcom.site.GutenbergLayout
@Table
class GutenbergLayoutModel(
@PrimaryKey @Column private var id: Int = 0,
@Column var slug: String = "",
@Column var siteId: Int = 0, // Foreign key
@Column var title: String = "",
@Column var preview: String = "",
@Column(name = "PREVIEW_TABLET") var previewTablet: String = "",
@Column(name = "PREVIEW_MOBILE") var previewMobile: String = "",
@Column var content: String = "",
@Column(name = "DEMO_URL") var demoUrl: String = ""
) : Identifiable {
override fun getId() = id
override fun setId(id: Int) {
this.id = id
}
}
fun GutenbergLayout.transform(site: SiteModel) = GutenbergLayoutModel(
slug = slug,
siteId = site.id,
title = title,
preview = preview,
previewMobile = previewMobile,
previewTablet = previewTablet,
content = content,
demoUrl = demoUrl
)
fun GutenbergLayoutModel.transform(categories: List<GutenbergLayoutCategoryModel>) = GutenbergLayout(
slug = slug,
title = title,
preview = preview,
previewTablet = previewTablet,
previewMobile = previewMobile,
content = content,
demoUrl = demoUrl,
categories = categories.transform()
)
fun List<GutenbergLayout>.transform(site: SiteModel) = map { it.transform(site) }
fun getLayoutId(siteId: Int, layoutSlug: String): Int? = WellSql.select(GutenbergLayoutModel::class.java)
.where()
.equals(GutenbergLayoutModelTable.SITE_ID, siteId)
.equals(GutenbergLayoutModelTable.SLUG, layoutSlug)
.endWhere().asModel.firstOrNull()?.id
| fluxc/src/main/java/org/wordpress/android/fluxc/model/layouts/GutenbergLayoutModel.kt | 1923462572 |
package org.kantega.niagara.data
import io.vavr.collection.TreeMap
fun <K,V> TreeMap<K,V>.update(key:K, f:(V)->V, defaultValue:()->V):TreeMap<K,V> =
this.computeIfPresent(key,{_,v->f(v)})._2.computeIfAbsent(key,{ defaultValue()})._2 | niagara-data/src/main/kotlin/org/kantega/niagara/data/maps.kt | 3449741373 |
package com.stronganizer.android.data.source.remote
import android.arch.lifecycle.LiveData
import com.stronganizer.android.data.model.User
import com.stronganizer.android.data.source.UserDataSource
/**
* Created by valio_stoyanov on 8/5/17.
*/
class UserRemoteDataSource : UserDataSource {
override fun save(user: User) {
TODO("not implemented")
}
override fun update(user: User) {
TODO("not implemented")
}
override fun delete(user: User) {
TODO("not implemented")
}
override fun findById(id: Int): LiveData<User> {
TODO("not implemented")
}
override fun findAll(): LiveData<List<User>> {
TODO("not implemented")
}
} | Stronganizer/app/src/main/java/com/stronganizer/android/data/source/remote/UserRemoteDataSource.kt | 648287366 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
/*
* Copyright (c) 2011-2014 Glowstone - Tad Hardesty
* Copyright (c) 2010-2011 Lightstone - Graham Edgecombe
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.lanternpowered.server.network.query
import io.netty.buffer.ByteBuf
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.channel.socket.DatagramPacket
import org.lanternpowered.api.cause.causeOf
import org.lanternpowered.api.event.EventManager
import org.lanternpowered.server.event.LanternEventFactory
import org.lanternpowered.api.plugin.name
import org.lanternpowered.api.plugin.version
import org.lanternpowered.api.text.toPlain
import org.lanternpowered.api.world.WorldManager
import org.lanternpowered.server.network.SimpleRemoteConnection
import org.lanternpowered.server.util.future.thenAsync
import org.spongepowered.api.Platform
import org.spongepowered.api.event.server.query.QueryServerEvent
import java.net.InetSocketAddress
import java.nio.charset.StandardCharsets
import java.util.LinkedHashMap
/**
* Class for handling UDP packets according to the minecraft server query protocol.
*
* @see QueryServer
* @see [Protocol Specifications](http://wiki.vg/Query)
*/
internal class QueryHandler(
private val queryServer: QueryServer,
private val showPlugins: Boolean
) : SimpleChannelInboundHandler<DatagramPacket>() {
override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {
this.queryServer.server.logger.error("Error in query handling", cause)
}
override fun channelReadComplete(ctx: ChannelHandlerContext) {
ctx.flush()
}
override fun channelRead0(ctx: ChannelHandlerContext, msg: DatagramPacket) {
val buf = msg.content()
if (buf.readableBytes() < 7) {
return
}
val magic = buf.readUnsignedShort()
val type = buf.readByte()
val sessionId = buf.readInt()
if (magic != 0xFEFD) {
return
}
if (type == ACTION_HANDSHAKE) {
handleHandshake(ctx, msg, sessionId)
} else if (type == ACTION_STATS) {
if (buf.readableBytes() < 4) {
return
}
val token = buf.readInt()
if (this.queryServer.verifyChallengeToken(msg.sender(), token)) {
if (buf.readableBytes() == 4) {
handleFullStats(ctx, msg, sessionId)
} else {
handleBasicStats(ctx, msg, sessionId)
}
}
}
}
private fun handleHandshake(ctx: ChannelHandlerContext, packet: DatagramPacket, sessionId: Int) {
val challengeToken = this.queryServer.generateChallengeToken(packet.sender())
val out = ctx.alloc().buffer()
out.writeByte(ACTION_HANDSHAKE.toInt())
out.writeInt(sessionId)
out.writeString(challengeToken.toString())
ctx.write(DatagramPacket(out, packet.sender()))
}
private fun handleBasicStats(ctx: ChannelHandlerContext, packet: DatagramPacket, sessionId: Int) {
val sender = packet.sender()
this.queryServer.server.syncExecutor.submit {
val event = createBasicEvent(ctx.channel())
EventManager.post(event)
event
}.thenAsync(ctx.channel().eventLoop()) { event ->
val buf = ctx.alloc().buffer()
buf.write(event, sessionId)
ctx.write(DatagramPacket(buf, sender))
}
}
private fun createBasicEvent(channel: Channel): QueryServerEvent.Basic {
val server = this.queryServer.server
val connection = SimpleRemoteConnection.of(channel)
val cause = causeOf(connection)
val address = channel.localAddress() as InetSocketAddress
return LanternEventFactory.createQueryServerEventBasic(cause,
address, "SMP", worldName, server.motd.toPlain(),
server.maxPlayers, Int.MAX_VALUE, server.onlinePlayers.size, 0)
}
private fun ByteBuf.write(event: QueryServerEvent.Basic, sessionId: Int) {
writeByte(ACTION_STATS.toInt())
writeInt(sessionId)
writeString(event.motd)
writeString(event.gameType)
writeString(event.map)
writeString(event.playerCount.toString())
writeString(event.maxPlayerCount.toString())
writeShortLE(event.address.port)
writeString(event.address.hostString)
}
private fun handleFullStats(ctx: ChannelHandlerContext, packet: DatagramPacket, sessionId: Int) {
val sender = packet.sender()
this.queryServer.server.syncExecutor.submit {
val event = createFullEvent(ctx.channel())
EventManager.post(event)
event
}.thenAsync(ctx.channel().eventLoop()) { event ->
val buf = ctx.alloc().buffer()
buf.write(event, sessionId)
ctx.write(DatagramPacket(buf, sender))
}
}
private fun createFullEvent(channel: Channel): QueryServerEvent.Full {
val game = this.queryServer.server.game
val server = game.server
val platform: Platform = game.platform
val api = platform.getContainer(Platform.Component.API)
val impl = platform.getContainer(Platform.Component.IMPLEMENTATION)
val mc = platform.getContainer(Platform.Component.GAME)
val plugins = StringBuilder()
.append(impl.name)
.append(" ")
.append(impl.version)
.append(" on ")
.append(api.name)
.append(" ")
.append(api.version)
if (this.showPlugins) {
val containers = game.pluginManager.plugins.toMutableList()
containers.remove(api)
containers.remove(impl)
containers.remove(mc)
var delim = ':'
for (plugin in containers) {
plugins.append(delim).append(' ').append(plugin.name)
delim = ';'
}
}
val playerNames = server.onlinePlayers.map { it.name }
val connection = SimpleRemoteConnection.of(channel)
val cause = causeOf(connection)
val address = channel.localAddress() as InetSocketAddress
return LanternEventFactory.createQueryServerEventFull(cause, address, mutableMapOf<String, String>(), "MINECRAFT", "SMP",
worldName, server.motd.toPlain(), playerNames, plugins.toString(), mc.version, server.maxPlayers, Int.MAX_VALUE, playerNames.size, 0)
}
private fun ByteBuf.write(event: QueryServerEvent.Full, sessionId: Int) {
val data: MutableMap<String, String> = LinkedHashMap()
data["hostname"] = event.motd
data["gametype"] = event.gameType
data["game_id"] = event.gameId
data["version"] = event.version
data["plugins"] = event.plugins
data["map"] = event.map
data["numplayers"] = event.playerCount.toString()
data["maxplayers"] = event.maxPlayerCount.toString()
data["hostport"] = event.address.port.toString()
data["hostip"] = event.address.hostString
event.customValuesMap.entries.stream()
.filter { entry -> !data.containsKey(entry.key) }
.forEach { entry -> data[entry.key] = entry.value }
writeByte(ACTION_STATS.toInt())
writeInt(sessionId)
// constant: splitnum\x00\x80\x00
writeBytes(byteArrayOf(0x73, 0x70, 0x6C, 0x69, 0x74, 0x6E, 0x75, 0x6D, 0x00, 0x80.toByte(), 0x00))
for ((key, value) in data) {
writeString(key)
writeString(value)
}
writeByte(0)
// constant: \x01player_\x00\x00
writeBytes(byteArrayOf(0x01, 0x70, 0x6C, 0x61, 0x79, 0x65, 0x72, 0x5F, 0x00, 0x00))
for (player in event.players) {
writeString(player)
}
writeByte(0)
}
private val worldName: String
get() = WorldManager.worlds.firstOrNull()?.properties?.key?.formatted ?: "none"
companion object {
private const val ACTION_HANDSHAKE: Byte = 9
private const val ACTION_STATS: Byte = 0
private fun ByteBuf.writeString(str: String) {
writeBytes(str.toByteArray(StandardCharsets.UTF_8)).writeByte(0)
}
}
}
| src/main/kotlin/org/lanternpowered/server/network/query/QueryHandler.kt | 2424876872 |
package org.kwicket.agilecoders.wicket.core.ajax.markup.html.bootstrap.form
import de.agilecoders.wicket.core.markup.html.bootstrap.form.BootstrapForm
import de.agilecoders.wicket.core.markup.html.bootstrap.form.FormType
import org.apache.wicket.behavior.Behavior
import org.apache.wicket.markup.html.WebMarkupContainer
import org.apache.wicket.markup.html.form.validation.IFormValidator
import org.apache.wicket.model.IModel
import org.kwicket.component.init
import org.kwicket.component.q
@Deprecated(replaceWith = ReplaceWith("org.kwicket.agilecoders.queued.bootstrapForm"), message = "Use in different package")
fun <T> WebMarkupContainer.bootstrapForm(
id: String,
model: IModel<T>? = null,
type: FormType? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
behaviors: List<Behavior>? = null,
validators: List<IFormValidator>? = null
) = q(
KBootstrapForm(
id = id,
model = model,
type = type,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
behaviors = behaviors,
validators = validators
)
)
open class KBootstrapForm<T>(
id: String,
model: IModel<T>? = null,
type: FormType? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
behaviors: List<Behavior>? = null,
validators: List<IFormValidator>? = null
) : BootstrapForm<T>(id, model) {
init {
init(
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
behaviors = behaviors
)
type?.let { type(it) }
validators?.forEach { add(it) }
}
} | kwicket-wicket-bootstrap-core/src/main/kotlin/org/kwicket/agilecoders/wicket/core/ajax/markup/html/bootstrap/form/KBootstrapForm.kt | 3723651538 |
package net.gtaun.shoebill.streamer.event.obj
/**
* @author Marvin Haschker
*/
@net.gtaun.shoebill.streamer.AllOpen
class PlayerEditDynamicObjectEvent(obj: net.gtaun.shoebill.streamer.data.DynamicObject, val player: net.gtaun.shoebill.entities.Player,
val response: Int, val pos: net.gtaun.shoebill.data.Vector3D,
val rot: net.gtaun.shoebill.data.Vector3D) : DynamicObjectEvent(obj)
| src/main/java/net/gtaun/shoebill/streamer/event/obj/PlayerEditDynamicObjectEvent.kt | 2114125157 |
/*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package debop4k.core.utils
import debop4k.core.AbstractCoreKotlinTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
/**
* SystemsKotlinTest
* @author debop [email protected]
*/
class SystemsKotlinTest : AbstractCoreKotlinTest() {
@Test fun retrieveJavaSpecificationVersion() {
log.debug("java version={}, implementation={}", Systems.javaVersion, Systems.javaImplementationVersion)
log.debug("java vendor={}, implementation={}", Systems.javaVendor, Systems.javaImplementationVendor)
log.debug("Java6={}", Systems.isJava6)
log.debug("Java7={}", Systems.isJava7)
log.debug("Java8={}", Systems.isJava8)
}
@Test
fun loadSystemPropertiesFromJava() {
val props = System.getProperties()
for (key in props.keys) {
log.debug("key={}, value={}", key, props[key])
}
}
@Test
fun loadSystemProperties() {
val props = Systems.systemProps
assertThat(props).isNotNull()
assertThat(props.size).isGreaterThan(0)
for (key in props.keys) {
log.debug("key={}, value={}", key, props[key])
}
}
@Test
fun loadPropertiesByName() {
log.debug("java home={}", Systems.javaHome)
assertThat(Systems.javaHome).isNotEmpty().containsIgnoringCase("Java")
log.debug("temp dir={}", Systems.tempDir)
log.debug("file separator={}", Systems.fileSeparator)
assertThat(Systems.fileSeparator).isNotEmpty()
assertThat(Systems.pathSeparator).isNotEmpty()
assertThat(Systems.lineSeparator).isNotEmpty()
log.debug("java class version={}", Systems.javaClassVersion)
assertThat(Systems.javaClassVersion).isNotEmpty().contains("5")
}
} | debop4k-core/src/test/kotlin/debop4k/core/utils/SystemsKotlinTest.kt | 1000963302 |
/*
* Copyright 2015, 2017 Thomas Harning Jr. <[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 us.eharning.atomun.keygen.internal.spi.bip0032
import us.eharning.atomun.keygen.KeyGeneratorAlgorithm
import us.eharning.atomun.keygen.StandardKeyGeneratorAlgorithm
import us.eharning.atomun.keygen.spi.KeyGeneratorBuilderSpi
import us.eharning.atomun.keygen.spi.KeyGeneratorServiceProvider
import javax.annotation.concurrent.Immutable
/**
* Registration class to perform the necessary default service provider registrations.
*
* @since 0.0.1
*/
@Immutable
class BIP0044KeyGeneratorServiceProvider : KeyGeneratorServiceProvider() {
/**
* Obtain a key generator builder SPI for the given algorithm.
*
* @param algorithm
* mnemonic algorithm to try to retrieve.
*
* @return SPI instance for the given algorithm, else null.
*
* @since 0.0.1
*/
override fun getKeyGeneratorBuilder(algorithm: KeyGeneratorAlgorithm): KeyGeneratorBuilderSpi? {
if (algorithm !== StandardKeyGeneratorAlgorithm.BIP0044) {
return null
}
return BUILDER_SPI
}
companion object {
private val BUILDER_SPI = BIP0044KeyGeneratorBuilderSpi()
}
}
| src/main/java/us/eharning/atomun/keygen/internal/spi/bip0032/BIP0044KeyGeneratorServiceProvider.kt | 1875614120 |
package io.rover.sdk.experiences.ui.blocks.concerns.layout
import io.rover.sdk.core.data.domain.Block
import io.rover.sdk.core.data.domain.ButtonBlock
import io.rover.sdk.core.data.domain.Height
import io.rover.sdk.core.data.domain.HorizontalAlignment
import io.rover.sdk.core.data.domain.VerticalAlignment
import io.rover.sdk.experiences.logging.log
import io.rover.sdk.experiences.platform.whenNotNull
import io.rover.sdk.core.streams.PublishSubject
import io.rover.sdk.core.streams.share
import io.rover.sdk.experiences.ui.RectF
import io.rover.sdk.experiences.ui.layout.ViewType
import io.rover.sdk.experiences.ui.layout.screen.ScreenViewModel
import io.rover.sdk.experiences.ui.navigation.NavigateToFromBlock
/**
* A mixin used by all blocks that contains the block layout and positioning concerns.
*
* - LayoutableViewModel probably needs to split, because we want to be able to delegate the frame()
* method to the new mixin version of BlockViewModel but obviously it should not specify view type
*/
internal class BlockViewModel(
private val block: Block,
private val paddingDeflections: Set<LayoutPaddingDeflection> = emptySet(),
private val measurable: Measurable? = null
) : BlockViewModelInterface {
override val viewType: ViewType
get() = throw RuntimeException(
"When delegating BlockViewModelInterface to an instance of BlockViewModel, you must still implement viewType yourself."
)
override fun stackedHeight(bounds: RectF): Float {
val alignment = block.position.verticalAlignment
return when (alignment) {
is VerticalAlignment.Stacked -> {
this.height(bounds) + alignment.topOffset.toFloat() + alignment.bottomOffset.toFloat()
}
else -> 0.0f
}
}
override val insets: Insets
get() = Insets(
block.insets.top,
block.insets.left,
block.insets.bottom,
block.insets.right
)
override val padding: Padding
get() = (listOf(Padding(
block.insets.left,
block.insets.top,
block.insets.right,
block.insets.bottom
)) + paddingDeflections.map { it.paddingDeflection }).reduce { acc, next -> acc + next }
override val isStacked: Boolean
get() = block.position.verticalAlignment is VerticalAlignment.Stacked
override val opacity: Float
get() = block.opacity.toFloat()
override fun frame(bounds: RectF): RectF {
val x = x(bounds)
val y = y(bounds)
val width = width(bounds)
val height = height(bounds)
return RectF(
x,
y,
(width + x),
(y + height)
)
}
/**
* Computes the Block's height.
*/
fun height(bounds: RectF): Float {
val verticalAlignment = block.position.verticalAlignment
return when (verticalAlignment) {
is VerticalAlignment.Fill -> {
val top = verticalAlignment.topOffset
val bottom = verticalAlignment.bottomOffset
bounds.height() - top.toFloat() - bottom.toFloat()
}
is VerticalAlignment.Stacked, is VerticalAlignment.Middle, is VerticalAlignment.Bottom, is VerticalAlignment.Top -> {
// we use the Measured interface to get at the height field on all of the non-Fill types.
val height = (verticalAlignment as VerticalAlignment.Measured).height
when (height) {
is Height.Intrinsic -> {
val boundsConsideringInsets = RectF(
bounds.left + insets.left + paddingDeflections.map { it.paddingDeflection.left }.sum(),
bounds.top,
bounds.left + width(bounds) - insets.right - paddingDeflections.map { it.paddingDeflection.right }.sum(),
bounds.bottom
)
bounds.width()
// TODO: boundsConsideringInsets could go negative if the insets are bigger than the
// bounds, causing illegal/undefined behaviour further down the chain.
// https://github.com/RoverPlatform/rover/issues/1460
if (measurable == null) {
log.w("Block is set to auto-height but no measurable is given.")
0f
} else {
measurable.intrinsicHeight(boundsConsideringInsets) +
insets.bottom +
insets.top +
paddingDeflections.map {
it.paddingDeflection.top + it.paddingDeflection.bottom
}.sum()
}
}
is Height.Static -> {
height.value.toFloat()
}
}
}
}
}
/**
* Computes the Block's width.
*/
override fun width(bounds: RectF): Float {
val alignment = block.position.horizontalAlignment
return when (alignment) {
is HorizontalAlignment.Fill -> {
bounds.width() - alignment.leftOffset.toFloat() - alignment.rightOffset.toFloat()
}
is HorizontalAlignment.Right, is HorizontalAlignment.Center, is HorizontalAlignment.Left -> {
listOf((alignment as HorizontalAlignment.Measured).width.toFloat(), 0.0f).max()!!
}
}
}
private val eventSource = PublishSubject<BlockViewModelInterface.Event>()
override val events = eventSource.share()
override val isClickable: Boolean
get() = block is ButtonBlock || block.tapBehavior != Block.TapBehavior.None
override fun click() {
// I don't have an epic (any other asynchronous behaviour to compose) here, just a single
// event emitter, so I'll just publish an event directly.
val tapBehavior = block.tapBehavior
val navigateTo = when (tapBehavior) {
is Block.TapBehavior.GoToScreen -> { NavigateToFromBlock.GoToScreenAction(tapBehavior.screenId, block) }
is Block.TapBehavior.OpenUri -> { NavigateToFromBlock.External(tapBehavior.uri, block) }
is Block.TapBehavior.PresentWebsite -> { NavigateToFromBlock.PresentWebsiteAction(tapBehavior.url, block) }
is Block.TapBehavior.None -> { NavigateToFromBlock.None(block) }
is Block.TapBehavior.Custom -> { NavigateToFromBlock.Custom(block) }
}
navigateTo.whenNotNull {
eventSource.onNext(
BlockViewModelInterface.Event.Clicked(it, block.id)
)
}
}
override fun touched() {
eventSource.onNext(
BlockViewModelInterface.Event.Touched(block.id)
)
}
override fun released() {
eventSource.onNext(
BlockViewModelInterface.Event.Released(block.id)
)
}
/**
* Computes the Block's absolute horizontal coordinate in the [ScreenViewModel]'s coordinate
* space.
*/
private fun x(bounds: RectF): Float {
val width = width(bounds)
val alignment = block.position.horizontalAlignment
return when (alignment) {
is HorizontalAlignment.Center -> bounds.left + ((bounds.width() - width) / 2) + alignment.offset.toFloat()
is HorizontalAlignment.Fill -> bounds.left + alignment.leftOffset.toFloat()
is HorizontalAlignment.Left -> bounds.left + alignment.offset.toFloat()
is HorizontalAlignment.Right -> bounds.right - width - alignment.offset.toFloat()
}
}
/**
* Computes the Block's absolute vertical coordinate in the [ScreenViewModel]'s coordinate
* space.
*/
private fun y(bounds: RectF): Float {
val height = height(bounds)
val alignment = block.position.verticalAlignment
return when (alignment) {
is VerticalAlignment.Bottom -> bounds.bottom - height - alignment.offset.toFloat()
is VerticalAlignment.Fill -> bounds.top + alignment.topOffset.toFloat()
is VerticalAlignment.Top -> bounds.top + alignment.offset.toFloat()
is VerticalAlignment.Middle -> bounds.top + ((bounds.height() - height) / 2) + alignment.offset.toFloat()
is VerticalAlignment.Stacked -> bounds.top + alignment.topOffset.toFloat()
}
}
}
| experiences/src/main/kotlin/io/rover/sdk/experiences/ui/blocks/concerns/layout/BlockViewModel.kt | 1450884285 |
package voice.folderPicker.selectType
import androidx.annotation.StringRes
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Card
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import voice.common.compose.VoiceTheme
import voice.data.folders.FolderType
import voice.folderPicker.FolderTypeIcon
import voice.folderPicker.R
@Composable
internal fun FolderModeSelectionCard(
onFolderModeSelected: (FolderMode) -> Unit,
selectedFolderMode: FolderMode,
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
) {
Column(
modifier = Modifier.padding(top = 8.dp, bottom = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
FolderMode.values().forEach { folderMode ->
val selectFolder = { onFolderModeSelected(folderMode) }
FolderModeColumn(selectFolder = selectFolder, selectedFolderMode = selectedFolderMode, folderMode = folderMode)
}
}
}
}
@Composable
private fun FolderModeColumn(
selectedFolderMode: FolderMode,
folderMode: FolderMode,
selectFolder: () -> Unit,
) {
Row(
modifier = Modifier
.clickable(onClick = selectFolder)
.padding(end = 24.dp, start = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
RadioButton(
selected = selectedFolderMode == folderMode,
onClick = selectFolder,
)
Spacer(Modifier.size(16.dp))
Text(
text = stringResource(id = folderMode.title()),
modifier = Modifier
.weight(1F)
.padding(vertical = 8.dp),
)
FolderTypeIcon(
folderType = when (folderMode) {
FolderMode.Audiobooks -> FolderType.Root
FolderMode.SingleBook -> FolderType.SingleFolder
},
)
}
}
@StringRes
private fun FolderMode.title(): Int {
return when (this) {
FolderMode.Audiobooks -> R.string.folder_mode_root
FolderMode.SingleBook -> R.string.folder_mode_single
}
}
@Composable
@Preview
private fun FolderModeSelectionCardPreview() {
VoiceTheme {
FolderModeSelectionCard(
onFolderModeSelected = {},
selectedFolderMode = FolderMode.Audiobooks,
)
}
}
| folderPicker/src/main/kotlin/voice/folderPicker/selectType/FolderModeSelectionCard.kt | 2332074314 |
package voice.data.repo.internals.migrations
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.squareup.anvil.annotations.ContributesMultibinding
import voice.common.AppScope
import javax.inject.Inject
@ContributesMultibinding(
scope = AppScope::class,
boundType = Migration::class,
)
class Migration39to40
@Inject constructor() : IncrementalMigration(39) {
private val BOOK_TABLE_NAME = "tableBooks"
private val BOOK_TIME = "bookTime"
override fun migrate(db: SupportSQLiteDatabase) {
val positionZeroContentValues = ContentValues().apply {
put(BOOK_TIME, 0)
}
db.update(
BOOK_TABLE_NAME,
SQLiteDatabase.CONFLICT_FAIL,
positionZeroContentValues,
"$BOOK_TIME < ?",
arrayOf(0),
)
}
}
| data/src/main/kotlin/voice/data/repo/internals/migrations/Migration39to40.kt | 3028515941 |
package com.nikita.movies_shmoovies.movies
import com.nikita.movies_shmoovies.common.network.MoviesService
import com.nikita.movies_shmoovies.movies.adapters.RecyclerItem
import com.nikita.movies_shmoovies.movies.adapters.RegularItem
import kotlinx.coroutines.experimental.async
interface MovieInfoInteractor {
fun getMovieInformation(id: String): MovieInformation
}
data class MovieInformation(val movieDetails: MovieDetails, val crewAndCast: CrewAndCast){
data class MovieDetails(val original_title: String,
val backdrop_path: String?,
val poster_path: String?,
val overview: String,
val budget: Int,
val revenue: Int,
val runtime: Int,
val release_date: String,
val status: String,
val homepage: String,
val genres: List<Genre>?,
val vote_average: Float) {
data class Genre(val name: String) : RegularItem
}
data class CrewAndCast(val cast: List<Cast>?,
val crew: List<Crew>?){
data class Cast(val character: String,
val name: String,
val profile_path: String,
val id: Int) : RegularItem
data class Crew(val name: String,
val job: String) : RegularItem
}
}
class MoviesInfoInteractor(val moviesService: MoviesService) : MovieInfoInteractor {
override fun getMovieInformation(id: String): MovieInformation {
return MovieInformation(getMovieDetails(id), getMovieCredits(id))
}
fun getMovieDetails(id: String): MovieInformation.MovieDetails {
return moviesService.getMovieDetails(id)
}
fun getMovieCredits(id: String): MovieInformation.CrewAndCast {
return moviesService.getMovieCredits(id)
}
} | app/src/main/kotlin/com/nikita/movies_shmoovies/movies/MoviesInfoInteractor.kt | 1930978468 |
package com.nikita.movies_shmoovies.movies.adapters
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.TextView
import com.nikita.movies_shmoovies.R
import com.nikita.movies_shmoovies.common.utils.findView
interface RecyclerItem
interface ErrorItem : RecyclerItem
interface RegularItem : RecyclerItem
class ErrorHolder(view: View) : RecyclerView.ViewHolder(view) {
val errorTxt = view.findView<TextView>(R.id.error_item)
}
data class ErrorContent(val errorTxt: String) : ErrorItem
| app/src/main/kotlin/com/nikita/movies_shmoovies/movies/adapters/ErrorHolder.kt | 3075828194 |
package org.videolan.vlc.gui
import android.content.Intent
import android.widget.EditText
import androidx.test.espresso.Espresso
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.contrib.DrawerActions.open
import androidx.test.espresso.matcher.RootMatchers.isPlatformPopup
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.rule.ActivityTestRule
import com.google.android.material.internal.NavigationMenuItemView
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.ObsoleteCoroutinesApi
import org.hamcrest.Matchers.*
import org.junit.After
import org.junit.Rule
import org.junit.Test
import org.videolan.medialibrary.interfaces.Medialibrary
import org.videolan.vlc.*
import org.videolan.vlc.gui.dialogs.SavePlaylistDialog
import org.videolan.tools.CoroutineContextProvider
import org.videolan.resources.EXTRA_TARGET
import org.videolan.vlc.util.TestCoroutineContextProvider
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
class PlaylistFragmentUITest: BaseUITest() {
@Rule
@JvmField
val activityTestRule = ActivityTestRule(MainActivity::class.java, true, false)
lateinit var activity: MainActivity
override fun beforeTest() {
SavePlaylistDialog.overrideCreator = false
SavePlaylistDialog.registerCreator(clazz = CoroutineContextProvider::class.java) { TestCoroutineContextProvider() }
val intent = Intent().apply {
putExtra(EXTRA_TARGET, R.id.nav_playlists)
}
activityTestRule.launchActivity(intent)
activity = activityTestRule.activity
}
@After
fun resetData() {
Medialibrary.getInstance().playlists.map { it.delete() }
}
private fun createDummyPlaylist() {
val ml = Medialibrary.getInstance()
val pl = ml.createPlaylist(DUMMY_PLAYLIST)
pl.append(ml.getPagedVideos(Medialibrary.SORT_DEFAULT, false, 5, 0).map { it.id })
pl.append(ml.getPagedAudio(Medialibrary.SORT_DEFAULT, false, 5, 0).map { it.id })
}
@Test
fun whenNoMedia_checkListEmpty() {
onView(withId(R.id.audio_list))
.check(matches(withCount(equalTo(0))))
}
@Test
fun whenPlaylistAddedFromDirectoriesView_checkPlaylistUpdated() {
// Navigate to directories view
onView(withId(R.id.root_container))
.perform(open())
onView(allOf(instanceOf(NavigationMenuItemView::class.java), hasDescendant(withText(R.string.directories))))
.check(matches(isDisplayed()))
.perform(click())
// Add Internal Storage to playlist
onView(withRecyclerView(R.id.network_list).atPosition(3))
.perform(longClick())
openActionBarOverflowOrOptionsMenu(context)
onView(allOf(isDescendantOfA(withId(R.id.dialog_playlist_name)), instanceOf(EditText::class.java)))
.perform(click(), typeTextIntoFocusedView("storage"))
onView(withId(R.id.dialog_playlist_save))
.perform(click())
// Navigate back to playlists view
onView(withId(R.id.root_container))
.perform(open())
onView(allOf(instanceOf(NavigationMenuItemView::class.java), hasDescendant(withText(R.string.playlists))))
.check(matches(isDisplayed()))
.perform(click())
onView(withId(R.id.audio_list))
.check(matches(withCount(equalTo(1))))
onView(withRecyclerView(R.id.audio_list).atPosition(0))
.check(matches(hasDescendant(withText("storage"))))
}
@Test
fun whenOnePlaylist_checkCardDetails() {
createDummyPlaylist()
Thread.sleep(2000)
onView(withId(R.id.audio_list))
.check(matches(sizeOfAtLeast(1)))
// Section Header should be T
// onView(withId(R.id.section_header))
// .check(matches(withText(DUMMY_PLAYLIST[0].toString().toUpperCase())))
val rvMatcher = withRecyclerView(R.id.audio_list)
onView(rvMatcher.atPositionOnView(0, R.id.title))
.check(matches(withText(DUMMY_PLAYLIST)))
onView(rvMatcher.atPositionOnView(0, R.id.subtitle))
.check(matches(withText("1 tracks")))
}
@Test
fun whenOnePlaylist_checkContextMenuWorks() {
createDummyPlaylist()
Thread.sleep(1500)
onView(withId(R.id.audio_list))
.check(matches(sizeOfAtLeast(1)))
val rvMatcher = withRecyclerView(R.id.audio_list)
onView(rvMatcher.atPositionOnView(0, R.id.item_more))
.perform(click())
assertThat(activity.supportFragmentManager.findFragmentByTag("context"), notNullValue())
onView(withId(R.id.ctx_list))
.check(matches(isDisplayed()))
.check(matches(sizeOfAtLeast(5)))
.check(matches(hasDescendant(withText(R.string.play))))
.check(matches(hasDescendant(withText(R.string.append))))
.check(matches(hasDescendant(withText(R.string.insert_next))))
.check(matches(hasDescendant(withText(R.string.add_to_playlist))))
.check(matches(hasDescendant(withText(R.string.delete))))
}
@Test
fun whenOnePlaylist_checkLongPressWorks() {
createDummyPlaylist()
Thread.sleep(1500)
onView(withId(R.id.audio_list))
.check(matches(sizeOfAtLeast(1)))
val rvMatcher = withRecyclerView(R.id.audio_list)
onView(rvMatcher.atPosition(0))
.perform(longClick())
onView(withId(R.id.action_mode_audio_play))
.check(matches(isDisplayed()))
onView(withId(R.id.action_mode_audio_info))
.check(matches(isDisplayed()))
}
@Test
fun whenAtRoot_checkAppbarWorks() {
onView(withId(R.id.ml_menu_filter))
.check(matches(isDisplayed()))
// Check sort works
onView(withId(R.id.ml_menu_sortby))
.check(matches(isDisplayed()))
.perform(click())
onView(anyOf(withText(R.string.sortby_name), withId(R.id.ml_menu_sortby_name)))
.inRoot(isPlatformPopup())
.check(matches(isDisplayed()))
Espresso.pressBack()
// Check overflow menu works
openActionBarOverflowOrOptionsMenu(context)
onView(withText(R.string.refresh))
.inRoot(isPlatformPopup())
.check(matches(isDisplayed()))
Espresso.pressBack()
// Check search shows
onView(withId(R.id.ml_menu_filter))
.perform(click())
Espresso.pressBack()
Espresso.pressBack()
// Check everything is reset
onView(withId(R.id.ml_menu_filter))
.check(matches(isDisplayed()))
onView(withId(R.id.ml_menu_sortby))
.check(matches(isDisplayed()))
}
companion object {
val DUMMY_PLAYLIST = "test"
}
} | application/vlc-android/androidTest/org/videolan/vlc/gui/PlaylistFragmentUITest.kt | 1659322493 |
package cc.aoeiuv020.panovel.api.site
import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext
import java.net.URL
class Wukong0 : DslJsoupNovelContext() {init {
hide = true
site {
name = "悟空看书0"
baseUrl = "https://www.wkxs.net"
logo = "https://imgsa.baidu.com/forum/w%3D580/sign=95ca1b6f75310a55c424defc87474387/930dadd12f2eb938f9acfb6ed9628535e7dd6f50.jpg"
}
search {
get {
// 电脑版搜索要验证码,
// https://m.wkxs.net/modules/article/search.php?searchtype=articlename&searchkey=%B6%BC%CA%D0&t_btnsearch=
charset = "GBK"
url = "//m.wkxs.net/modules/article/search.php"
data {
"searchtype" to "articlename"
"searchkey" to it
// 加上&page=1可以避开搜索时间间隔的限制,
// 也可以通过不加载cookies避开搜索时间间隔的限制,
"page" to "1"
}
}
document {
if (URL(root.ownerDocument().location()).path.startsWith("/book_")) {
single {
name("tbody > tr > td.info > h1") {
it.ownText()
}
author("tbody > tr > td.info > p:nth-child(2) > a")
}
} else {
items("body > div.waps_r > table > tbody > tr") {
name("> td:nth-child(2) > div > a:nth-child(1)")
author("> td:nth-child(2) > div > p > span.mr15", block = pickString("作者:(\\S*)"))
}
}
}
}
// https://www.wkxs.net/book_885/
bookIdRegex = "/book_(\\d+)"
detailPageTemplate = "/book_%s/"
detail {
document {
novel {
name("#info > h1") {
it.ownText()
}
author("#info > h1 > small > a")
}
image("#picbox > div > img")
update("#info > div.update", format = "yyyy-MM-dd HH:mm", block = pickString(".*(([^(]*))"))
introduction("#intro", block = ownLinesString())
}
}
chapters {
document {
items("body > div.zjbox > dl > dd > a")
lastUpdate("#info > div.update", format = "yyyy-MM-dd HH:mm", block = pickString(".*(([^(]*))"))
}
}
bookIdWithChapterIdRegex = "/book_(\\d+/\\d+)"
contentPageTemplate = "/book_%s.html"
content {
document {
items("#content", block = ownLinesSplitWhitespace())
}.dropWhile {
it.startsWith("悟空看书")
|| it.startsWith("www.wkxs.net")
|| it.startsWith("www.wukong.la")
|| it == "最新章节!"
}.dropLastWhile {
it == "-->>"
}
}
}
}
| api/src/main/java/cc/aoeiuv020/panovel/api/site/wukong0.kt | 3281857343 |
package net.nemerosa.ontrack.extension.av.properties
interface FilePropertyType {
val id: String
fun readProperty(content: List<String>, targetProperty: String?): String?
fun replaceProperty(content: List<String>, targetProperty: String?, targetVersion: String): List<String>
} | ontrack-extension-auto-versioning/src/main/java/net/nemerosa/ontrack/extension/av/properties/FilePropertyType.kt | 4082408344 |
package io.sportner.cblmapper.exceptions
import java.lang.reflect.Type
open class CBLMapperClassException(protected val exceptionClass: Type,
protected val description: String) : RuntimeException() {
override fun toString(): String {
return String.format("CBLMapperClassException for class '%s': %s", this.exceptionClass.toString(), this.description)
}
}
| cblmapper/src/main/java/io/sportner/cblmapper/exceptions/CBLMapperClassException.kt | 2898337100 |
package net.nemerosa.ontrack.extension.general
import net.nemerosa.ontrack.model.settings.SettingsProvider
import net.nemerosa.ontrack.model.support.SettingsRepository
import org.springframework.stereotype.Component
@Component
class PreviousPromotionConditionSettingsProvider(
private val settingsRepository: SettingsRepository
) : SettingsProvider<PreviousPromotionConditionSettings> {
override fun getSettings() = PreviousPromotionConditionSettings(
previousPromotionRequired = settingsRepository.getBoolean(PreviousPromotionConditionSettings::class.java, "previousPromotionRequired", false)
)
override fun getSettingsClass(): Class<PreviousPromotionConditionSettings> =
PreviousPromotionConditionSettings::class.java
} | ontrack-extension-general/src/main/java/net/nemerosa/ontrack/extension/general/PreviousPromotionConditionSettingsProvider.kt | 412493991 |
package net.nemerosa.ontrack.extension.chart
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.model.annotations.APIDescription
/**
* Reference to a chart that an entity exposes.
*
* @property id Unique ID for this chart in the context of the entity exposing the charts
* @property title Chart title
* @property type Chart type, as supported by the client: `count`, `percentage`, `duration`, etc.
* @property config Additional fields that the chart [type] required
* @property parameters Parameters that the client must pass to get the chart data
*/
@APIDescription("Reference to a chart that an entity exposes.")
data class ChartDefinition(
@APIDescription("Unique ID for this chart in the context of the entity exposing the charts")
val id: String,
@APIDescription("Chart title")
val title: String,
@APIDescription("Chart type, as supported by the client: `count`, `percentage`, `duration`, etc.")
val type: String,
@APIDescription("Additional fields that the chart type required")
val config: JsonNode,
@APIDescription("Parameters that the client must pass to get the chart data")
val parameters: JsonNode,
)
| ontrack-extension-chart/src/main/java/net/nemerosa/ontrack/extension/chart/ChartDefinition.kt | 3120860594 |
class simple_class_2_MyClass(val b: Int, var c: Int)
fun simple_class_2_genMyClass(i: Int): simple_class_2_MyClass {
return simple_class_2_MyClass(i, i)
}
fun simple_class_2_change(x: Int): Int {
val y = simple_class_2_MyClass(x, x)
y.c = x
y.c = x
y.c = 1
y.c = x + 1
return y.c
}
fun simple_class_2_testGen(i: Int): Int {
val j = simple_class_2_genMyClass(i)
return j.b
}
| translator/src/test/kotlin/tests/simple_class_2/simple_class_2.kt | 11322498 |
// 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 org.jetbrains.plugins.github.extensions
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeAndWaitIfNeed
import com.intellij.openapi.project.Project
import com.intellij.util.AuthData
import git4idea.DialogManager
import git4idea.remote.InteractiveGitHttpAuthDataProvider
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.ui.GithubChooseAccountDialog
import org.jetbrains.plugins.github.util.GithubUtil
import java.awt.Component
internal class InteractiveGithubHttpAuthDataProvider(private val project: Project,
private val potentialAccounts: Collection<GithubAccount>,
private val authenticationManager: GithubAuthenticationManager) : InteractiveGitHttpAuthDataProvider {
@CalledInAwt
override fun getAuthData(parentComponent: Component?): AuthData? {
val dialog = GithubChooseAccountDialog(project,
parentComponent,
potentialAccounts,
null,
false,
true,
"Choose GitHub Account",
"Log In")
DialogManager.show(dialog)
if (!dialog.isOK) return null
val account = dialog.account
val token = invokeAndWaitIfNeed(parentComponent?.let(ModalityState::stateForComponent) ?: ModalityState.any()) {
authenticationManager.getOrRequestTokenForAccount(account, project, parentComponent)
} ?: return null
if (dialog.setDefault) authenticationManager.setDefaultAccount(project, account)
return AuthData(GithubUtil.GIT_AUTH_PASSWORD_SUBSTITUTE, token)
}
} | plugins/github/src/org/jetbrains/plugins/github/extensions/InteractiveGithubHttpAuthDataProvider.kt | 3042673365 |
package com.robyn.dayplus2.data.source.enums
/**
* Created by yifei on 11/20/2017.
*/
enum class EventType : EventFilter {
ALL_EVENTS,
SINCE_EVENTS,
UNTIL_EVENTS,
STARRED_EVENTS,
CATEGORY_EVENTS;
fun codeToFilterType(code: Int) {
when (code) {
0 -> ALL_EVENTS
}
}
}
| app/src/main/java/com/robyn/dayplus2/data/source/enums/EventType.kt | 423595778 |
package home.smart.fly.animations.ui.activity
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.appcompat.app.AppCompatActivity
import home.smart.fly.animations.R
import home.smart.fly.animations.utils.StatusBarUtil
import kotlinx.android.synthetic.main.include_view.*
class MergeIncludeViewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
StatusBarUtil.setColor(this,ContextCompat.getColor(this,R.color.colorPrimary))
setContentView(R.layout.activity_merge_include_view)
back.setOnClickListener { finish() }
}
}
| app/src/main/java/home/smart/fly/animations/ui/activity/MergeIncludeViewActivity.kt | 2316161680 |
package com.rimmer.yttrium.serialize
import com.rimmer.yttrium.*
import io.netty.buffer.ByteBuf
import org.joda.time.DateTime
import java.util.*
/** Utility functions for generating json data. */
class JsonWriter(val buffer: ByteBuf) {
private var depth = 0
private var hasValue = 0
fun startObject(): JsonWriter {
buffer.writeByte('{'.toInt())
depth++
return this
}
fun endObject(): JsonWriter {
buffer.writeByte('}'.toInt())
depth--
hasValue = depth
return this
}
fun startArray(): JsonWriter {
buffer.writeByte('['.toInt())
depth++
return this
}
fun endArray(): JsonWriter {
buffer.writeByte(']'.toInt())
depth--
hasValue = depth
return this
}
fun arrayField(): JsonWriter {
if(hasValue < depth) {
hasValue = depth
} else {
buffer.writeByte(','.toInt())
}
return this
}
fun field(name: ByteArray): JsonWriter {
if(hasValue < depth) {
hasValue = depth
} else {
buffer.writeByte(','.toInt())
}
buffer.writeByte('"'.toInt())
buffer.writeBytes(name)
buffer.writeByte('"'.toInt())
buffer.writeByte(':'.toInt())
return this
}
fun field(name: String) = field(name.toByteArray())
fun nullValue() {
buffer.writeBytes(nullBytes)
}
fun value(s: String): JsonWriter {
buffer.writeByte('"'.toInt())
val escaped = StringBuilder(s.length)
for(c in s) {
when {
c == '"' -> escaped.append("\\\"")
c == '\\' -> escaped.append("\\\\")
c < 0x20.toChar() -> when(c) {
'\b' -> escaped.append("\\b")
0x0C.toChar() -> escaped.append("\\f")
'\n' -> escaped.append("\\n")
'\r' -> escaped.append("\\r")
'\t' -> escaped.append("\\t")
}
else -> escaped.append(c)
}
}
buffer.writeBytes(escaped.toString().toByteArray())
buffer.writeByte('"'.toInt())
return this
}
fun value(s: ByteString): JsonWriter {
buffer.writeByte('"'.toInt())
val escaped = ByteStringBuilder(s.size)
for(c in s) {
when {
c == '"'.toByte() -> escaped.append("\\\"".utf8)
c == '\\'.toByte() -> escaped.append("\\\\".utf8)
c < 0x20.toByte() -> when(c) {
'\b'.toByte() -> escaped.append("\\b".utf8)
0x0C.toByte() -> escaped.append("\\f".utf8)
'\n'.toByte() -> escaped.append("\\n".utf8)
'\r'.toByte() -> escaped.append("\\r".utf8)
'\t'.toByte() -> escaped.append("\\t".utf8)
}
else -> escaped.append(c)
}
}
escaped.string.write(buffer)
buffer.writeByte('"'.toInt())
return this
}
fun value(i: Double): JsonWriter {
buffer.writeBytes(i.toString().toByteArray())
return this
}
fun value(i: Long): JsonWriter {
buffer.writeBytes(i.toString().toByteArray())
return this
}
fun value(i: DateTime) = value(i.millis)
fun value(i: Float) = value(i.toDouble())
fun value(i: Int) = value(i.toLong())
fun value(i: Short) = value(i.toLong())
fun value(i: Byte) = value(i.toLong())
fun value(i: Boolean): JsonWriter {
buffer.writeBytes(if(i) trueBytes else falseBytes)
return this
}
fun value(i: ByteBuf): JsonWriter {
buffer.writeByte('"'.toInt())
val base64 = Base64.getEncoder().encode(i.nioBuffer())
buffer.writeBytes(base64)
buffer.writeByte('"'.toInt())
return this
}
fun value(i: ByteArray): JsonWriter {
buffer.writeByte('"'.toInt())
val base64 = Base64.getEncoder().encode(i)
buffer.writeBytes(base64)
buffer.writeByte('"'.toInt())
return this
}
companion object {
val trueBytes = "true".toByteArray()
val falseBytes = "false".toByteArray()
val nullBytes = "null".toByteArray()
}
} | Core/src/com/rimmer/yttrium/serialize/JsonWriter.kt | 1685110063 |
package de.grannath.pardona.commands
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.mockito.Mockito
import java.util.Random
class RollExpressionTest {
@Test
fun rollingW6() {
val random = mockedRandom(sides = 6,
values = 3)
assertThat(random.roll("1w6")).isEqualTo(3)
}
@Test
fun rollingD6() {
val random = mockedRandom(sides = 6,
values = 3)
assertThat(random.roll("1d6")).isEqualTo(3)
}
@Test
fun rollingMultipleDice() {
val random = mockedRandom(3, 4, 5, sides = 8)
assertThat(random.roll("3w8")).isEqualTo(12)
}
@Test
fun defaultsToOneDice() {
val random = mockedRandom(2, sides = 10)
assertThat(random.roll("d10")).isEqualTo(2)
}
}
class rollCommandTest {
@Test
fun handlesSingleExpression() {
val command = RollCommand(mockedRandom(2, sides = 10))
assertThat(command.buildReply(listOf("d10"))).endsWith(" 2")
}
@Test
fun handlesSingleConstant() {
val command = RollCommand(mockedRandom(2, sides = 10))
assertThat(command.buildReply(listOf("12"))).endsWith(" 12")
}
@Test
fun handlesSimpleSum() {
val random = Mockito.mock(Random::class.java)
Mockito.`when`(random.nextInt(Mockito.anyInt()))
.thenReturn(5)
.thenReturn(2)
.thenReturn(12)
val command = RollCommand(random)
assertThat(command.buildReply(listOf("2d6", "+", "w20"))).endsWith(" 22")
}
@Test
fun handlesLongerSums() {
val random = Mockito.mock(Random::class.java)
Mockito.`when`(random.nextInt(Mockito.anyInt()))
.thenReturn(5)
.thenReturn(2)
.thenReturn(12)
.thenReturn(6)
.thenReturn(9)
val command = RollCommand(random)
assertThat(command.buildReply(listOf("2d6", "+", "w20-2w10", "+5"))).endsWith(" 10")
}
} | src/test/kotlin/de/grannath/pardona/commands/RollTest.kt | 3658205619 |
package org.jetbrains.anko.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.intentions.JetSelfTargetingIntention
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.lazy.descriptors.ClassResolutionScopesSupport
import org.jetbrains.kotlin.resolve.scopes.*
import org.jetbrains.kotlin.resolve.scopes.ExplicitImportsScope
import org.jetbrains.kotlin.resolve.scopes.utils.asLexicalScope
import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsFileScope
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices
import org.jetbrains.kotlin.types.lowerIfFlexible
abstract class AnkoIntention<TElement : JetElement>(
elementType: Class<TElement>,
text: String,
familyName: String = text
) : JetSelfTargetingIntention<TElement>(elementType, text, familyName) {
private fun isTypeOf(descriptor: ClassifierDescriptor, vararg fqName: String): Boolean {
val resolvedName = DescriptorUtils.getFqNameSafe(descriptor).asString()
return fqName.any { it == resolvedName }
}
protected fun JetCallExpression.isValueParameterTypeOf(parameterIndex: Int, resolvedCall: ResolvedCall<*>?, vararg fqName: String): Boolean {
val ctxArgumentDescriptor = (resolvedCall ?: getResolvedCall(analyze()))?.resultingDescriptor
?.valueParameters?.get(parameterIndex)?.type?.lowerIfFlexible()
?.constructor?.declarationDescriptor ?: return false
return isTypeOf(ctxArgumentDescriptor, *fqName)
}
protected fun JetCallExpression.isReceiverParameterTypeOf(resolvedCall: ResolvedCall<*>?, vararg fqName: String): Boolean {
val receiverDescriptor = (resolvedCall ?: getResolvedCall(analyze()))?.resultingDescriptor
?.dispatchReceiverParameter?.type?.lowerIfFlexible()
?.constructor?.declarationDescriptor ?: return false
return isTypeOf(receiverDescriptor, *fqName)
}
protected val JetDotQualifiedExpression.receiver: JetExpression?
get() = receiverExpression
protected val JetDotQualifiedExpression.selector: JetExpression?
get() = selectorExpression
protected val PsiElement.text: String
get() = getText()
protected val JetBinaryExpressionWithTypeRHS.operation: JetSimpleNameExpression
get() = operationReference
protected inline fun <reified E : PsiElement> PsiElement?.require(name: String? = null, sub: E.() -> Boolean): Boolean {
return require<E>(name) && (this as E).sub()
}
protected inline fun <reified E : PsiElement> PsiElement?.require(name: String? = null): Boolean {
if (this !is E) return false
if (name != null && name != this.getText()) return false
return true
}
protected inline fun PsiElement?.requireCall(functionName: String? = null, argCount: Int? = null, sub: JetCallExpression.() -> Boolean): Boolean {
return requireCall(functionName, argCount) && (this as JetCallExpression).sub()
}
suppress("NOTHING_TO_INLINE")
protected inline fun PsiElement?.requireCall(functionName: String? = null, argCount: Int? = null): Boolean {
if (this !is JetCallExpression) return false
if (functionName != null && functionName != calleeExpression?.getText()) return false
if (argCount != null && argCount != valueArguments.size()) return false
return true
}
private fun getResolutionScope(descriptor: DeclarationDescriptor): LexicalScope {
return when (descriptor) {
is PackageFragmentDescriptor -> {
val moduleDescriptor = descriptor.containingDeclaration
getResolutionScope(moduleDescriptor.getPackage(descriptor.fqName))
}
is PackageViewDescriptor ->
descriptor.memberScope.memberScopeAsFileScope()
is ClassDescriptorWithResolutionScopes ->
descriptor.scopeForMemberDeclarationResolution
is ClassDescriptor -> {
val outerScope = getResolutionScope(descriptor.containingDeclaration)
ClassResolutionScopesSupport(descriptor, LockBasedStorageManager.NO_LOCKS, { outerScope })
.scopeForMemberDeclarationResolution()
}
is FunctionDescriptor ->
FunctionDescriptorUtil.getFunctionInnerScope(getResolutionScope(descriptor.containingDeclaration),
descriptor, RedeclarationHandler.DO_NOTHING)
is PropertyDescriptor ->
JetScopeUtils.getPropertyDeclarationInnerScope(descriptor,
getResolutionScope(descriptor.containingDeclaration),
RedeclarationHandler.DO_NOTHING)
is LocalVariableDescriptor -> {
val declaration = DescriptorToSourceUtils.descriptorToDeclaration(descriptor) as JetDeclaration
declaration.analyze()[BindingContext.RESOLUTION_SCOPE, declaration]!!.asLexicalScope()
}
else -> throw IllegalArgumentException("Cannot find resolution scope for $descriptor")
}
}
abstract fun replaceWith(element: TElement, psiFactory: JetPsiFactory): NewElement?
final override fun applyTo(element: TElement, editor: Editor) {
val project = editor.project ?: return
val resolutionFacade = element.getResolutionFacade()
val containingJetDeclaration = JetStubbedPsiUtil.getContainingDeclaration(element) ?: return
val containingDeclaration = resolutionFacade.resolveToDescriptor(containingJetDeclaration)
as? CallableDescriptor ?: return
val jetFile = element.getContainingJetFile()
val psiFactory = JetPsiFactory(project)
val newElement = replaceWith(element, psiFactory) ?: return
val newExpression = newElement.element
val explicitlyImportedSymbols = newElement.newFqNames.flatMap { fqName ->
resolutionFacade.resolveImportReference(jetFile.findModuleDescriptor(), FqName("$ANKO_PACKAGE$fqName"))
}
val symbolScope = getResolutionScope(containingDeclaration)
val scope = LexicalChainedScope(symbolScope, containingDeclaration,
false, null, "ReplaceWith resolution scope", ExplicitImportsScope(explicitlyImportedSymbols))
var bindingContext = analyzeInContext(newExpression, containingDeclaration, scope, resolutionFacade)
val functionDescriptor = newExpression.getResolvedCall(bindingContext)?.resultingDescriptor ?: return
ImportInsertHelper.getInstance(project).importDescriptor(element.getContainingJetFile(), functionDescriptor)
element.replace(newExpression)
}
private fun analyzeInContext(
expression: JetExpression,
symbolDescriptor: CallableDescriptor,
scope: LexicalScope,
resolutionFacade: ResolutionFacade
): BindingContext {
val traceContext = BindingTraceContext()
resolutionFacade.getFrontendService(symbolDescriptor.module, ExpressionTypingServices::class.java)
.getTypeInfo(scope, expression, TypeUtils.NO_EXPECTED_TYPE, DataFlowInfo.EMPTY, traceContext, false)
return traceContext.bindingContext
}
private companion object {
private val ANKO_PACKAGE = "org.jetbrains.anko."
}
}
object FqNames {
val ACTIVITY_FQNAME = "android.app.Activity"
val CONTEXT_FQNAME = "android.content.Context"
val VIEW_FQNAME = "android.view.View"
}
class NewElement(val element: JetExpression, vararg newFqNames: String) {
val newFqNames = newFqNames.toList()
} | preview/intentions/src/org/jetbrains/anko/idea/intentions/AnkoIntention.kt | 148849983 |
package com.hedvig.botService.chat.house
import com.hedvig.botService.utils.ssnLookupAndStore
import com.hedvig.botService.utils.storeAndTrimAndAddSSNToChat
import com.hedvig.botService.utils.storeFamilyName
import com.hedvig.botService.chat.*
import com.hedvig.botService.chat.FreeChatConversation.FREE_CHAT_ONBOARDING_START
import com.hedvig.botService.chat.OnboardingConversationDevi.ProductTypes
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_ANCILLARY_AREA
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_HAS_EXTRA_BUILDINGS
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_HAS_WATER_EXTRA_BUILDING
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_LAST_NAME
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_ADDRESS_LOOK_UP_SUCCESS
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_EXTRA_BUILDING_TYPE_MORE_THAN_ONE
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_EXTRA_BUILDING_TYPE_ONE
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_NUMBER_OF_BATHROOMS
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_NUMBER_OF_EXTRA_BUILDINGS
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_HOUSE_HOUSEHOLD_MEMBERS
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_HOUSE_HAS_MORE_THAN_FOUR_FLOORS_FROM_NO
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_HOUSE_HAS_MORE_THAN_FOUR_FLOORS_FROM_YES
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_HOUSE_OR_APARTMENT
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_MORE_EXTRA_BUILDING_TYPE
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_NUMBER_OF_BATHROOMS_FROM_SUCCESS_LOOKUP
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_REAL_ESTATE_LOOKUP_CORRECT
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_SQUARE_METERS
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_SQUARE_METERS_EXTRA_BUILDING
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_SQUARE_METERS_FAILED_LOOKUP
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_SSN
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_SSN_UNDER_EIGHTEEN
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_STREET_ADDRESS
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_SUBLETTING_HOUSE
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_YEAR_OF_CONSTRUCTION
import com.hedvig.botService.chat.house.HouseConversationConstants.ASK_ZIP_CODE
import com.hedvig.botService.chat.house.HouseConversationConstants.CONVERSATION_APARTMENT_DONE
import com.hedvig.botService.chat.house.HouseConversationConstants.CONVERSATION_RENT_DONE
import com.hedvig.botService.chat.house.HouseConversationConstants.HOUSE_CONVERSATION_DONE
import com.hedvig.botService.chat.house.HouseConversationConstants.HOUSE_FIRST
import com.hedvig.botService.chat.house.HouseConversationConstants.IN_LOOP_ASK_EXTRA_BUILDING_TYPE
import com.hedvig.botService.chat.house.HouseConversationConstants.MORE_BATHROOMS_QUESTIONS_CALL
import com.hedvig.botService.chat.house.HouseConversationConstants.MORE_EXTRA_BUILDINGS_QUESTIONS_CALL
import com.hedvig.botService.chat.house.HouseConversationConstants.MORE_EXTRA_BUILDING_SQM_QUESTIONS_CALL
import com.hedvig.botService.chat.house.HouseConversationConstants.MORE_FLOORS_QUESTIONS_CALL
import com.hedvig.botService.chat.house.HouseConversationConstants.MORE_HOUSEHOLD_MEMBERS_QUESTIONS_CALL
import com.hedvig.botService.chat.house.HouseConversationConstants.MORE_SQM_QUESTIONS_CALL
import com.hedvig.botService.chat.house.HouseConversationConstants.MORE_TOTAL_SQM_QUESTIONS_CALL
import com.hedvig.botService.chat.house.HouseConversationConstants.MORE_YEAR_OF_CONSTRUCTION_QUESTIONS_CALL
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_MORE_THAN_FOUR_FLOORS
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_ATTEFALL
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_FRIGGEBO
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_GARAGE
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_HAS_WATER_NO
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_HAS_WATER_YES
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_YES
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_ADDRESS_LOOK_UP_SUCCESS_YES
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_APARTMENT
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_BOATHOUSE
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_CARPORT
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_GUESTHOUSE
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_EXTRA_BUILDING_SAUNA
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_REAL_ESTATE_LOOKUP_CORRECT_YES
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_RENT
import com.hedvig.botService.chat.house.HouseConversationConstants.SELECT_SUBLETTING_HOUSE_YES
import com.hedvig.botService.dataTypes.*
import com.hedvig.botService.enteties.UserContext
import com.hedvig.botService.enteties.message.*
import com.hedvig.botService.serviceIntegration.lookupService.LookupService
import com.hedvig.botService.serviceIntegration.lookupService.dto.RealEstateDto
import com.hedvig.botService.serviceIntegration.memberService.MemberService
import com.hedvig.botService.serviceIntegration.memberService.dto.Nationality
import com.hedvig.botService.serviceIntegration.productPricing.dto.ExtraBuildingType
import com.hedvig.botService.services.events.HouseUnderwritingLimitCallMeExceedsEvent
import com.hedvig.botService.utils.ConversationUtils.isYoungerThan18
import com.hedvig.botService.utils.MessageUtil
import com.hedvig.libs.translations.Translations
import org.slf4j.LoggerFactory
import org.springframework.context.ApplicationEventPublisher
class HouseOnboardingConversation
constructor(
private val memberService: MemberService,
private val lookupService: LookupService,
override var eventPublisher: ApplicationEventPublisher,
private val conversationFactory: ConversationFactory,
translations: Translations,
userContext: UserContext
) : Conversation(eventPublisher, translations, userContext) {
var queuePos: Int? = null
init {
createInputMessage(
HOUSE_FIRST
) { body, userContext, message ->
message.body.text = body.selectedItem.text
addToChat(message)
when (body.selectedItem.value) {
SELECT_RENT.value -> {
userContext.onBoardingData.houseType = ProductTypes.RENT.toString()
ASK_SSN.id
}
else -> {
userContext.onBoardingData.houseType = ProductTypes.HOUSE.toString()
ASK_SSN.id
}
}
}
createInputMessage(
ASK_SSN
) { body, userContext, message ->
handleSsnResponse(body, message)
}
this.setExpectedReturnType(ASK_SSN.id, SSNSweden())
createInputMessage(
ASK_SSN_UNDER_EIGHTEEN
) { body, userContext, message ->
handleSsnResponse(body, message)
}
this.setExpectedReturnType(ASK_SSN_UNDER_EIGHTEEN.id, SSNSweden())
createInputMessage(
ASK_LAST_NAME
) { body, userContext, message ->
userContext.storeFamilyName(body)
addToChat(message)
ASK_STREET_ADDRESS.id
}
createInputMessage(
ASK_STREET_ADDRESS
) { _, userContext, message ->
userContext.onBoardingData.addressStreet = message.body.text
addToChat(message)
ASK_ZIP_CODE.id
}
createInputMessage(
ASK_ZIP_CODE
) { body, userContext, message ->
userContext.onBoardingData.addressZipCode = message.body.text
addToChat(message)
if (userContext.hasHouseProduct()) {
realEstateLookup()
} else {
ASK_SQUARE_METERS.id
}
}
this.setExpectedReturnType(ASK_ZIP_CODE.id, ZipCodeSweden())
createInputMessage(
ASK_SQUARE_METERS
) { body, userContext, message ->
handleSquareMetersResponse(message)
}
this.setExpectedReturnType(ASK_SQUARE_METERS.id, HouseLivingSpaceSquareMeters())
createInputMessage(
ASK_SQUARE_METERS_FAILED_LOOKUP
) { body, userContext, message ->
handleSquareMetersResponse(message)
}
this.setExpectedReturnType(ASK_SQUARE_METERS_FAILED_LOOKUP.id, HouseLivingSpaceSquareMeters())
createInputMessage(
ASK_ANCILLARY_AREA
) { body, userContext, message ->
val ancillaryArea = (message.body as MessageBodyNumber).value
userContext.onBoardingData.houseAncillaryArea = ancillaryArea
addToChat(message)
if (ancillaryArea + userContext.onBoardingData.livingSpace > MAX_LIVING_SPACE_INCLUDING_ANCILLARY_AREA_SQM) {
MORE_TOTAL_SQM_QUESTIONS_CALL.id
} else {
ASK_YEAR_OF_CONSTRUCTION.id
}
}
this.setExpectedReturnType(ASK_ANCILLARY_AREA.id, AncillaryAreaSquareMeters())
createInputMessage(
ASK_YEAR_OF_CONSTRUCTION
) { body, userContext, message ->
val yearOfConstruction = (message.body as MessageBodyNumber).value
userContext.onBoardingData.yearOfConstruction = yearOfConstruction
addToChat(message)
if (yearOfConstruction < MIN_YEAR_OF_CONSTRUCTION) {
MORE_YEAR_OF_CONSTRUCTION_QUESTIONS_CALL.id
} else {
ASK_NUMBER_OF_BATHROOMS.id
}
}
this.setExpectedReturnType(ASK_YEAR_OF_CONSTRUCTION.id, HouseYearOfConstruction())
createInputMessage(
ASK_NUMBER_OF_BATHROOMS
) { body, userContext, message ->
handleNumberOfBathroomsResponse(message)
}
this.setExpectedReturnType(ASK_NUMBER_OF_BATHROOMS.id, HouseBathrooms())
createInputMessage(
ASK_NUMBER_OF_BATHROOMS_FROM_SUCCESS_LOOKUP
) { body, userContext, message ->
handleNumberOfBathroomsResponse(message)
}
this.setExpectedReturnType(ASK_NUMBER_OF_BATHROOMS_FROM_SUCCESS_LOOKUP.id, HouseBathrooms())
createInputMessage(
ASK_HOUSE_HOUSEHOLD_MEMBERS
) { body, userContext, message ->
handleHouseholdMembersResponse(message)
}
this.setExpectedReturnType(ASK_HOUSE_HOUSEHOLD_MEMBERS.id, HouseholdMemberNumber())
createInputMessage(
ASK_SUBLETTING_HOUSE
) { body, userContext, message ->
message.body.text = body.selectedItem.text
addToChat(message)
when (body.selectedItem.value) {
SELECT_SUBLETTING_HOUSE_YES.value -> {
userContext.onBoardingData.isSubLetting = true
ASK_HOUSE_HAS_MORE_THAN_FOUR_FLOORS_FROM_YES.id
}
else -> {
userContext.onBoardingData.isSubLetting = false
ASK_HOUSE_HAS_MORE_THAN_FOUR_FLOORS_FROM_NO.id
}
}
}
createInputMessage(
ASK_HOUSE_HAS_MORE_THAN_FOUR_FLOORS_FROM_YES
) { body, userContext, message ->
handleFloorsResponse(body, message)
}
createInputMessage(
ASK_HOUSE_HAS_MORE_THAN_FOUR_FLOORS_FROM_NO
) { body, userContext, message ->
handleFloorsResponse(body, message)
}
createInputMessage(
ASK_HAS_EXTRA_BUILDINGS
) { body, userContext, message ->
message.body.text = body.selectedItem.text
addToChat(message)
when (body.selectedItem.value) {
SELECT_EXTRA_BUILDING_YES.value -> {
userContext.onBoardingData.hasExtraBuildings = true
ASK_NUMBER_OF_EXTRA_BUILDINGS.id
}
else -> {
userContext.onBoardingData.hasExtraBuildings = false
userContext.onBoardingData.nrExtraBuildings = 0
HOUSE_CONVERSATION_DONE
}
}
}
createInputMessage(
ASK_NUMBER_OF_EXTRA_BUILDINGS
) { body, userContext, message ->
addToChat(message)
userContext.onBoardingData.nrExtraBuildings = body.value
when {
body.value == 0 -> {
HOUSE_CONVERSATION_DONE
}
body.value > MAX_NUMBER_OF_EXTRA_BUILDING -> {
MORE_EXTRA_BUILDINGS_QUESTIONS_CALL.id
}
body.value == 1 -> {
ASK_EXTRA_BUILDING_TYPE_ONE.id
}
else -> {
ASK_EXTRA_BUILDING_TYPE_MORE_THAN_ONE.id
}
}
}
this.setExpectedReturnType(ASK_NUMBER_OF_EXTRA_BUILDINGS.id, HouseExtraBuildings())
createInputMessage(
ASK_EXTRA_BUILDING_TYPE_ONE
) { body, userContext, message ->
handleExtraBuildingTypeResponse(body, userContext, message, 1)
}
createInputMessage(
ASK_EXTRA_BUILDING_TYPE_MORE_THAN_ONE
) { body, userContext, message ->
handleExtraBuildingTypeResponse(body, userContext, message, 1)
}
for (buildingNumber in 1..4) {
if (buildingNumber != 1) {
createInputMessage(
IN_LOOP_ASK_EXTRA_BUILDING_TYPE,
buildingNumber
) { body, userContext, message ->
handleExtraBuildingTypeResponse(body, userContext, message, buildingNumber)
}
}
createInputMessage(
ASK_MORE_EXTRA_BUILDING_TYPE,
buildingNumber
) { body, userContext, message ->
handleMoreExtraBuildingTypeResponse(body, userContext, message, buildingNumber)
}
createInputMessage(
ASK_SQUARE_METERS_EXTRA_BUILDING,
buildingNumber
) { body, userContext, message ->
val extraBuildingSQM = (message.body as MessageBodyNumber).value
userContext.onBoardingData.setHouseExtraBuildingSQM(
extraBuildingSQM,
buildingNumber
)
addToChat(message)
if (extraBuildingSQM > MAX_EXTRA_BUILDING_SQM) {
MORE_EXTRA_BUILDING_SQM_QUESTIONS_CALL.id
} else {
ASK_HAS_WATER_EXTRA_BUILDING.id + buildingNumber
}
}
this.setExpectedReturnType(ASK_SQUARE_METERS_EXTRA_BUILDING.id + buildingNumber, HouseExtraBuildingSQM())
createInputMessage(
ASK_HAS_WATER_EXTRA_BUILDING,
buildingNumber
) { body, userContext, message ->
message.body.text = body.selectedItem.text
addToChat(message)
when (body.selectedItem.value) {
SELECT_EXTRA_BUILDING_HAS_WATER_YES.value -> {
userContext.onBoardingData.setHouseExtraBuildingHasWater(true, buildingNumber)
}
SELECT_EXTRA_BUILDING_HAS_WATER_NO.value -> {
userContext.onBoardingData.setHouseExtraBuildingHasWater(false, buildingNumber)
}
}
if (userContext.onBoardingData.nrExtraBuildings <= buildingNumber) {
HOUSE_CONVERSATION_DONE
} else {
IN_LOOP_ASK_EXTRA_BUILDING_TYPE.id + (1 + buildingNumber)
}
}
}
createInputMessage(
ASK_ADDRESS_LOOK_UP_SUCCESS
) { body, userContext, message ->
message.body.text = body.selectedItem.text
addToChat(message)
when (body.selectedItem.value) {
SELECT_ADDRESS_LOOK_UP_SUCCESS_YES.value -> {
if (userContext.hasHouseProduct()) {
realEstateLookup()
} else {
ASK_SQUARE_METERS.id
}
}
else -> ASK_STREET_ADDRESS.id
}
}
createInputMessage(
ASK_REAL_ESTATE_LOOKUP_CORRECT
) { body, userContext, message ->
message.body.text = body.selectedItem.text
addToChat(message)
when (body.selectedItem.value) {
SELECT_REAL_ESTATE_LOOKUP_CORRECT_YES.value -> {
when {
userContext.onBoardingData.livingSpace > MAX_LIVING_SPACE_SQM ->
MORE_SQM_QUESTIONS_CALL.id
(userContext.onBoardingData.houseAncillaryArea +
userContext.onBoardingData.livingSpace) > MAX_LIVING_SPACE_INCLUDING_ANCILLARY_AREA_SQM ->
MORE_TOTAL_SQM_QUESTIONS_CALL.id
userContext.onBoardingData.yearOfConstruction < MIN_YEAR_OF_CONSTRUCTION ->
MORE_YEAR_OF_CONSTRUCTION_QUESTIONS_CALL.id
else ->
ASK_NUMBER_OF_BATHROOMS_FROM_SUCCESS_LOOKUP.id
}
}
else -> ASK_SQUARE_METERS.id
}
}
addAskMoreQuestionsMessage(MORE_SQM_QUESTIONS_CALL)
addAskMoreQuestionsMessage(MORE_HOUSEHOLD_MEMBERS_QUESTIONS_CALL)
addAskMoreQuestionsMessage(MORE_TOTAL_SQM_QUESTIONS_CALL)
addAskMoreQuestionsMessage(MORE_YEAR_OF_CONSTRUCTION_QUESTIONS_CALL)
addAskMoreQuestionsMessage(MORE_FLOORS_QUESTIONS_CALL)
addAskMoreQuestionsMessage(MORE_BATHROOMS_QUESTIONS_CALL)
addAskMoreQuestionsMessage(MORE_EXTRA_BUILDINGS_QUESTIONS_CALL)
addAskMoreQuestionsMessage(MORE_EXTRA_BUILDING_SQM_QUESTIONS_CALL)
//To be able edit house/apartment answer
createInputMessage(
ASK_HOUSE_OR_APARTMENT
) { body, userContext, message ->
message.body.text = body.selectedItem.text
addToChat(message)
when (body.selectedItem.value) {
SELECT_APARTMENT.value -> {
userContext.completeConversation(this)
val conversation =
conversationFactory.createConversation(OnboardingConversationDevi::class.java, userContext)
userContext.startConversation(
conversation,
OnboardingConversationDevi.MESSAGE_LAGENHET_NO_PERSONNUMMER
)
CONVERSATION_APARTMENT_DONE
}
else -> ASK_SSN.id
}
}
}
private fun realEstateLookup(): String =
lookupService.realEstateLookup(
userContext.memberId,
RealEstateDto(
userContext.onBoardingData.addressStreet,
userContext.onBoardingData.addressZipCode.replace(" ", "")
)
)?.let { realEstate ->
userContext.onBoardingData.apply {
houseAncillaryArea = realEstate.ancillaryArea
yearOfConstruction = realEstate.yearOfConstruction
livingSpace = realEstate.livingSpace.toFloat()
}
ASK_REAL_ESTATE_LOOKUP_CORRECT.id
} ?: ASK_SQUARE_METERS.id
private fun handleSsnResponse(body: MessageBodyNumber, message: Message): String {
val (trimmedSSN, memberBirthDate) = userContext.storeAndTrimAndAddSSNToChat(body) {
message.body.text = it
addToChat(message)
it
}
if (isYoungerThan18(memberBirthDate)) {
return ASK_SSN_UNDER_EIGHTEEN.id
}
val hasAddress = memberService.ssnLookupAndStore(userContext, trimmedSSN, Nationality.SWEDEN)
return if (hasAddress) {
ASK_ADDRESS_LOOK_UP_SUCCESS.id
} else {
ASK_LAST_NAME.id
}
}
private fun addAskMoreQuestionsMessage(message: NumberInputMessage) {
createInputMessage(
message
) { body, userContext, message ->
addToChat(message)
userContext.completeConversation(this)
val phoneNumber = message.body.text
userContext.onBoardingData.phoneNumber = phoneNumber
val reason = MessageUtil.getBaseMessageId(message.id)
.replace("message.house.more.questions.call.", "")
.replace(".", " ")
eventPublisher.publishEvent(
HouseUnderwritingLimitCallMeExceedsEvent(
userContext.memberId,
userContext.onBoardingData.firstName,
userContext.onBoardingData.familyName,
phoneNumber,
reason
)
)
val conversation = conversationFactory.createConversation(FreeChatConversation::class.java, userContext)
userContext.startConversation(conversation, FREE_CHAT_ONBOARDING_START)
FREE_CHAT_ONBOARDING_START
}
}
private fun handleFloorsResponse(body: MessageBodySingleSelect, message: Message): String {
message.body.text = body.selectedItem.text
addToChat(message)
return when (body.selectedItem.value) {
SELECT_MORE_THAN_FOUR_FLOORS.value -> {
MORE_FLOORS_QUESTIONS_CALL.id
}
else -> {
ASK_HAS_EXTRA_BUILDINGS.id
}
}
}
private fun handleSquareMetersResponse(message: Message): String {
val livingSpace = (message.body as MessageBodyNumber).value.toFloat()
userContext.onBoardingData.livingSpace = livingSpace
addToChat(message)
return if (userContext.hasHouseProduct()) {
if (livingSpace > MAX_LIVING_SPACE_SQM) {
MORE_SQM_QUESTIONS_CALL.id
} else {
ASK_ANCILLARY_AREA.id
}
} else {
if (livingSpace > OnboardingConversationDevi.MAX_LIVING_SPACE_RENT_SQM) {
MORE_SQM_QUESTIONS_CALL.id
} else {
userContext.completeConversation(this)
val conversation =
conversationFactory.createConversation(OnboardingConversationDevi::class.java, userContext)
userContext.startConversation(
conversation,
OnboardingConversationDevi.MESSAGE_ASK_NR_RESIDENTS
)
CONVERSATION_RENT_DONE
}
}
}
private fun handleNumberOfBathroomsResponse(message: Message): String {
val bathrooms = (message.body as MessageBodyNumber).value
userContext.onBoardingData.numberOfBathrooms = bathrooms
addToChat(message)
return if (bathrooms > MAX_NUMBER_OF_BATHROOMS) {
MORE_BATHROOMS_QUESTIONS_CALL.id
} else {
ASK_HOUSE_HOUSEHOLD_MEMBERS.id
}
}
private fun handleHouseholdMembersResponse(message: Message): String {
val nrPersons = (message.body as MessageBodyNumber).value
userContext.onBoardingData.setPersonInHouseHold(nrPersons)
addToChat(message)
return if (nrPersons > MAX_NUMBER_OF_HOUSE_HOLD_MEMBERS) {
MORE_HOUSEHOLD_MEMBERS_QUESTIONS_CALL.id
} else {
ASK_SUBLETTING_HOUSE.id
}
}
private fun handleExtraBuildingTypeResponse(
body: MessageBodySingleSelect,
userContext: UserContext,
message: Message,
buildingNumber: Int
): String {
message.body.text = body.selectedItem.text
addToChat(message)
return when (body.selectedItem.value) {
SELECT_EXTRA_BUILDING_GARAGE.value -> {
userContext.onBoardingData.setHouseExtraBuildingType(
ExtraBuildingType.GARAGE,
buildingNumber,
this.userContext.locale,
translations
)
ASK_SQUARE_METERS_EXTRA_BUILDING.id + buildingNumber
}
SELECT_EXTRA_BUILDING_FRIGGEBO.value -> {
userContext.onBoardingData.setHouseExtraBuildingType(
ExtraBuildingType.FRIGGEBOD,
buildingNumber,
this.userContext.locale,
translations
)
ASK_SQUARE_METERS_EXTRA_BUILDING.id + buildingNumber
}
SELECT_EXTRA_BUILDING_ATTEFALL.value -> {
userContext.onBoardingData.setHouseExtraBuildingType(
ExtraBuildingType.ATTEFALL,
buildingNumber,
this.userContext.locale,
translations
)
ASK_SQUARE_METERS_EXTRA_BUILDING.id + buildingNumber
}
else -> {
ASK_MORE_EXTRA_BUILDING_TYPE.id + buildingNumber
}
}
}
private fun handleMoreExtraBuildingTypeResponse(
body: MessageBodySingleSelect,
userContext: UserContext,
message: Message,
buildingNumber: Int
): String {
message.body.text = body.selectedItem.text
addToChat(message)
when (body.selectedItem.value) {
SELECT_EXTRA_BUILDING_GUESTHOUSE.value -> {
userContext.onBoardingData.setHouseExtraBuildingType(
ExtraBuildingType.GUESTHOUSE,
buildingNumber,
this.userContext.locale,
translations
)
}
SELECT_EXTRA_BUILDING_CARPORT.value -> {
userContext.onBoardingData.setHouseExtraBuildingType(
ExtraBuildingType.CARPORT,
buildingNumber,
this.userContext.locale,
translations
)
}
SELECT_EXTRA_BUILDING_SAUNA.value -> {
userContext.onBoardingData.setHouseExtraBuildingType(
ExtraBuildingType.SAUNA,
buildingNumber,
this.userContext.locale,
translations
)
}
SELECT_EXTRA_BUILDING_BOATHOUSE.value -> {
userContext.onBoardingData.setHouseExtraBuildingType(
ExtraBuildingType.BOATHOUSE,
buildingNumber,
this.userContext.locale,
translations
)
}
else -> {
userContext.onBoardingData.setHouseExtraBuildingType(
ExtraBuildingType.OTHER,
buildingNumber,
this.userContext.locale,
translations
)
}
}
return ASK_SQUARE_METERS_EXTRA_BUILDING.id + buildingNumber
}
public override fun completeRequest(nxtMsg: String) {
var nxtMsg = nxtMsg
when (nxtMsg) {
HOUSE_CONVERSATION_DONE -> {
userContext.completeConversation(this)
val conversation =
conversationFactory.createConversation(OnboardingConversationDevi::class.java, userContext)
userContext.startConversation(
conversation,
OnboardingConversationDevi.MESSAGE_50K_LIMIT
)
}
"" -> {
log.error("I dont know where to go next...")
nxtMsg = "error"
}
}
super.completeRequest(nxtMsg)
}
override fun init() {
log.info("Starting house conversation")
startConversation(HOUSE_FIRST.id)
}
override fun init(startMessage: String) {
log.info("Starting house onboarding conversation with message: $startMessage")
startConversation(startMessage) // Id of first message
}
override fun handleMessage(m: Message) {
var nxtMsg = ""
if (!validateReturnType(m)) {
return
}
// Lambda
if (this.hasSelectItemCallback(m.id) && m.body.javaClass == MessageBodySingleSelect::class.java) {
// MessageBodySingleSelect body = (MessageBodySingleSelect) m.body;
nxtMsg = this.execSelectItemCallback(m.id, m.body as MessageBodySingleSelect)
addToChat(m)
}
val onBoardingData = userContext.onBoardingData
// ... and then the incoming message id
nxtMsg = m.id
addToChat(m)
completeRequest(nxtMsg)
}
override fun receiveEvent(e: EventTypes, value: String) {
when (e) {
// This is used to let Hedvig say multiple message after another
EventTypes.MESSAGE_FETCHED -> {
log.info("Message fetched: $value")
// New way of handeling relay messages
val relay = getRelay(value)
if (relay != null) {
completeRequest(relay)
}
}
}
}
override fun canAcceptAnswerToQuestion(): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getSelectItemsForAnswer(): List<SelectItem> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
private fun createInputMessage(
message: SingleSelectMessage,
ordinal: Int? = null,
callback: (MessageBodySingleSelect, UserContext, Message) -> String
) {
this.createChatMessage(
message.id + (ordinal ?: ""),
WrappedMessage(
MessageBodySingleSelect(
message.text,
message.selectOptions.map { SelectOption(it.text, it.value) }
),
receiveMessageCallback = callback
)
)
}
private fun createInputMessage(
message: NumberInputMessage,
ordinal: Int? = null,
callback: (MessageBodyNumber, UserContext, Message) -> String
) {
this.createChatMessage(
message.id + (ordinal ?: ""),
WrappedMessage(
MessageBodyNumber(
message.text,
message.placeholder
),
receiveMessageCallback = callback
)
)
}
private fun createInputMessage(
message: TextInputMessage,
ordinal: Int? = null,
callback: (MessageBodyText, UserContext, Message) -> String
) {
this.createChatMessage(
message.id + (ordinal ?: ""),
WrappedMessage(
MessageBodyText(
message.text,
message.textContentType,
message.keyboardType,
message.placeholder
),
receiveMessageCallback = callback
)
)
}
private fun UserContext.hasHouseProduct() =
this.onBoardingData.houseType == ProductTypes.HOUSE.toString()
companion object {
private val log = LoggerFactory.getLogger(HouseOnboardingConversation::class.java)
private const val MAX_LIVING_SPACE_SQM = 250
private const val MAX_LIVING_SPACE_INCLUDING_ANCILLARY_AREA_SQM = 300
private const val MIN_YEAR_OF_CONSTRUCTION = 1925
private const val MAX_NUMBER_OF_HOUSE_HOLD_MEMBERS = 6
private const val MAX_NUMBER_OF_BATHROOMS = 2
private const val MAX_NUMBER_OF_EXTRA_BUILDING = 4
private const val MAX_EXTRA_BUILDING_SQM = 75
}
}
| src/main/java/com/hedvig/botService/chat/house/HouseOnboardingConversation.kt | 3289776320 |
package co.nums.intellij.aem.htl.extensions
import co.nums.intellij.aem.htl.HtlLanguage
import co.nums.intellij.aem.htl.definitions.HtlBlock
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.xml.*
private val htlBlockTypes = HtlBlock.values().map { it.type }
private val htlVariableBlockTypes = HtlBlock.values().filter { it.identifierType.isVariable() }.map { it.type }
private val htlImplicitVariableBlockTypes = HtlBlock.values().filter { it.iterable }.map { it.type }
fun XmlAttribute.isHtlBlock() = (firstChild as? XmlToken)?.isHtlBlock() ?: false
fun XmlAttribute.isHtlVariableBlock(): Boolean {
val blockType = (firstChild as? XmlToken)?.text?.substringBefore(".")?.toLowerCase()
return blockType in htlVariableBlockTypes
}
fun XmlAttribute.isHtlVariableDeclaration(): Boolean {
val blockName = (firstChild as? XmlToken)?.text ?: return false
val blockType = blockName.substringBefore(".").toLowerCase()
return blockType in htlVariableBlockTypes
&& (blockType in htlImplicitVariableBlockTypes || blockHasIdentifier(blockName))
}
private fun blockHasIdentifier(blockName: String): Boolean {
val blockIdentifier = blockName.substringAfter('.', missingDelimiterValue = "")
return blockIdentifier.isNotEmpty()
}
fun XmlAttribute.isHtlTemplateBlock(): Boolean {
val blockName = (firstChild as? XmlToken)?.text ?: return false
val blockType = blockName.substringBefore(".").toLowerCase()
return blockType == HtlBlock.TEMPLATE.type
}
fun XmlToken.isHtlBlock() = htlBlockTypes.contains(text.substringBefore(".").toLowerCase())
/**
* Returns declared use object type from XML attribute or from HTL expression in XML attribute.
* Returns `null` if type cannot be retrieved. Method does not check whether this XML attribute
* is actually `data-sly-use`.
*
* @return use object type or `null`
*/
fun XmlAttribute.getUseObjectType(): String? {
var useObjectType: String
val blockValue = this.valueElement ?: return null
val htlFile = blockValue.containingFile.viewProvider.getPsi(HtlLanguage) ?: return null
val htlExpressionStart = htlFile.findElementAt(blockValue.textOffset) ?: return null
if (htlExpressionStart.isHtlExpressionToken()) {
val nextToken = PsiTreeUtil.nextVisibleLeaf(htlExpressionStart) ?: return null
useObjectType = if (nextToken.isPartOfHtlString()) nextToken.text else ""
} else {
useObjectType = blockValue.text
}
useObjectType = useObjectType.trim('"', '\'', ' ')
if (useObjectType.isBlank()) {
return null
}
return useObjectType
}
| src/main/kotlin/co/nums/intellij/aem/htl/extensions/XmlAttributeExtensions.kt | 504438161 |
package kotlin4fun.eshop.customerregister.customer
import org.hibernate.annotations.Type
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.repository.query.Param
import java.util.UUID
import java.util.UUID.randomUUID
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table
@Entity
@Table(name = "customers")
data class Customer(@Id @Type(type = "uuid-char") val id: UUID = randomUUID(),
@Column(name = "firstname") val firstName: String,
@Column(name = "lastname") val lastName: String)
interface CustomerRepository : JpaRepository<Customer, UUID> {
fun findByFirstNameAndLastName(@Param("firstName") firstName: String,
@Param("lastName") lastName: String, pageable: Pageable): Page<Customer>
fun findByFirstName(firstName: String, pageable: Pageable): Page<Customer>
fun findByLastName(lastName: String, pageable: Pageable): Page<Customer>
} | customer-register-service/src/main/kotlin/kotlin4fun/eshop/customerregister/customer/Customer.kt | 1572678198 |
/*
* 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.transition
import android.graphics.drawable.Drawable
import com.github.panpf.sketch.target.DisplayTarget
import com.github.panpf.sketch.target.Target
/**
* A [Target] that supports applying [Transition]s.
*/
interface TransitionDisplayTarget : DisplayTarget {
/**
* The current [Drawable].
*/
val drawable: Drawable?
}
| sketch/src/main/java/com/github/panpf/sketch/transition/TransitionDisplayTarget.kt | 1119561129 |
package ru.dageev.compiler.domain.node.statement
import ru.dageev.compiler.bytecodegeneration.statement.StatementGenerator
import ru.dageev.compiler.domain.scope.Scope
/**
* Created by dageev
* on 15-May-16.
*/
class Block(val scope: Scope, val statements: List<Statement>) : Statement {
override fun accept(generator: StatementGenerator) {
generator.generate(this)
}
override fun toString(): String {
return "Block(statements=$statements)"
}
} | src/main/kotlin/ru/dageev/compiler/domain/node/statement/Block.kt | 3661889116 |
package org.wikipedia.feed.featured
import android.content.Context
import android.net.Uri
import android.view.LayoutInflater
import org.wikipedia.databinding.ViewCardFeaturedArticleBinding
import org.wikipedia.feed.view.CardFooterView
import org.wikipedia.feed.view.DefaultFeedCardView
import org.wikipedia.feed.view.FeedAdapter
import org.wikipedia.history.HistoryEntry
import org.wikipedia.page.PageTitle
import org.wikipedia.readinglist.LongPressMenu
import org.wikipedia.readinglist.database.ReadingListPage
import org.wikipedia.settings.SiteInfoClient
import org.wikipedia.views.ImageZoomHelper
@Suppress("LeakingThis")
open class FeaturedArticleCardView(context: Context) : DefaultFeedCardView<FeaturedArticleCard>(context) {
private val binding = ViewCardFeaturedArticleBinding.inflate(LayoutInflater.from(context), this, true)
init {
binding.viewFeaturedArticleCardContentContainer.setOnClickListener {
card?.let {
callback?.onSelectPage(it, it.historyEntry(), binding.viewWikiArticleCard.getSharedElements())
}
}
binding.viewFeaturedArticleCardContentContainer.setOnLongClickListener { view ->
if (ImageZoomHelper.isZooming) {
ImageZoomHelper.dispatchCancelEvent(binding.viewFeaturedArticleCardContentContainer)
} else {
LongPressMenu(view, true, object : LongPressMenu.Callback {
override fun onOpenLink(entry: HistoryEntry) {
card?.let {
callback?.onSelectPage(it, entry, false)
}
}
override fun onOpenInNewTab(entry: HistoryEntry) {
card?.let {
callback?.onSelectPage(it, entry, true)
}
}
override fun onAddRequest(entry: HistoryEntry, addToDefault: Boolean) {
callback?.onAddPageToList(entry, addToDefault)
}
override fun onMoveRequest(page: ReadingListPage?, entry: HistoryEntry) {
callback?.onMovePageToList(page!!.listId, entry)
}
}).show(card?.historyEntry())
}
false
}
}
override var card: FeaturedArticleCard? = null
set(value) {
field = value
value?.let {
setLayoutDirectionByWikiSite(it.wikiSite(), binding.viewFeaturedArticleCardContentContainer)
articleTitle(it.articleTitle())
articleSubtitle(it.articleSubtitle())
extract(it.extract())
image(it.image())
header(it)
footer(it)
}
}
override var callback: FeedAdapter.Callback? = null
set(value) {
field = value
binding.viewFeaturedArticleCardHeader.setCallback(value)
}
private fun articleTitle(articleTitle: String) {
binding.viewWikiArticleCard.setTitle(articleTitle)
}
private fun articleSubtitle(articleSubtitle: String?) {
binding.viewWikiArticleCard.setDescription(articleSubtitle)
}
private fun extract(extract: String?) {
binding.viewWikiArticleCard.setExtract(extract, EXTRACT_MAX_LINES)
}
private fun header(card: FeaturedArticleCard) {
binding.viewFeaturedArticleCardHeader.setTitle(card.title())
.setLangCode(card.wikiSite().languageCode)
.setCard(card)
.setCallback(callback)
}
private fun footer(card: FeaturedArticleCard) {
binding.viewFeaturedArticleCardFooter.callback = footerCallback
binding.viewFeaturedArticleCardFooter.setFooterActionText(card.footerActionText(), card.wikiSite().languageCode)
}
private fun image(uri: Uri?) {
binding.viewWikiArticleCard.setImageUri(uri, false)
uri?.run {
ImageZoomHelper.setViewZoomable(binding.viewWikiArticleCard.getImageView())
}
}
open val footerCallback: CardFooterView.Callback?
get() = CardFooterView.Callback {
card?.let {
callback?.onSelectPage(it, HistoryEntry(PageTitle(
SiteInfoClient.getMainPageForLang(it.wikiSite().languageCode), it.wikiSite()),
it.historyEntry().source), false
)
}
}
companion object {
const val EXTRACT_MAX_LINES = 8
}
}
| app/src/main/java/org/wikipedia/feed/featured/FeaturedArticleCardView.kt | 595248346 |
package com.bl_lia.kirakiratter.presentation.adapter.notification
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import com.bl_lia.kirakiratter.domain.entity.Account
import com.bl_lia.kirakiratter.domain.entity.Notification
import com.bl_lia.kirakiratter.domain.entity.Status
import io.reactivex.subjects.PublishSubject
class NotificationAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
enum class ViewType(val value: Int) {
Follow(1), Boost(2), Favourite(3), Reblog(4), Mention(5);
companion object {
fun valueOf(value: Int): ViewType? =
ViewType.values().find { it.value == value }
}
}
val onClickAccount = PublishSubject.create<Pair<Account, ImageView>>()
val onClickReply = PublishSubject.create<Status>()
val onClickReblog = PublishSubject.create<Notification>()
val onClickFavourite = PublishSubject.create<Notification>()
val onClickTranslate = PublishSubject.create<Notification>()
private val list: MutableList<Notification> = mutableListOf()
val maxId: Int?
get() {
if (list.isEmpty()) {
return null
}
return list.last().id
}
override fun getItemCount(): Int = list.size
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder =
when (ViewType.valueOf(viewType)) {
ViewType.Boost,
ViewType.Favourite,
ViewType.Reblog,
ViewType.Mention -> {
val view = LayoutInflater.from(parent?.context).inflate(NotificationItemViewHolder.LAYOUT, parent, false)
NotificationItemViewHolder.newInstance(view)
}
ViewType.Follow -> {
val view = LayoutInflater.from(parent?.context).inflate(NotificationFollowItemViewHolder.LAYOUT, parent, false)
NotificationFollowItemViewHolder.newInstance(view)
}
else -> throw RuntimeException("No ViewHolder found")
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
if (holder is NotificationItemViewHolder) {
holder.bind(list[position])
holder.onClickAccount.subscribe(onClickAccount)
holder.onClickReply.subscribe(onClickReply)
holder.onClickReblog.subscribe(onClickReblog)
holder.onClickFavourite.subscribe(onClickFavourite)
holder.onClickTranslate.subscribe(onClickTranslate)
return
}
if (holder is NotificationFollowItemViewHolder) {
holder.bind(list[position])
holder.onClickAccount.subscribe(onClickAccount)
return
}
}
override fun getItemViewType(position: Int): Int =
when (list[position].type) {
"follow" -> ViewType.Follow.value
"favourite" -> ViewType.Favourite.value
"reblog" -> ViewType.Reblog.value
"boost" -> ViewType.Boost.value
"mention" -> ViewType.Mention.value
else -> -1
}
fun reset(newList: List<Notification>) {
list.clear()
list.addAll(newList)
notifyDataSetChanged()
}
fun add(moreList: List<Notification>) {
list.addAll(moreList)
notifyDataSetChanged()
}
fun update(notification: Notification) {
list.indexOfFirst {
it.id == notification.id
}.also { index ->
if (index > -1) {
list.set(index, notification)
notifyItemChanged(index)
}
}
}
fun addTranslatedText(notification: Notification, translatedText: String) {
list.indexOfFirst {
it.id == notification.id
}.also { index ->
if (index > -1) {
val s = if (notification.status?.reblog != null) {
notification.copy(
status = notification.status.copy(
reblog = notification.status.reblog.copy(
content = notification.status.reblog.content?.copy(translatedText = translatedText)
)
)
)
} else {
notification.copy(
status = notification.status?.copy(
content = notification.status.content?.copy(translatedText = translatedText)
)
)
}
list.set(index, s)
notifyItemChanged(index)
}
}
}
} | app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/adapter/notification/NotificationAdapter.kt | 3830722753 |
package com.stripe.android.financialconnections.model
import androidx.annotation.RestrictTo
import kotlinx.parcelize.Parcelize
import kotlinx.serialization.Required
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@Parcelize
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
data class BankAccount(
@SerialName(value = "id") @Required
val id: String,
@SerialName(value = "last4") @Required
val last4: String,
@SerialName(value = "bank_name") val bankName: String? = null,
@SerialName(value = "routing_number") val routingNumber: String? = null
) : PaymentAccount()
| financial-connections/src/main/java/com/stripe/android/financialconnections/model/BankAccount.kt | 1760930583 |
package pl.wendigo.chrome.api.network
import kotlinx.serialization.json.Json
/**
* Network domain allows tracking network activities of the page. It exposes information about http,
file, data and other requests and responses, their headers, bodies, timing, etc.
*
* @link Protocol [Network](https://chromedevtools.github.io/devtools-protocol/tot/Network) domain documentation.
*/
class NetworkDomain internal constructor(connection: pl.wendigo.chrome.protocol.ProtocolConnection) :
pl.wendigo.chrome.protocol.Domain(
"Network",
"""Network domain allows tracking network activities of the page. It exposes information about http,
file, data and other requests and responses, their headers, bodies, timing, etc.""",
connection
) {
/**
* Tells whether clearing browser cache is supported.
*
* @link Protocol [Network#canClearBrowserCache](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canClearBrowserCache) method documentation.
*/
@Deprecated(level = DeprecationLevel.WARNING, message = "canClearBrowserCache is deprecated.")
fun canClearBrowserCache(): io.reactivex.rxjava3.core.Single<CanClearBrowserCacheResponse> = connection.request("Network.canClearBrowserCache", null, CanClearBrowserCacheResponse.serializer())
/**
* Tells whether clearing browser cookies is supported.
*
* @link Protocol [Network#canClearBrowserCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canClearBrowserCookies) method documentation.
*/
@Deprecated(level = DeprecationLevel.WARNING, message = "canClearBrowserCookies is deprecated.")
fun canClearBrowserCookies(): io.reactivex.rxjava3.core.Single<CanClearBrowserCookiesResponse> = connection.request("Network.canClearBrowserCookies", null, CanClearBrowserCookiesResponse.serializer())
/**
* Tells whether emulation of network conditions is supported.
*
* @link Protocol [Network#canEmulateNetworkConditions](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canEmulateNetworkConditions) method documentation.
*/
@Deprecated(level = DeprecationLevel.WARNING, message = "canEmulateNetworkConditions is deprecated.")
fun canEmulateNetworkConditions(): io.reactivex.rxjava3.core.Single<CanEmulateNetworkConditionsResponse> = connection.request("Network.canEmulateNetworkConditions", null, CanEmulateNetworkConditionsResponse.serializer())
/**
* Clears browser cache.
*
* @link Protocol [Network#clearBrowserCache](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-clearBrowserCache) method documentation.
*/
fun clearBrowserCache(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.clearBrowserCache", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Clears browser cookies.
*
* @link Protocol [Network#clearBrowserCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-clearBrowserCookies) method documentation.
*/
fun clearBrowserCookies(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.clearBrowserCookies", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Response to Network.requestIntercepted which either modifies the request to continue with any
modifications, or blocks it, or completes it with the provided response bytes. If a network
fetch occurs as a result which encounters a redirect an additional Network.requestIntercepted
event will be sent with the same InterceptionId.
Deprecated, use Fetch.continueRequest, Fetch.fulfillRequest and Fetch.failRequest instead.
*
* @link Protocol [Network#continueInterceptedRequest](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-continueInterceptedRequest) method documentation.
*/
@Deprecated(level = DeprecationLevel.WARNING, message = "continueInterceptedRequest is deprecated.")
@pl.wendigo.chrome.protocol.Experimental
fun continueInterceptedRequest(input: ContinueInterceptedRequestRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.continueInterceptedRequest", Json.encodeToJsonElement(ContinueInterceptedRequestRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Deletes browser cookies with matching name and url or domain/path pair.
*
* @link Protocol [Network#deleteCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-deleteCookies) method documentation.
*/
fun deleteCookies(input: DeleteCookiesRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.deleteCookies", Json.encodeToJsonElement(DeleteCookiesRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Disables network tracking, prevents network events from being sent to the client.
*
* @link Protocol [Network#disable](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-disable) method documentation.
*/
fun disable(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.disable", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Activates emulation of network conditions.
*
* @link Protocol [Network#emulateNetworkConditions](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-emulateNetworkConditions) method documentation.
*/
fun emulateNetworkConditions(input: EmulateNetworkConditionsRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.emulateNetworkConditions", Json.encodeToJsonElement(EmulateNetworkConditionsRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Enables network tracking, network events will now be delivered to the client.
*
* @link Protocol [Network#enable](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-enable) method documentation.
*/
fun enable(input: EnableRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.enable", Json.encodeToJsonElement(EnableRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Returns all browser cookies. Depending on the backend support, will return detailed cookie
information in the `cookies` field.
*
* @link Protocol [Network#getAllCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getAllCookies) method documentation.
*/
fun getAllCookies(): io.reactivex.rxjava3.core.Single<GetAllCookiesResponse> = connection.request("Network.getAllCookies", null, GetAllCookiesResponse.serializer())
/**
* Returns the DER-encoded certificate.
*
* @link Protocol [Network#getCertificate](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCertificate) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun getCertificate(input: GetCertificateRequest): io.reactivex.rxjava3.core.Single<GetCertificateResponse> = connection.request("Network.getCertificate", Json.encodeToJsonElement(GetCertificateRequest.serializer(), input), GetCertificateResponse.serializer())
/**
* Returns all browser cookies for the current URL. Depending on the backend support, will return
detailed cookie information in the `cookies` field.
*
* @link Protocol [Network#getCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCookies) method documentation.
*/
fun getCookies(input: GetCookiesRequest): io.reactivex.rxjava3.core.Single<GetCookiesResponse> = connection.request("Network.getCookies", Json.encodeToJsonElement(GetCookiesRequest.serializer(), input), GetCookiesResponse.serializer())
/**
* Returns content served for the given request.
*
* @link Protocol [Network#getResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBody) method documentation.
*/
fun getResponseBody(input: GetResponseBodyRequest): io.reactivex.rxjava3.core.Single<GetResponseBodyResponse> = connection.request("Network.getResponseBody", Json.encodeToJsonElement(GetResponseBodyRequest.serializer(), input), GetResponseBodyResponse.serializer())
/**
* Returns post data sent with the request. Returns an error when no data was sent with the request.
*
* @link Protocol [Network#getRequestPostData](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getRequestPostData) method documentation.
*/
fun getRequestPostData(input: GetRequestPostDataRequest): io.reactivex.rxjava3.core.Single<GetRequestPostDataResponse> = connection.request("Network.getRequestPostData", Json.encodeToJsonElement(GetRequestPostDataRequest.serializer(), input), GetRequestPostDataResponse.serializer())
/**
* Returns content served for the given currently intercepted request.
*
* @link Protocol [Network#getResponseBodyForInterception](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBodyForInterception) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun getResponseBodyForInterception(input: GetResponseBodyForInterceptionRequest): io.reactivex.rxjava3.core.Single<GetResponseBodyForInterceptionResponse> = connection.request("Network.getResponseBodyForInterception", Json.encodeToJsonElement(GetResponseBodyForInterceptionRequest.serializer(), input), GetResponseBodyForInterceptionResponse.serializer())
/**
* Returns a handle to the stream representing the response body. Note that after this command,
the intercepted request can't be continued as is -- you either need to cancel it or to provide
the response body. The stream only supports sequential read, IO.read will fail if the position
is specified.
*
* @link Protocol [Network#takeResponseBodyForInterceptionAsStream](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-takeResponseBodyForInterceptionAsStream) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun takeResponseBodyForInterceptionAsStream(input: TakeResponseBodyForInterceptionAsStreamRequest): io.reactivex.rxjava3.core.Single<TakeResponseBodyForInterceptionAsStreamResponse> = connection.request("Network.takeResponseBodyForInterceptionAsStream", Json.encodeToJsonElement(TakeResponseBodyForInterceptionAsStreamRequest.serializer(), input), TakeResponseBodyForInterceptionAsStreamResponse.serializer())
/**
* This method sends a new XMLHttpRequest which is identical to the original one. The following
parameters should be identical: method, url, async, request body, extra headers, withCredentials
attribute, user, password.
*
* @link Protocol [Network#replayXHR](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-replayXHR) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun replayXHR(input: ReplayXHRRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.replayXHR", Json.encodeToJsonElement(ReplayXHRRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Searches for given string in response content.
*
* @link Protocol [Network#searchInResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-searchInResponseBody) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun searchInResponseBody(input: SearchInResponseBodyRequest): io.reactivex.rxjava3.core.Single<SearchInResponseBodyResponse> = connection.request("Network.searchInResponseBody", Json.encodeToJsonElement(SearchInResponseBodyRequest.serializer(), input), SearchInResponseBodyResponse.serializer())
/**
* Blocks URLs from loading.
*
* @link Protocol [Network#setBlockedURLs](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setBlockedURLs) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun setBlockedURLs(input: SetBlockedURLsRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setBlockedURLs", Json.encodeToJsonElement(SetBlockedURLsRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Toggles ignoring of service worker for each request.
*
* @link Protocol [Network#setBypassServiceWorker](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setBypassServiceWorker) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun setBypassServiceWorker(input: SetBypassServiceWorkerRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setBypassServiceWorker", Json.encodeToJsonElement(SetBypassServiceWorkerRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Toggles ignoring cache for each request. If `true`, cache will not be used.
*
* @link Protocol [Network#setCacheDisabled](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCacheDisabled) method documentation.
*/
fun setCacheDisabled(input: SetCacheDisabledRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setCacheDisabled", Json.encodeToJsonElement(SetCacheDisabledRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.
*
* @link Protocol [Network#setCookie](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookie) method documentation.
*/
fun setCookie(input: SetCookieRequest): io.reactivex.rxjava3.core.Single<SetCookieResponse> = connection.request("Network.setCookie", Json.encodeToJsonElement(SetCookieRequest.serializer(), input), SetCookieResponse.serializer())
/**
* Sets given cookies.
*
* @link Protocol [Network#setCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookies) method documentation.
*/
fun setCookies(input: SetCookiesRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setCookies", Json.encodeToJsonElement(SetCookiesRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* For testing.
*
* @link Protocol [Network#setDataSizeLimitsForTest](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setDataSizeLimitsForTest) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun setDataSizeLimitsForTest(input: SetDataSizeLimitsForTestRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setDataSizeLimitsForTest", Json.encodeToJsonElement(SetDataSizeLimitsForTestRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Specifies whether to always send extra HTTP headers with the requests from this page.
*
* @link Protocol [Network#setExtraHTTPHeaders](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setExtraHTTPHeaders) method documentation.
*/
fun setExtraHTTPHeaders(input: SetExtraHTTPHeadersRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setExtraHTTPHeaders", Json.encodeToJsonElement(SetExtraHTTPHeadersRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Specifies whether to attach a page script stack id in requests
*
* @link Protocol [Network#setAttachDebugStack](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setAttachDebugStack) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun setAttachDebugStack(input: SetAttachDebugStackRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setAttachDebugStack", Json.encodeToJsonElement(SetAttachDebugStackRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Sets the requests to intercept that match the provided patterns and optionally resource types.
Deprecated, please use Fetch.enable instead.
*
* @link Protocol [Network#setRequestInterception](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setRequestInterception) method documentation.
*/
@Deprecated(level = DeprecationLevel.WARNING, message = "setRequestInterception is deprecated.")
@pl.wendigo.chrome.protocol.Experimental
fun setRequestInterception(input: SetRequestInterceptionRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setRequestInterception", Json.encodeToJsonElement(SetRequestInterceptionRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Allows overriding user agent with the given string.
*
* @link Protocol [Network#setUserAgentOverride](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setUserAgentOverride) method documentation.
*/
fun setUserAgentOverride(input: SetUserAgentOverrideRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Network.setUserAgentOverride", Json.encodeToJsonElement(SetUserAgentOverrideRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Returns information about the COEP/COOP isolation status.
*
* @link Protocol [Network#getSecurityIsolationStatus](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getSecurityIsolationStatus) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun getSecurityIsolationStatus(input: GetSecurityIsolationStatusRequest): io.reactivex.rxjava3.core.Single<GetSecurityIsolationStatusResponse> = connection.request("Network.getSecurityIsolationStatus", Json.encodeToJsonElement(GetSecurityIsolationStatusRequest.serializer(), input), GetSecurityIsolationStatusResponse.serializer())
/**
* Fetches the resource and returns the content.
*
* @link Protocol [Network#loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-loadNetworkResource) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun loadNetworkResource(input: LoadNetworkResourceRequest): io.reactivex.rxjava3.core.Single<LoadNetworkResourceResponse> = connection.request("Network.loadNetworkResource", Json.encodeToJsonElement(LoadNetworkResourceRequest.serializer(), input), LoadNetworkResourceResponse.serializer())
/**
* Fired when data chunk was received over the network.
*/
fun dataReceived(): io.reactivex.rxjava3.core.Flowable<DataReceivedEvent> = connection.events("Network.dataReceived", DataReceivedEvent.serializer())
/**
* Fired when EventSource message is received.
*/
fun eventSourceMessageReceived(): io.reactivex.rxjava3.core.Flowable<EventSourceMessageReceivedEvent> = connection.events("Network.eventSourceMessageReceived", EventSourceMessageReceivedEvent.serializer())
/**
* Fired when HTTP request has failed to load.
*/
fun loadingFailed(): io.reactivex.rxjava3.core.Flowable<LoadingFailedEvent> = connection.events("Network.loadingFailed", LoadingFailedEvent.serializer())
/**
* Fired when HTTP request has finished loading.
*/
fun loadingFinished(): io.reactivex.rxjava3.core.Flowable<LoadingFinishedEvent> = connection.events("Network.loadingFinished", LoadingFinishedEvent.serializer())
/**
* Details of an intercepted HTTP request, which must be either allowed, blocked, modified or
mocked.
Deprecated, use Fetch.requestPaused instead.
*/
fun requestIntercepted(): io.reactivex.rxjava3.core.Flowable<RequestInterceptedEvent> = connection.events("Network.requestIntercepted", RequestInterceptedEvent.serializer())
/**
* Fired if request ended up loading from cache.
*/
fun requestServedFromCache(): io.reactivex.rxjava3.core.Flowable<RequestServedFromCacheEvent> = connection.events("Network.requestServedFromCache", RequestServedFromCacheEvent.serializer())
/**
* Fired when page is about to send HTTP request.
*/
fun requestWillBeSent(): io.reactivex.rxjava3.core.Flowable<RequestWillBeSentEvent> = connection.events("Network.requestWillBeSent", RequestWillBeSentEvent.serializer())
/**
* Fired when resource loading priority is changed
*/
fun resourceChangedPriority(): io.reactivex.rxjava3.core.Flowable<ResourceChangedPriorityEvent> = connection.events("Network.resourceChangedPriority", ResourceChangedPriorityEvent.serializer())
/**
* Fired when a signed exchange was received over the network
*/
fun signedExchangeReceived(): io.reactivex.rxjava3.core.Flowable<SignedExchangeReceivedEvent> = connection.events("Network.signedExchangeReceived", SignedExchangeReceivedEvent.serializer())
/**
* Fired when HTTP response is available.
*/
fun responseReceived(): io.reactivex.rxjava3.core.Flowable<ResponseReceivedEvent> = connection.events("Network.responseReceived", ResponseReceivedEvent.serializer())
/**
* Fired when WebSocket is closed.
*/
fun webSocketClosed(): io.reactivex.rxjava3.core.Flowable<WebSocketClosedEvent> = connection.events("Network.webSocketClosed", WebSocketClosedEvent.serializer())
/**
* Fired upon WebSocket creation.
*/
fun webSocketCreated(): io.reactivex.rxjava3.core.Flowable<WebSocketCreatedEvent> = connection.events("Network.webSocketCreated", WebSocketCreatedEvent.serializer())
/**
* Fired when WebSocket message error occurs.
*/
fun webSocketFrameError(): io.reactivex.rxjava3.core.Flowable<WebSocketFrameErrorEvent> = connection.events("Network.webSocketFrameError", WebSocketFrameErrorEvent.serializer())
/**
* Fired when WebSocket message is received.
*/
fun webSocketFrameReceived(): io.reactivex.rxjava3.core.Flowable<WebSocketFrameReceivedEvent> = connection.events("Network.webSocketFrameReceived", WebSocketFrameReceivedEvent.serializer())
/**
* Fired when WebSocket message is sent.
*/
fun webSocketFrameSent(): io.reactivex.rxjava3.core.Flowable<WebSocketFrameSentEvent> = connection.events("Network.webSocketFrameSent", WebSocketFrameSentEvent.serializer())
/**
* Fired when WebSocket handshake response becomes available.
*/
fun webSocketHandshakeResponseReceived(): io.reactivex.rxjava3.core.Flowable<WebSocketHandshakeResponseReceivedEvent> = connection.events("Network.webSocketHandshakeResponseReceived", WebSocketHandshakeResponseReceivedEvent.serializer())
/**
* Fired when WebSocket is about to initiate handshake.
*/
fun webSocketWillSendHandshakeRequest(): io.reactivex.rxjava3.core.Flowable<WebSocketWillSendHandshakeRequestEvent> = connection.events("Network.webSocketWillSendHandshakeRequest", WebSocketWillSendHandshakeRequestEvent.serializer())
/**
* Fired upon WebTransport creation.
*/
fun webTransportCreated(): io.reactivex.rxjava3.core.Flowable<WebTransportCreatedEvent> = connection.events("Network.webTransportCreated", WebTransportCreatedEvent.serializer())
/**
* Fired when WebTransport handshake is finished.
*/
fun webTransportConnectionEstablished(): io.reactivex.rxjava3.core.Flowable<WebTransportConnectionEstablishedEvent> = connection.events("Network.webTransportConnectionEstablished", WebTransportConnectionEstablishedEvent.serializer())
/**
* Fired when WebTransport is disposed.
*/
fun webTransportClosed(): io.reactivex.rxjava3.core.Flowable<WebTransportClosedEvent> = connection.events("Network.webTransportClosed", WebTransportClosedEvent.serializer())
/**
* Fired when additional information about a requestWillBeSent event is available from the
network stack. Not every requestWillBeSent event will have an additional
requestWillBeSentExtraInfo fired for it, and there is no guarantee whether requestWillBeSent
or requestWillBeSentExtraInfo will be fired first for the same request.
*/
fun requestWillBeSentExtraInfo(): io.reactivex.rxjava3.core.Flowable<RequestWillBeSentExtraInfoEvent> = connection.events("Network.requestWillBeSentExtraInfo", RequestWillBeSentExtraInfoEvent.serializer())
/**
* Fired when additional information about a responseReceived event is available from the network
stack. Not every responseReceived event will have an additional responseReceivedExtraInfo for
it, and responseReceivedExtraInfo may be fired before or after responseReceived.
*/
fun responseReceivedExtraInfo(): io.reactivex.rxjava3.core.Flowable<ResponseReceivedExtraInfoEvent> = connection.events("Network.responseReceivedExtraInfo", ResponseReceivedExtraInfoEvent.serializer())
/**
* Fired exactly once for each Trust Token operation. Depending on
the type of the operation and whether the operation succeeded or
failed, the event is fired before the corresponding request was sent
or after the response was received.
*/
fun trustTokenOperationDone(): io.reactivex.rxjava3.core.Flowable<TrustTokenOperationDoneEvent> = connection.events("Network.trustTokenOperationDone", TrustTokenOperationDoneEvent.serializer())
/**
* Returns list of dependant domains that should be enabled prior to enabling this domain.
*/
override fun getDependencies(): List<pl.wendigo.chrome.protocol.Domain> {
return arrayListOf(
pl.wendigo.chrome.api.debugger.DebuggerDomain(connection),
pl.wendigo.chrome.api.runtime.RuntimeDomain(connection),
pl.wendigo.chrome.api.security.SecurityDomain(connection),
)
}
}
/**
* Represents response frame that is returned from [Network#canClearBrowserCache](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canClearBrowserCache) operation call.
* Tells whether clearing browser cache is supported.
*
* @link [Network#canClearBrowserCache](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canClearBrowserCache) method documentation.
* @see [NetworkDomain.canClearBrowserCache]
*/
@kotlinx.serialization.Serializable
data class CanClearBrowserCacheResponse(
/**
* True if browser cache can be cleared.
*/
val result: Boolean
)
/**
* Represents response frame that is returned from [Network#canClearBrowserCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canClearBrowserCookies) operation call.
* Tells whether clearing browser cookies is supported.
*
* @link [Network#canClearBrowserCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canClearBrowserCookies) method documentation.
* @see [NetworkDomain.canClearBrowserCookies]
*/
@kotlinx.serialization.Serializable
data class CanClearBrowserCookiesResponse(
/**
* True if browser cookies can be cleared.
*/
val result: Boolean
)
/**
* Represents response frame that is returned from [Network#canEmulateNetworkConditions](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canEmulateNetworkConditions) operation call.
* Tells whether emulation of network conditions is supported.
*
* @link [Network#canEmulateNetworkConditions](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-canEmulateNetworkConditions) method documentation.
* @see [NetworkDomain.canEmulateNetworkConditions]
*/
@kotlinx.serialization.Serializable
data class CanEmulateNetworkConditionsResponse(
/**
* True if emulation of network conditions is supported.
*/
val result: Boolean
)
/**
* Represents request frame that can be used with [Network#continueInterceptedRequest](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-continueInterceptedRequest) operation call.
*
* Response to Network.requestIntercepted which either modifies the request to continue with any
modifications, or blocks it, or completes it with the provided response bytes. If a network
fetch occurs as a result which encounters a redirect an additional Network.requestIntercepted
event will be sent with the same InterceptionId.
Deprecated, use Fetch.continueRequest, Fetch.fulfillRequest and Fetch.failRequest instead.
* @link [Network#continueInterceptedRequest](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-continueInterceptedRequest) method documentation.
* @see [NetworkDomain.continueInterceptedRequest]
*/
@kotlinx.serialization.Serializable
data class ContinueInterceptedRequestRequest(
/**
*
*/
val interceptionId: InterceptionId,
/**
* If set this causes the request to fail with the given reason. Passing `Aborted` for requests
marked with `isNavigationRequest` also cancels the navigation. Must not be set in response
to an authChallenge.
*/
val errorReason: ErrorReason? = null,
/**
* If set the requests completes using with the provided base64 encoded raw response, including
HTTP status line and headers etc... Must not be set in response to an authChallenge. (Encoded as a base64 string when passed over JSON)
*/
val rawResponse: String? = null,
/**
* If set the request url will be modified in a way that's not observable by page. Must not be
set in response to an authChallenge.
*/
val url: String? = null,
/**
* If set this allows the request method to be overridden. Must not be set in response to an
authChallenge.
*/
val method: String? = null,
/**
* If set this allows postData to be set. Must not be set in response to an authChallenge.
*/
val postData: String? = null,
/**
* If set this allows the request headers to be changed. Must not be set in response to an
authChallenge.
*/
val headers: Headers? = null,
/**
* Response to a requestIntercepted with an authChallenge. Must not be set otherwise.
*/
val authChallengeResponse: AuthChallengeResponse? = null
)
/**
* Represents request frame that can be used with [Network#deleteCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-deleteCookies) operation call.
*
* Deletes browser cookies with matching name and url or domain/path pair.
* @link [Network#deleteCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-deleteCookies) method documentation.
* @see [NetworkDomain.deleteCookies]
*/
@kotlinx.serialization.Serializable
data class DeleteCookiesRequest(
/**
* Name of the cookies to remove.
*/
val name: String,
/**
* If specified, deletes all the cookies with the given name where domain and path match
provided URL.
*/
val url: String? = null,
/**
* If specified, deletes only cookies with the exact domain.
*/
val domain: String? = null,
/**
* If specified, deletes only cookies with the exact path.
*/
val path: String? = null
)
/**
* Represents request frame that can be used with [Network#emulateNetworkConditions](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-emulateNetworkConditions) operation call.
*
* Activates emulation of network conditions.
* @link [Network#emulateNetworkConditions](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-emulateNetworkConditions) method documentation.
* @see [NetworkDomain.emulateNetworkConditions]
*/
@kotlinx.serialization.Serializable
data class EmulateNetworkConditionsRequest(
/**
* True to emulate internet disconnection.
*/
val offline: Boolean,
/**
* Minimum latency from request sent to response headers received (ms).
*/
val latency: Double,
/**
* Maximal aggregated download throughput (bytes/sec). -1 disables download throttling.
*/
val downloadThroughput: Double,
/**
* Maximal aggregated upload throughput (bytes/sec). -1 disables upload throttling.
*/
val uploadThroughput: Double,
/**
* Connection type if known.
*/
val connectionType: ConnectionType? = null
)
/**
* Represents request frame that can be used with [Network#enable](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-enable) operation call.
*
* Enables network tracking, network events will now be delivered to the client.
* @link [Network#enable](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-enable) method documentation.
* @see [NetworkDomain.enable]
*/
@kotlinx.serialization.Serializable
data class EnableRequest(
/**
* Buffer size in bytes to use when preserving network payloads (XHRs, etc).
*/
@pl.wendigo.chrome.protocol.Experimental val maxTotalBufferSize: Int? = null,
/**
* Per-resource buffer size in bytes to use when preserving network payloads (XHRs, etc).
*/
@pl.wendigo.chrome.protocol.Experimental val maxResourceBufferSize: Int? = null,
/**
* Longest post body size (in bytes) that would be included in requestWillBeSent notification
*/
val maxPostDataSize: Int? = null
)
/**
* Represents response frame that is returned from [Network#getAllCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getAllCookies) operation call.
* Returns all browser cookies. Depending on the backend support, will return detailed cookie
information in the `cookies` field.
*
* @link [Network#getAllCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getAllCookies) method documentation.
* @see [NetworkDomain.getAllCookies]
*/
@kotlinx.serialization.Serializable
data class GetAllCookiesResponse(
/**
* Array of cookie objects.
*/
val cookies: List<Cookie>
)
/**
* Represents request frame that can be used with [Network#getCertificate](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCertificate) operation call.
*
* Returns the DER-encoded certificate.
* @link [Network#getCertificate](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCertificate) method documentation.
* @see [NetworkDomain.getCertificate]
*/
@kotlinx.serialization.Serializable
data class GetCertificateRequest(
/**
* Origin to get certificate for.
*/
val origin: String
)
/**
* Represents response frame that is returned from [Network#getCertificate](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCertificate) operation call.
* Returns the DER-encoded certificate.
*
* @link [Network#getCertificate](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCertificate) method documentation.
* @see [NetworkDomain.getCertificate]
*/
@kotlinx.serialization.Serializable
data class GetCertificateResponse(
/**
*
*/
val tableNames: List<String>
)
/**
* Represents request frame that can be used with [Network#getCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCookies) operation call.
*
* Returns all browser cookies for the current URL. Depending on the backend support, will return
detailed cookie information in the `cookies` field.
* @link [Network#getCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCookies) method documentation.
* @see [NetworkDomain.getCookies]
*/
@kotlinx.serialization.Serializable
data class GetCookiesRequest(
/**
* The list of URLs for which applicable cookies will be fetched.
If not specified, it's assumed to be set to the list containing
the URLs of the page and all of its subframes.
*/
val urls: List<String>? = null
)
/**
* Represents response frame that is returned from [Network#getCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCookies) operation call.
* Returns all browser cookies for the current URL. Depending on the backend support, will return
detailed cookie information in the `cookies` field.
*
* @link [Network#getCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCookies) method documentation.
* @see [NetworkDomain.getCookies]
*/
@kotlinx.serialization.Serializable
data class GetCookiesResponse(
/**
* Array of cookie objects.
*/
val cookies: List<Cookie>
)
/**
* Represents request frame that can be used with [Network#getResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBody) operation call.
*
* Returns content served for the given request.
* @link [Network#getResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBody) method documentation.
* @see [NetworkDomain.getResponseBody]
*/
@kotlinx.serialization.Serializable
data class GetResponseBodyRequest(
/**
* Identifier of the network request to get content for.
*/
val requestId: RequestId
)
/**
* Represents response frame that is returned from [Network#getResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBody) operation call.
* Returns content served for the given request.
*
* @link [Network#getResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBody) method documentation.
* @see [NetworkDomain.getResponseBody]
*/
@kotlinx.serialization.Serializable
data class GetResponseBodyResponse(
/**
* Response body.
*/
val body: String,
/**
* True, if content was sent as base64.
*/
val base64Encoded: Boolean
)
/**
* Represents request frame that can be used with [Network#getRequestPostData](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getRequestPostData) operation call.
*
* Returns post data sent with the request. Returns an error when no data was sent with the request.
* @link [Network#getRequestPostData](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getRequestPostData) method documentation.
* @see [NetworkDomain.getRequestPostData]
*/
@kotlinx.serialization.Serializable
data class GetRequestPostDataRequest(
/**
* Identifier of the network request to get content for.
*/
val requestId: RequestId
)
/**
* Represents response frame that is returned from [Network#getRequestPostData](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getRequestPostData) operation call.
* Returns post data sent with the request. Returns an error when no data was sent with the request.
*
* @link [Network#getRequestPostData](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getRequestPostData) method documentation.
* @see [NetworkDomain.getRequestPostData]
*/
@kotlinx.serialization.Serializable
data class GetRequestPostDataResponse(
/**
* Request body string, omitting files from multipart requests
*/
val postData: String
)
/**
* Represents request frame that can be used with [Network#getResponseBodyForInterception](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBodyForInterception) operation call.
*
* Returns content served for the given currently intercepted request.
* @link [Network#getResponseBodyForInterception](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBodyForInterception) method documentation.
* @see [NetworkDomain.getResponseBodyForInterception]
*/
@kotlinx.serialization.Serializable
data class GetResponseBodyForInterceptionRequest(
/**
* Identifier for the intercepted request to get body for.
*/
val interceptionId: InterceptionId
)
/**
* Represents response frame that is returned from [Network#getResponseBodyForInterception](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBodyForInterception) operation call.
* Returns content served for the given currently intercepted request.
*
* @link [Network#getResponseBodyForInterception](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBodyForInterception) method documentation.
* @see [NetworkDomain.getResponseBodyForInterception]
*/
@kotlinx.serialization.Serializable
data class GetResponseBodyForInterceptionResponse(
/**
* Response body.
*/
val body: String,
/**
* True, if content was sent as base64.
*/
val base64Encoded: Boolean
)
/**
* Represents request frame that can be used with [Network#takeResponseBodyForInterceptionAsStream](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-takeResponseBodyForInterceptionAsStream) operation call.
*
* Returns a handle to the stream representing the response body. Note that after this command,
the intercepted request can't be continued as is -- you either need to cancel it or to provide
the response body. The stream only supports sequential read, IO.read will fail if the position
is specified.
* @link [Network#takeResponseBodyForInterceptionAsStream](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-takeResponseBodyForInterceptionAsStream) method documentation.
* @see [NetworkDomain.takeResponseBodyForInterceptionAsStream]
*/
@kotlinx.serialization.Serializable
data class TakeResponseBodyForInterceptionAsStreamRequest(
/**
*
*/
val interceptionId: InterceptionId
)
/**
* Represents response frame that is returned from [Network#takeResponseBodyForInterceptionAsStream](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-takeResponseBodyForInterceptionAsStream) operation call.
* Returns a handle to the stream representing the response body. Note that after this command,
the intercepted request can't be continued as is -- you either need to cancel it or to provide
the response body. The stream only supports sequential read, IO.read will fail if the position
is specified.
*
* @link [Network#takeResponseBodyForInterceptionAsStream](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-takeResponseBodyForInterceptionAsStream) method documentation.
* @see [NetworkDomain.takeResponseBodyForInterceptionAsStream]
*/
@kotlinx.serialization.Serializable
data class TakeResponseBodyForInterceptionAsStreamResponse(
/**
*
*/
val stream: pl.wendigo.chrome.api.io.StreamHandle
)
/**
* Represents request frame that can be used with [Network#replayXHR](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-replayXHR) operation call.
*
* This method sends a new XMLHttpRequest which is identical to the original one. The following
parameters should be identical: method, url, async, request body, extra headers, withCredentials
attribute, user, password.
* @link [Network#replayXHR](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-replayXHR) method documentation.
* @see [NetworkDomain.replayXHR]
*/
@kotlinx.serialization.Serializable
data class ReplayXHRRequest(
/**
* Identifier of XHR to replay.
*/
val requestId: RequestId
)
/**
* Represents request frame that can be used with [Network#searchInResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-searchInResponseBody) operation call.
*
* Searches for given string in response content.
* @link [Network#searchInResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-searchInResponseBody) method documentation.
* @see [NetworkDomain.searchInResponseBody]
*/
@kotlinx.serialization.Serializable
data class SearchInResponseBodyRequest(
/**
* Identifier of the network response to search.
*/
val requestId: RequestId,
/**
* String to search for.
*/
val query: String,
/**
* If true, search is case sensitive.
*/
val caseSensitive: Boolean? = null,
/**
* If true, treats string parameter as regex.
*/
val isRegex: Boolean? = null
)
/**
* Represents response frame that is returned from [Network#searchInResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-searchInResponseBody) operation call.
* Searches for given string in response content.
*
* @link [Network#searchInResponseBody](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-searchInResponseBody) method documentation.
* @see [NetworkDomain.searchInResponseBody]
*/
@kotlinx.serialization.Serializable
data class SearchInResponseBodyResponse(
/**
* List of search matches.
*/
val result: List<pl.wendigo.chrome.api.debugger.SearchMatch>
)
/**
* Represents request frame that can be used with [Network#setBlockedURLs](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setBlockedURLs) operation call.
*
* Blocks URLs from loading.
* @link [Network#setBlockedURLs](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setBlockedURLs) method documentation.
* @see [NetworkDomain.setBlockedURLs]
*/
@kotlinx.serialization.Serializable
data class SetBlockedURLsRequest(
/**
* URL patterns to block. Wildcards ('*') are allowed.
*/
val urls: List<String>
)
/**
* Represents request frame that can be used with [Network#setBypassServiceWorker](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setBypassServiceWorker) operation call.
*
* Toggles ignoring of service worker for each request.
* @link [Network#setBypassServiceWorker](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setBypassServiceWorker) method documentation.
* @see [NetworkDomain.setBypassServiceWorker]
*/
@kotlinx.serialization.Serializable
data class SetBypassServiceWorkerRequest(
/**
* Bypass service worker and load from network.
*/
val bypass: Boolean
)
/**
* Represents request frame that can be used with [Network#setCacheDisabled](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCacheDisabled) operation call.
*
* Toggles ignoring cache for each request. If `true`, cache will not be used.
* @link [Network#setCacheDisabled](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCacheDisabled) method documentation.
* @see [NetworkDomain.setCacheDisabled]
*/
@kotlinx.serialization.Serializable
data class SetCacheDisabledRequest(
/**
* Cache disabled state.
*/
val cacheDisabled: Boolean
)
/**
* Represents request frame that can be used with [Network#setCookie](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookie) operation call.
*
* Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.
* @link [Network#setCookie](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookie) method documentation.
* @see [NetworkDomain.setCookie]
*/
@kotlinx.serialization.Serializable
data class SetCookieRequest(
/**
* Cookie name.
*/
val name: String,
/**
* Cookie value.
*/
val value: String,
/**
* The request-URI to associate with the setting of the cookie. This value can affect the
default domain, path, source port, and source scheme values of the created cookie.
*/
val url: String? = null,
/**
* Cookie domain.
*/
val domain: String? = null,
/**
* Cookie path.
*/
val path: String? = null,
/**
* True if cookie is secure.
*/
val secure: Boolean? = null,
/**
* True if cookie is http-only.
*/
val httpOnly: Boolean? = null,
/**
* Cookie SameSite type.
*/
val sameSite: CookieSameSite? = null,
/**
* Cookie expiration date, session cookie if not set
*/
val expires: TimeSinceEpoch? = null,
/**
* Cookie Priority type.
*/
@pl.wendigo.chrome.protocol.Experimental val priority: CookiePriority? = null,
/**
* True if cookie is SameParty.
*/
@pl.wendigo.chrome.protocol.Experimental val sameParty: Boolean? = null,
/**
* Cookie source scheme type.
*/
@pl.wendigo.chrome.protocol.Experimental val sourceScheme: CookieSourceScheme? = null,
/**
* Cookie source port. Valid values are {-1, [1, 65535]}, -1 indicates an unspecified port.
An unspecified port value allows protocol clients to emulate legacy cookie scope for the port.
This is a temporary ability and it will be removed in the future.
*/
@pl.wendigo.chrome.protocol.Experimental val sourcePort: Int? = null
)
/**
* Represents response frame that is returned from [Network#setCookie](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookie) operation call.
* Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.
*
* @link [Network#setCookie](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookie) method documentation.
* @see [NetworkDomain.setCookie]
*/
@kotlinx.serialization.Serializable
data class SetCookieResponse(
/**
* Always set to true. If an error occurs, the response indicates protocol error.
*/
val success: Boolean
)
/**
* Represents request frame that can be used with [Network#setCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookies) operation call.
*
* Sets given cookies.
* @link [Network#setCookies](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookies) method documentation.
* @see [NetworkDomain.setCookies]
*/
@kotlinx.serialization.Serializable
data class SetCookiesRequest(
/**
* Cookies to be set.
*/
val cookies: List<CookieParam>
)
/**
* Represents request frame that can be used with [Network#setDataSizeLimitsForTest](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setDataSizeLimitsForTest) operation call.
*
* For testing.
* @link [Network#setDataSizeLimitsForTest](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setDataSizeLimitsForTest) method documentation.
* @see [NetworkDomain.setDataSizeLimitsForTest]
*/
@kotlinx.serialization.Serializable
data class SetDataSizeLimitsForTestRequest(
/**
* Maximum total buffer size.
*/
val maxTotalSize: Int,
/**
* Maximum per-resource size.
*/
val maxResourceSize: Int
)
/**
* Represents request frame that can be used with [Network#setExtraHTTPHeaders](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setExtraHTTPHeaders) operation call.
*
* Specifies whether to always send extra HTTP headers with the requests from this page.
* @link [Network#setExtraHTTPHeaders](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setExtraHTTPHeaders) method documentation.
* @see [NetworkDomain.setExtraHTTPHeaders]
*/
@kotlinx.serialization.Serializable
data class SetExtraHTTPHeadersRequest(
/**
* Map with extra HTTP headers.
*/
val headers: Headers
)
/**
* Represents request frame that can be used with [Network#setAttachDebugStack](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setAttachDebugStack) operation call.
*
* Specifies whether to attach a page script stack id in requests
* @link [Network#setAttachDebugStack](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setAttachDebugStack) method documentation.
* @see [NetworkDomain.setAttachDebugStack]
*/
@kotlinx.serialization.Serializable
data class SetAttachDebugStackRequest(
/**
* Whether to attach a page script stack for debugging purpose.
*/
val enabled: Boolean
)
/**
* Represents request frame that can be used with [Network#setRequestInterception](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setRequestInterception) operation call.
*
* Sets the requests to intercept that match the provided patterns and optionally resource types.
Deprecated, please use Fetch.enable instead.
* @link [Network#setRequestInterception](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setRequestInterception) method documentation.
* @see [NetworkDomain.setRequestInterception]
*/
@kotlinx.serialization.Serializable
data class SetRequestInterceptionRequest(
/**
* Requests matching any of these patterns will be forwarded and wait for the corresponding
continueInterceptedRequest call.
*/
val patterns: List<RequestPattern>
)
/**
* Represents request frame that can be used with [Network#setUserAgentOverride](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setUserAgentOverride) operation call.
*
* Allows overriding user agent with the given string.
* @link [Network#setUserAgentOverride](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setUserAgentOverride) method documentation.
* @see [NetworkDomain.setUserAgentOverride]
*/
@kotlinx.serialization.Serializable
data class SetUserAgentOverrideRequest(
/**
* User agent to use.
*/
val userAgent: String,
/**
* Browser langugage to emulate.
*/
val acceptLanguage: String? = null,
/**
* The platform navigator.platform should return.
*/
val platform: String? = null,
/**
* To be sent in Sec-CH-UA-* headers and returned in navigator.userAgentData
*/
@pl.wendigo.chrome.protocol.Experimental val userAgentMetadata: pl.wendigo.chrome.api.emulation.UserAgentMetadata? = null
)
/**
* Represents request frame that can be used with [Network#getSecurityIsolationStatus](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getSecurityIsolationStatus) operation call.
*
* Returns information about the COEP/COOP isolation status.
* @link [Network#getSecurityIsolationStatus](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getSecurityIsolationStatus) method documentation.
* @see [NetworkDomain.getSecurityIsolationStatus]
*/
@kotlinx.serialization.Serializable
data class GetSecurityIsolationStatusRequest(
/**
* If no frameId is provided, the status of the target is provided.
*/
val frameId: pl.wendigo.chrome.api.page.FrameId? = null
)
/**
* Represents response frame that is returned from [Network#getSecurityIsolationStatus](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getSecurityIsolationStatus) operation call.
* Returns information about the COEP/COOP isolation status.
*
* @link [Network#getSecurityIsolationStatus](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getSecurityIsolationStatus) method documentation.
* @see [NetworkDomain.getSecurityIsolationStatus]
*/
@kotlinx.serialization.Serializable
data class GetSecurityIsolationStatusResponse(
/**
*
*/
val status: SecurityIsolationStatus
)
/**
* Represents request frame that can be used with [Network#loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-loadNetworkResource) operation call.
*
* Fetches the resource and returns the content.
* @link [Network#loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-loadNetworkResource) method documentation.
* @see [NetworkDomain.loadNetworkResource]
*/
@kotlinx.serialization.Serializable
data class LoadNetworkResourceRequest(
/**
* Frame id to get the resource for.
*/
val frameId: pl.wendigo.chrome.api.page.FrameId,
/**
* URL of the resource to get content for.
*/
val url: String,
/**
* Options for the request.
*/
val options: LoadNetworkResourceOptions
)
/**
* Represents response frame that is returned from [Network#loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-loadNetworkResource) operation call.
* Fetches the resource and returns the content.
*
* @link [Network#loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network#method-loadNetworkResource) method documentation.
* @see [NetworkDomain.loadNetworkResource]
*/
@kotlinx.serialization.Serializable
data class LoadNetworkResourceResponse(
/**
*
*/
val resource: LoadNetworkResourcePageResult
)
/**
* Fired when data chunk was received over the network.
*
* @link [Network#dataReceived](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-dataReceived) event documentation.
*/
@kotlinx.serialization.Serializable
data class DataReceivedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* Data chunk length.
*/
val dataLength: Int,
/**
* Actual bytes received (might be less than dataLength for compressed encodings).
*/
val encodedDataLength: Int
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "dataReceived"
}
/**
* Fired when EventSource message is received.
*
* @link [Network#eventSourceMessageReceived](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-eventSourceMessageReceived) event documentation.
*/
@kotlinx.serialization.Serializable
data class EventSourceMessageReceivedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* Message type.
*/
val eventName: String,
/**
* Message identifier.
*/
val eventId: String,
/**
* Message content.
*/
val data: String
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "eventSourceMessageReceived"
}
/**
* Fired when HTTP request has failed to load.
*
* @link [Network#loadingFailed](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-loadingFailed) event documentation.
*/
@kotlinx.serialization.Serializable
data class LoadingFailedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* Resource type.
*/
val type: ResourceType,
/**
* User friendly error message.
*/
val errorText: String,
/**
* True if loading was canceled.
*/
val canceled: Boolean? = null,
/**
* The reason why loading was blocked, if any.
*/
val blockedReason: BlockedReason? = null,
/**
* The reason why loading was blocked by CORS, if any.
*/
val corsErrorStatus: CorsErrorStatus? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "loadingFailed"
}
/**
* Fired when HTTP request has finished loading.
*
* @link [Network#loadingFinished](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-loadingFinished) event documentation.
*/
@kotlinx.serialization.Serializable
data class LoadingFinishedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* Total number of bytes received for this request.
*/
val encodedDataLength: Double,
/**
* Set when 1) response was blocked by Cross-Origin Read Blocking and also
2) this needs to be reported to the DevTools console.
*/
val shouldReportCorbBlocking: Boolean? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "loadingFinished"
}
/**
* Details of an intercepted HTTP request, which must be either allowed, blocked, modified or
mocked.
Deprecated, use Fetch.requestPaused instead.
*
* @link [Network#requestIntercepted](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-requestIntercepted) event documentation.
*/
@kotlinx.serialization.Serializable
data class RequestInterceptedEvent(
/**
* Each request the page makes will have a unique id, however if any redirects are encountered
while processing that fetch, they will be reported with the same id as the original fetch.
Likewise if HTTP authentication is needed then the same fetch id will be used.
*/
val interceptionId: InterceptionId,
/**
*
*/
val request: Request,
/**
* The id of the frame that initiated the request.
*/
val frameId: pl.wendigo.chrome.api.page.FrameId,
/**
* How the requested resource will be used.
*/
val resourceType: ResourceType,
/**
* Whether this is a navigation request, which can abort the navigation completely.
*/
val isNavigationRequest: Boolean,
/**
* Set if the request is a navigation that will result in a download.
Only present after response is received from the server (i.e. HeadersReceived stage).
*/
val isDownload: Boolean? = null,
/**
* Redirect location, only sent if a redirect was intercepted.
*/
val redirectUrl: String? = null,
/**
* Details of the Authorization Challenge encountered. If this is set then
continueInterceptedRequest must contain an authChallengeResponse.
*/
val authChallenge: AuthChallenge? = null,
/**
* Response error if intercepted at response stage or if redirect occurred while intercepting
request.
*/
val responseErrorReason: ErrorReason? = null,
/**
* Response code if intercepted at response stage or if redirect occurred while intercepting
request or auth retry occurred.
*/
val responseStatusCode: Int? = null,
/**
* Response headers if intercepted at the response stage or if redirect occurred while
intercepting request or auth retry occurred.
*/
val responseHeaders: Headers? = null,
/**
* If the intercepted request had a corresponding requestWillBeSent event fired for it, then
this requestId will be the same as the requestId present in the requestWillBeSent event.
*/
val requestId: RequestId? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "requestIntercepted"
}
/**
* Fired if request ended up loading from cache.
*
* @link [Network#requestServedFromCache](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-requestServedFromCache) event documentation.
*/
@kotlinx.serialization.Serializable
data class RequestServedFromCacheEvent(
/**
* Request identifier.
*/
val requestId: RequestId
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "requestServedFromCache"
}
/**
* Fired when page is about to send HTTP request.
*
* @link [Network#requestWillBeSent](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-requestWillBeSent) event documentation.
*/
@kotlinx.serialization.Serializable
data class RequestWillBeSentEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Loader identifier. Empty string if the request is fetched from worker.
*/
val loaderId: LoaderId,
/**
* URL of the document this request is loaded for.
*/
val documentURL: String,
/**
* Request data.
*/
val request: Request,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* Timestamp.
*/
val wallTime: TimeSinceEpoch,
/**
* Request initiator.
*/
val initiator: Initiator,
/**
* Redirect response data.
*/
val redirectResponse: Response? = null,
/**
* Type of this resource.
*/
val type: ResourceType? = null,
/**
* Frame identifier.
*/
val frameId: pl.wendigo.chrome.api.page.FrameId? = null,
/**
* Whether the request is initiated by a user gesture. Defaults to false.
*/
val hasUserGesture: Boolean? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "requestWillBeSent"
}
/**
* Fired when resource loading priority is changed
*
* @link [Network#resourceChangedPriority](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-resourceChangedPriority) event documentation.
*/
@kotlinx.serialization.Serializable
data class ResourceChangedPriorityEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* New priority
*/
val newPriority: ResourcePriority,
/**
* Timestamp.
*/
val timestamp: MonotonicTime
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "resourceChangedPriority"
}
/**
* Fired when a signed exchange was received over the network
*
* @link [Network#signedExchangeReceived](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-signedExchangeReceived) event documentation.
*/
@kotlinx.serialization.Serializable
data class SignedExchangeReceivedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Information about the signed exchange response.
*/
val info: SignedExchangeInfo
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "signedExchangeReceived"
}
/**
* Fired when HTTP response is available.
*
* @link [Network#responseReceived](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-responseReceived) event documentation.
*/
@kotlinx.serialization.Serializable
data class ResponseReceivedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Loader identifier. Empty string if the request is fetched from worker.
*/
val loaderId: LoaderId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* Resource type.
*/
val type: ResourceType,
/**
* Response data.
*/
val response: Response,
/**
* Frame identifier.
*/
val frameId: pl.wendigo.chrome.api.page.FrameId? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "responseReceived"
}
/**
* Fired when WebSocket is closed.
*
* @link [Network#webSocketClosed](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketClosed) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketClosedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webSocketClosed"
}
/**
* Fired upon WebSocket creation.
*
* @link [Network#webSocketCreated](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketCreated) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketCreatedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* WebSocket request URL.
*/
val url: String,
/**
* Request initiator.
*/
val initiator: Initiator? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webSocketCreated"
}
/**
* Fired when WebSocket message error occurs.
*
* @link [Network#webSocketFrameError](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketFrameError) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketFrameErrorEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* WebSocket error message.
*/
val errorMessage: String
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webSocketFrameError"
}
/**
* Fired when WebSocket message is received.
*
* @link [Network#webSocketFrameReceived](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketFrameReceived) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketFrameReceivedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* WebSocket response data.
*/
val response: WebSocketFrame
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webSocketFrameReceived"
}
/**
* Fired when WebSocket message is sent.
*
* @link [Network#webSocketFrameSent](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketFrameSent) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketFrameSentEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* WebSocket response data.
*/
val response: WebSocketFrame
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webSocketFrameSent"
}
/**
* Fired when WebSocket handshake response becomes available.
*
* @link [Network#webSocketHandshakeResponseReceived](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketHandshakeResponseReceived) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketHandshakeResponseReceivedEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* WebSocket response data.
*/
val response: WebSocketResponse
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webSocketHandshakeResponseReceived"
}
/**
* Fired when WebSocket is about to initiate handshake.
*
* @link [Network#webSocketWillSendHandshakeRequest](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webSocketWillSendHandshakeRequest) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebSocketWillSendHandshakeRequestEvent(
/**
* Request identifier.
*/
val requestId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* UTC Timestamp.
*/
val wallTime: TimeSinceEpoch,
/**
* WebSocket request data.
*/
val request: WebSocketRequest
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webSocketWillSendHandshakeRequest"
}
/**
* Fired upon WebTransport creation.
*
* @link [Network#webTransportCreated](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webTransportCreated) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebTransportCreatedEvent(
/**
* WebTransport identifier.
*/
val transportId: RequestId,
/**
* WebTransport request URL.
*/
val url: String,
/**
* Timestamp.
*/
val timestamp: MonotonicTime,
/**
* Request initiator.
*/
val initiator: Initiator? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webTransportCreated"
}
/**
* Fired when WebTransport handshake is finished.
*
* @link [Network#webTransportConnectionEstablished](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webTransportConnectionEstablished) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebTransportConnectionEstablishedEvent(
/**
* WebTransport identifier.
*/
val transportId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webTransportConnectionEstablished"
}
/**
* Fired when WebTransport is disposed.
*
* @link [Network#webTransportClosed](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-webTransportClosed) event documentation.
*/
@kotlinx.serialization.Serializable
data class WebTransportClosedEvent(
/**
* WebTransport identifier.
*/
val transportId: RequestId,
/**
* Timestamp.
*/
val timestamp: MonotonicTime
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "webTransportClosed"
}
/**
* Fired when additional information about a requestWillBeSent event is available from the
network stack. Not every requestWillBeSent event will have an additional
requestWillBeSentExtraInfo fired for it, and there is no guarantee whether requestWillBeSent
or requestWillBeSentExtraInfo will be fired first for the same request.
*
* @link [Network#requestWillBeSentExtraInfo](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-requestWillBeSentExtraInfo) event documentation.
*/
@kotlinx.serialization.Serializable
data class RequestWillBeSentExtraInfoEvent(
/**
* Request identifier. Used to match this information to an existing requestWillBeSent event.
*/
val requestId: RequestId,
/**
* A list of cookies potentially associated to the requested URL. This includes both cookies sent with
the request and the ones not sent; the latter are distinguished by having blockedReason field set.
*/
val associatedCookies: List<BlockedCookieWithReason>,
/**
* Raw request headers as they will be sent over the wire.
*/
val headers: Headers,
/**
* The client security state set for the request.
*/
val clientSecurityState: ClientSecurityState? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "requestWillBeSentExtraInfo"
}
/**
* Fired when additional information about a responseReceived event is available from the network
stack. Not every responseReceived event will have an additional responseReceivedExtraInfo for
it, and responseReceivedExtraInfo may be fired before or after responseReceived.
*
* @link [Network#responseReceivedExtraInfo](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-responseReceivedExtraInfo) event documentation.
*/
@kotlinx.serialization.Serializable
data class ResponseReceivedExtraInfoEvent(
/**
* Request identifier. Used to match this information to another responseReceived event.
*/
val requestId: RequestId,
/**
* A list of cookies which were not stored from the response along with the corresponding
reasons for blocking. The cookies here may not be valid due to syntax errors, which
are represented by the invalid cookie line string instead of a proper cookie.
*/
val blockedCookies: List<BlockedSetCookieWithReason>,
/**
* Raw response headers as they were received over the wire.
*/
val headers: Headers,
/**
* The IP address space of the resource. The address space can only be determined once the transport
established the connection, so we can't send it in `requestWillBeSentExtraInfo`.
*/
val resourceIPAddressSpace: IPAddressSpace,
/**
* Raw response header text as it was received over the wire. The raw text may not always be
available, such as in the case of HTTP/2 or QUIC.
*/
val headersText: String? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "responseReceivedExtraInfo"
}
/**
* Fired exactly once for each Trust Token operation. Depending on
the type of the operation and whether the operation succeeded or
failed, the event is fired before the corresponding request was sent
or after the response was received.
*
* @link [Network#trustTokenOperationDone](https://chromedevtools.github.io/devtools-protocol/tot/Network#event-trustTokenOperationDone) event documentation.
*/
@kotlinx.serialization.Serializable
data class TrustTokenOperationDoneEvent(
/**
* Detailed success or error status of the operation.
'AlreadyExists' also signifies a successful operation, as the result
of the operation already exists und thus, the operation was abort
preemptively (e.g. a cache hit).
*/
val status: String,
/**
*
*/
val type: TrustTokenOperationType,
/**
*
*/
val requestId: RequestId,
/**
* Top level origin. The context in which the operation was attempted.
*/
val topLevelOrigin: String? = null,
/**
* Origin of the issuer in case of a "Issuance" or "Redemption" operation.
*/
val issuerOrigin: String? = null,
/**
* The number of obtained Trust Tokens on a successful "Issuance" operation.
*/
val issuedTokenCount: Int? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Network"
override fun eventName() = "trustTokenOperationDone"
}
| src/main/kotlin/pl/wendigo/chrome/api/network/Domain.kt | 4080330750 |
package au.com.codeka.warworlds.client.game.world
import au.com.codeka.warworlds.client.App
import au.com.codeka.warworlds.client.concurrency.Threads
import au.com.codeka.warworlds.client.store.StarCursor
import au.com.codeka.warworlds.client.util.eventbus.EventHandler
import au.com.codeka.warworlds.common.Log
import au.com.codeka.warworlds.common.proto.*
import au.com.codeka.warworlds.common.sim.MutableStar
import au.com.codeka.warworlds.common.sim.Simulation
import au.com.codeka.warworlds.common.sim.StarModifier
import au.com.codeka.warworlds.common.sim.SuspiciousModificationException
import com.google.common.collect.Lists
import java.util.*
/**
* Manages the [Star]s we keep cached and stuff.
*/
object StarManager {
private val log = Log("StarManager")
private val stars = App.dataStore.stars()
private val starModifier = StarModifier { 0 }
fun create() {
App.eventBus.register(eventListener)
}
/** Gets the star with the given ID. Might return null if don't have that star cached yet. */
fun getStar(id: Long): Star? {
// TODO: this probably shouldn't happen on a UI thread...
return stars[id]
}
/** Gets all of the stars in the given sector. */
fun searchSectorStars(sectorCoord: SectorCoord): StarCursor {
return stars.searchSectorStars(sectorCoord)
}
val myStars: StarCursor
get() = stars.myStars
fun searchMyStars(search: String?): StarCursor {
return stars.searchMyStars(search!!)
}
/**
* Gets the most recent value of last_simulation out of all our empire's stars. This is sent to
* the server in the [au.com.codeka.warworlds.common.proto.HelloPacket], so that the server
* can update us on all our stars that have been updated since we last connected.
*/
val lastSimulationOfOurStar: Long?
get() = stars.lastSimulationOfOurStar
/**
* Queue up the given [Star] to be simulated. The star will be simulated in the background
* and will be posted to the event bus when complete.
*/
fun queueSimulateStar(star: Star) {
// Something more scalable that just queuing them all to the background thread pool...
App.taskRunner.runTask(Runnable { simulateStarSync(star) }, Threads.BACKGROUND)
}
/**
* Simulate the star on the current thread.
*/
fun simulateStarSync(star: Star) {
val mutableStar = MutableStar.from(star)
Simulation().simulate(mutableStar)
// No need to save the star, it's just a simulation, but publish it to the event bus so
// clients can see it.
App.eventBus.publish(mutableStar.build())
}
fun updateStar(star: Star, m: StarModification) {
// Be sure to record our empire_id in the request.
val modification = m.copy(empire_id = EmpireManager.getMyEmpire().id)
App.taskRunner.runTask(Runnable {
// If there's any auxiliary stars, grab them now, too.
var auxiliaryStars: MutableList<Star>? = null
if (modification.star_id != null) {
auxiliaryStars = ArrayList()
val s = stars[modification.star_id!!]
if (s != null) {
auxiliaryStars.add(s)
}
}
// Modify the star.
val mutableStar = MutableStar.from(star)
try {
starModifier.modifyStar(mutableStar, Lists.newArrayList(modification), auxiliaryStars)
} catch (e: SuspiciousModificationException) {
// Mostly we don't care about these on the client, but it'll be good to log them.
log.error("Unexpected suspicious modification.", e)
return@Runnable
}
// Save the now-modified star.
val newStar = mutableStar.build()
stars.put(star.id, newStar, EmpireManager.getMyEmpire())
App.eventBus.publish(newStar)
// Send the modification to the server as well.
App.server.send(Packet(
modify_star = ModifyStarPacket(
star_id = star.id,
modification = Lists.newArrayList(modification))))
}, Threads.BACKGROUND)
}
private val eventListener: Any = object : Any() {
/**
* When the server tells us that a star has been updated, we'll want to update our cached copy
* of it.
*/
@EventHandler(thread = Threads.BACKGROUND)
fun onStarUpdatedPacket(pkt: StarUpdatedPacket) {
log.info("Stars updating, saving to database.")
val startTime = System.nanoTime()
val values: MutableMap<Long?, Star> = HashMap()
for (star in pkt.stars) {
App.eventBus.publish(star)
values[star.id] = star
}
stars.putAll(values, EmpireManager.getMyEmpire())
val endTime = System.nanoTime()
log.info("Updated %d stars in DB in %d ms", pkt.stars.size, (endTime - startTime) / 1000000L)
}
}
} | client/src/main/kotlin/au/com/codeka/warworlds/client/game/world/StarManager.kt | 507636052 |
package au.com.codeka.warworlds.client.game.empire
import android.content.Context
import android.widget.FrameLayout
/**
* ColoniesView shows a list of stars, which you can expand to see colonies that
* belong to those stars.
*/
class ColoniesView(context: Context?) /*
private StarsListAdapter adapter;
private EmpireStarsFetcher fetcher;
public ColoniesView() {
fetcher = new EmpireStarsFetcher(EmpireStarsFetcher.Filter.Colonies, null);
// fetch the first few stars
fetcher.getStars(0, 20);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.empire_colonies_tab, container, false);
ExpandableListView starsList = (ExpandableListView) v.findViewById(R.id.stars);
adapter = new ColonyStarsListAdapter(inflater, fetcher);
starsList.setAdapter(adapter);
starsList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Star star = (Star) adapter.getGroup(groupPosition);
Colony colony = (Colony) adapter.getChild(groupPosition, childPosition);
Planet planet = (Planet) star.getPlanets()[colony.getPlanetIndex() - 1];
// end this activity, go back to the starfield and navigate to the given colony
Intent intent = new Intent();
intent.putExtra("au.com.codeka.warworlds.Result",
EmpireActivity.EmpireActivityResult.NavigateToPlanet.getValue());
intent.putExtra("au.com.codeka.warworlds.SectorX", star.getSectorX());
intent.putExtra("au.com.codeka.warworlds.SectorY", star.getSectorY());
intent.putExtra("au.com.codeka.warworlds.StarOffsetX", star.getOffsetX());
intent.putExtra("au.com.codeka.warworlds.StarOffsetY", star.getOffsetY());
intent.putExtra("au.com.codeka.warworlds.StarKey", star.getKey());
intent.putExtra("au.com.codeka.warworlds.PlanetIndex", planet.getIndex());
getActivity().setResult(EmpireActivity.RESULT_OK, intent);
getActivity().finish();
return false;
}
});
final EditText searchBox = (EditText) v.findViewById(R.id.search_text);
searchBox.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
performSearch(searchBox.getText().toString());
return true;
}
return false;
}
});
ImageButton searchBtn = (ImageButton) v.findViewById(R.id.search_button);
searchBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
performSearch(searchBox.getText().toString());
}
});
return v;
}
@Override
public void onStart() {
super.onStart();
StarManager.eventBus.register(eventHandler);
}
@Override
public void onStop() {
super.onStop();
StarManager.eventBus.unregister(eventHandler);
}
private void performSearch(String search) {
fetcher = new EmpireStarsFetcher(EmpireStarsFetcher.Filter.Colonies, search);
adapter.updateFetcher(fetcher);
}
private Object eventHandler = new Object() {
@EventHandler
public void onStarUpdated(Star star) {
adapter.notifyDataSetChanged();
}
};
public static class ColonyStarsListAdapter extends StarsListAdapter {
private LayoutInflater inflater;
private MyEmpire empire;
public ColonyStarsListAdapter(LayoutInflater inflater, EmpireStarsFetcher fetcher) {
super(fetcher);
this.inflater = inflater;
empire = EmpireManager.i.getEmpire();
}
@Override
public int getNumChildren(Star star) {
int numColonies = 0;
for (int i = 0; i < star.getColonies().size(); i++) {
Integer empireID = ((Colony) star.getColonies().get(i)).getEmpireID();
if (empireID != null && empireID == empire.getID()) {
numColonies ++;
}
}
return numColonies;
}
@Override
public Object getChild(Star star, int index) {
int colonyIndex = 0;
for (int i = 0; i < star.getColonies().size(); i++) {
Integer empireID = ((Colony) star.getColonies().get(i)).getEmpireID();
if (empireID != null && empireID == empire.getID()) {
if (colonyIndex == index) {
return star.getColonies().get(i);
}
colonyIndex ++;
}
}
// Shouldn't get here...
return null;
}
@Override
public View getStarView(Star star, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.empire_colony_list_star_row, parent, false);
}
ImageView starIcon = (ImageView) view.findViewById(R.id.star_icon);
TextView starName = (TextView) view.findViewById(R.id.star_name);
TextView starType = (TextView) view.findViewById(R.id.star_type);
TextView starGoodsDelta = (TextView) view.findViewById(R.id.star_goods_delta);
TextView starGoodsTotal = (TextView) view.findViewById(R.id.star_goods_total);
TextView starMineralsDelta = (TextView) view.findViewById(R.id.star_minerals_delta);
TextView starMineralsTotal = (TextView) view.findViewById(R.id.star_minerals_total);
if (star == null) {
starIcon.setImageBitmap(null);
starName.setText("");
starType.setText("");
starGoodsDelta.setText("");
starGoodsTotal.setText("???");
starMineralsDelta.setText("");
starMineralsTotal.setText("???");
} else {
int imageSize = (int)(star.getSize() * star.getStarType().getImageScale() * 2);
Sprite sprite = StarImageManager.getInstance().getSprite(star, imageSize, true);
starIcon.setImageDrawable(new SpriteDrawable(sprite));
starName.setText(star.getName());
starType.setText(star.getStarType().getDisplayName());
MyEmpire myEmpire = EmpireManager.i.getEmpire();
EmpirePresence empirePresence = null;
for (BaseEmpirePresence baseEmpirePresence : star.getEmpirePresences()) {
if (baseEmpirePresence.getEmpireKey().equals(myEmpire.getKey())) {
empirePresence = (EmpirePresence) baseEmpirePresence;
break;
}
}
if (StarSimulationQueue.needsSimulation(star) || empirePresence == null) {
// if the star hasn't been simulated for > 5 minutes, schedule a simulation
// now and just display ??? for the various parameters
starGoodsDelta.setText("");
starGoodsTotal.setText("???");
starMineralsDelta.setText("");
starMineralsTotal.setText("???");
StarSimulationQueue.i.simulate(star, false);
} else {
starGoodsDelta.setText(String.format(Locale.ENGLISH, "%s%d/hr",
empirePresence.getDeltaGoodsPerHour() < 0 ? "-" : "+",
Math.abs(Math.round(empirePresence.getDeltaGoodsPerHour()))));
if (empirePresence.getDeltaGoodsPerHour() < 0) {
starGoodsDelta.setTextColor(Color.RED);
} else {
starGoodsDelta.setTextColor(Color.GREEN);
}
starGoodsTotal.setText(String.format(Locale.ENGLISH, "%d / %d",
Math.round(empirePresence.getTotalGoods()),
Math.round(empirePresence.getMaxGoods())));
starMineralsDelta.setText(String.format(Locale.ENGLISH, "%s%d/hr",
empirePresence.getDeltaMineralsPerHour() < 0 ? "-" : "+",
Math.abs(Math.round(empirePresence.getDeltaMineralsPerHour()))));
if (empirePresence.getDeltaMineralsPerHour() < 0) {
starMineralsDelta.setTextColor(Color.RED);
} else {
starMineralsDelta.setTextColor(Color.GREEN);
}
starMineralsTotal.setText(String.format(Locale.ENGLISH, "%d / %d",
Math.round(empirePresence.getTotalMinerals()),
Math.round(empirePresence.getMaxMinerals())));
}
}
return view;
}
@Override
public View getChildView(Star star, int index, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.empire_colony_list_colony_row, parent, false);
}
ImageView planetIcon = (ImageView) view.findViewById(R.id.planet_icon);
TextView colonyName = (TextView) view.findViewById(R.id.colony_name);
TextView colonySummary = (TextView) view.findViewById(R.id.colony_summary);
planetIcon.setImageBitmap(null);
colonyName.setText("");
colonySummary.setText("");
if (star != null) {
Colony colony = (Colony) getChild(star, index);
Planet planet = (Planet) star.getPlanets()[colony.getPlanetIndex() - 1];
if (planet != null) {
Sprite sprite = PlanetImageManager.getInstance().getSprite(planet);
planetIcon.setImageDrawable(new SpriteDrawable(sprite));
colonyName.setText(String.format("%s %s", star.getName(),
RomanNumeralFormatter.format(planet.getIndex())));
if (star.getLastSimulation().compareTo(DateTime.now(DateTimeZone.UTC)
.minusMinutes(5)) < 0) {
// if the star hasn't been simulated for > 5 minutes, just display ???
// for the various parameters (a simulation will be scheduled)
colonySummary.setText("Pop: ?");
} else {
colonySummary.setText(String.format("Pop: %d",
(int) colony.getPopulation()));
}
}
}
return view;
}
}*/ : FrameLayout(context!!) | client/src/main/kotlin/au/com/codeka/warworlds/client/game/empire/ColoniesView.kt | 3715445191 |
package com.vimeo.networking2.annotation
annotation class BasicAnnotation | model-generator/integrations/models-input/src/main/java/com/vimeo/networking2/annotation/BasicAnnotation.kt | 2811306360 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator.fixes
import org.rust.ide.inspections.RsInspectionsTestBase
import org.rust.ide.inspections.RsTypeCheckInspection
class AddAsTyFixTest : RsInspectionsTestBase(RsTypeCheckInspection::class) {
fun `test numeric value cast`() = checkFixByText("Add safe cast to u8", """
fn main () {
let _: u8 = <error>42u16/*caret*/</error>;
}
""", """
fn main () {
let _: u8 = 42u16 as u8;
}
""")
fun `test numeric inferred value cast`() = checkFixByText("Add safe cast to f32", """
fn main () {
let _: f32 = <error>42/*caret*/</error>;
}
""", """
fn main () {
let _: f32 = 42 as f32;
}
""")
fun `test numeric variable cast`() = checkFixByText("Add safe cast to i64", """
fn main () {
let x: i32 = 42;
let y: i64 = <error>x/*caret*/</error>;
}
""", """
fn main () {
let x: i32 = 42;
let y: i64 = x as i64;
}
""")
fun `test numeric function call result cast`() = checkFixByText("Add safe cast to f32", """
fn answer() -> i32 {42}
fn main () {
let _: f32 = <error>answer()/*caret*/</error>;
}
""", """
fn answer() -> i32 {42}
fn main () {
let _: f32 = answer() as f32;
}
""")
fun `test type alias`() = checkFixByText("Add safe cast to Foo", """
type Foo = f32;
fn answer() -> i32 {42}
fn main () {
let _: Foo = <error>answer()/*caret*/</error>;
}
""", """
type Foo = f32;
fn answer() -> i32 {42}
fn main () {
let _: Foo = answer() as Foo;
}
""")
}
| src/test/kotlin/org/rust/ide/annotator/fixes/AddAsTyFixTest.kt | 3688554742 |
interface GameStage
{
fun handleController(controller: Controller)
fun update()
val root: PIXI.DisplayObject
val gameSize: Point
val ended: Boolean
}
class IngameStage(val size: Point, val levelIndex: Int): GameStage
{
val node = PIXI.Container()
val level = Level(node, Layout.levels[levelIndex], size)
var running = true
override fun handleController(controller: Controller)
{
/*if (controller.isActive(ControllerAction.Step))
{
running = false
level.update()
}*/
if (controller.isActive(ControllerAction.Up))
{
level.jump()
}
if (controller.isActive(ControllerAction.Select))
{
level.action()
}
when
{
controller.isActive(ControllerAction.Left) ->
level.moveLeft()
controller.isActive(ControllerAction.Right) ->
level.moveRight()
}
}
override fun update()
{
if (running)
{
level.update()
}
}
override val root: PIXI.DisplayObject
get() = node
override val gameSize: Point
get() = size
override val ended: Boolean
get() = level.completed
}
| src/GameStage.kt | 403530569 |
package com.habitrpg.android.habitica.ui.fragments.social
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import com.habitrpg.android.habitica.MainNavDirections
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.databinding.FragmentInboxMessageListBinding
import com.habitrpg.android.habitica.extensions.addOkButton
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.social.ChatMessage
import com.habitrpg.android.habitica.ui.activities.FullProfileActivity
import com.habitrpg.android.habitica.ui.activities.MainActivity
import com.habitrpg.android.habitica.ui.adapter.social.InboxAdapter
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import com.habitrpg.android.habitica.ui.helpers.KeyboardUtil
import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator
import com.habitrpg.android.habitica.ui.viewmodels.InboxViewModel
import com.habitrpg.android.habitica.ui.viewmodels.InboxViewModelFactory
import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar
import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar.Companion.showSnackbar
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class InboxMessageListFragment : BaseMainFragment<FragmentInboxMessageListBinding>() {
override var binding: FragmentInboxMessageListBinding? = null
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentInboxMessageListBinding {
return FragmentInboxMessageListBinding.inflate(inflater, container, false)
}
@Inject
lateinit var socialRepository: SocialRepository
@Inject
lateinit var configManager: AppConfigManager
private var chatAdapter: InboxAdapter? = null
private var chatRoomUser: String? = null
private var replyToUserUUID: String? = null
private val viewModel: InboxViewModel by viewModels(factoryProducer = {
InboxViewModelFactory(replyToUserUUID, chatRoomUser)
})
private var refreshDisposable: Disposable? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
this.hidesToolbar = true
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
showsBackButton = true
super.onViewCreated(view, savedInstanceState)
arguments?.let {
val args = InboxMessageListFragmentArgs.fromBundle(it)
setReceivingUser(args.username, args.userID)
}
val layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this.getActivity())
layoutManager.reverseLayout = true
layoutManager.stackFromEnd = false
binding?.recyclerView?.layoutManager = layoutManager
val observable = if (replyToUserUUID?.isNotBlank() == true) {
apiClient.getMember(replyToUserUUID!!)
} else {
apiClient.getMemberWithUsername(chatRoomUser ?: "")
}
compositeSubscription.add(
observable.subscribe(
{ member ->
setReceivingUser(member.username, member.id)
activity?.title = member.displayName
chatAdapter = InboxAdapter(viewModel.user.value, member)
chatAdapter?.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
if (positionStart == 0) {
binding?.recyclerView?.scrollToPosition(0)
}
}
})
viewModel.messages.observe(this.viewLifecycleOwner) {
markMessagesAsRead(it)
chatAdapter?.submitList(it)
}
binding?.recyclerView?.adapter = chatAdapter
binding?.recyclerView?.itemAnimator = SafeDefaultItemAnimator()
chatAdapter?.let { adapter ->
compositeSubscription.add(
adapter.getUserLabelClickFlowable().subscribe(
{
FullProfileActivity.open(it)
},
RxErrorHandler.handleEmptyError()
)
)
compositeSubscription.add(adapter.getDeleteMessageFlowable().subscribe({ this.showDeleteConfirmationDialog(it) }, RxErrorHandler.handleEmptyError()))
compositeSubscription.add(adapter.getFlagMessageClickFlowable().subscribe({ this.showFlagConfirmationDialog(it) }, RxErrorHandler.handleEmptyError()))
compositeSubscription.add(adapter.getCopyMessageFlowable().subscribe({ this.copyMessageToClipboard(it) }, RxErrorHandler.handleEmptyError()))
}
},
RxErrorHandler.handleEmptyError()
)
)
binding?.chatBarView?.sendAction = { sendMessage(it) }
binding?.chatBarView?.maxChatLength = configManager.maxChatLength()
binding?.chatBarView?.hasAcceptedGuidelines = true
}
override fun onResume() {
if (replyToUserUUID?.isNotBlank() != true && chatRoomUser?.isNotBlank() != true) {
parentFragmentManager.popBackStack()
}
startAutoRefreshing()
super.onResume()
}
override fun onAttach(context: Context) {
view?.invalidate()
view?.forceLayout()
super.onAttach(context)
}
override fun onDestroyView() {
super.onDestroyView()
stopAutoRefreshing()
}
override fun onPause() {
super.onPause()
stopAutoRefreshing()
}
override fun onDestroy() {
socialRepository.close()
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
this.activity?.menuInflater?.inflate(R.menu.inbox_chat, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.open_profile -> {
openProfile()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun markMessagesAsRead(messages: List<ChatMessage>) {
socialRepository.markSomePrivateMessagesAsRead(viewModel.user.value, messages)
}
private fun startAutoRefreshing() {
if (refreshDisposable != null && refreshDisposable?.isDisposed != true) {
refreshDisposable?.dispose()
}
refreshDisposable = Observable.interval(30, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
refreshConversation()
},
RxErrorHandler.handleEmptyError()
)
refreshConversation()
}
private fun stopAutoRefreshing() {
if (refreshDisposable?.isDisposed != true) {
refreshDisposable?.dispose()
refreshDisposable = null
}
}
private fun refreshConversation() {
if (viewModel.memberID?.isNotBlank() != true) { return }
compositeSubscription.add(
this.socialRepository.retrieveInboxMessages(replyToUserUUID ?: "", 0)
.subscribe(
{}, RxErrorHandler.handleEmptyError(),
{
viewModel.invalidateDataSource()
}
)
)
}
private fun sendMessage(chatText: String) {
viewModel.memberID?.let { userID ->
socialRepository.postPrivateMessage(userID, chatText)
.delay(200, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
viewModel.invalidateDataSource()
},
{ error ->
RxErrorHandler.reportError(error)
binding?.let {
val alert = HabiticaAlertDialog(it.chatBarView.context)
alert.setTitle("You cannot reply to this conversation")
alert.setMessage("This user is unable to receive your private message")
alert.addOkButton()
alert.show()
}
binding?.chatBarView?.message = chatText
}
)
KeyboardUtil.dismissKeyboard(getActivity())
}
}
private fun setReceivingUser(chatRoomUser: String?, replyToUserUUID: String?) {
this.chatRoomUser = chatRoomUser
this.replyToUserUUID = replyToUserUUID
activity?.title = chatRoomUser
}
private fun copyMessageToClipboard(chatMessage: ChatMessage) {
val clipMan = getActivity()?.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
val messageText = ClipData.newPlainText("Chat message", chatMessage.text)
clipMan?.setPrimaryClip(messageText)
val activity = getActivity() as? MainActivity
if (activity != null) {
showSnackbar(activity.snackbarContainer, getString(R.string.chat_message_copied), HabiticaSnackbar.SnackbarDisplayType.NORMAL)
}
}
private fun showFlagConfirmationDialog(chatMessage: ChatMessage) {
val directions = MainNavDirections.actionGlobalReportMessageActivity(chatMessage.text ?: "", chatMessage.user ?: "", chatMessage.id, null)
MainNavigationController.navigate(directions)
}
private fun showDeleteConfirmationDialog(chatMessage: ChatMessage) {
val context = context
if (context != null) {
AlertDialog.Builder(context)
.setTitle(R.string.confirm_delete_tag_title)
.setMessage(R.string.confirm_delete_tag_message)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.yes) { _, _ -> socialRepository.deleteMessage(chatMessage).subscribe({ }, RxErrorHandler.handleEmptyError()) }
.setNegativeButton(R.string.no, null).show()
}
}
private fun openProfile() {
replyToUserUUID?.let { FullProfileActivity.open(it) }
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/InboxMessageListFragment.kt | 4227842275 |
package nl.rsdt.japp.jotial.data.structures.area348
import android.os.Parcel
import android.os.Parcelable
import com.google.android.gms.maps.model.LatLng
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 20-10-2015
* Class that servers as a deserialization object for the most abstract Info.
*/
open class BaseInfo
/**
* Initializes a new instance of BaseInfo from the parcel.
*/
protected constructor(`in`: Parcel) : Parcelable {
/**
* The id of the Info.
*/
var id: Int = 0
/**
* The latitude of the Info.
*/
var latitude: Double = 0.toDouble()
/**
* The longitude of the Info.
*/
var longitude: Double = 0.toDouble()
val latLng: LatLng
get() = LatLng(latitude, longitude)
init {
id = `in`.readInt()
latitude = `in`.readDouble()
longitude = `in`.readDouble()
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(id)
dest.writeDouble(latitude)
dest.writeDouble(longitude)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR: Parcelable.Creator<BaseInfo>{
override fun createFromParcel(`in`: Parcel): BaseInfo {
return BaseInfo(`in`)
}
override fun newArray(size: Int): Array<BaseInfo?> {
return arrayOfNulls(size)
}
}
}
| app/src/main/java/nl/rsdt/japp/jotial/data/structures/area348/BaseInfo.kt | 3729375056 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.uwb.rxjava3.mock
import androidx.core.uwb.RangingCapabilities
import androidx.core.uwb.RangingParameters
import androidx.core.uwb.RangingResult
import androidx.core.uwb.UwbAddress
import androidx.core.uwb.UwbComplexChannel
import androidx.core.uwb.UwbControllerSessionScope
import kotlinx.coroutines.flow.Flow
class TestUwbControllerSessionScope(
private val uwbClient: TestUwbClient,
override val rangingCapabilities: RangingCapabilities,
override val localAddress: UwbAddress,
override val uwbComplexChannel: UwbComplexChannel
) : UwbControllerSessionScope {
private val uwbClientSessionScope =
TestUwbClientSessionScope(uwbClient, rangingCapabilities, localAddress)
override suspend fun addControlee(address: UwbAddress) {
val uwbAddress = com.google.android.gms.nearby.uwb.UwbAddress(address.address)
uwbClient.addControlee(uwbAddress)
}
override suspend fun removeControlee(address: UwbAddress) {
val uwbAddress = com.google.android.gms.nearby.uwb.UwbAddress(address.address)
uwbClient.removeControlee(uwbAddress)
}
override fun prepareSession(parameters: RangingParameters): Flow<RangingResult> {
return uwbClientSessionScope.prepareSession(parameters)
}
} | core/uwb/uwb-rxjava3/src/androidTest/java/androidx/core/uwb/rxjava3/mock/TestUwbControllerSessionScope.kt | 3324254552 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.tv.foundation.lazy.grid
/**
* DSL marker used to distinguish between lazy grid dsl scope and the item content scope.
*/
@DslMarker
annotation class TvLazyGridScopeMarker
| tv/tv-foundation/src/main/java/androidx/tv/foundation/lazy/grid/TvLazyGridScopeMarker.kt | 3466923453 |
package org.elm.ide.refactoring
import com.intellij.lang.ImportOptimizer
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiRecursiveElementWalkingVisitor
import org.elm.ide.inspections.ImportVisitor
import org.elm.lang.core.psi.ElmFile
import org.elm.lang.core.psi.elements.ElmImportClause
import org.elm.lang.core.psi.elements.removeItem
import org.elm.lang.core.psi.parentOfType
import org.elm.lang.core.psi.prevSiblings
import org.elm.lang.core.resolve.scope.ModuleScope
class ElmImportOptimizer: ImportOptimizer {
override fun supports(file: PsiFile): Boolean =
file is ElmFile
override fun processFile(file: PsiFile): Runnable {
if (file !is ElmFile) error("expected an Elm File!")
// Pre-compute the unused elements prior to performing the
// actual edits in the Runnable on the UI thread.
val visitor = ImportVisitor(ModuleScope.getImportDecls(file))
file.accept(object : PsiRecursiveElementWalkingVisitor() {
override fun visitElement(element: PsiElement) {
element.accept(visitor)
super.visitElement(element)
}
})
return Runnable {
val documentManager = PsiDocumentManager.getInstance(file.project)
val document = documentManager.getDocument(file)
if (document != null) {
documentManager.commitDocument(document)
}
execute(visitor)
}
}
private fun execute(visitor: ImportVisitor) {
for (unusedImport in visitor.unusedImports) {
val prevNewline = unusedImport.prevSiblings.firstOrNull { it.textContains('\n') }
if (prevNewline == null) unusedImport.delete()
else unusedImport.parent.deleteChildRange(prevNewline, unusedImport)
}
for (item in visitor.unusedExposedItems) {
val exposingList = item.parentOfType<ElmImportClause>()?.exposingList ?: continue
if (exposingList.allExposedItems.size <= 1) exposingList.delete()
else exposingList.removeItem(item)
}
for (alias in visitor.unusedModuleAliases) {
val parent = alias.parentOfType<ElmImportClause>() ?: continue
// Delete the alias and the preceding whitespace
parent.deleteChildRange(parent.moduleQID.nextSibling, alias)
}
}
}
| src/main/kotlin/org/elm/ide/refactoring/ElmImportOptimizer.kt | 3051816065 |
/*******************************************************************************
* Copyright 2000-2015 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.ui.builder
import org.eclipse.core.runtime.IProgressMonitor
import org.eclipse.core.runtime.IStatus
import org.eclipse.core.runtime.NullProgressMonitor
import org.eclipse.core.runtime.Status
import org.eclipse.core.runtime.jobs.IJobChangeEvent
import org.eclipse.core.runtime.jobs.Job
import org.eclipse.core.runtime.jobs.JobChangeAdapter
import org.eclipse.jdt.core.IJavaProject
import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.core.model.KotlinAnalysisProjectCache
import org.jetbrains.kotlin.progress.CompilationCanceledException
import org.jetbrains.kotlin.progress.CompilationCanceledStatus
import org.jetbrains.kotlin.progress.ProgressIndicatorAndCompilationCanceledStatus
public class KotlinAnalysisJob(private val javaProject: IJavaProject) : Job("Kotlin Analysis") {
init {
setPriority(DECORATE)
setSystem(true)
}
val familyIndicator = constructFamilyIndicator(javaProject)
@Volatile var canceled = false
override fun run(monitor: IProgressMonitor): IStatus {
try {
canceled = false
ProgressIndicatorAndCompilationCanceledStatus.setCompilationCanceledStatus(object : CompilationCanceledStatus {
override fun checkCanceled() {
if (canceled) throw CompilationCanceledException()
}
})
if (!javaProject.isOpen) {
return Status.OK_STATUS
}
val analysisResult = KotlinAnalysisProjectCache.getAnalysisResult(javaProject)
return AnalysisResultStatus(Status.OK_STATUS, analysisResult)
} catch (e: CompilationCanceledException) {
return AnalysisResultStatus(Status.CANCEL_STATUS, AnalysisResult.EMPTY)
} finally {
ProgressIndicatorAndCompilationCanceledStatus.setCompilationCanceledStatus(null)
}
}
override fun belongsTo(family: Any): Boolean = family == familyIndicator
override fun canceling() {
super.canceling()
canceled = true
}
class AnalysisResultStatus(val status: IStatus, val analysisResult: AnalysisResult): IStatus by status
}
private fun constructFamilyIndicator(javaProject: IJavaProject): String {
return javaProject.getProject().getName() + "_kotlinAnalysisFamily"
}
fun runCancellableAnalysisFor(javaProject: IJavaProject, postAnalysisTask: (AnalysisResult) -> Unit = {}) {
val family = constructFamilyIndicator(javaProject)
Job.getJobManager().cancel(family)
Job.getJobManager().join(family, NullProgressMonitor()) // It should be fast enough
KotlinAnalysisProjectCache.resetCache(javaProject.project)
val analysisJob = KotlinAnalysisJob(javaProject)
analysisJob.addJobChangeListener(object : JobChangeAdapter() {
override fun done(event: IJobChangeEvent) {
val result = event.result
if (result is KotlinAnalysisJob.AnalysisResultStatus && result.isOK) {
postAnalysisTask(result.analysisResult)
}
}
})
analysisJob.schedule()
} | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/builder/KotlinAnalysisJob.kt | 745768070 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.editor.markup.EffectType
@State(name = "MinecraftSettings", storages = [Storage("minecraft_dev.xml")])
class MinecraftSettings : PersistentStateComponent<MinecraftSettings.State> {
data class State(
var isShowProjectPlatformIcons: Boolean = true,
var isShowEventListenerGutterIcons: Boolean = true,
var isShowChatColorGutterIcons: Boolean = true,
var isShowChatColorUnderlines: Boolean = false,
var underlineType: UnderlineType = UnderlineType.DOTTED
)
private var state = State()
override fun getState(): State {
return state
}
override fun loadState(state: State) {
this.state = state
}
// State mappings
var isShowProjectPlatformIcons: Boolean
get() = state.isShowProjectPlatformIcons
set(showProjectPlatformIcons) {
state.isShowProjectPlatformIcons = showProjectPlatformIcons
}
var isShowEventListenerGutterIcons: Boolean
get() = state.isShowEventListenerGutterIcons
set(showEventListenerGutterIcons) {
state.isShowEventListenerGutterIcons = showEventListenerGutterIcons
}
var isShowChatColorGutterIcons: Boolean
get() = state.isShowChatColorGutterIcons
set(showChatColorGutterIcons) {
state.isShowChatColorGutterIcons = showChatColorGutterIcons
}
var isShowChatColorUnderlines: Boolean
get() = state.isShowChatColorUnderlines
set(showChatColorUnderlines) {
state.isShowChatColorUnderlines = showChatColorUnderlines
}
var underlineType: UnderlineType
get() = state.underlineType
set(underlineType) {
state.underlineType = underlineType
}
val underlineTypeIndex: Int
get() {
val type = underlineType
return UnderlineType.values().indices.firstOrNull { type == UnderlineType.values()[it] } ?: 0
}
enum class UnderlineType(private val regular: String, val effectType: EffectType) {
NORMAL("Normal", EffectType.LINE_UNDERSCORE),
BOLD("Bold", EffectType.BOLD_LINE_UNDERSCORE),
DOTTED("Dotted", EffectType.BOLD_DOTTED_LINE),
BOXED("Boxed", EffectType.BOXED),
ROUNDED_BOXED("Rounded Boxed", EffectType.ROUNDED_BOX),
WAVED("Waved", EffectType.WAVE_UNDERSCORE);
override fun toString(): String {
return regular
}
}
companion object {
val instance: MinecraftSettings
get() = ApplicationManager.getApplication().getService(MinecraftSettings::class.java)
}
}
| src/main/kotlin/MinecraftSettings.kt | 2710173229 |
package net.devromik.bw.x
import net.devromik.bw.Color.*
import net.devromik.bw.Coloring
import net.devromik.bw.INVALID_MAX_WHITE
import net.devromik.bw.checkColoring
import net.devromik.tree.Tree
import net.devromik.tree.root
import org.junit.Test
import org.junit.Assert.*
/**
* @author Shulnyaev Roman
*/
class FixedRootColorSingleChildXResultTest {
/**
* root -> child -> child
*/
@Test fun maxWhiteMap_1() {
val tree = Tree<String>(
root() {
child {
child()
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
// BLACK
var result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
var maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(1, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 4))
// WHITE
result = FixedRootColorSingleChildXResult(tree.root, WHITE, top)
maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(1, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(3, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(2, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 4))
// GRAY
result = FixedRootColorSingleChildXResult(tree.root, GRAY, top)
maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(2, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(1, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 4))
}
/**
* root
* -> child
* -> child
* -> child
*/
@Test fun maxWhiteMap_2() {
val tree = Tree<String>(
root() {
child {
child()
child()
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
// BLACK
var result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
var maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 3))
// WHITE
result = FixedRootColorSingleChildXResult(tree.root, WHITE, top)
maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(2, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(1, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 3))
// GRAY
result = FixedRootColorSingleChildXResult(tree.root, GRAY, top)
maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(1, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 3))
}
/**
* root
* -> child
* -> child
* -> child
* -> child
* -> child
*/
@Test fun maxWhiteMap_3() {
val tree = Tree<String>(
root() {
child {
child {
child {
child()
child()
}
}
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
// BLACK
var result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
var maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 5))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(2, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(1, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 5))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(1, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 5))
// WHITE
result = FixedRootColorSingleChildXResult(tree.root, WHITE, top)
maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(2, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(1, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 5))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(4, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 5))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(3, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(1, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 5))
// GRAY
result = FixedRootColorSingleChildXResult(tree.root, GRAY, top)
maxWhiteMap = result.maxWhiteMap()
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = -1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 0))
assertEquals(1, maxWhiteMap.get(rootColor = BLACK, black = 1))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 2))
assertEquals(0, maxWhiteMap.get(rootColor = BLACK, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = BLACK, black = 5))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = -1))
assertEquals(3, maxWhiteMap.get(rootColor = WHITE, black = 0))
assertEquals(1, maxWhiteMap.get(rootColor = WHITE, black = 1))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = WHITE, black = 5))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = -1))
assertEquals(2, maxWhiteMap.get(rootColor = GRAY, black = 0))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 1))
assertEquals(0, maxWhiteMap.get(rootColor = GRAY, black = 2))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 3))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 4))
assertEquals(INVALID_MAX_WHITE, maxWhiteMap.get(rootColor = GRAY, black = 5))
}
/**
* root -> child -> child
*/
@Test fun coloring_1() {
val tree = Tree<String>(
root() {
child {
child()
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
val coloring = Coloring(tree)
/* ***** Root color BLACK ***** */
var result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
// Last chain node color BLACK
result.color(coloring, lastChainNodeColor = BLACK, black = 2, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 0)
result.color(coloring, lastChainNodeColor = BLACK, black = 3, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 3, white = 0)
// Last chain node color WHITE
result.color(coloring, lastChainNodeColor = WHITE, black = 1, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 1)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 1, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 0)
result.color(coloring, lastChainNodeColor = GRAY, black = 2, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 0)
/* ***** Root color WHITE ***** */
result = FixedRootColorSingleChildXResult(tree.root, WHITE, top)
// Last chain node color BLACK
result.color(coloring, lastChainNodeColor = BLACK, black = 1, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 1)
// Last chain node color WHITE
result.color(coloring, lastChainNodeColor = WHITE, black = 0, maxWhite = 3)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 3)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 0, maxWhite = 2)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 2)
/* ***** Root color GRAY ***** */
result = FixedRootColorSingleChildXResult(tree.root, GRAY, top)
// Last chain node color BLACK
result.color(coloring, lastChainNodeColor = BLACK, black = 1, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 0)
result.color(coloring, lastChainNodeColor = BLACK, black = 2, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 0)
// Last chain node color WHITE
result.color(coloring, lastChainNodeColor = WHITE, black = 0, maxWhite = 2)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 2)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 0, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 1)
result.color(coloring, lastChainNodeColor = GRAY, black = 1, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 0)
}
/**
* root
* -> child
* -> child
* -> child
*/
@Test fun coloring_2() {
val tree = Tree<String>(
root() {
child { // new root
child() // should be ignored
child() // should be ignored
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
val coloring = Coloring(tree)
/* ***** Root color BLACK ***** */
var result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
// Last chain node color BLACK
result.color(coloring, lastChainNodeColor = BLACK, black = 2, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 0)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 1, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 0)
/* ***** Root color WHITE ***** */
result = FixedRootColorSingleChildXResult(tree.root, WHITE, top)
// Last chain node color WHITE
result.color(coloring, lastChainNodeColor = WHITE, black = 0, maxWhite = 2)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 2)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 0, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 1)
/* ***** Root color GRAY ***** */
result = FixedRootColorSingleChildXResult(tree.root, GRAY, top)
// Last chain node color BLACK
result.color(coloring, lastChainNodeColor = BLACK, black = 1, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 0)
// Last chain node color WHITE
result.color(coloring, lastChainNodeColor = WHITE, black = 0, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 1)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 0, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 0)
}
/**
* root
* -> child
* -> child
* -> child
* -> child
* -> child
*/
@Test fun coloring_3() {
val tree = Tree<String>(
root() {
child {
child {
child { // new root
child() // should be ignored
child() // should be ignored
}
}
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
val coloring = Coloring(tree)
/* ***** Root color BLACK ***** */
var result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
// Last chain node color BLACK
result.color(coloring, lastChainNodeColor = BLACK, black = 2, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 0)
result.color(coloring, lastChainNodeColor = BLACK, black = 3, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 3, white = 0)
result.color(coloring, lastChainNodeColor = BLACK, black = 4, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 4, white = 0)
// Last chain node color WHITE
result.color(coloring, lastChainNodeColor = WHITE, black = 1, maxWhite = 2)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 2)
result.color(coloring, lastChainNodeColor = WHITE, black = 2, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 1)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 1, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 1)
result.color(coloring, lastChainNodeColor = GRAY, black = 2, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 0)
result.color(coloring, lastChainNodeColor = GRAY, black = 3, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 3, white = 0)
/* ***** Root color WHITE ***** */
result = FixedRootColorSingleChildXResult(tree.root, WHITE, top)
// Last chain node color BLACK
result.color(coloring, lastChainNodeColor = BLACK, black = 1, maxWhite = 2)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 2)
result.color(coloring, lastChainNodeColor = BLACK, black = 2, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 1)
// Last chain node color WHITE
result.color(coloring, lastChainNodeColor = WHITE, black = 0, maxWhite = 4)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 4)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 0, maxWhite = 3)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 3)
result.color(coloring, lastChainNodeColor = GRAY, black = 1, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 1)
/* ***** Root color GRAY ***** */
result = FixedRootColorSingleChildXResult(tree.root, GRAY, top)
// Last chain node color BLACK
result.color(coloring, lastChainNodeColor = BLACK, black = 1, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 1)
result.color(coloring, lastChainNodeColor = BLACK, black = 2, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 0)
result.color(coloring, lastChainNodeColor = BLACK, black = 3, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 3, white = 0)
// Last chain node color WHITE
result.color(coloring, lastChainNodeColor = WHITE, black = 0, maxWhite = 3)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 3)
result.color(coloring, lastChainNodeColor = WHITE, black = 1, maxWhite = 1)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 1)
// Last chain node color GRAY
result.color(coloring, lastChainNodeColor = GRAY, black = 0, maxWhite = 2)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 0, white = 2)
result.color(coloring, lastChainNodeColor = GRAY, black = 1, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 1, white = 0)
result.color(coloring, lastChainNodeColor = GRAY, black = 2, maxWhite = 0)
checkColoring(tree, result.subtreeSize, coloring = coloring, black = 2, white = 0)
}
/**
* root -> child -> child
*/
@Test fun subtreeSize_1() {
val tree = Tree<String>(
root() {
child {
child()
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
val result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
assertEquals(3, result.subtreeSize())
assertEquals(tree.root.childAt(0).childAt(0), result.lastChainNode)
}
/**
* root
* -> child
* -> child
* -> child
*/
@Test fun subtreeSize_2() {
val tree = Tree<String>(
root() {
child { // new root
child() // should be ignored
child() // should be ignored
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
val result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
assertEquals(2, result.subtreeSize())
assertEquals(tree.root.childAt(0), result.lastChainNode)
}
/**
* root
* -> child
* -> child
* -> child
* -> child
* -> child
*/
@Test fun subtreeSize_3() {
val tree = Tree<String>(
root() {
child {
child {
child { // new root
child() // should be ignored
child() // should be ignored
}
}
}
}
)
tree.index()
val top = SingleNodeXResult(tree.root)
val result = FixedRootColorSingleChildXResult(tree.root, BLACK, top)
assertEquals(4, result.subtreeSize())
assertEquals(tree.root.childAt(0).childAt(0).childAt(0), result.lastChainNode)
}
} | sources/src/test/kotlin/net/devromik/bw/x/FixedRootColorSingleChildXResultTest.kt | 4160715948 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.bungeecord.creator
import com.demonwav.mcdev.creator.ProjectConfig
import com.demonwav.mcdev.creator.ProjectCreator
import com.demonwav.mcdev.creator.buildsystem.BuildSystemType
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleBuildSystem
import com.demonwav.mcdev.creator.buildsystem.gradle.GradleCreator
import com.demonwav.mcdev.creator.buildsystem.maven.MavenBuildSystem
import com.demonwav.mcdev.creator.buildsystem.maven.MavenCreator
import com.demonwav.mcdev.platform.PlatformType
import com.demonwav.mcdev.platform.bukkit.BukkitLikeConfiguration
import com.demonwav.mcdev.util.MinecraftVersions
import com.demonwav.mcdev.util.SemanticVersion
import com.demonwav.mcdev.util.VersionRange
import com.intellij.openapi.module.Module
import com.intellij.util.lang.JavaVersion
import java.nio.file.Path
class BungeeCordProjectConfig(override var type: PlatformType) :
ProjectConfig(), MavenCreator, GradleCreator, BukkitLikeConfiguration {
override lateinit var mainClass: String
var minecraftVersion = ""
val semanticMinecraftVersion: SemanticVersion
get() = if (minecraftVersion.isBlank()) SemanticVersion.release() else SemanticVersion.parse(minecraftVersion)
override val dependencies = mutableListOf<String>()
override fun hasDependencies() = listContainsAtLeastOne(dependencies)
override fun setDependencies(string: String) {
dependencies.clear()
dependencies.addAll(commaSplit(string))
}
override val softDependencies = mutableListOf<String>()
override fun hasSoftDependencies() = listContainsAtLeastOne(softDependencies)
override fun setSoftDependencies(string: String) {
softDependencies.clear()
softDependencies.addAll(commaSplit(string))
}
override val preferredBuildSystem = BuildSystemType.MAVEN
override val javaVersion: JavaVersion
get() = MinecraftVersions.requiredJavaVersion(semanticMinecraftVersion)
override val compatibleGradleVersions: VersionRange? = null
override fun buildMavenCreator(
rootDirectory: Path,
module: Module,
buildSystem: MavenBuildSystem
): ProjectCreator {
return BungeeCordMavenCreator(rootDirectory, module, buildSystem, this)
}
override fun buildGradleCreator(
rootDirectory: Path,
module: Module,
buildSystem: GradleBuildSystem
): ProjectCreator {
return BungeeCordGradleCreator(rootDirectory, module, buildSystem, this)
}
}
| src/main/kotlin/platform/bungeecord/creator/BungeeCordProjectConfig.kt | 2071510723 |
package org.ccci.gto.android.common.util
import java.text.DecimalFormat
import java.text.NumberFormat
import java.util.Currency
import java.util.Locale
import org.ccci.gto.android.common.compat.util.LocaleCompat
import org.ccci.gto.android.common.compat.util.LocaleCompat.Category
import timber.log.Timber
@JvmOverloads
fun Double.formatCurrency(currency: String?, locale: Locale = LocaleCompat.getDefault(Category.FORMAT)) =
formatCurrency(currency?.toCurrencyOrNull(), locale)
fun Double.formatCurrency(
currency: Currency? = null,
locale: Locale = LocaleCompat.getDefault(Category.FORMAT)
): String = NumberFormat.getCurrencyInstance(locale)
.also {
if (currency != null) {
it.currency = currency
it.minimumFractionDigits = currency.defaultFractionDigits
it.maximumFractionDigits = currency.defaultFractionDigits
} else if (it is DecimalFormat) {
val symbols = it.decimalFormatSymbols
symbols.currencySymbol = ""
it.decimalFormatSymbols = symbols
}
}
.format(this)
fun String.toCurrencyOrNull() = try {
Currency.getInstance(this)
} catch (e: IllegalArgumentException) {
Timber.tag("CurrencyUtils").e(e, "Unsupported currency: %s", this)
null
}
| gto-support-util/src/main/java/org/ccci/gto/android/common/util/CurrencyUtils.kt | 1899661730 |
package eu.kanade.tachiyomi.extension.en.bilibilicomics
import eu.kanade.tachiyomi.annotations.Nsfw
import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor
import eu.kanade.tachiyomi.network.POST
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.add
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import okhttp3.Headers
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import org.jsoup.Jsoup
import rx.Observable
import uy.kohesive.injekt.injectLazy
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import java.util.concurrent.TimeUnit
@Nsfw
class BilibiliComics : HttpSource() {
override val name = "BILIBILI COMICS"
override val baseUrl = "https://www.bilibilicomics.com"
override val lang = "en"
override val supportsLatest = true
override val client: OkHttpClient = network.cloudflareClient.newBuilder()
.addInterceptor(RateLimitInterceptor(1, 1, TimeUnit.SECONDS))
.build()
override fun headersBuilder(): Headers.Builder = Headers.Builder()
.add("Accept", ACCEPT_JSON)
.add("Origin", baseUrl)
.add("Referer", "$baseUrl/")
private val json: Json by injectLazy()
override fun popularMangaRequest(page: Int): Request {
val requestPayload = buildJsonObject {
put("id", FEATURED_ID)
put("isAll", 0)
put("page_num", 1)
put("page_size", 6)
}
val requestBody = requestPayload.toString().toRequestBody(JSON_MEDIA_TYPE)
val newHeaders = headersBuilder()
.add("Content-Length", requestBody.contentLength().toString())
.add("Content-Type", requestBody.contentType().toString())
.build()
return POST(
"$baseUrl/$BASE_API_ENDPOINT/GetClassPageSixComics?device=pc&platform=web",
headers = newHeaders,
body = requestBody
)
}
override fun popularMangaParse(response: Response): MangasPage {
val result = json.decodeFromString<BilibiliResultDto<BilibiliFeaturedDto>>(response.body!!.string())
if (result.code != 0) {
return MangasPage(emptyList(), hasNextPage = false)
}
val comicList = result.data!!.rollSixComics
.map(::popularMangaFromObject)
return MangasPage(comicList, hasNextPage = false)
}
private fun popularMangaFromObject(comic: BilibiliComicDto): SManga = SManga.create().apply {
title = comic.title
thumbnail_url = comic.verticalCover
url = "/detail/mc${comic.comicId}"
}
override fun latestUpdatesRequest(page: Int): Request {
val requestPayload = buildJsonObject {
put("day", day)
}
val requestBody = requestPayload.toString().toRequestBody(JSON_MEDIA_TYPE)
val newHeaders = headersBuilder()
.add("Content-Length", requestBody.contentLength().toString())
.add("Content-Type", requestBody.contentType().toString())
.build()
return POST(
"$baseUrl/$BASE_API_ENDPOINT/GetSchedule?device=pc&platform=web",
headers = newHeaders,
body = requestBody
)
}
override fun latestUpdatesParse(response: Response): MangasPage {
val result = json.decodeFromString<BilibiliResultDto<BilibiliScheduleDto>>(response.body!!.string())
if (result.code != 0) {
return MangasPage(emptyList(), hasNextPage = false)
}
val comicList = result.data!!.list
.map(::latestMangaFromObject)
return MangasPage(comicList, hasNextPage = false)
}
private fun latestMangaFromObject(comic: BilibiliComicDto): SManga = SManga.create().apply {
title = comic.title
thumbnail_url = comic.verticalCover
url = "/detail/mc${comic.comicId}"
}
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
return when {
query.startsWith(prefixIdSearch) -> {
val id = query.removePrefix(prefixIdSearch)
client.newCall(mangaDetailsApiRequestById(id)).asObservableSuccess()
.map { response ->
mangaDetailsParse(response).let { MangasPage(listOf(it), false) }
}
}
else -> {
client.newCall(searchMangaRequest(page, query, filters)).asObservableSuccess()
.map { response ->
searchMangaParse(response)
}
}
}
}
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val jsonPayload = buildJsonObject {
put("area_id", -1)
put("is_finish", -1)
put("is_free", 1)
put("key_word", query)
put("order", 0)
put("page_num", page)
put("page_size", 9)
put("style_id", -1)
}
val requestBody = jsonPayload.toString().toRequestBody(JSON_MEDIA_TYPE)
val refererUrl = "$baseUrl/search".toHttpUrl().newBuilder()
.addQueryParameter("keyword", query)
.toString()
val newHeaders = headersBuilder()
.add("Content-Length", requestBody.contentLength().toString())
.add("Content-Type", requestBody.contentType().toString())
.add("X-Page", page.toString())
.set("Referer", refererUrl)
.build()
return POST(
"$baseUrl/$BASE_API_ENDPOINT/Search?device=pc&platform=web",
headers = newHeaders,
body = requestBody
)
}
override fun searchMangaParse(response: Response): MangasPage {
val result = json.decodeFromString<BilibiliResultDto<BilibiliSearchDto>>(response.body!!.string())
if (result.code != 0) {
return MangasPage(emptyList(), hasNextPage = false)
}
val comicList = result.data!!.list
.map(::searchMangaFromObject)
return MangasPage(comicList, hasNextPage = false)
}
private fun searchMangaFromObject(comic: BilibiliComicDto): SManga = SManga.create().apply {
title = Jsoup.parse(comic.title).text()
thumbnail_url = comic.verticalCover
url = "/detail/mc${comic.id}"
}
// Workaround to allow "Open in browser" use the real URL.
override fun fetchMangaDetails(manga: SManga): Observable<SManga> {
return client.newCall(mangaDetailsApiRequest(manga))
.asObservableSuccess()
.map { response ->
mangaDetailsParse(response).apply { initialized = true }
}
}
private fun mangaDetailsApiRequest(manga: SManga): Request {
val comicId = manga.url.substringAfterLast("/mc").toInt()
val jsonPayload = buildJsonObject { put("comic_id", comicId) }
val requestBody = jsonPayload.toString().toRequestBody(JSON_MEDIA_TYPE)
val newHeaders = headersBuilder()
.add("Content-Length", requestBody.contentLength().toString())
.add("Content-Type", requestBody.contentType().toString())
.set("Referer", baseUrl + manga.url)
.build()
return POST(
"$baseUrl/$BASE_API_ENDPOINT/ComicDetail?device=pc&platform=web",
headers = newHeaders,
body = requestBody
)
}
private fun mangaDetailsApiRequestById(id: String): Request {
val comicId = id.toInt()
val jsonPayload = buildJsonObject { put("comic_id", comicId) }
val requestBody = jsonPayload.toString().toRequestBody(JSON_MEDIA_TYPE)
val newHeaders = headersBuilder()
.add("Content-Length", requestBody.contentLength().toString())
.add("Content-Type", requestBody.contentType().toString())
.set("Referer", "$baseUrl/detail/mc$id")
.build()
return POST(
"$baseUrl/$BASE_API_ENDPOINT/ComicDetail?device=pc&platform=web",
headers = newHeaders,
body = requestBody
)
}
override fun mangaDetailsParse(response: Response): SManga = SManga.create().apply {
val result = json.decodeFromString<BilibiliResultDto<BilibiliComicDto>>(response.body!!.string())
val comic = result.data!!
title = comic.title
author = comic.authorName.joinToString()
status = if (comic.isFinish == 1) SManga.COMPLETED else SManga.ONGOING
genre = comic.styles.joinToString()
description = comic.classicLines
thumbnail_url = comic.verticalCover
}
// Chapters are available in the same url of the manga details.
override fun chapterListRequest(manga: SManga): Request = mangaDetailsApiRequest(manga)
override fun chapterListParse(response: Response): List<SChapter> {
val result = json.decodeFromString<BilibiliResultDto<BilibiliComicDto>>(response.body!!.string())
if (result.code != 0)
return emptyList()
return result.data!!.episodeList
.filter { episode -> episode.isLocked.not() }
.map { ep -> chapterFromObject(ep, result.data.id) }
}
private fun chapterFromObject(episode: BilibiliEpisodeDto, comicId: Int): SChapter = SChapter.create().apply {
name = "Ep. " + episode.order.toString().removeSuffix(".0") +
" - " + episode.title
chapter_number = episode.order
scanlator = [email protected]
date_upload = episode.publicationTime.substringBefore("T").toDate()
url = "/mc$comicId/${episode.id}"
}
override fun pageListRequest(chapter: SChapter): Request {
val chapterId = chapter.url.substringAfterLast("/").toInt()
val jsonPayload = buildJsonObject { put("ep_id", chapterId) }
val requestBody = jsonPayload.toString().toRequestBody(JSON_MEDIA_TYPE)
val newHeaders = headersBuilder()
.add("Content-Length", requestBody.contentLength().toString())
.add("Content-Type", requestBody.contentType().toString())
.set("Referer", baseUrl + chapter.url)
.build()
return POST(
"$baseUrl/$BASE_API_ENDPOINT/GetImageIndex?device=pc&platform=web",
headers = newHeaders,
body = requestBody
)
}
override fun pageListParse(response: Response): List<Page> {
val result = json.decodeFromString<BilibiliResultDto<BilibiliReader>>(response.body!!.string())
if (result.code != 0) {
return emptyList()
}
return result.data!!.images
.mapIndexed { i, page -> Page(i, page.path, "") }
}
override fun imageUrlRequest(page: Page): Request {
val jsonPayload = buildJsonObject {
put("urls", buildJsonArray { add(page.url) }.toString())
}
val requestBody = jsonPayload.toString().toRequestBody(JSON_MEDIA_TYPE)
val newHeaders = headersBuilder()
.add("Content-Length", requestBody.contentLength().toString())
.add("Content-Type", requestBody.contentType().toString())
.build()
return POST(
"$baseUrl/$BASE_API_ENDPOINT/ImageToken?device=pc&platform=web",
headers = newHeaders,
body = requestBody
)
}
override fun imageUrlParse(response: Response): String {
val result = json.decodeFromString<BilibiliResultDto<List<BilibiliPageDto>>>(response.body!!.string())
val page = result.data!![0]
return "${page.url}?token=${page.token}"
}
private fun String.toDate(): Long {
return try {
DATE_FORMATTER.parse(this)?.time ?: 0L
} catch (e: ParseException) {
0L
}
}
private val day: Int
get() {
return when (Calendar.getInstance().get(Calendar.DAY_OF_WEEK)) {
Calendar.SUNDAY -> 0
Calendar.MONDAY -> 1
Calendar.TUESDAY -> 2
Calendar.WEDNESDAY -> 3
Calendar.THURSDAY -> 4
Calendar.FRIDAY -> 5
else -> 6
}
}
companion object {
private const val BASE_API_ENDPOINT = "twirp/comic.v1.Comic"
private const val ACCEPT_JSON = "application/json, text/plain, */*"
private val JSON_MEDIA_TYPE = "application/json;charset=UTF-8".toMediaType()
private const val FEATURED_ID = 3
const val prefixIdSearch = "id:"
private val DATE_FORMATTER by lazy { SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH) }
}
}
| src/en/bilibilicomics/src/eu/kanade/tachiyomi/extension/en/bilibilicomics/BilibiliComics.kt | 560140968 |
package com.hana053.micropost.service
import com.hana053.micropost.domain.User
interface AuthService {
fun isMyself(user: User): Boolean
fun logout()
fun auth(): Boolean
} | app/src/main/kotlin/com/hana053/micropost/service/AuthService.kt | 2756902105 |
package pl.shockah.godwit.geom
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import pl.shockah.godwit.ease.Easable
import pl.shockah.godwit.ease.ease
import pl.shockah.godwit.geom.polygon.Polygon
import kotlin.math.sqrt
class Circle(
position: Vec2 = ImmutableVec2.ZERO,
var radius: Float
) : Shape.Filled, Shape.Outline, Easable<Circle> {
var position: MutableVec2 = position.mutableCopy()
override val boundingBox: Rectangle
get() = Rectangle.centered(position, vec2(radius * 2, radius * 2))
override val center: Vec2
get() = position
companion object {
init {
Shape.registerCollisionHandler { a: Circle, b: Circle ->
(b.position - a.position).length < b.radius + a.radius
}
Shape.registerCollisionHandler { circle: Circle, line: Line ->
line.point1 in circle || line.point2 in circle || !(circle intersect line).isEmpty()
}
Shape.registerCollisionHandler { circle: Circle, rectangle: Rectangle ->
val testPoint = circle.position.mutableCopy()
if (circle.position.x < rectangle.position.x)
testPoint.x = rectangle.position.x
else if (circle.position.x > rectangle.position.x + rectangle.size.x)
testPoint.x = rectangle.position.x + rectangle.size.x
if (circle.position.y < rectangle.position.y)
testPoint.y = rectangle.position.y
else if (circle.position.y > rectangle.position.y + rectangle.size.y)
testPoint.y = rectangle.position.y + rectangle.size.y
return@registerCollisionHandler (circle.position - testPoint).length < circle.radius
}
Shape.registerCollisionHandler { circle: Circle, polygon: Polygon ->
for (line in polygon.lines) {
if (circle collides line)
return@registerCollisionHandler true
}
return@registerCollisionHandler false
}
}
}
override fun copy(): Circle {
return Circle(position, radius)
}
override fun equals(other: Any?): Boolean {
return other is Circle && position == other.position && radius == other.radius
}
override fun hashCode(): Int {
return position.hashCode() * 31 + radius.hashCode()
}
override fun translate(vector: Vec2) {
position.xy += vector
}
override fun mirror(horizontal: Boolean, vertical: Boolean) {
if (horizontal)
position.x *= -1f
if (vertical)
position.y *= -1f
}
override fun scale(scale: Float) {
position.xy *= scale
radius *= scale
}
override operator fun contains(point: Vec2): Boolean {
return (position - point).length <= radius
}
infix fun intersect(line: Line): List<ImmutableVec2> {
val baX = line.point2.x - line.point1.x
val baY = line.point2.y - line.point1.y
val caX = position.x - line.point1.x
val caY = position.y - line.point1.y
val a = baX * baX + baY * baY
val bBy2 = baX * caX + baY * caY
val c = caX * caX + caY * caY - radius * radius
val pBy2 = bBy2 / a
val q = c / a
val disc = pBy2 * pBy2 - q
if (disc < 0)
return emptyList()
val tmpSqrt = sqrt(disc)
val abScalingFactor1 = -pBy2 + tmpSqrt
val abScalingFactor2 = -pBy2 - tmpSqrt
val p1 = vec2(line.point1.x - baX * abScalingFactor1, line.point1.y - baY * abScalingFactor1)
if (disc == 0f)
return listOf(p1)
val p2 = vec2(line.point1.x - baX * abScalingFactor2, line.point1.y - baY * abScalingFactor2)
return listOf(p1, p2)
}
override fun ease(other: Circle, f: Float): Circle {
return Circle(
position.ease(other.position, f),
f.ease(radius, other.radius)
)
}
private fun draw(shapes: ShapeRenderer) {
shapes.circle(position.x, position.y, radius)
}
override fun drawFilled(shapes: ShapeRenderer) {
draw(shapes)
}
override fun drawOutline(shapes: ShapeRenderer) {
draw(shapes)
}
} | core/src/pl/shockah/godwit/geom/Circle.kt | 1279757992 |
package jp.org.example.geckour.glyph
import com.squareup.moshi.JsonAdapter
import se.ansman.kotshi.KotshiJsonAdapterFactory
@KotshiJsonAdapterFactory
abstract class AppJsonAdapterFactory : JsonAdapter.Factory {
companion object {
val INSTANCE: AppJsonAdapterFactory = KotshiAppJsonAdapterFactory()
}
} | app/src/main/java/jp/org/example/geckour/glyph/AppJsonAdapterFactory.kt | 2349330067 |
package com.habitrpg.common.habitica.models
import com.habitrpg.common.habitica.models.notifications.AchievementData
import com.habitrpg.common.habitica.models.notifications.ChallengeWonData
import com.habitrpg.common.habitica.models.notifications.FirstDropData
import com.habitrpg.common.habitica.models.notifications.GroupTaskApprovedData
import com.habitrpg.common.habitica.models.notifications.GroupTaskNeedsWorkData
import com.habitrpg.common.habitica.models.notifications.GroupTaskRequiresApprovalData
import com.habitrpg.common.habitica.models.notifications.GuildInvitationData
import com.habitrpg.common.habitica.models.notifications.LoginIncentiveData
import com.habitrpg.common.habitica.models.notifications.NewChatMessageData
import com.habitrpg.common.habitica.models.notifications.NewStuffData
import com.habitrpg.common.habitica.models.notifications.NotificationData
import com.habitrpg.common.habitica.models.notifications.PartyInvitationData
import com.habitrpg.common.habitica.models.notifications.QuestInvitationData
import com.habitrpg.common.habitica.models.notifications.UnallocatedPointsData
class Notification {
enum class Type(val type: String) {
// Notification types coming from the server
LOGIN_INCENTIVE("LOGIN_INCENTIVE"),
NEW_STUFF("NEW_STUFF"),
NEW_CHAT_MESSAGE("NEW_CHAT_MESSAGE"),
NEW_MYSTERY_ITEMS("NEW_MYSTERY_ITEMS"),
GROUP_TASK_NEEDS_WORK("GROUP_TASK_NEEDS_WORK"),
GROUP_TASK_APPROVED("GROUP_TASK_APPROVED"),
GROUP_TASK_REQUIRES_APPROVAL("GROUP_TASK_REQUIRES_APPROVAL"),
UNALLOCATED_STATS_POINTS("UNALLOCATED_STATS_POINTS"),
WON_CHALLENGE("WON_CHALLENGE"),
// Achievements
ACHIEVEMENT_PARTY_UP("ACHIEVEMENT_PARTY_UP"),
ACHIEVEMENT_PARTY_ON("ACHIEVEMENT_PARTY_ON"),
ACHIEVEMENT_BEAST_MASTER("ACHIEVEMENT_BEAST_MASTER"),
ACHIEVEMENT_MOUNT_MASTER("ACHIEVEMENT_MOUNT_MASTER"),
ACHIEVEMENT_TRIAD_BINGO("ACHIEVEMENT_TRIAD_BINGO"),
ACHIEVEMENT_GUILD_JOINED("GUILD_JOINED_ACHIEVEMENT"),
ACHIEVEMENT_CHALLENGE_JOINED("CHALLENGE_JOINED_ACHIEVEMENT"),
ACHIEVEMENT_INVITED_FRIEND("INVITED_FRIEND_ACHIEVEMENT"),
ACHIEVEMENT_GENERIC("ACHIEVEMENT"),
ACHIEVEMENT_ONBOARDING_COMPLETE("ONBOARDING_COMPLETE"),
ACHIEVEMENT_ALL_YOUR_BASE("ACHIEVEMENT_ALL_YOUR_BASE"),
ACHIEVEMENT_BACK_TO_BASICS("ACHIEVEMENT_BACK_TO_BASICS"),
ACHIEVEMENT_JUST_ADD_WATER("ACHIEVEMENT_JUST_ADD_WATER"),
ACHIEVEMENT_LOST_MASTERCLASSER("ACHIEVEMENT_LOST_MASTERCLASSER"),
ACHIEVEMENT_MIND_OVER_MATTER("ACHIEVEMENT_MIND_OVER_MATTER"),
ACHIEVEMENT_DUST_DEVIL("ACHIEVEMENT_DUST_DEVIL"),
ACHIEVEMENT_ARID_AUTHORITY("ACHIEVEMENT_ARID_AUTHORITY"),
ACHIEVEMENT_MONSTER_MAGUS("ACHIEVEMENT_MONSTER_MAGUS"),
ACHIEVEMENT_UNDEAD_UNDERTAKER("ACHIEVEMENT_UNDEAD_UNDERTAKER"),
ACHIEVEMENT_PRIMED_FOR_PAINTING("ACHIEVEMENT_PRIMED_FOR_PAINTING"),
ACHIEVEMENT_PEARLY_PRO("ACHIEVEMENT_PEARLY_PRO"),
ACHIEVEMENT_TICKLED_PINK("ACHIEVEMENT_TICKLED_PINK"),
ACHIEVEMENT_ROSY_OUTLOOK("ACHIEVEMENT_ROSY_OUTLOOK"),
ACHIEVEMENT_BUG_BONANZA("ACHIEVEMENT_BUG_BONANZA"),
ACHIEVEMENT_BARE_NECESSITIES("ACHIEVEMENT_BARE_NECESSITIES"),
ACHIEVEMENT_FRESHWATER_FRIENDS("ACHIEVEMENT_FRESHWATER_FRIENDS"),
ACHIEVEMENT_GOOD_AS_GOLD("ACHIEVEMENT_GOOD_AS_GOLD"),
ACHIEVEMENT_ALL_THAT_GLITTERS("ACHIEVEMENT_ALL_THAT_GLITTERS"),
ACHIEVEMENT_BONE_COLLECTOR("ACHIEVEMENT_BONE_COLLECTOR"),
ACHIEVEMENT_SKELETON_CREW("ACHIEVEMENT_SKELETON_CREW"),
ACHIEVEMENT_SEEING_RED("ACHIEVEMENT_SEEING_RED"),
ACHIEVEMENT_RED_LETTER_DAY("ACHIEVEMENT_RED_LETTER_DAY"),
FIRST_DROP("FIRST_DROPS"),
// Custom notification types (created by this app)
GUILD_INVITATION("GUILD_INVITATION"),
PARTY_INVITATION("PARTY_INVITATION"),
QUEST_INVITATION("QUEST_INVITATION"),
}
var id: String = ""
var type: String? = null
var seen: Boolean? = null
var data: NotificationData? = null
fun getDataType(): java.lang.reflect.Type? {
return when (type) {
Type.LOGIN_INCENTIVE.type -> LoginIncentiveData::class.java
Type.NEW_STUFF.type -> NewStuffData::class.java
Type.NEW_CHAT_MESSAGE.type -> NewChatMessageData::class.java
Type.GROUP_TASK_NEEDS_WORK.type -> GroupTaskNeedsWorkData::class.java
Type.GROUP_TASK_APPROVED.type -> GroupTaskApprovedData::class.java
Type.GROUP_TASK_REQUIRES_APPROVAL.type -> GroupTaskRequiresApprovalData::class.java
Type.UNALLOCATED_STATS_POINTS.type -> UnallocatedPointsData::class.java
Type.GUILD_INVITATION.type -> GuildInvitationData::class.java
Type.PARTY_INVITATION.type -> PartyInvitationData::class.java
Type.QUEST_INVITATION.type -> QuestInvitationData::class.java
Type.FIRST_DROP.type -> FirstDropData::class.java
Type.ACHIEVEMENT_GENERIC.type -> AchievementData::class.java
Type.WON_CHALLENGE.type -> ChallengeWonData::class.java
Type.ACHIEVEMENT_ALL_YOUR_BASE.type -> AchievementData::class.java
Type.ACHIEVEMENT_BACK_TO_BASICS.type -> AchievementData::class.java
Type.ACHIEVEMENT_JUST_ADD_WATER.type -> AchievementData::class.java
Type.ACHIEVEMENT_LOST_MASTERCLASSER.type -> AchievementData::class.java
Type.ACHIEVEMENT_MIND_OVER_MATTER.type -> AchievementData::class.java
Type.ACHIEVEMENT_DUST_DEVIL.type -> AchievementData::class.java
Type.ACHIEVEMENT_ARID_AUTHORITY.type -> AchievementData::class.java
Type.ACHIEVEMENT_MONSTER_MAGUS.type -> AchievementData::class.java
Type.ACHIEVEMENT_UNDEAD_UNDERTAKER.type -> AchievementData::class.java
Type.ACHIEVEMENT_PRIMED_FOR_PAINTING.type -> AchievementData::class.java
Type.ACHIEVEMENT_PEARLY_PRO.type -> AchievementData::class.java
Type.ACHIEVEMENT_TICKLED_PINK.type -> AchievementData::class.java
Type.ACHIEVEMENT_ROSY_OUTLOOK.type -> AchievementData::class.java
Type.ACHIEVEMENT_BUG_BONANZA.type -> AchievementData::class.java
Type.ACHIEVEMENT_BARE_NECESSITIES.type -> AchievementData::class.java
Type.ACHIEVEMENT_FRESHWATER_FRIENDS.type -> AchievementData::class.java
Type.ACHIEVEMENT_GOOD_AS_GOLD.type -> AchievementData::class.java
Type.ACHIEVEMENT_ALL_THAT_GLITTERS.type -> AchievementData::class.java
Type.ACHIEVEMENT_GOOD_AS_GOLD.type -> AchievementData::class.java
Type.ACHIEVEMENT_BONE_COLLECTOR.type -> AchievementData::class.java
Type.ACHIEVEMENT_SKELETON_CREW.type -> AchievementData::class.java
Type.ACHIEVEMENT_SEEING_RED.type -> AchievementData::class.java
Type.ACHIEVEMENT_RED_LETTER_DAY.type -> AchievementData::class.java
else -> null
}
}
val priority: Int
get() {
return when (type) {
Type.NEW_STUFF.type -> 1
Type.GUILD_INVITATION.type -> 2
Type.PARTY_INVITATION.type -> 3
Type.UNALLOCATED_STATS_POINTS.type -> 4
Type.NEW_MYSTERY_ITEMS.type -> 5
Type.NEW_CHAT_MESSAGE.type -> 6
else -> 100
}
}
}
| common/src/main/java/com/habitrpg/common/habitica/models/Notification.kt | 2301213036 |
package com.zeyad.usecases.app.annimations
import android.os.Build
import android.support.annotation.RequiresApi
import android.transition.ChangeBounds
import android.transition.ChangeImageTransform
import android.transition.ChangeTransform
import android.transition.TransitionSet
/**
* @author ZIaDo on 3/29/16.
*/
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
class DetailsTransition @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
constructor() : TransitionSet() {
init {
ordering = TransitionSet.ORDERING_TOGETHER
addTransition(ChangeBounds())
.addTransition(ChangeTransform())
.addTransition(ChangeImageTransform())
}
}
| sampleApp/src/main/java/com/zeyad/usecases/app/annimations/DetailsTransition.kt | 914023828 |
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
package assimp.format.fbx
import assimp.*
import glm_.bool
import glm_.c
import glm_.i
/** @file FBXDocument.h
* @brief FBX DOM */
//#define _AI_CONCAT(a,b) a ## b
//#define AI_CONCAT(a,b) _AI_CONCAT(a,b)
/** Represents a delay-parsed FBX objects. Many objects in the scene
* are not needed by assimp, so it makes no sense to parse them
* upfront. */
class LazyObject(val id: Long, val element: Element, val doc: Document) {
var object_: Object? = null
var flags = Flags.NULL.ordinal
enum class Flags { NULL, BEING_CONSTRUCTED, FAILED_TO_CONSTRUCT }
infix fun Int.wo(other: Flags) = and(other.ordinal.inv())
infix fun Int.or(f: LazyObject.Flags) = or(f.ordinal)
fun <T> get(dieOnError: Boolean = false) = get(dieOnError) as? T
fun get(dieOnError: Boolean = false): Object? {
if (isBeingConstructed || failedToConstruct) return null
if (object_ != null) return object_
/* if this is the root object, we return a dummy since there is no root object int he fbx file - it is just
referenced with id 0. */
if (id == 0L) {
object_ = Object(id, element, "Model::RootNode")
return object_
}
val key = element.keyToken
val tokens = element.tokens
if (tokens.size < 3) domError("expected at least 3 tokens: id, name and class tag", element)
var name = tokens[1].parseAsString
/* small fix for binary reading: binary fbx files don't use prefixes such as Model:: in front of their names.
The loading code expects this at many places, though!
so convert the binary representation (a 0x0001) to the double colon notation. */
if (tokens[1].isBinary)
for (i in name.indices) {
if (name[i].i == 0x0 && name[i + 1].i == 0x1)
name = name.substring(i + 2) + "::" + name.substring(0, i)
}
else name = name.trimNUL()
val classtag = tokens[2].parseAsString
// prevent recursive calls
flags = flags or Flags.BEING_CONSTRUCTED
try {
// this needs to be relatively fast since it happens a lot,
// so avoid constructing strings all the time.
val obType = key.begin
val length = key.end - key.begin
// For debugging
//dumpObjectClassInfo( objtype, classtag )
object_ = when {
buffer.strncmp("Geometry", obType, length) -> MeshGeometry(id, element, name, doc).takeIf { classtag == "Mesh" }
buffer.strncmp("NodeAttribute", obType, length) -> when (classtag) {
"Camera" -> Camera(id, element, doc, name)
"CameraSwitcher" -> CameraSwitcher(id, element, doc, name)
"Light" -> Light(id, element, doc, name)
"Null" -> Null(id, element, doc, name)
"LimbNode" -> LimbNode(id, element, doc, name)
else -> null
}
buffer.strncmp("Deformer", obType, length) -> when (classtag) {
"Cluster" -> Cluster(id, element, doc, name)
"Skin" -> Skin(id, element, doc, name)
else -> null
}
buffer.strncmp("Model", obType, length) -> // FK and IK effectors are not supported
Model(id, element, doc, name).takeIf { classtag != "IKEffector" && classtag != "FKEffector" }
buffer.strncmp("Material", obType, length) -> Material(id, element, doc, name)
buffer.strncmp("Texture", obType, length) -> Texture(id, element, doc, name)
buffer.strncmp("LayeredTexture", obType, length) -> LayeredTexture(id, element, doc, name)
buffer.strncmp("Video", obType, length) -> Video(id, element, doc, name)
buffer.strncmp("AnimationStack", obType, length) -> AnimationStack(id, element, name, doc)
buffer.strncmp("AnimationLayer", obType, length) -> AnimationLayer(id, element, name, doc)
// note: order matters for these two
buffer.strncmp("AnimationCurve", obType, length) -> AnimationCurve(id, element, name, doc)
buffer.strncmp("AnimationCurveNode", obType, length) -> AnimationCurveNode(id, element, name, doc)
else -> object_
}
} catch (ex: Exception) {
flags = flags wo Flags.BEING_CONSTRUCTED
flags = flags or Flags.FAILED_TO_CONSTRUCT
// note: the error message is already formatted, so raw logging is ok
logger.error(ex) {}
if (dieOnError || doc.settings.strictMode) throw Exception()
}
if (object_ == null) {
//DOMError("failed to convert element to DOM object, class: " + classtag + ", name: " + name,&element);
}
flags = flags wo Flags.BEING_CONSTRUCTED
return object_
}
// inline fun <reified T> get(dieOnError: Boolean = false): T {
// const Object * const ob = Get(dieOnError)
// return ob ? dynamic_cast<const T*>(ob) : NULL
// }
val isBeingConstructed get() = flags == Flags.BEING_CONSTRUCTED.ordinal
val failedToConstruct get() = flags == Flags.FAILED_TO_CONSTRUCT.ordinal
}
/** Base class for in-memory (DOM) representations of FBX objects */
open class Object(val id: Long, val element: Element, val name: String)
/** DOM class for generic FBX NoteAttribute blocks. NoteAttribute's just hold a property table,
* fixed members are added by deriving classes. */
open class NodeAttribute(id: Long, element: Element, doc: Document, name: String) : Object(id, element, name) {
val props: PropertyTable
init {
val sc = element.scope
val classname = element[2].parseAsString
/* hack on the deriving type but Null/LimbNode attributes are the only case in which the property table is by
design absent and no warning should be generated for it. */
val isNullOrLimb = classname == "Null" || classname == "LimbNode"
props = getPropertyTable(doc, "NodeAttribute.Fbx$classname", element, sc, isNullOrLimb)
}
}
/** DOM base class for FBX camera settings attached to a node */
class CameraSwitcher(id: Long, element: Element, doc: Document, name: String) : NodeAttribute(id, element, doc, name) {
val cameraId = element.scope["CameraId"]?.let { it[0].parseAsInt } ?: 0
val cameraName = element.scope["CameraName"]?.let { it[0].stringContents } ?: ""
val cameraIndexName = element.scope["CameraIndex"]?.let { it[0].stringContents } ?: ""
}
//
//
//#define fbx_stringize(a) #a
//
//#define fbx_simple_property(name, type, default_value) \
//type name() const {
// \
// return PropertyGet<type>(Props(), fbx_stringize(name), (default_value)); \
//}
//
//// XXX improve logging
//#define fbx_simple_enum_property(name, type, default_value) \
//type name() const {
// \
// const int ival = PropertyGet<int>(Props(), fbx_stringize(name), static_cast<int>(default_value)); \
// if (ival < 0 || ival >= AI_CONCAT(type, _MAX)) {
// \
// ai_assert(static_cast<int>(default_value) >= 0 && static_cast<int>(default_value) < AI_CONCAT(type, _MAX)); \
// return static_cast<type>(default_value); \
// } \
// return static_cast<type>(ival); \
//}
//
/** DOM base class for FBX cameras attached to a node */
class Camera(id: Long, element: Element, doc: Document, name: String) : NodeAttribute(id, element, doc, name) {
val position get() = props("Position", AiVector3D())
val upVector get() = props("UpVector", AiVector3D(0, 1, 0))
val interestPosition get() = props("InterestPosition", AiVector3D())
val aspectWidth get() = props("AspectWidth", 1f)
val aspectHeight get() = props("AspectHeight", 1f)
val filmWidth get() = props("FilmWidth", 1f)
val filmHeight get() = props("FilmHeight", 1f)
val nearPlane get() = props("NearPlane", 0.1f)
val farPlane get() = props("FarPlane", 100f)
val filmAspectRatio get() = props("FilmAspectRatio", 1f)
val apertureMode get() = props("ApertureMode", 0)
val fieldOfView get() = props("FieldOfView", 1f)
val focalLength get() = props("FocalLength", 1f)
}
/** DOM base class for FBX null markers attached to a node */
class Null(id: Long, element: Element, doc: Document, name: String) : NodeAttribute(id, element, doc, name)
/** DOM base class for FBX limb node markers attached to a node */
class LimbNode(id: Long, element: Element, doc: Document, name: String) : NodeAttribute(id, element, doc, name)
/** DOM base class for FBX lights attached to a node */
class Light(id: Long, element: Element, doc: Document, name: String) : NodeAttribute(id, element, doc, name) {
enum class Type { Point, Directional, Spot, Area, Volume }
enum class Decay { None, Linear, Quadratic, Cubic }
val color get() = props("Color", AiVector3D(1))
val type get() = Type.values()[props("Type", Type.Point.ordinal)]
val castLightOnObject get() = props("CastLightOnObject", defaultValue = false)
val drawVolumetricLight get() = props("DrawVolumetricLight", defaultValue = true)
val drawGroundProjection get() = props("DrawGroundProjection", defaultValue = true)
val drawFrontFacingVolumetricLight get() = props("DrawFrontFacingVolumetricLight", defaultValue = false)
val intensity get() = props("Intensity", 100f)
val innerAngle get() = props("InnerAngle", 0f)
val outerAngle get() = props("OuterAngle", 45f)
val fog get() = props("Fog", 50)
val decayType get() = Decay.values()[props("DecayType", Decay.Quadratic.ordinal)]
val decayStart get() = props("DecayStart", 1f)
val fileName get() = props("FileName", "")
val enableNearAttenuation get() = props("EnableNearAttenuation", defaultValue = false)
val nearAttenuationStart get() = props("NearAttenuationStart", 0f)
val nearAttenuationEnd get() = props("NearAttenuationEnd", 0f)
val enableFarAttenuation get() = props("EnableFarAttenuation", defaultValue = false)
val farAttenuationStart get() = props("FarAttenuationStart", 0f)
val farAttenuationEnd get() = props("FarAttenuationEnd", 0f)
val castShadows get() = props("CastShadows", defaultValue = true)
val shadowColor get() = props("ShadowColor", AiVector3D())
val areaLightShape get() = props("AreaLightShape", 0)
val LeftBarnDoor get() = props("LeftBarnDoor", 20f)
val RightBarnDoor get() = props("RightBarnDoor", 20f)
val TopBarnDoor get() = props("TopBarnDoor", 20f)
val BottomBarnDoor get() = props("BottomBarnDoor", 20f)
val EnableBarnDoor get() = props("EnableBarnDoor", defaultValue = true)
}
//
/** DOM base class for FBX models (even though its semantics are more "node" than "model" */
class Model(id: Long, element: Element, doc: Document, name: String) : Object(id, element, name) {
val materials = ArrayList<Material>()
val geometry = ArrayList<Geometry>()
val attributes = ArrayList<NodeAttribute>()
val shading = element.scope["Shading"]?.get(0)?.stringContents ?: "Y"
val culling = element.scope["Culling"]?.get(0)?.parseAsString ?: ""
val props = getPropertyTable(doc, "Model.FbxNode", element, element.scope)
init {
resolveLinks(element, doc)
}
enum class RotOrder { EulerXYZ, EulerXZY, EulerYZX, EulerYXZ, EulerZXY, EulerZYX, SphericXYZ }
enum class TransformInheritance { RrSs, RSrs, Rrs }
val quaternionInterpolate get() = props("QuaternionInterpolate", 0)
val rotationOffset get() = props("RotationOffset", AiVector3D())
val rotationPivot get() = props("RotationPivot", AiVector3D())
val scalingOffset get() = props("ScalingOffset", AiVector3D())
val scalingPivot get() = props("ScalingPivot", AiVector3D())
val translationActive get() = props("TranslationActive", defaultValue = false)
val translationMin get() = props("TranslationMin", AiVector3D())
val translationMax get() = props("TranslationMax", AiVector3D())
val translationMinX get() = props("TranslationMinX", defaultValue = false)
val translationMaxX get() = props("TranslationMaxX", defaultValue = false)
val translationMinY get() = props("TranslationMinY", defaultValue = false)
val translationMaxY get() = props("TranslationMaxY", defaultValue = false)
val translationMinZ get() = props("TranslationMinZ", defaultValue = false)
val translationMaxZ get() = props("TranslationMaxZ", defaultValue = false)
val rotationOrder get() = RotOrder.values()[props("RotationOrder", RotOrder.EulerXYZ.ordinal)]
val rotationSpaceForLimitOnly get() = props("RotationSpaceForLimitOnlyMaxZ", defaultValue = false)
val rotationStiffnessX get() = props("RotationStiffnessX", 0f)
val rotationStiffnessY get() = props("RotationStiffnessY", 0f)
val rotationStiffnessZ get() = props("RotationStiffnessZ", 0f)
val axisLen get() = props("AxisLen", 0f)
val preRotation get() = props("PreRotation", AiVector3D())
val postRotation get() = props("PostRotation", AiVector3D())
val rotationActive get() = props("RotationActive", defaultValue = false)
val rotationMin get() = props("RotationMin", AiVector3D())
val rotationMax get() = props("RotationMax", AiVector3D())
val rotationMinX get() = props("RotationMinX", defaultValue = false)
val rotationMaxX get() = props("RotationMaxX", defaultValue = false)
val rotationMinY get() = props("RotationMinY", defaultValue = false)
val rotationMaxY get() = props("RotationMaxY", defaultValue = false)
val rotationMinZ get() = props("RotationMinZ", defaultValue = false)
val rotationMaxZ get() = props("RotationMaxZ", defaultValue = false)
val inheritType get() = TransformInheritance.values()[props("InheritType", TransformInheritance.RrSs.ordinal)]
val scalingActive get() = props("ScalingActive", defaultValue = false)
val scalingMin get() = props("ScalingMin", AiVector3D())
val scalingMax get() = props("ScalingMax", AiVector3D(1f))
val scalingMinX get() = props("ScalingMinX", defaultValue = false)
val scalingMaxX get() = props("ScalingMaxX", defaultValue = false)
val scalingMinY get() = props("ScalingMinY", defaultValue = false)
val scalingMaxY get() = props("ScalingMaxY", defaultValue = false)
val scalingMinZ get() = props("ScalingMinZ", defaultValue = false)
val scalingMaxZ get() = props("ScalingMaxZ", defaultValue = false)
val geometricTranslation get() = props("GeometricTranslation", AiVector3D())
val geometricRotation get() = props("GeometricRotation", AiVector3D())
val geometricScaling get() = props("GeometricScaling", AiVector3D(1f))
val minDampRangeX get() = props("MinDampRangeX", 0f)
val minDampRangeY get() = props("MinDampRangeY", 0f)
val minDampRangeZ get() = props("MinDampRangeZ", 0f)
val maxDampRangeX get() = props("MaxDampRangeX", 0f)
val maxDampRangeY get() = props("MaxDampRangeY", 0f)
val maxDampRangeZ get() = props("MaxDampRangeZ", 0f)
val minDampStrengthX get() = props("MinDampStrengthX", 0f)
val minDampStrengthY get() = props("MinDampStrengthY", 0f)
val minDampStrengthZ get() = props("MinDampStrengthZ", 0f)
val maxDampStrengthX get() = props("MaxDampStrengthX", 0f)
val maxDampStrengthY get() = props("MaxDampStrengthY", 0f)
val maxDampStrengthZ get() = props("MaxDampStrengthZ", 0f)
val preferredAngleX get() = props("PreferredAngleX", 0f)
val preferredAngleY get() = props("PreferredAngleY", 0f)
val preferredAngleZ get() = props("PreferredAngleZ", 0f)
val show get() = props["Show"] ?: true
val lodBox get() = props["LODBox"] ?: false
val freeze get() = props["Freeze"] ?: false
/** convenience method to check if the node has a Null node marker */
val isNull get() = attributes.any { it is Null }
fun resolveLinks(element: Element, doc: Document) {
val arr = arrayOf("Geometry", "Material", "NodeAttribute")
// resolve material
val conns = doc.getConnectionsByDestinationSequenced(id, arr)
materials.ensureCapacity(conns.size)
geometry.ensureCapacity(conns.size)
attributes.ensureCapacity(conns.size)
for (con in conns) {
// material and geometry links should be Object-Object connections
if (con.prop.isNotEmpty()) continue
val ob = con.sourceObject
if (ob == null) {
domWarning("failed to read source object for incoming Model link, ignoring", element)
continue
}
var `continue` = true
when (ob) {
is Material -> materials += ob
is Geometry -> geometry += ob
is NodeAttribute -> attributes += ob
else -> `continue` = false
}
if(`continue`) continue
domWarning("source object for model link is neither Material, NodeAttribute nor Geometry, ignoring", element)
continue
}
}
}
/** DOM class for generic FBX textures */
class Texture(id: Long, element: Element, doc: Document, name: String) : Object(id, element, name) {
val uvTrans = element.scope["ModelUVTranslation"]?.let { AiVector2D(it[0].parseAsFloat, it[1].parseAsFloat) }
?: AiVector2D()
val uvScaling = element.scope["ModelUVScaling"]?.let { AiVector2D(it[0].parseAsFloat, it[1].parseAsFloat) }
?: AiVector2D(1)
val type = element.scope["Type"]?.get(0)?.parseAsString ?: ""
val relativeFileName = element.scope["RelativeFileName"]?.get(0)?.parseAsString ?: ""
val fileName = element.scope["FileName"]?.get(0)?.parseAsString ?: ""
val alphaSource = element.scope["Texture_Alpha_Source"]?.get(0)?.parseAsString ?: ""
val props = getPropertyTable(doc, "Texture.FbxFileTexture", element, element.scope)
val crop = element.scope["Cropping"].let { sc -> IntArray(4, { sc?.get(it)?.parseAsInt ?: 0 }) }
var media: Video? = null
init {
// resolve video links
if (doc.settings.readTextures) {
val conns = doc.getConnectionsByDestinationSequenced(id)
for (con in conns) {
val ob = con.sourceObject
if (ob == null) {
domWarning("failed to read source object for texture link, ignoring", element)
continue
}
media = ob as? Video
}
}
}
}
/** DOM class for layered FBX textures */
class LayeredTexture(id: Long, element: Element, doc: Document, name: String) : Object(id, element, name) {
val textures = ArrayList<Texture>()
val blendMode = element.scope["BlendModes"]?.let { BlendMode.values()[it[0].parseAsInt] }
?: BlendMode.Translucent
val alpha = element.scope["Alphas"]?.get(0)?.parseAsFloat ?: 0f
//Can only be called after construction of the layered texture object due to construction flag.
fun fillTexture(doc: Document) {
val conns = doc.getConnectionsByDestinationSequenced(id)
for (i in 0 until conns.size) {
val con = conns[i]
val ob = con.sourceObject
if (ob == null) {
domWarning("failed to read source object for texture link, ignoring", element)
continue
}
(ob as? Texture)?.let { textures += it }
}
}
val textureCount get() = textures.size
enum class BlendMode { Translucent, Additive, Modulate, Modulate2, Over, Normal, Dissolve, Darken, ColorBurn,
LinearBurn, DarkerColor, Lighten, Screen, ColorDodge, LinearDodge, LighterColor, SoftLight, HardLight,
VividLight, LinearLight, PinLight, HardMix, Difference, Exclusion, Subtract, Divide, Hue, Saturation, Color,
Luminosity, Overlay, BlendModeCount
}
}
/** DOM class for generic FBX videos */
class Video(id: Long, element: Element, doc: Document, name: String) : Object(id, element, name) {
val type = element.scope["Type"]?.get(0)?.parseAsString ?: ""
val relativeFileName = element.scope["RelativeFilename"]?.get(0)?.parseAsString ?: ""
val fileName = element.scope["FileName"]?.get(0)?.parseAsString ?: ""
var contentLength = 0
var content = byteArrayOf()
init {
element.scope["Content"]?.let {
//this field is ommited when the embedded texture is already loaded, let's ignore if it´s not found
try {
val token = it[0]
val data = token.begin
when {
!token.isBinary -> domWarning("video content is not binary data, ignoring", element)
token.end - data < 5 -> domError("binary data array is too short, need five (5) bytes for type signature and element count", element)
buffer[data].c != 'R' -> domWarning("video content is not raw binary data, ignoring", element)
else -> {
// read number of elements
val len = buffer.getInt(data + 1)
contentLength = len
content = ByteArray(len, { buffer.get(data + 5 + it) })
}
}
} catch (runtimeError: Exception) {
//we don´t need the content data for contents that has already been loaded
}
}
}
fun relinquishContent(): ByteArray {
val ptr = content
content = byteArrayOf()
return ptr
}
val props = getPropertyTable(doc, "Video.FbxVideo", element, element.scope)
}
/** DOM class for generic FBX materials */
class Material(id: Long, element: Element, doc: Document, name: String) : Object(id, element, name) {
val shading: String
val multiLayer: Boolean
val props: PropertyTable
init {
val sc = element.scope
val shadingModel = sc["ShadingModel"]
multiLayer = (sc["MultiLayer"]?.get(0)?.parseAsInt ?: 0).bool
shading = if (shadingModel != null) shadingModel[0].parseAsString
else "phong".also { domWarning("shading mode not specified, assuming phong", element) }
val templateName = when (shading.toLowerCase()) {
"phong" -> "Material.FbxSurfacePhong"
"lambert" -> "Material.FbxSurfaceLambert"
else -> "".also { domWarning("shading mode not recognized: $shading", element) }
}
props = getPropertyTable(doc, templateName, element, sc)
}
val textures = mutableMapOf<String, Texture>()
val layeredTextures = mutableMapOf<String, LayeredTexture>()
init {
// resolve texture links
val conns = doc.getConnectionsByDestinationSequenced(id)
for (con in conns) {
// texture link to properties, not objects
if (con.prop.isEmpty()) continue
val ob = con.sourceObject
if (ob == null) {
domWarning("failed to read source object for texture link, ignoring", element)
continue
}
val tex = ob as? Texture
if (tex == null) {
val layeredTexture = ob as? LayeredTexture
if (layeredTexture == null) {
domWarning("source object for texture link is not a texture or layered texture, ignoring", element)
continue
}
val prop = con.prop
if (layeredTextures.contains(prop)) domWarning("duplicate layered texture link: $prop", element)
layeredTextures[prop] = layeredTexture
layeredTexture.fillTexture(doc)
} else {
val prop = con.prop
if (textures.contains(prop)) domWarning("duplicate texture link: $prop", element)
textures[prop] = tex
}
}
}
}
/** Represents a FBX animation curve (i.e. a 1-dimensional set of keyframes and values therefor) */
class AnimationCurve(id: Long, element: Element, name: String, doc: Document) : Object(id, element, name) {
/** get list of keyframe positions (time). Invariant: |GetKeys()| > 0 */
val keys = ArrayList<Long>()
/** list of keyframe values. Invariant: |GetKeys()| == |GetValues()| && |GetKeys()| > 0 */
val values = ArrayList<Float>()
val attributes = ArrayList<Float>()
val flags = ArrayList<Int>()
init {
val sc = element.scope
val keyTime = sc["KeyTime"]!!
val keyValueFloat = sc["KeyValueFloat"]!!
keyTime.parseLongsDataArray(keys)
keyValueFloat.parseFloatsDataArray(values)
if (keys.size != values.size) domError("the number of key times does not match the number of keyframe values", keyTime)
// check if the key times are well-ordered
for (i in 0 until keys.size - 1)
if (keys[i] <= keys[i + 1])
domError("the keyframes are not in ascending order", keyTime)
sc["KeyAttrDataFloat"]?.parseFloatsDataArray(attributes)
sc["KeyAttrFlags"]?.parseIntsDataArray(flags)
}
}
/** Represents a FBX animation curve (i.e. a mapping from single animation curves to nodes) */
class AnimationCurveNode(id: Long, element: Element, name: String, val doc: Document,
targetPropWhitelist: ArrayList<String> = arrayListOf()) : Object(id, element, name) {
/** Object the curve is assigned to, this can be NULL if the target object has no DOM representation or could not
* be read for other reasons.*/
var target: Object? = null
val props: PropertyTable
val curves = mutableMapOf<String, AnimationCurve>()
/** Property of Target() that is being animated*/
var prop = ""
/* the optional white list specifies a list of property names for which the caller wants animations for.
If the curve node does not match one of these, std::range_error will be thrown. */
init {
val sc = element.scope
// find target node
val whitelist = arrayOf("Model", "NodeAttribute")
val conns = doc.getConnectionsBySourceSequenced(id, whitelist)
for (con in conns) {
// link should go for a property
if (con.prop.isEmpty()) continue
if (targetPropWhitelist.isNotEmpty()) {
val s = con.prop
var ok = false
for (p in targetPropWhitelist) {
if (s == p) {
ok = true
break
}
}
if (!ok) throw Exception("AnimationCurveNode target property is not in whitelist") // TODO handle better std::range_error?
}
val ob = con.destinationObject
if (ob == null) {
domWarning("failed to read destination object for AnimationCurveNode->Model link, ignoring", element)
continue
}
// XXX support constraints as DOM class
//ai_assert(dynamic_cast<const Model*>(ob) || dynamic_cast<const NodeAttribute*>(ob));
target = ob
if (target == null) continue
prop = con.prop
break
}
if (target == null) domWarning("failed to resolve target Model/NodeAttribute/Constraint for AnimationCurveNode", element)
props = getPropertyTable(doc, "AnimationCurveNode.FbxAnimCurveNode", element, sc, false)
}
fun curves(): MutableMap<String, AnimationCurve> {
if (curves.isEmpty()) {
// resolve attached animation curves
val conns = doc.getConnectionsByDestinationSequenced(id, "AnimationCurve")
for (con in conns) {
// link should go for a property
if (con.prop.isEmpty()) continue
val ob = con.sourceObject
if (ob == null) {
domWarning("failed to read source object for AnimationCurve->AnimationCurveNode link, ignoring", element)
continue
}
val anim = ob as? AnimationCurve
if (anim == null) {
domWarning("source object for ->AnimationCurveNode link is not an AnimationCurve", element)
continue
}
curves[con.prop] = anim
}
}
return curves
}
val targetAsModel get() = target as? Model
val targetAsNodeAttribute get() = target as? NodeAttribute
}
/** Represents a FBX animation layer (i.e. a list of node animations) */
class AnimationLayer(id: Long, element: Element, name: String, val doc: Document) : Object(id, element, name) {
/** note: the props table here bears little importance and is usually absent */
val props = getPropertyTable(doc, "AnimationLayer.FbxAnimLayer", element, element.scope, true)
/* the optional white list specifies a list of property names for which the caller
wants animations for. Curves not matching this list will not be added to the
animation layer. */
fun nodes(targetPropWhitelist: Array<String> = arrayOf()): ArrayList<AnimationCurveNode> {
val nodes = ArrayList<AnimationCurveNode>()
// resolve attached animation nodes
val conns = doc.getConnectionsByDestinationSequenced(id, "AnimationCurveNode")
nodes.ensureCapacity(conns.size)
for (con in conns) {
// link should not go to a property
if (con.prop.isEmpty()) continue
val ob = con.sourceObject
if (ob == null) {
domWarning("failed to read source object for AnimationCurveNode->AnimationLayer link, ignoring", element)
continue
}
val anim = ob as? AnimationCurveNode
if (anim == null) {
domWarning("source object for ->AnimationLayer link is not an AnimationCurveNode", element)
continue
}
if (targetPropWhitelist.isNotEmpty()) {
val s = anim.prop
var ok = false
for (p in targetPropWhitelist) {
if (s == p) {
ok = true
break
}
}
if (!ok) continue
}
nodes += anim
}
return nodes // pray for NRVO
}
}
/** Represents a FBX animation stack (i.e. a list of animation layers) */
class AnimationStack(id: Long, element: Element, name: String, doc: Document) : Object(id, element, name) {
// note: we don't currently use any of these properties so we shouldn't bother if it is missing
val props = getPropertyTable(doc, "AnimationStack.FbxAnimStack", element, element.scope, true)
val layers = ArrayList<AnimationLayer>()
init {
// resolve attached animation layers
val conns = doc.getConnectionsByDestinationSequenced(id, "AnimationLayer")
layers.ensureCapacity(conns.size)
for (con in conns) {
// link should not go to a property
if (con.prop.isNotEmpty()) continue
val ob = con.sourceObject
if (ob == null) {
domWarning("failed to read source object for AnimationLayer->AnimationStack link, ignoring", element)
continue
}
val anim = ob as? AnimationLayer
if (anim == null) {
domWarning("source object for ->AnimationStack link is not an AnimationLayer", element)
continue
}
layers += anim
}
}
val localStart get() = props("LocalStart", 0L)
val localStop get() = props("LocalStop", 0L)
val referenceStart get() = props("ReferenceStart", 0L)
val referenceStop get() = props("ReferenceStop", 0L)
}
/** DOM class for deformers */
open class Deformer(id: Long, element: Element, doc: Document, name: String) : Object(id, element, name) {
val props = getPropertyTable(doc, "Deformer.Fbx" + element[2].parseAsString, element, element.scope, true)
}
/** DOM class for skin deformer clusters (aka subdeformers) */
class Cluster(id: Long, element: Element, doc: Document, name: String) : Deformer(id, element, doc, name) {
/** get the list of deformer weights associated with this cluster. Use #GetIndices() to get the associated vertices.
* Both arrays have the same size (and may also be empty). */
val weights = ArrayList<Float>()
/** get indices into the vertex data of the geometry associated with this cluster. Use #GetWeights() to get the
* associated weights. Both arrays have the same size (and may also be empty). */
val indices = ArrayList<Int>()
val transform: AiMatrix4x4
val transformLink: AiMatrix4x4
var node: Model? = null
init {
val sc = element.scope
val loadedIndexes = sc.getArray("Indexes")
val loadedWeights = sc.getArray("Weights")
val transform = getRequiredElement(sc, "Transform", element)
val transformLink = getRequiredElement(sc, "TransformLink", element)
this.transform = transform.readMatrix()
this.transformLink = transformLink.readMatrix()
// it is actually possible that there be Deformer's with no weights
if (loadedIndexes.isNotEmpty() != loadedWeights.isNotEmpty()) domError("either Indexes or Weights are missing from Cluster", element)
if (loadedIndexes.isNotEmpty()) {
loadedIndexes[0].parseIntsDataArray(indices)
loadedWeights[0].parseFloatsDataArray(weights)
}
if (indices.size != weights.size) domError("sizes of index and weight array don't match up", element)
// read assigned node
val conns = doc.getConnectionsByDestinationSequenced(id, "Model")
for (con in conns) {
val mod = processSimpleConnection<Model>(con, false, "Model -> Cluster", element)
if (mod != null) {
node = mod
break
}
}
if (node == null) domError("failed to read target Node for Cluster", element)
}
}
/** DOM class for skin deformers */
class Skin(id: Long, element: Element, doc: Document, name: String) : Deformer(id, element, doc, name) {
val accuracy = element.scope["Link_DeformAcuracy"]?.get(0)?.parseAsFloat ?: 0f
val clusters = ArrayList<Cluster>()
init {
// resolve assigned clusters
val conns = doc.getConnectionsByDestinationSequenced(id, "Deformer")
clusters.ensureCapacity(conns.size)
for (con in conns) {
val cluster = processSimpleConnection<Cluster>(con, false, "Cluster -> Skin", element)
if (cluster != null) {
clusters += cluster
continue
}
}
}
}
/** Represents a link between two FBX objects. */
class Connection(val insertionOrder: Long, val src: Long, val dest: Long, val prop: String, val doc: Document) : Comparable<Connection> {
init {
assert(doc.objects.contains(src))
// dest may be 0 (root node)
assert(dest != 0L || doc.objects.contains(dest))
}
/** note: a connection ensures that the source and dest objects exist, but not that they have DOM representations,
* so the return value of one of these functions can still be NULL. */
val sourceObject get() = doc[src]!!.get()
val destinationObject get() = doc[dest]!!.get()
// these, however, are always guaranteed to be valid
val lazySourceObject get() = doc[src]!!
val lazyDestinationObject get() = doc[dest]!!
override fun compareTo(other: Connection) = insertionOrder.compareTo(other.insertionOrder)
// bool Compare(const Connection* c)
// const {
// ai_assert(NULL != c)
//
// return InsertionOrder() < c->InsertionOrder()
// }
}
//
//// XXX again, unique_ptr would be useful. shared_ptr is too
//// bloated since the objects have a well-defined single owner
//// during their entire lifetime (Document). FBX files have
//// up to many thousands of objects (most of which we never use),
//// so the memory overhead for them should be kept at a minimum.
//typedef std::map<uint64_t, LazyObject*> ObjectMap
//typedef std::fbx_unordered_map<std::string, std::shared_ptr<const PropertyTable> > PropertyTemplateMap
//
//typedef std::multimap<uint64_t, const Connection*> ConnectionMap
/** DOM class for global document settings, a single instance per document can
* be accessed via Document.Globals(). */
class FileGlobalSettings(val doc: Document, val props: PropertyTable) {
val upAxis get() = props("UpAxis", 1)
val upAxisSign get() = props("UpAxisSign", 1)
val frontAxis get() = props("FrontAxis", 2)
val frontAxisSign get() = props("FrontAxisSign", 1)
val coordAxis get() = props("CoordAxis", 1)
val coordAxisSign get() = props("CoordAxisSign", 1)
val originalUpAxis get() = props("OriginalUpAxis", 1)
val originalUpAxisSign get() = props("OriginalUpAxisSign", 1)
val unitScaleFactor get() = props("UnitScaleFactor", 1.0)
val originalUnitScaleFactor get() = props("OriginalUnitScaleFactor", 1.0)
val ambientColor get() = props("AmbientColor", AiVector3D())
val defaultCamera get() = props("DefaultCamera", "")
enum class FrameRate { DEFAULT, _120, _100, _60, _50, _48, _30, _30_DROP, NTSC_DROP_FRAME, NTSC_FULL_FRAME, PAL,
CINEMA, _1000, CINEMA_ND, CUSTOM // end-of-enum sentinel
}
val timeMode get() = FrameRate.values()[props("TimeMode", FrameRate.DEFAULT.ordinal)]
val timeSpanStart get() = props("TimeSpanStart", 0L)
val timeSpanStop get() = props("TimeSpanStop", 0L)
val customFrameRate get() = props("CustomFrameRate", -1f)
}
/** DOM root for a FBX file */
class Document(val parser: Parser, val settings: ImportSettings) {
val objects = mutableMapOf<Long, LazyObject>()
val templates = HashMap<String, PropertyTable>()
val srcConnections = mutableMapOf<Long, ArrayList<Connection>>()
val destConnections = mutableMapOf<Long, ArrayList<Connection>>()
var fbxVersion = 0
var creator = ""
val creationTimeStamp = IntArray(7)
private val animationStacks = ArrayList<Long>()
val animationStacksResolved = ArrayList<AnimationStack>()
var globals: FileGlobalSettings? = null
init {
readHeader()
readPropertyTemplates()
readGlobalSettings()
/* This order is important, connections need parsed objects to check whether connections are ok or not.
Objects may not be evaluated yet, though, since this may require valid connections. */
readObjects()
readConnections()
}
operator fun get(id: Long) = objects[id]
//
// bool IsBinary()
// const {
// return parser.IsBinary()
// }
//
// unsigned int FBXVersion()
// const {
// return fbxVersion
// }
//
// const std::string& Creator()
// const {
// return creator
// }
//
// // elements (in this order): Year, Month, Day, Hour, Second, Millisecond
// const unsigned int* CreationTimeStamp()
// const {
// return creationTimeStamp
// }
//
// const FileGlobalSettings& GlobalSettings()
// const {
// ai_assert(globals.get())
// return * globals.get()
// }
//
// const PropertyTemplateMap& Templates()
// const {
// return templates
// }
//
// const ObjectMap& Objects()
// const {
// return objects
// }
//
// const ImportSettings& Settings()
// const {
// return settings
// }
//
// const ConnectionMap& ConnectionsBySource()
// const {
// return src_connections
// }
//
// const ConnectionMap& ConnectionsByDestination()
// const {
// return dest_connections
// }
//
/* note: the implicit rule in all DOM classes is to always resolve from destination to source (since the FBX object
hierarchy is, with very few exceptions, a DAG, this avoids cycles). In all cases that may involve back-facing
edges in the object graph, use LazyObject::IsBeingConstructed() to check. */
fun getConnectionsBySourceSequenced(source: Long) = getConnectionsSequenced(source, srcConnections)
fun getConnectionsByDestinationSequenced(dest: Long) = getConnectionsSequenced(dest, destConnections)
fun getConnectionsBySourceSequenced(source: Long, classname: String) = getConnectionsBySourceSequenced(source, arrayOf(classname))
fun getConnectionsByDestinationSequenced(dest: Long, classname: String) = getConnectionsByDestinationSequenced(dest, arrayOf(classname))
fun getConnectionsBySourceSequenced(source: Long, classnames: Array<String>) = getConnectionsSequenced(source, true, srcConnections, classnames)
fun getConnectionsByDestinationSequenced(dest: Long, classnames: Array<String>) = getConnectionsSequenced(dest, false, destConnections, classnames)
fun animationStacks(): ArrayList<AnimationStack> {
if (animationStacksResolved.isNotEmpty() || animationStacks.isEmpty()) return animationStacksResolved
animationStacksResolved.ensureCapacity(animationStacks.size)
for (id in animationStacks) {
val stack = get(id)?.get<AnimationStack>()
if (stack == null) {
domWarning("failed to read AnimationStack object")
continue
}
animationStacksResolved += stack
}
return animationStacksResolved
}
fun getConnectionsSequenced(id: Long, conns: MutableMap<Long, ArrayList<Connection>>): ArrayList<Connection> {
val range = conns[id] ?: arrayListOf()
return ArrayList<Connection>(range.size).apply {// NRVO should handle this
addAll(range)
sort()
}
}
val MAX_CLASSNAMES = 6
fun getConnectionsSequenced(id: Long, isSrc: Boolean, conns: MutableMap<Long, ArrayList<Connection>>, classnames: Array<String>): ArrayList<Connection> {
assert(classnames.size in 1..MAX_CLASSNAMES)
val temp = ArrayList<Connection>()
val range = conns[id] ?: return temp
temp.ensureCapacity(range.size)
for (it in range) {
val key = (if (isSrc) it.lazyDestinationObject else it.lazySourceObject).element.keyToken
var obType = key.begin
for (name in classnames) {
assert(name.isNotEmpty())
if (key.end - key.begin == name.length && buffer.strncmp(name, obType)) {
obType = 0
break
}
}
if (obType != 0) continue
temp += it
}
temp.sort()
return temp // NRVO should handle this
}
fun readHeader() {
// Read ID objects from "Objects" section
val sc = parser.root
val eHead = sc["FBXHeaderExtension"]
if (eHead?.compound == null) domError("no FBXHeaderExtension dictionary found")
val sHead = eHead.compound!!
fbxVersion = getRequiredElement(sHead, "FBXVersion", eHead)[0].parseAsInt
// While we may have some success with newer files, we don't support the older 6.n fbx format
if (fbxVersion < lowerSupportedVersion) domError("unsupported, old format version, supported are only FBX 2011, FBX 2012 and FBX 2013")
if (fbxVersion > upperSupportedVersion)
if (settings.strictMode) domError("unsupported, newer format version, supported are only FBX 2011, FBX 2012 and FBX 2013 (turn off strict mode to try anyhow) ")
else domWarning("unsupported, newer format version, supported are only FBX 2011, FBX 2012 and FBX 2013, trying to read it nevertheless")
sHead["Creator"]?.let { creator = it[0].parseAsString }
sHead["CreationTimeStamp"]?.let {
it.compound?.let {
creationTimeStamp[0] = it["Year"]!![0].parseAsInt
creationTimeStamp[1] = it["Month"]!![0].parseAsInt
creationTimeStamp[2] = it["Day"]!![0].parseAsInt
creationTimeStamp[3] = it["Hour"]!![0].parseAsInt
creationTimeStamp[4] = it["Minute"]!![0].parseAsInt
creationTimeStamp[5] = it["Second"]!![0].parseAsInt
creationTimeStamp[6] = it["Millisecond"]!![0].parseAsInt
}
}
}
fun readObjects() {
// read ID objects from "Objects" section
val sc = parser.root
val eObjects = sc["Objects"]
if (eObjects?.compound == null) domError("no Objects dictionary found")
// add a dummy entry to represent the Model::RootNode object (id 0), which is only indirectly defined in the input file
objects[0L] = LazyObject(0L, eObjects, this)
val sObjects = eObjects.compound!!
for (el in sObjects.elements) {
val key = el.key
for (e in el.value) {
// extract ID
val tok = e.tokens
if (tok.isEmpty()) domError("expected ID after object key", e)
val id = tok[0].parseAsId
// id=0 is normally implicit
if (id == 0L) domError("encountered object with implicitly defined id 0", e)
if (objects.contains(id)) domWarning("encountered duplicate object id, ignoring first occurrence", e)
objects[id] = LazyObject(id, e, this)
// grab all animation stacks upfront since there is no listing of them
if (key == "AnimationStack") animationStacks += id
}
}
}
fun readPropertyTemplates() {
// read property templates from "Definitions" section
val eDefs = parser.root["Definitions"]
if (eDefs?.compound == null) {
domWarning("no Definitions dictionary found")
return
}
val sDefs = eDefs.compound!!
val oTypes = sDefs.getCollection("ObjectType")
for (el in oTypes) {
val sc = el.compound
if (sc == null) {
domWarning("expected nested scope in ObjectType, ignoring", el)
continue
}
val tok = el.tokens
if (tok.isEmpty()) {
domWarning("expected name for ObjectType element, ignoring", el)
continue
}
val oName = tok[0].parseAsString
val templs = sc.getCollection("PropertyTemplate")
for (e in templs) {
val s = e.compound
if (s == null) {
domWarning("expected nested scope in PropertyTemplate, ignoring", e)
continue
}
val t = e.tokens
if (t.isEmpty()) {
domWarning("expected name for PropertyTemplate element, ignoring", e)
continue
}
val pName = t[0].parseAsString
s["Properties70"]?.let {
val props = PropertyTable(it, null)
templates[oName + "." + pName] = props
}
}
}
}
fun readConnections() {
val sc = parser.root
// read property templates from "Definitions" section
val eConns = sc["Connections"]
if (eConns?.compound == null) domError("no Connections dictionary found")
var insertionOrder = 0L
val sConns = eConns.compound!!
val conns = sConns.getCollection("C")
for (el in conns) {
val type = el[0].parseAsString
// PP = property-property connection, ignored for now
// (tokens: "PP", ID1, "Property1", ID2, "Property2")
if (type == "PP") continue
val src = el[1].parseAsId
val dest = el[2].parseAsId
// OO = object-object connection
// OP = object-property connection, in which case the destination property follows the object ID
val prop = if (type == "OP") el[3].parseAsString else ""
if (!objects.contains(src)) {
domWarning("source object for connection does not exist", el)
continue
}
// dest may be 0 (root node) but we added a dummy object before
if (!objects.contains(dest)) {
domWarning("destination object for connection does not exist", el)
continue
}
// add new connection
val c = Connection(insertionOrder++, src, dest, prop, this)
srcConnections.getOrPut(src, ::arrayListOf) += c
destConnections.getOrPut(dest, ::arrayListOf) += c
}
}
fun readGlobalSettings() {
val sc = parser.root
val eHead = sc["GlobalSettings"]
if (eHead?.compound == null) {
domWarning("no GlobalSettings dictionary found")
globals = FileGlobalSettings(this, PropertyTable())
return
}
val props = getPropertyTable(this, "", eHead, eHead.compound!!, true)
if (props.lazyProps.isEmpty() && props.props.isEmpty())
domError("GlobalSettings dictionary contains no property table")
globals = FileGlobalSettings(this, props)
}
//
// private :
// const ImportSettings& settings
//
// ObjectMap objects
// const Parser& parser
//
// PropertyTemplateMap templates
// ConnectionMap src_connections
// ConnectionMap dest_connections
//
// unsigned int fbxVersion
// std::string creator
// unsigned int creationTimeStamp[7]
//
// std::vector<uint64_t> animationStacks
// mutable std::vector<const AnimationStack*> animationStacksResolved
//
// std::unique_ptr<FileGlobalSettings> globals
companion object {
val lowerSupportedVersion = 7100
val upperSupportedVersion = 7400
}
} | src/main/kotlin/assimp/format/fbx/fbxDocument.kt | 2102041635 |
package info.nightscout.androidaps.plugins.general.tidepool.utils
import com.google.gson.Gson
import com.google.gson.GsonBuilder
object GsonInstance {
private var gson_instance: Gson? = null
fun defaultGsonInstance(): Gson {
if (gson_instance == null) {
gson_instance = GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create()
}
return gson_instance as Gson
}
} | app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/utils/GsonInstance.kt | 2743472739 |
package lijin.heinika.cn.mygankio.entiy
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import android.arch.persistence.room.TypeConverter
import android.arch.persistence.room.TypeConverters
import com.google.gson.annotations.SerializedName
import lijin.heinika.cn.mygankio.entiy.converter.StringListConverter
/**
* _id : 5827f41b421aa911d3bb7ecb
* createdAt : 2016-11-13T13:03:23.38Z
* desc : 独立全端开发的开源小作:简诗 2.0
* images : ["http://img.gank.io/b6be7a85-4035-437f-9521-65593fdbc48e"]
* publishedAt : 2016-11-14T11:36:49.680Z
* source : web
* type : Android
* url : https://www.v2ex.com/t/320154
* used : true
* who : wingjay
*/
@Entity(tableName = "ganhuo")
data class GanHuoBean(
@SerializedName("_id") @PrimaryKey val id: String,
val createdAt: String,
val desc: String,
val publishedAt: String,
val source: String,
val type: String,
val url: String,
val used: Boolean,
val who: String,
@TypeConverters(StringListConverter::class)
val images: List<String>
)
| app/src/main/java/lijin/heinika/cn/mygankio/entiy/GanHuoBean.kt | 1440498672 |
package chat.willow.hopper.routes.connection
import chat.willow.hopper.connections.IHopperConnections
import chat.willow.hopper.logging.loggerFor
import chat.willow.hopper.routes.*
import chat.willow.hopper.routes.shared.EmptyBody
import chat.willow.hopper.routes.shared.ErrorResponseBody
import chat.willow.hopper.websocket.IWebSocketUserTracker
import chat.willow.hopper.websocket.messages.ConnectionStarted
import com.squareup.moshi.Moshi
import spark.Request
data class ConnectionStartContext(val authenticatedContext: AuthenticatedContext, val id: String) {
companion object Builder: IContextBuilder<ConnectionStartContext> {
override fun build(request: Request): ConnectionStartContext? {
val authContext = AuthenticatedContext.Builder.build(request) ?: return null
val id = request.params("connection_id") ?: return null
return ConnectionStartContext(authContext, id)
}
}
}
class ConnectionStartRouteHandler(moshi: Moshi, private val connections: IHopperConnections, private val tracker: IWebSocketUserTracker) :
JsonRouteHandler<EmptyBody, EmptyBody, ConnectionStartContext>(
EmptyBody,
EmptyBody,
moshi.stringSerialiser(),
ConnectionStartContext.Builder
) {
private val LOGGER = loggerFor<ConnectionStartRouteHandler>()
override fun handle(request: EmptyBody, context: ConnectionStartContext): RouteResult<EmptyBody, ErrorResponseBody> {
LOGGER.info("handling GET /connection/<id>/start: $request")
// todo: sanity check id
val server = connections[context.id] ?: return jsonFailure(404, message = "couldn't find a server with id ${context.id}")
connections.start(context.id)
tracker.send(ConnectionStarted.Payload(id = context.id), user = context.authenticatedContext.user)
return RouteResult.success(value = EmptyBody)
}
} | src/main/kotlin/chat/willow/hopper/routes/connection/ConnectionStartRouteHandler.kt | 3687644983 |
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.reflect.KProperty
import kotlin.reflect.jvm.isAccessible
import kotlin.test.*
object Delegate {
var storage = ""
operator fun getValue(instance: Any?, property: KProperty<*>) = storage
operator fun setValue(instance: Any?, property: KProperty<*>, value: String) { storage = value }
}
class Foo {
var result: String by Delegate
}
fun box(): String {
val foo = Foo()
foo.result = "Fail"
val d = (Foo::result).apply { isAccessible = true }.getDelegate(foo) as Delegate
foo.result = "OK"
assertEquals(d, (Foo::result).apply { isAccessible = true }.getDelegate(foo))
return d.getValue(foo, Foo::result)
}
| backend.native/tests/external/codegen/box/reflection/properties/getDelegate/memberProperty.kt | 1716946218 |
/*
* 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.`object`
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.action.TextObjectAction
import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.command.MappingMode
import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.handler.TextObjectActionHandler
import com.maddyhome.idea.vim.helper.enumSetOf
import java.util.*
import javax.swing.KeyStroke
class MotionInnerBigWordAction : TextObjectAction() {
override fun makeActionHandler(): TextObjectActionHandler = object : TextObjectActionHandler() {
override fun getRange(editor: Editor,
caret: Caret,
context: DataContext,
count: Int,
rawCount: Int,
argument: Argument?): TextRange {
return VimPlugin.getMotion().getWordRange(editor, caret, count, false, true)
}
}
override val mappingModes: Set<MappingMode> = MappingMode.VO
override val keyStrokesSet: Set<List<KeyStroke>> = parseKeysSet("iW")
override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_MOT_CHARACTERWISE, CommandFlags.FLAG_MOT_INCLUSIVE)
}
| src/com/maddyhome/idea/vim/action/motion/object/MotionInnerBigWordAction.kt | 3940929325 |
package com.guardafilme.ui.main
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.firebase.ui.auth.IdpResponse
import com.google.android.gms.ads.MobileAds
import com.guardafilme.R
import com.guardafilme.data.AuthProvider
import com.guardafilme.ui.welcome.WelcomeActivity
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_main.*
import javax.inject.Inject
class MainActivity : AppCompatActivity(), MainContract.View {
val RC_SIGN_IN = 1234
@Inject
lateinit var presenter: MainContract.Presenter
@Inject
lateinit var authProvider: AuthProvider
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
presenter.attach(this)
setContentView(R.layout.activity_main)
window.statusBarColor = ContextCompat.getColor(this, R.color.colorAccentDark)
MobileAds.initialize(this, getString(R.string.admob_id))
}
override fun onStart() {
super.onStart()
presenter.loadCurrentUser()
login_button.setOnClickListener {
presenter.loginClicked()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val response = IdpResponse.fromResultIntent(data)
// Successfully signed in
if (resultCode == Activity.RESULT_OK) {
presenter.loadCurrentUser()
} else {
// Sign in failed
presenter.loginError(response?.error?.errorCode)
}
}
}
override fun showLoginMessage() {
login_message_layout.visibility = View.VISIBLE
}
override fun openLogin() {
startActivityForResult(
authProvider.getAuthIntent(),
RC_SIGN_IN)
}
override fun openWelcome() {
startActivity(WelcomeActivity.createIntent(this))
finish()
}
override fun showCanceledLoginMessage() {
showSnackbar(R.string.sign_in_cancelled)
}
override fun showNetworkErrorMessage() {
showSnackbar(R.string.no_internet_connection)
}
override fun showUnknownErrorMessage() {
showSnackbar(R.string.unknown_error)
}
fun showSnackbar(messageId: Int) {
val snack = Snackbar.make(findViewById(R.id.main_layout), messageId, Snackbar.LENGTH_LONG)
snack.show()
}
}
| app/src/main/java/com/guardafilme/ui/main/MainActivity.kt | 3151882660 |
package com.guardafilme.di
import android.app.Application
import dagger.BindsInstance
import dagger.Component
import dagger.android.AndroidInjectionModule
import dagger.android.AndroidInjector
import dagger.android.DaggerApplication
import dagger.android.support.AndroidSupportInjectionModule
import com.guardafilme.GuardaFilmeApplication
import com.guardafilme.data.UserRepository
import com.guardafilme.ui.welcome.WelcomeActivityModule
import javax.inject.Singleton
/**
* Created by lucassantos on 19/10/17.
*/
@Singleton
@Component(modules = arrayOf(
ApplicationModule::class,
AndroidInjectionModule::class,
ActivityBindingModule::class))
interface ApplicationComponent {
fun inject(application: GuardaFilmeApplication)
// fun getUserRepository(): UserRepository
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: Application): ApplicationComponent.Builder
fun build(): ApplicationComponent
}
} | app/src/main/java/com/guardafilme/di/ApplicationComponent.kt | 3455260170 |
package com.bluelinelabs.conductor.viewpager
import com.bluelinelabs.conductor.viewpager.util.TestActivity
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(manifest = Config.NONE)
class StateSaveTests {
private val testController = Robolectric.buildActivity(TestActivity::class.java)
.setup()
.get()
.testController()
private val pagerAdapter = testController.pagerAdapter
private val pager = testController.pager
private val destroyedItems = testController.destroyedItems
@Test
fun testNoMaxSaves() {
// Load all pages
for (i in 0 until pagerAdapter.count) {
pager.currentItem = i
}
// Ensure all non-visible pages are saved
assertEquals(
destroyedItems.size,
pagerAdapter.savedPages.size()
)
}
@Test
fun testMaxSavedSet() {
val maxPages = 3
pagerAdapter.setMaxPagesToStateSave(maxPages)
// Load all pages
for (i in 0 until pagerAdapter.count) {
pager.currentItem = i
}
val firstSelectedItem = pagerAdapter.count / 2
for (i in pagerAdapter.count downTo firstSelectedItem) {
pager.currentItem = i
}
var savedPages = pagerAdapter.savedPages
// Ensure correct number of pages are saved
assertEquals(maxPages, savedPages.size())
// Ensure correct pages are saved
assertEquals(destroyedItems[destroyedItems.lastIndex], savedPages.keyAt(0))
assertEquals(destroyedItems[destroyedItems.lastIndex - 1], savedPages.keyAt(1))
assertEquals(destroyedItems[destroyedItems.lastIndex - 2], savedPages.keyAt(2))
val secondSelectedItem = 1
for (i in firstSelectedItem downTo secondSelectedItem) {
pager.currentItem = i
}
savedPages = pagerAdapter.savedPages
// Ensure correct number of pages are saved
assertEquals(maxPages, savedPages.size())
// Ensure correct pages are saved
assertEquals(destroyedItems[destroyedItems.lastIndex], savedPages.keyAt(0))
assertEquals(destroyedItems[destroyedItems.lastIndex - 1], savedPages.keyAt(1))
assertEquals(destroyedItems[destroyedItems.lastIndex - 2], savedPages.keyAt(2))
}
} | conductor-modules/viewpager/src/test/java/com/bluelinelabs/conductor/viewpager/StateSaveTests.kt | 1138506274 |
package com.keenencharles.unsplash.models
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
@Parcelize
data class CurrentUserCollection(
var id: Int? = null,
var title: String? = null,
var curated: Boolean? = null,
@SerializedName("user") var user: User? = null,
@SerializedName("cover_photo") var coverPhoto: CoverPhoto? = null,
@SerializedName("published_at") var publishedAt: String? = null,
@SerializedName("updated_at") var updatedAt: String? = null,
) : Parcelable | androidunsplash/src/main/java/com/keenencharles/unsplash/models/CurrentUserCollection.kt | 826707636 |
package com.sjn.stamp.ui
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.media.MediaBrowserCompat
import android.view.View
interface MediaBrowsable {
val mediaBrowser: MediaBrowserCompat?
fun searchMediaItems(query: String, extras: Bundle?, callback: MediaBrowserCompat.SearchCallback)
fun playByCategory(mediaId: String)
fun playByMediaId(mediaId: String)
fun navigateToBrowser(mediaId: String, fragment: Fragment, sharedElements: List<Pair<String, View>>)
fun sendCustomAction(action: String, extras: Bundle?, callback: MediaBrowserCompat.CustomActionCallback?)
}
| app/src/main/java/com/sjn/stamp/ui/MediaBrowsable.kt | 3167587853 |
package com.fsck.k9.storage
import android.app.Application
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/**
* A Robolectric test that does not create an instance of our [Application] class.
*/
@RunWith(RobolectricTestRunner::class)
@Config(application = EmptyApplication::class)
abstract class RobolectricTest
class EmptyApplication : Application()
| app/storage/src/test/java/com/fsck/k9/storage/RobolectricTest.kt | 371453028 |
package com.fsck.k9.controller.push
import com.fsck.k9.Account
import com.fsck.k9.Account.FolderMode
import com.fsck.k9.Preferences
import com.fsck.k9.backend.BackendManager
import com.fsck.k9.backend.api.BackendPusher
import com.fsck.k9.backend.api.BackendPusherCallback
import com.fsck.k9.controller.MessagingController
import com.fsck.k9.mailstore.FolderRepository
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import timber.log.Timber
internal class AccountPushController(
private val backendManager: BackendManager,
private val messagingController: MessagingController,
private val preferences: Preferences,
private val folderRepository: FolderRepository,
backgroundDispatcher: CoroutineDispatcher = Dispatchers.IO,
private val account: Account
) {
private val coroutineScope = CoroutineScope(backgroundDispatcher)
@Volatile
private var backendPusher: BackendPusher? = null
private val backendPusherCallback = object : BackendPusherCallback {
override fun onPushEvent(folderServerId: String) {
syncFolders(folderServerId)
}
override fun onPushError(exception: Exception) {
messagingController.handleException(account, exception)
}
override fun onPushNotSupported() {
Timber.v("AccountPushController(%s) - Push not supported. Disabling Push for account.", account.uuid)
disablePush()
}
}
fun start() {
Timber.v("AccountPushController(%s).start()", account.uuid)
startBackendPusher()
startListeningForPushFolders()
}
fun stop() {
Timber.v("AccountPushController(%s).stop()", account.uuid)
stopListeningForPushFolders()
stopBackendPusher()
}
fun reconnect() {
Timber.v("AccountPushController(%s).reconnect()", account.uuid)
backendPusher?.reconnect()
}
private fun startBackendPusher() {
val backend = backendManager.getBackend(account)
backendPusher = backend.createPusher(backendPusherCallback).also { backendPusher ->
backendPusher.start()
}
}
private fun stopBackendPusher() {
backendPusher?.stop()
backendPusher = null
}
private fun startListeningForPushFolders() {
coroutineScope.launch {
folderRepository.getPushFoldersFlow(account).collect { remoteFolders ->
val folderServerIds = remoteFolders.map { it.serverId }
updatePushFolders(folderServerIds)
}
}
}
private fun stopListeningForPushFolders() {
coroutineScope.cancel()
}
private fun updatePushFolders(folderServerIds: List<String>) {
Timber.v("AccountPushController(%s).updatePushFolders(): %s", account.uuid, folderServerIds)
backendPusher?.updateFolders(folderServerIds)
}
private fun syncFolders(folderServerId: String) {
messagingController.synchronizeMailboxBlocking(account, folderServerId)
}
private fun disablePush() {
account.folderPushMode = FolderMode.NONE
preferences.saveAccount(account)
}
}
| app/core/src/main/java/com/fsck/k9/controller/push/AccountPushController.kt | 1544219383 |
// 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 com.intellij.openapi.externalSystem.util
import com.intellij.configurationStore.StoreUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.testFramework.runInEdtAndWait
fun Project.use(save: Boolean = false, action: (Project) -> Unit) {
try {
action(this)
}
finally {
forceCloseProject(save)
}
}
fun Project.forceCloseProject(save: Boolean = false) {
runInEdtAndWait {
val projectManager = ProjectManagerEx.getInstanceEx()
if (save) {
StoreUtil.saveSettings(this, forceSavingAllSettings = true)
}
projectManager.forceCloseProject(this)
}
}
| platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/util/ExternalSystemProjectUtil.kt | 3420468251 |
package com.joe.zatuji.module.favorite
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import com.joe.zatuji.R
import com.joe.zatuji.base.staggered.BasePicListFragment
import com.joe.zatuji.base.staggered.BasePicListPresenter
import com.joe.zatuji.base.staggered.IBasePicListView
import com.joe.zatuji.helper.DialogHelper
import com.joe.zatuji.module.gallery.GalleryActivity
import com.joe.zatuji.repo.bean.Empty
import com.joe.zatuji.repo.bean.FavoriteTag
import com.joe.zatuji.view.DownloadTagDialog
import com.joe.zatuji.view.FavoriteTagDialog
import com.joe.zatuji.view.FavoriteTagMenuDialog
import com.joe.zatuji.view.LockTagDialog
import com.joey.cheetah.core.list.AbsItemViewBinder
import com.joey.cheetah.core.utils.ResGetter
import com.joey.cheetah.mvp.auto.Presenter
/**
* Description:
* author:Joey
* date:2018/11/22
*/
class FavoriteTagFragment : BasePicListFragment<FavoriteTag>(), IFavoriteTagView, FavoriteTagDialog.OnCreateCallBack, FavoriteTagMenuDialog.OnMenuClickListener, LockTagDialog.OnPwdListener {
@Presenter
private val presenter = FavoriteTagPresenter(this)
private val createTagView: FavoriteTagDialog by lazy {
FavoriteTagDialog(activity).setOnCreateCallBack(this)
}
private val editTagView: FavoriteTagMenuDialog by lazy {
FavoriteTagMenuDialog(activity).setOnMenuClickListener(this)
}
private val downloadView: DownloadTagDialog by lazy {
DownloadTagDialog(activity!!)
}
private val lockTagView: LockTagDialog by lazy {
LockTagDialog(activity).setOnPwdListener(this)
}
companion object {
private const val EDIT_TAG = 1
private const val DELETE_TAG = 2
private const val ENTER = 3
private const val DOWNLOAD = 4
}
override fun initArguments(p0: Bundle?) {}
override fun initView() {
super.initView()
setHasOptionsMenu(true)
updateTitle()
}
override fun onHiddenChanged(hidden: Boolean) {
super.onHiddenChanged(hidden)
if (!hidden) {
updateTitle()
}
}
private fun updateTitle() {
activity?.title = ResGetter.string(R.string.tab_home_favorite)
}
override fun switchMenu(show: Boolean) {
setMenuVisibility(show)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_favorite, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.action_add) {
createTagView.show(null)
}
return true
}
override fun onItemClick(pos: Int, item: FavoriteTag) {
if (item.is_lock) {
lockTagView.show(item, ENTER)
} else {
GalleryActivity.start(activity!!, item)
}
}
override fun onItemLongClick(pos: Int, item: FavoriteTag): Boolean {
editTagView.show(item)
return true
}
override fun emptyView(): AbsItemViewBinder<Empty, *> {
return FavoriteEmptyItemViewBinder()
}
override fun layoutManager(): RecyclerView.LayoutManager {
return GridLayoutManager(activity, 2)
}
override fun viewBinder(): AbsItemViewBinder<FavoriteTag, *> {
return FavoriteTagItemViewBinder()
}
override fun itemType(): Class<FavoriteTag> {
return FavoriteTag::class.java
}
override fun listPresenter(): BasePicListPresenter<IBasePicListView> {
return presenter as BasePicListPresenter<IBasePicListView>
}
override fun initLayout(): Int {
return R.layout.fragment_favorite
}
override fun onCreate(tag: FavoriteTag) {
presenter.createTag(tag)
}
override fun onUpdate(tag: FavoriteTag) {
presenter.updateTag(tag)
}
override fun onEdit(tag: FavoriteTag) {
if (tag.is_lock) {
lockTagView.show(tag, EDIT_TAG)
} else {
createTagView.show(tag)
}
}
override fun onPwdSuccess(tag: FavoriteTag, action: Int) {
when (action) {
EDIT_TAG -> createTagView.show(tag)
DELETE_TAG -> delete(tag)
ENTER -> GalleryActivity.start(activity!!, tag)
DOWNLOAD -> presenter.download(tag)
}
}
override fun onDelete(tag: FavoriteTag) {
if (tag.is_lock) {
lockTagView.show(tag, DELETE_TAG)
} else {
delete(tag)
}
}
private fun delete(tag: FavoriteTag) {
DialogHelper.confirmDialog(getString(R.string.delete_tag), ResGetter.stringFormat(R.string.delete_tag_hint, tag.tag), {
presenter.deleteTag(tag)
true
})
}
override fun onDownload(tag: FavoriteTag) {
if (tag.is_lock) {
lockTagView.show(tag, DOWNLOAD)
} else {
presenter.download(tag)
}
}
override fun onLoadMore() {
// 不支持load more
}
override fun onDestroy() {
super.onDestroy()
createTagView.dismiss()
editTagView.dismiss()
lockTagView.dismiss()
}
override fun showDownload(tag:FavoriteTag) {
downloadView.show(tag, {
presenter.cancelDownload()
})
}
override fun completeDownload() {
downloadView.dismiss()
toast("下载完成")
}
override fun updateProgress(it: Int) {
downloadView.updateProgress(it)
}
} | app/src/main/java/com/joe/zatuji/module/favorite/FavoriteTagFragment.kt | 2893034661 |
package com.joe.zatuji.repo.bean
import com.google.gson.annotations.SerializedName
/**
* Description:
* author:Joey
* date:2018/11/26
*/
data class FeedBack(@SerializedName("user_name")val userName:String,
@SerializedName("user_email")val email:String,
@SerializedName("version")val version:String,
@SerializedName("user_id")val userId:String,
@SerializedName("type")val type:String,
@SerializedName("android_version")val androidVersion:String,
@SerializedName("content")val content:String) | app/src/main/java/com/joe/zatuji/repo/bean/FeedBack.kt | 121513484 |
package test
import android.app.*
import android.widget.*
import android.os.Bundle
import org.jetbrains.anko.*
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
import org.robolectric.*
import org.junit.Test
import kotlin.test.*
public open class TestActivity() : Activity() {
public override fun onCreate(savedInstanceState: Bundle?): Unit {
super.onCreate(savedInstanceState)
linearLayout {}
}
}
RunWith(javaClass<RobolectricTestRunner>())
public class RobolectricTest() {
Test
public fun test() {
val activity = Robolectric.buildActivity(javaClass<TestActivity>()).create().get()
val vibrator = activity.vibrator
vibrator.vibrate(100)
println("[COMPLETE]")
}
} | dsl/testData/robolectric/ServiceTest.kt | 943807920 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.maven.maven3
import com.intellij.openapi.roots.ui.distribution.AbstractDistributionInfo
import org.jetbrains.idea.maven.project.MavenConfigurableBundle
open class BundledDistributionInfo(version: String) : AbstractDistributionInfo() {
override val name: String = MavenConfigurableBundle.message("maven.run.configuration.bundled.distribution.name", version)
override val description: String = MavenConfigurableBundle.message("maven.run.configuration.bundled.distribution.description")
}
class Bundled3DistributionInfo(version: String?) : BundledDistributionInfo(version ?: "3") | plugins/maven/src/main/java/org/jetbrains/idea/maven/maven3/MavenBundledDistributionInfo.kt | 2993906192 |
// 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 org.jetbrains.debugger
import com.intellij.icons.AllIcons
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.ColoredTextContainer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.util.ui.UIUtil
import com.intellij.xdebugger.XDebuggerBundle
import com.intellij.xdebugger.frame.XExecutionStack
import com.intellij.xdebugger.frame.XStackFrame
import com.intellij.xdebugger.frame.XSuspendContext
import com.intellij.xdebugger.impl.frame.XDebuggerFramesList
import com.intellij.xdebugger.settings.XDebuggerSettingsManager
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.rejectedPromise
import org.jetbrains.concurrency.resolvedPromise
import org.jetbrains.debugger.frame.CallFrameView
import org.jetbrains.debugger.values.StringValue
import java.awt.Color
import java.util.*
/**
* Debugging several VMs simultaneously should be similar to debugging multi-threaded Java application when breakpoints suspend only one thread.
* 1. When thread is paused and another thread reaches breakpoint, show notification about it with possibility to switch thread.
* 2. Stepping and releasing affects only current thread.
* 3. When another thread is selected in Frames view, it changes its icon from (0) to (v) and becomes current, i.e. step/release commands
* are applied to it.
* 4. Stepping/releasing updates current thread icon and clears frame, but doesn't switch thread. To release other threads, user needs to
* select them firstly.
*/
abstract class SuspendContextView(protected val debugProcess: MultiVmDebugProcess,
activeStack: ExecutionStackView,
@Volatile var activeVm: Vm)
: XSuspendContext() {
private val stacks: MutableMap<Vm, ScriptExecutionStack> = Collections.synchronizedMap(LinkedHashMap<Vm, ScriptExecutionStack>())
init {
val mainVm = debugProcess.mainVm
val vmList = debugProcess.collectVMs
if (mainVm != null && !vmList.isEmpty()) {
// main vm should go first
vmList.forEach {
val context = it.suspendContextManager.context
val stack: ScriptExecutionStack =
if (context == null) {
RunningThreadExecutionStackView(it)
}
else if (context == activeStack.suspendContext) {
activeStack
}
else {
logger<SuspendContextView>().error("Paused VM was lost.")
InactiveAtBreakpointExecutionStackView(it)
}
stacks[it] = stack
}
}
else {
stacks[activeVm] = activeStack
}
}
override fun getActiveExecutionStack(): ScriptExecutionStack? = stacks[activeVm]
override fun getExecutionStacks(): Array<out XExecutionStack> = stacks.values.toTypedArray()
fun evaluateExpression(expression: String): Promise<String> {
val activeStack = stacks[activeVm]!!
val frame = activeStack.topFrame ?: return rejectedPromise("Top frame is null")
if (frame !is CallFrameView) return rejectedPromise("Can't evaluate on non-paused thread")
return evaluateExpression(frame.callFrame.evaluateContext, expression)
}
private fun evaluateExpression(evaluateContext: EvaluateContext, expression: String) = evaluateContext.evaluate(expression)
.thenAsync {
val value = it.value
if (value is StringValue && value.isTruncated) {
value.fullString
}
else {
resolvedPromise(value.valueString!!)
}
}
fun pauseInactiveThread(inactiveThread: ExecutionStackView) {
stacks[inactiveThread.vm] = inactiveThread
}
fun hasPausedThreads(): Boolean {
return stacks.values.any { it is ExecutionStackView }
}
fun resume(vm: Vm) {
val prevStack = stacks[vm]
if (prevStack is ExecutionStackView) {
stacks[vm] = RunningThreadExecutionStackView(prevStack.vm)
}
}
fun resumeCurrentThread() {
resume(activeVm)
}
fun setActiveThread(selectedStackFrame: XStackFrame?): Boolean {
if (selectedStackFrame !is CallFrameView) return false
var selectedVm: Vm? = null
for ((key, value) in stacks) {
if (value is ExecutionStackView && value.topFrame?.vm == selectedStackFrame.vm) {
selectedVm = key
break
}
}
val selectedVmStack = stacks[selectedVm]
if (selectedVm != null && selectedVmStack is ExecutionStackView) {
activeVm = selectedVm
stacks[selectedVm] = selectedVmStack.copyWithIsCurrent(true)
stacks.keys.forEach {
val stack = stacks[it]
if (it != selectedVm && stack is ExecutionStackView) {
stacks[it] = stack.copyWithIsCurrent(false)
}
}
return stacks[selectedVm] !== selectedVmStack
}
return false
}
}
class RunningThreadExecutionStackView(vm: Vm) : ScriptExecutionStack(vm, vm.presentableName, AllIcons.Debugger.ThreadRunning) {
override fun computeStackFrames(firstFrameIndex: Int, container: XStackFrameContainer?) {
// add dependency to DebuggerBundle?
container?.errorOccurred(XDebuggerBundle.message("debugger.frames.dialog.message.not.available.for.unsuspended"))
}
override fun getTopFrame(): XStackFrame? = null
}
class InactiveAtBreakpointExecutionStackView(vm: Vm) : ScriptExecutionStack(vm, vm.presentableName, AllIcons.Debugger.ThreadAtBreakpoint) {
override fun getTopFrame(): XStackFrame? = null
override fun computeStackFrames(firstFrameIndex: Int, container: XStackFrameContainer?) {}
}
abstract class ScriptExecutionStack(val vm: Vm, @NlsContexts.ListItem displayName : String, icon: javax.swing.Icon)
: XExecutionStack(displayName, icon) {
override fun hashCode(): Int {
return vm.hashCode()
}
override fun equals(other: Any?): Boolean {
return other is ScriptExecutionStack && other.vm == vm
}
}
// TODO should be AllIcons.Debugger.ThreadCurrent, but because of strange logic to add non-equal XExecutionStacks we can't update icon.
private fun getThreadIcon(isCurrent: Boolean) = AllIcons.Debugger.ThreadAtBreakpoint
class ExecutionStackView(val suspendContext: SuspendContext<*>,
internal val viewSupport: DebuggerViewSupport,
private val topFrameScript: Script?,
private val topFrameSourceInfo: SourceInfo? = null,
@NlsContexts.ListItem displayName: String = "",
isCurrent: Boolean = true)
: ScriptExecutionStack(suspendContext.vm, displayName, getThreadIcon(isCurrent)) {
private var topCallFrameView: CallFrameView? = null
override fun getTopFrame(): CallFrameView? {
val topCallFrame = suspendContext.topFrame
if (topCallFrameView == null || topCallFrameView!!.callFrame != topCallFrame) {
topCallFrameView = topCallFrame?.let { CallFrameView(it, viewSupport, topFrameScript, topFrameSourceInfo,
vm = suspendContext.vm,
methodReturnValue = suspendContext.methodReturnValue) }
}
return topCallFrameView
}
override fun computeStackFrames(firstFrameIndex: Int, container: XExecutionStack.XStackFrameContainer) {
// WipSuspendContextManager set context to null on resume _before_ vm.getDebugListener().resumed() call() (in any case, XFramesView can queue event to EDT), so, IDE state could be outdated compare to VM (our) state
suspendContext.frames
.onSuccess(suspendContext) { frames ->
val count = frames.size - firstFrameIndex
val result: List<XStackFrame>
if (count < 1) {
result = emptyList()
}
else {
result = ArrayList(count)
for (i in firstFrameIndex until frames.size) {
if (i == 0) {
result.add(topFrame!!)
continue
}
val frame = frames[i]
val asyncFunctionName = frame.asyncFunctionName
if (asyncFunctionName != null) {
result.add(AsyncFramesHeader(asyncFunctionName))
}
// if script is null, it is native function (Object.forEach for example), so, skip it
val script = suspendContext.vm.scriptManager.getScript(frame)
if (script != null) {
val sourceInfo = viewSupport.getSourceInfo(script, frame)
val isInLibraryContent = sourceInfo != null && viewSupport.isInLibraryContent(sourceInfo, script)
if (isInLibraryContent && !XDebuggerSettingsManager.getInstance().dataViewSettings.isShowLibraryStackFrames) {
continue
}
result.add(CallFrameView(frame, viewSupport, script, sourceInfo, isInLibraryContent, suspendContext.vm))
}
}
}
container.addStackFrames(result, true)
}
}
fun copyWithIsCurrent(isCurrent: Boolean): ExecutionStackView {
if (icon == getThreadIcon(isCurrent)) return this
return ExecutionStackView(suspendContext, viewSupport, topFrameScript, topFrameSourceInfo, displayName, isCurrent)
}
}
private val ASYNC_HEADER_ATTRIBUTES = SimpleTextAttributes(SimpleTextAttributes.STYLE_UNDERLINE or SimpleTextAttributes.STYLE_BOLD,
UIUtil.getInactiveTextColor())
private class AsyncFramesHeader(val asyncFunctionName: String) : XStackFrame(), XDebuggerFramesList.ItemWithCustomBackgroundColor {
override fun customizePresentation(component: ColoredTextContainer) {
component.append(XDebuggerBundle.message("debugger.frames.label.async.call.from.function", asyncFunctionName), ASYNC_HEADER_ATTRIBUTES)
}
override fun getBackgroundColor(): Color? = null
} | platform/script-debugger/debugger-ui/src/SuspendContextView.kt | 2551262263 |
package marmor.com.stickman
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
public class StickManActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_stick_man)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_stick_man, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true
}
return super.onOptionsItemSelected(item)
}
}
| StickMan/app/src/main/kotlin/marmor/com/stickman/StickManActivity.kt | 3929431440 |
package com.github.plombardi89.kocean
import com.github.plombardi89.kocean.model.HostAndPort
import org.junit.Test
import org.junit.Assert.*
class ClientExceptionTest {
Test fun noProxySpecified_invalidResponseReceivedMessageDoesNotContainProxyInformation() {
val configWithoutProxy = KOceanConfig("foobar")
val exception = ClientException.invalidResponse(configWithoutProxy)
assertEquals("Invalid response (host: api.digitalocean.com:443)", exception.getMessage())
}
Test fun invalidResponseReceivedMessageIsFormattedCorrectlyWhenUsingAProxy() {
val configWithProxy = KOceanConfig(apiToken = "foobar", proxyHost = HostAndPort("localhost", 8033))
val exception = ClientException.invalidResponse(configWithProxy)
assertEquals("Invalid response (host: api.digitalocean.com:443, proxy: localhost:8033)", exception.getMessage())
}
} | src/test/kotlin/com/github/plombardi89/kocean/ClientExceptionTest.kt | 3911081256 |
package com.janyo.janyoshare.handler
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Message
import android.support.v4.app.ActivityOptionsCompat
import android.support.v7.app.AlertDialog
import android.widget.Toast
import com.janyo.janyoshare.R
import com.janyo.janyoshare.activity.FileTransferActivity
import com.janyo.janyoshare.activity.FileTransferConfigureActivity
import com.janyo.janyoshare.service.ReceiveFileService
import com.janyo.janyoshare.util.FileTransferHelper
import com.janyo.janyoshare.util.SocketUtil
import com.zyao89.view.zloading.ZLoadingDialog
class ReceiveHandler : Handler()
{
lateinit var spotsDialog: ZLoadingDialog
lateinit var context: Context
override fun handleMessage(msg: Message)
{
when (msg.what)
{
FileTransferConfigureActivity.CREATE_CONNECTION ->
{
spotsDialog.setHintText(context.getString(R.string.hint_socket_connecting))
}
FileTransferConfigureActivity.VERIFY_DEVICE ->
{
@Suppress("UNCHECKED_CAST")
val map = msg.obj as HashMap<String, Any>
val socketUtil = map["socket"] as SocketUtil
AlertDialog.Builder(context)
.setCancelable(false)
.setTitle(R.string.hint_socket_verify_device_title)
.setMessage(String.format(context.getString(R.string.hint_socket_verify_device_message), map["message"]))
.setPositiveButton(R.string.action_done, { _, _ ->
Thread(Runnable {
socketUtil.sendMessage(FileTransferConfigureActivity.VERIFY_DONE)
val message = Message()
message.what = FileTransferConfigureActivity.CONNECTED
message.obj = map["message"]
sendMessage(message)
FileTransferHelper.getInstance().ip = socketUtil.ip
socketUtil.clientDisconnect()
}).start()
})
.setNegativeButton(R.string.action_cancel, { _, _ ->
Thread(Runnable {
socketUtil.sendMessage(FileTransferConfigureActivity.VERIFY_CANCEL)
val message = Message()
message.what = FileTransferConfigureActivity.VERIFY_ERROR
sendMessage(message)
}).start()
})
.show()
}
FileTransferConfigureActivity.CONNECTED ->
{
spotsDialog.dismiss()
Toast.makeText(context, R.string.hint_socket_connected, Toast.LENGTH_SHORT)
.show()
FileTransferHelper.getInstance().tag = 2
context.startService(Intent(context, ReceiveFileService::class.java))
(context as Activity).finish()
context.startActivity(Intent(context, FileTransferActivity::class.java), ActivityOptionsCompat.makeSceneTransitionAnimation(context as Activity).toBundle())
}
FileTransferConfigureActivity.SCAN_COMPLETE ->
{
spotsDialog.dismiss()
val isDeviceFind = msg.obj as Boolean
if (!isDeviceFind)
Toast.makeText(context, R.string.hint_socket_scan_complete, Toast.LENGTH_SHORT)
.show()
}
FileTransferConfigureActivity.VERIFY_ERROR ->
{
spotsDialog.dismiss()
Toast.makeText(context, R.string.hint_socket_verify_error, Toast.LENGTH_SHORT)
.show()
}
}
}
} | app/src/main/java/com/janyo/janyoshare/handler/ReceiveHandler.kt | 2011218969 |
package com.andgate.ikou.actor
import java.util.*
class CommandProcessor
{
private val TAG: String = "CommandProcessor"
// Command history stores commands that were executed and are now finished
var history = Vector<Command>()
// Command buffer stores commands to be executed when the current command is finished
var buffer = LinkedList<Command>()
var is_accepting = true
fun update()
{
for(i in buffer.indices) buffer[i].execute()
history.addAll(buffer)
buffer.clear()
}
fun accept(new_comm: Command)
{
if(is_accepting) buffer.add(new_comm)
}
fun nuke_history()
{
history.clear()
}
fun nuke_buffer()
{
buffer.clear()
}
fun rejectAll()
{
is_accepting = false
}
fun acceptAll()
{
is_accepting = true
}
} | core/src/com/andgate/ikou/actor/CommandProcessor.kt | 852292008 |
/*
* Copyright (C) 2019. Zac Sweers
*
* 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.sweers.catchup.service.github.model
import java.time.LocalDate
import java.time.format.DateTimeFormatter.ISO_LOCAL_DATE
internal data class SearchQuery(val createdSince: LocalDate?, val minStars: Int) {
override fun toString(): String {
// Returning null here is not ideal, but it lets retrofit drop the query param altogether.
val builder = StringBuilder()
if (createdSince != null) {
builder.append("created:>=")
.append(ISO_LOCAL_DATE.format(createdSince))
.append(' ')
}
if (minStars != 0) {
builder.append("stars:>=")
.append(minStars)
}
return builder.toString()
.trim { it <= ' ' }
}
}
| services/github/src/main/kotlin/io/sweers/catchup/service/github/model/SearchQuery.kt | 3505628195 |
/* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.amapi.extensibility.demo.notification
import android.util.Log
import com.amapi.extensibility.demo.commands.CommandUtils
import com.amapi.extensibility.demo.commands.InMemoryCommandRepository
import com.amapi.extensibility.demo.util.TAG
import com.google.android.managementapi.commands.CommandListener
import com.google.android.managementapi.commands.model.Command
import com.google.android.managementapi.notification.NotificationReceiverService
class NotificationReceiverService : NotificationReceiverService() {
override fun getCommandListener(): CommandListener {
return object : CommandListener {
override fun onCommandStatusChanged(command: Command) {
Log.i(TAG, "onCommandStatusChanged: ${CommandUtils.parseCommandForPrettyPrint(command)}")
InMemoryCommandRepository.onCommandStatusChanged(command)
}
}
}
}
| app/src/main/java/com/amapi/extensibility/demo/notification/NotificationReceiverService.kt | 2151250050 |
/*
* Copyright (C) 2016 yuzumone
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package net.yuzumone.sdnmonitor.di
import android.content.Context
import android.support.v4.app.Fragment
import dagger.Module
import dagger.Provides
@Module
class FragmentModule(val fragment: Fragment) {
@Provides
fun provideContext(): Context {
return fragment.context
}
} | app/src/main/kotlin/net/yuzumone/sdnmonitor/di/FragmentModule.kt | 288286883 |
// 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 git4idea.ui.branch.dashboard
import com.intellij.dvcs.branch.GroupingKey
import com.intellij.icons.AllIcons
import com.intellij.ide.CommonActionsManager
import com.intellij.ide.DataManager
import com.intellij.ide.DefaultTreeExpander
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ActionPlaces.VCS_LOG_BRANCHES_PLACE
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.IdeBorderFactory.createBorder
import com.intellij.ui.JBColor
import com.intellij.ui.OnePixelSplitter
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SideBorder
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.speedSearch.SpeedSearch
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBUI.Panels.simplePanel
import com.intellij.util.ui.StatusText.getDefaultEmptyText
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import com.intellij.util.ui.table.ComponentsListFocusTraversalPolicy
import com.intellij.vcs.log.VcsLogBranchLikeFilter
import com.intellij.vcs.log.VcsLogFilterCollection
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.impl.MainVcsLogUiProperties
import com.intellij.vcs.log.impl.VcsLogApplicationSettings
import com.intellij.vcs.log.impl.VcsLogContentProvider.MAIN_LOG_ID
import com.intellij.vcs.log.impl.VcsLogManager
import com.intellij.vcs.log.impl.VcsLogManager.BaseVcsLogUiFactory
import com.intellij.vcs.log.impl.VcsLogNavigationUtil.jumpToBranch
import com.intellij.vcs.log.impl.VcsLogProjectTabsProperties
import com.intellij.vcs.log.ui.VcsLogColorManager
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys
import com.intellij.vcs.log.ui.VcsLogUiImpl
import com.intellij.vcs.log.ui.filter.VcsLogFilterUiEx
import com.intellij.vcs.log.ui.frame.MainFrame
import com.intellij.vcs.log.ui.frame.ProgressStripe
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.visible.VisiblePackRefresher
import com.intellij.vcs.log.visible.VisiblePackRefresherImpl
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import com.intellij.vcs.log.visible.filters.with
import com.intellij.vcs.log.visible.filters.without
import git4idea.i18n.GitBundle.message
import git4idea.i18n.GitBundleExtensions.messagePointer
import git4idea.repo.GitRepository
import git4idea.ui.branch.dashboard.BranchesDashboardActions.DeleteBranchAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.FetchAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.ShowBranchDiffAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.ShowMyBranchesAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.ToggleFavoriteAction
import git4idea.ui.branch.dashboard.BranchesDashboardActions.UpdateSelectedBranchAction
import org.jetbrains.annotations.ApiStatus
import java.awt.Component
import java.awt.datatransfer.DataFlavor
import java.awt.event.ActionEvent
import javax.swing.AbstractAction
import javax.swing.Action
import javax.swing.JComponent
import javax.swing.TransferHandler
import javax.swing.event.TreeSelectionListener
internal class BranchesDashboardUi(project: Project, private val logUi: BranchesVcsLogUi) : Disposable {
private val uiController = BranchesDashboardController(project, this)
private val tree = BranchesTreeComponent(project).apply {
accessibleContext.accessibleName = message("git.log.branches.tree.accessible.name")
}
private val filteringTree = FilteringBranchesTree(project, tree, uiController, place = VCS_LOG_BRANCHES_PLACE, disposable = this)
private val branchViewSplitter = BranchViewSplitter()
private val branchesTreePanel = BranchesTreePanel().withBorder(createBorder(JBColor.border(), SideBorder.LEFT))
private val branchesScrollPane = ScrollPaneFactory.createScrollPane(filteringTree.component, true)
private val branchesProgressStripe = ProgressStripe(branchesScrollPane, this, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS)
private val branchesTreeWithLogPanel = simplePanel()
private val mainPanel = simplePanel().apply { DataManager.registerDataProvider(this, uiController) }
private val branchesSearchFieldPanel = simplePanel()
private val branchesSearchField = filteringTree.installSearchField().apply {
textEditor.border = JBUI.Borders.emptyLeft(5)
accessibleContext.accessibleName = message("git.log.branches.search.field.accessible.name")
// fixme: this needs to be dynamic
accessibleContext.accessibleDescription = message("git.log.branches.search.field.accessible.description",
KeymapUtil.getFirstKeyboardShortcutText("Vcs.Log.FocusTextFilter"))
}
private val branchesSearchFieldWrapper = NonOpaquePanel(branchesSearchField).apply(UIUtil::setNotOpaqueRecursively)
private lateinit var branchesPanelExpandableController: ExpandablePanelController
private val treeSelectionListener = TreeSelectionListener {
if (!branchesPanelExpandableController.isExpanded()) return@TreeSelectionListener
val ui = logUi
val properties = ui.properties
if (properties[CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY]) {
updateLogBranchFilter()
}
else if (properties[NAVIGATE_LOG_TO_BRANCH_ON_BRANCH_SELECTION_PROPERTY]) {
navigateToSelectedBranch(false)
}
}
internal fun updateLogBranchFilter() {
val ui = logUi
val selectedFilters = filteringTree.getSelectedBranchFilters()
val oldFilters = ui.filterUi.filters
val newFilters = if (selectedFilters.isNotEmpty()) {
oldFilters.without(VcsLogBranchLikeFilter::class.java).with(VcsLogFilterObject.fromBranches(selectedFilters))
} else {
oldFilters.without(VcsLogBranchLikeFilter::class.java)
}
ui.filterUi.filters = newFilters
}
internal fun navigateToSelectedBranch(focus: Boolean) {
val selectedReference = filteringTree.getSelectedBranchFilters().singleOrNull() ?: return
logUi.jumpToBranch(selectedReference, false, focus)
}
internal fun toggleGrouping(key: GroupingKey, state: Boolean) {
filteringTree.toggleGrouping(key, state)
}
internal fun isGroupingEnabled(key: GroupingKey) = filteringTree.isGroupingEnabled(key)
internal fun getSelectedRepositories(branchInfo: BranchInfo): List<GitRepository> {
return filteringTree.getSelectedRepositories(branchInfo)
}
internal fun getSelectedRemotes(): Set<RemoteInfo> {
return filteringTree.getSelectedRemotes()
}
internal fun getRootsToFilter(): Set<VirtualFile> {
val roots = logUi.logData.roots.toSet()
if (roots.size == 1) return roots
return VcsLogUtil.getAllVisibleRoots(roots, logUi.filterUi.filters)
}
private val BRANCHES_UI_FOCUS_TRAVERSAL_POLICY = object : ComponentsListFocusTraversalPolicy() {
override fun getOrderedComponents(): List<Component> = listOf(filteringTree.component, logUi.table,
logUi.changesBrowser.preferredFocusedComponent,
logUi.filterUi.textFilterComponent.textField)
}
private val showBranches get() = logUi.properties.get(SHOW_GIT_BRANCHES_LOG_PROPERTY)
init {
initMainUi()
installLogUi()
toggleBranchesPanelVisibility()
}
@RequiresEdt
private fun installLogUi() {
uiController.registerDataPackListener(logUi.logData)
uiController.registerLogUiPropertiesListener(logUi.properties)
uiController.registerLogUiFilterListener(logUi.filterUi)
branchesSearchFieldWrapper.setVerticalSizeReferent(logUi.toolbar)
branchViewSplitter.secondComponent = logUi.mainLogComponent
mainPanel.add(branchesTreeWithLogPanel)
filteringTree.component.addTreeSelectionListener(treeSelectionListener)
}
@RequiresEdt
private fun disposeBranchesUi() {
branchViewSplitter.secondComponent.removeAll()
uiController.removeDataPackListener(logUi.logData)
uiController.removeLogUiPropertiesListener(logUi.properties)
filteringTree.component.removeTreeSelectionListener(treeSelectionListener)
}
private fun initMainUi() {
val diffAction = ShowBranchDiffAction()
diffAction.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("Diff.ShowDiff"), branchesTreeWithLogPanel)
val deleteAction = DeleteBranchAction()
val shortcuts = KeymapUtil.getActiveKeymapShortcuts("SafeDelete").shortcuts + KeymapUtil.getActiveKeymapShortcuts(
"EditorDeleteToLineStart").shortcuts
deleteAction.registerCustomShortcutSet(CustomShortcutSet(*shortcuts), branchesTreeWithLogPanel)
createFocusFilterFieldAction(branchesSearchFieldWrapper)
installPasteAction(filteringTree)
val toggleFavoriteAction = ToggleFavoriteAction()
val fetchAction = FetchAction(this)
val showMyBranchesAction = ShowMyBranchesAction(uiController)
val newBranchAction = ActionManager.getInstance().getAction("Git.New.Branch.In.Log")
val updateSelectedAction = UpdateSelectedBranchAction()
val defaultTreeExpander = DefaultTreeExpander(filteringTree.component)
val commonActionsManager = CommonActionsManager.getInstance()
val expandAllAction = commonActionsManager.createExpandAllHeaderAction(defaultTreeExpander, branchesTreePanel)
val collapseAllAction = commonActionsManager.createCollapseAllHeaderAction(defaultTreeExpander, branchesTreePanel)
val actionManager = ActionManager.getInstance()
val hideBranchesAction = actionManager.getAction("Git.Log.Hide.Branches")
val settings = actionManager.getAction("Git.Log.Branches.Settings")
val group = DefaultActionGroup()
group.add(hideBranchesAction)
group.add(Separator())
group.add(newBranchAction)
group.add(updateSelectedAction)
group.add(deleteAction)
group.add(diffAction)
group.add(showMyBranchesAction)
group.add(fetchAction)
group.add(toggleFavoriteAction)
group.add(actionManager.getAction("Git.Log.Branches.Navigate.Log.To.Selected.Branch"))
group.add(Separator())
group.add(settings)
group.add(actionManager.getAction("Git.Log.Branches.Grouping.Settings"))
group.add(expandAllAction)
group.add(collapseAllAction)
val toolbar = actionManager.createActionToolbar("Git.Log.Branches", group, false)
toolbar.setTargetComponent(branchesTreePanel)
val branchesButton = ExpandStripeButton(messagePointer("action.Git.Log.Show.Branches.text"), AllIcons.Actions.ArrowExpand)
.apply {
border = createBorder(JBColor.border(), SideBorder.RIGHT)
addActionListener {
if (logUi.properties.exists(SHOW_GIT_BRANCHES_LOG_PROPERTY)) {
logUi.properties.set(SHOW_GIT_BRANCHES_LOG_PROPERTY, true)
}
}
}
branchesSearchFieldPanel.withBackground(UIUtil.getListBackground()).withBorder(createBorder(JBColor.border(), SideBorder.BOTTOM))
branchesSearchFieldPanel.addToCenter(branchesSearchFieldWrapper)
branchesTreePanel.addToTop(branchesSearchFieldPanel).addToCenter(branchesProgressStripe)
branchesPanelExpandableController = ExpandablePanelController(toolbar.component, branchesButton, branchesTreePanel)
branchViewSplitter.firstComponent = branchesTreePanel
branchesTreeWithLogPanel.addToLeft(branchesPanelExpandableController.expandControlPanel).addToCenter(branchViewSplitter)
mainPanel.isFocusCycleRoot = true
mainPanel.focusTraversalPolicy = BRANCHES_UI_FOCUS_TRAVERSAL_POLICY
}
fun toggleBranchesPanelVisibility() {
branchesPanelExpandableController.toggleExpand(showBranches)
updateBranchesTree(true)
}
private fun createFocusFilterFieldAction(searchField: Component) {
DumbAwareAction.create { e ->
val project = e.getRequiredData(CommonDataKeys.PROJECT)
if (IdeFocusManager.getInstance(project).getFocusedDescendantFor(filteringTree.component) != null) {
IdeFocusManager.getInstance(project).requestFocus(searchField, true)
}
else {
IdeFocusManager.getInstance(project).requestFocus(filteringTree.component, true)
}
}.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("Find"), branchesTreePanel)
}
private fun installPasteAction(tree: FilteringBranchesTree) {
tree.component.actionMap.put(TransferHandler.getPasteAction().getValue(Action.NAME), object: AbstractAction () {
override fun actionPerformed(e: ActionEvent?) {
val speedSearch = tree.searchModel.speedSearch as? SpeedSearch ?: return
val pasteContent =
CopyPasteManager.getInstance().getContents<String>(DataFlavor.stringFlavor)
// the same filtering logic as in javax.swing.text.PlainDocument.insertString (e.g. DnD to search field)
?.let { StringUtil.convertLineSeparators(it, " ") }
speedSearch.type(pasteContent)
speedSearch.update()
}
})
}
inner class BranchesTreePanel : BorderLayoutPanel(), DataProvider {
override fun getData(dataId: String): Any? {
return when {
GIT_BRANCHES.`is`(dataId) -> filteringTree.getSelectedBranches()
GIT_BRANCH_FILTERS.`is`(dataId) -> filteringTree.getSelectedBranchFilters()
BRANCHES_UI_CONTROLLER.`is`(dataId) -> uiController
VcsLogInternalDataKeys.LOG_UI_PROPERTIES.`is`(dataId) -> logUi.properties
else -> null
}
}
}
fun getMainComponent(): JComponent {
return mainPanel
}
fun updateBranchesTree(initial: Boolean) {
if (showBranches) {
filteringTree.update(initial)
}
}
fun refreshTree() {
filteringTree.refreshTree()
}
fun refreshTreeModel() {
filteringTree.refreshNodeDescriptorsModel()
}
fun startLoadingBranches() {
filteringTree.component.emptyText.text = message("action.Git.Loading.Branches.progress")
branchesTreePanel.isEnabled = false
branchesProgressStripe.startLoading()
}
fun stopLoadingBranches() {
filteringTree.component.emptyText.text = getDefaultEmptyText()
branchesTreePanel.isEnabled = true
branchesProgressStripe.stopLoading()
}
override fun dispose() {
disposeBranchesUi()
}
}
internal class BranchesVcsLogUiFactory(logManager: VcsLogManager, logId: String, filters: VcsLogFilterCollection? = null)
: BaseVcsLogUiFactory<BranchesVcsLogUi>(logId, filters, logManager.uiProperties, logManager.colorManager) {
override fun createVcsLogUiImpl(logId: String,
logData: VcsLogData,
properties: MainVcsLogUiProperties,
colorManager: VcsLogColorManager,
refresher: VisiblePackRefresherImpl,
filters: VcsLogFilterCollection?) =
BranchesVcsLogUi(logId, logData, colorManager, properties, refresher, filters)
}
internal class BranchesVcsLogUi(id: String, logData: VcsLogData, colorManager: VcsLogColorManager,
uiProperties: MainVcsLogUiProperties, refresher: VisiblePackRefresher,
initialFilters: VcsLogFilterCollection?) :
VcsLogUiImpl(id, logData, colorManager, uiProperties, refresher, initialFilters) {
private val branchesUi =
BranchesDashboardUi(logData.project, this)
.also { branchesUi -> Disposer.register(this, branchesUi) }
internal val mainLogComponent: JComponent
get() = mainFrame
internal val changesBrowser: ChangesBrowserBase
get() = mainFrame.changesBrowser
override fun createMainFrame(logData: VcsLogData, uiProperties: MainVcsLogUiProperties,
filterUi: VcsLogFilterUiEx, isEditorDiffPreview: Boolean) =
MainFrame(logData, this, uiProperties, filterUi, isEditorDiffPreview, this)
.apply {
isFocusCycleRoot = false
focusTraversalPolicy = null //new focus traversal policy will be configured include branches tree
}
override fun getMainComponent() = branchesUi.getMainComponent()
}
@ApiStatus.Internal
val SHOW_GIT_BRANCHES_LOG_PROPERTY =
object : VcsLogProjectTabsProperties.CustomBooleanTabProperty("Show.Git.Branches") {
override fun defaultValue(logId: String) = logId == MAIN_LOG_ID
}
@ApiStatus.Internal
val CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY =
object : VcsLogApplicationSettings.CustomBooleanProperty("Change.Log.Filter.on.Branch.Selection") {
override fun defaultValue() = false
}
@ApiStatus.Internal
val NAVIGATE_LOG_TO_BRANCH_ON_BRANCH_SELECTION_PROPERTY =
object : VcsLogApplicationSettings.CustomBooleanProperty("Navigate.Log.To.Branch.on.Branch.Selection") {
override fun defaultValue() = false
}
private class BranchViewSplitter(first: JComponent? = null, second: JComponent? = null)
: OnePixelSplitter(false, "vcs.branch.view.splitter.proportion", 0.3f) {
init {
firstComponent = first
secondComponent = second
}
}
| plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesDashboardUi.kt | 2901739840 |
// FIX: Replace with 'require()' call
// WITH_STDLIB
fun test(b: Boolean) {
<caret>if (b) {
throw IllegalArgumentException("test")
}
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceGuardClauseWithFunctionCall/require/basic.kt | 2693153828 |
package ch.abertschi.adfree
import android.app.Notification
import android.service.notification.StatusBarNotification
import ch.abertschi.adfree.model.PreferencesFactory
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info
import org.jetbrains.anko.warn
import java.lang.Exception
class GoogleCastManager(val prefs: PreferencesFactory) : AnkoLogger {
companion object {
private val ID = "com.google.android.gms|g:com.google.android.gms.cast.rcn.NOTIFICATIONS"
}
private var enabled: Boolean = false
private var action: Notification.Action? = null
init {
enabled = prefs.isGoogleCastEnabled()
}
fun setEnabled(e: Boolean) {
enabled = e
prefs.setGoogleCastEnabled(e)
}
fun isEnabled(): Boolean {
return enabled
}
// val act = sbn.notification.actions.get(1)
// info { act.title }
// act?.run {
// if (act.title.contains("Unmute")) {
// act.actionIntent.send()
// info { "send intent" }
// }
// }
// recordNotification(sbn)
// info { "debug this" }
fun updateNotification(sbn: StatusBarNotification) {
if (sbn.groupKey.contains(ID)) {
info { sbn.groupKey }
if (sbn.notification?.actions?.size == 4) {
val act = sbn.notification.actions[1]
info { "updating action for chromecast manager"}
info { act.title }
info { act }
action = act
}
}
}
fun muteAudio() {
if (!enabled) return
try {
info { "muting google cast audio with action $action" }
action?.run { action?.actionIntent?.send() }
} catch (e: Exception) {
warn { "muting failed" }
warn { e }
}
}
fun unmuteAudio() {
if (!enabled) return
try {
info { "unmuting google cast audio with action $action" }
action?.run { action?.actionIntent?.send() }
} catch (e: Exception) {
warn { "unmuting failed" }
warn { e }
}
}
} | app/src/main/java/ch/abertschi/adfree/GoogleCastManager.kt | 65741903 |
package lt.markmerkk.ui_2.views.calendar_edit
/**
* Defines that can change [QuickEditAction]
*/
interface QuickEditChangableAction {
fun changeActiveAction(quickEditAction: QuickEditAction)
} | app/src/main/java/lt/markmerkk/ui_2/views/calendar_edit/QuickEditChangableAction.kt | 2834218997 |
/*
* 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.utils.io
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
import kotlin.test.*
private const val TEXT = "test\u00f0."
private val BYTES = byteArrayOf(0x74, 0x65, 0x73, 0x74, 0xf0.toByte(), 0x2e)
class ISOTest {
@Ignore
@Test
fun testEncode() {
val bytes = Charsets.ISO_8859_1.newEncoder().encode(TEXT).readBytes()
assertTrue {
bytes.contentEquals(BYTES)
}
}
@Ignore
@Test
fun testEncodeUnmappable() {
assertFailsWith<MalformedInputException> {
Charsets.ISO_8859_1.newEncoder().encode("\u0422")
}
}
@Ignore
@Test
fun testDecode() {
val pkt = ByteReadPacket(BYTES)
val result = Charsets.ISO_8859_1.newDecoder().decode(pkt)
assertEquals(TEXT, result)
}
}
| ktor-io/js/test/io/ktor/utils/io/ISOTest.kt | 1103498810 |
package eu.kanade.tachiyomi.data.notification
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.core.content.ContextCompat
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.backup.BackupRestoreService
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.data.download.DownloadService
import eu.kanade.tachiyomi.data.library.LibraryUpdateService
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.ui.main.MainActivity
import eu.kanade.tachiyomi.ui.manga.MangaController
import eu.kanade.tachiyomi.ui.reader.ReaderActivity
import eu.kanade.tachiyomi.util.lang.launchIO
import eu.kanade.tachiyomi.util.storage.DiskUtil
import eu.kanade.tachiyomi.util.storage.getUriCompat
import eu.kanade.tachiyomi.util.system.notificationManager
import eu.kanade.tachiyomi.util.system.toShareIntent
import eu.kanade.tachiyomi.util.system.toast
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import uy.kohesive.injekt.injectLazy
import java.io.File
import eu.kanade.tachiyomi.BuildConfig.APPLICATION_ID as ID
/**
* Global [BroadcastReceiver] that runs on UI thread
* Pending Broadcasts should be made from here.
* NOTE: Use local broadcasts if possible.
*/
class NotificationReceiver : BroadcastReceiver() {
private val downloadManager: DownloadManager by injectLazy()
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
// Dismiss notification
ACTION_DISMISS_NOTIFICATION -> dismissNotification(context, intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1))
// Resume the download service
ACTION_RESUME_DOWNLOADS -> DownloadService.start(context)
// Pause the download service
ACTION_PAUSE_DOWNLOADS -> {
DownloadService.stop(context)
downloadManager.pauseDownloads()
}
// Clear the download queue
ACTION_CLEAR_DOWNLOADS -> downloadManager.clearQueue(true)
// Launch share activity and dismiss notification
ACTION_SHARE_IMAGE ->
shareImage(
context,
intent.getStringExtra(EXTRA_FILE_LOCATION)!!,
intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)
)
// Delete image from path and dismiss notification
ACTION_DELETE_IMAGE ->
deleteImage(
context,
intent.getStringExtra(EXTRA_FILE_LOCATION)!!,
intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)
)
// Share backup file
ACTION_SHARE_BACKUP ->
shareFile(
context,
intent.getParcelableExtra(EXTRA_URI)!!,
"application/x-protobuf+gzip",
intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)
)
ACTION_CANCEL_RESTORE -> cancelRestore(
context,
intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)
)
// Cancel library update and dismiss notification
ACTION_CANCEL_LIBRARY_UPDATE -> cancelLibraryUpdate(context, Notifications.ID_LIBRARY_PROGRESS)
// Open reader activity
ACTION_OPEN_CHAPTER -> {
openChapter(
context,
intent.getLongExtra(EXTRA_MANGA_ID, -1),
intent.getLongExtra(EXTRA_CHAPTER_ID, -1)
)
}
// Mark updated manga chapters as read
ACTION_MARK_AS_READ -> {
val notificationId = intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)
if (notificationId > -1) {
dismissNotification(context, notificationId, intent.getIntExtra(EXTRA_GROUP_ID, 0))
}
val urls = intent.getStringArrayExtra(EXTRA_CHAPTER_URL) ?: return
val mangaId = intent.getLongExtra(EXTRA_MANGA_ID, -1)
if (mangaId > -1) {
markAsRead(urls, mangaId)
}
}
// Download manga chapters
ACTION_DOWNLOAD_CHAPTER -> {
val notificationId = intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)
if (notificationId > -1) {
dismissNotification(context, notificationId, intent.getIntExtra(EXTRA_GROUP_ID, 0))
}
val urls = intent.getStringArrayExtra(EXTRA_CHAPTER_URL) ?: return
val mangaId = intent.getLongExtra(EXTRA_MANGA_ID, -1)
if (mangaId > -1) {
downloadChapters(urls, mangaId)
}
}
// Share crash dump file
ACTION_SHARE_CRASH_LOG ->
shareFile(
context,
intent.getParcelableExtra(EXTRA_URI)!!,
"text/plain",
intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)
)
}
}
/**
* Dismiss the notification
*
* @param notificationId the id of the notification
*/
private fun dismissNotification(context: Context, notificationId: Int) {
context.notificationManager.cancel(notificationId)
}
/**
* Called to start share intent to share image
*
* @param context context of application
* @param path path of file
* @param notificationId id of notification
*/
private fun shareImage(context: Context, path: String, notificationId: Int) {
dismissNotification(context, notificationId)
context.startActivity(File(path).getUriCompat(context).toShareIntent(context))
}
/**
* Called to start share intent to share backup file
*
* @param context context of application
* @param path path of file
* @param notificationId id of notification
*/
private fun shareFile(context: Context, uri: Uri, fileMimeType: String, notificationId: Int) {
dismissNotification(context, notificationId)
context.startActivity(uri.toShareIntent(context, fileMimeType))
}
/**
* Starts reader activity
*
* @param context context of application
* @param mangaId id of manga
* @param chapterId id of chapter
*/
private fun openChapter(context: Context, mangaId: Long, chapterId: Long) {
val db = DatabaseHelper(context)
val manga = db.getManga(mangaId).executeAsBlocking()
val chapter = db.getChapter(chapterId).executeAsBlocking()
if (manga != null && chapter != null) {
val intent = ReaderActivity.newIntent(context, manga, chapter).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
}
context.startActivity(intent)
} else {
context.toast(context.getString(R.string.chapter_error))
}
}
/**
* Called to delete image
*
* @param path path of file
* @param notificationId id of notification
*/
private fun deleteImage(context: Context, path: String, notificationId: Int) {
// Dismiss notification
dismissNotification(context, notificationId)
// Delete file
val file = File(path)
file.delete()
DiskUtil.scanMedia(context, file)
}
/**
* Method called when user wants to stop a backup restore job.
*
* @param context context of application
* @param notificationId id of notification
*/
private fun cancelRestore(context: Context, notificationId: Int) {
BackupRestoreService.stop(context)
ContextCompat.getMainExecutor(context).execute { dismissNotification(context, notificationId) }
}
/**
* Method called when user wants to stop a library update
*
* @param context context of application
* @param notificationId id of notification
*/
private fun cancelLibraryUpdate(context: Context, notificationId: Int) {
LibraryUpdateService.stop(context)
ContextCompat.getMainExecutor(context).execute { dismissNotification(context, notificationId) }
}
/**
* Method called when user wants to mark manga chapters as read
*
* @param chapterUrls URLs of chapter to mark as read
* @param mangaId id of manga
*/
private fun markAsRead(chapterUrls: Array<String>, mangaId: Long) {
val db: DatabaseHelper = Injekt.get()
val preferences: PreferencesHelper = Injekt.get()
val sourceManager: SourceManager = Injekt.get()
launchIO {
chapterUrls.mapNotNull { db.getChapter(it, mangaId).executeAsBlocking() }
.forEach {
it.read = true
db.updateChapterProgress(it).executeAsBlocking()
if (preferences.removeAfterMarkedAsRead()) {
val manga = db.getManga(mangaId).executeAsBlocking()
if (manga != null) {
val source = sourceManager.get(manga.source)
if (source != null) {
downloadManager.deleteChapters(listOf(it), manga, source)
}
}
}
}
}
}
/**
* Method called when user wants to download chapters
*
* @param chapterUrls URLs of chapter to download
* @param mangaId id of manga
*/
private fun downloadChapters(chapterUrls: Array<String>, mangaId: Long) {
val db: DatabaseHelper = Injekt.get()
launchIO {
val chapters = chapterUrls.mapNotNull { db.getChapter(it, mangaId).executeAsBlocking() }
val manga = db.getManga(mangaId).executeAsBlocking()
if (chapters.isNotEmpty() && manga != null) {
downloadManager.downloadChapters(manga, chapters)
}
}
}
companion object {
private const val NAME = "NotificationReceiver"
private const val ACTION_SHARE_IMAGE = "$ID.$NAME.SHARE_IMAGE"
private const val ACTION_DELETE_IMAGE = "$ID.$NAME.DELETE_IMAGE"
private const val ACTION_SHARE_BACKUP = "$ID.$NAME.SEND_BACKUP"
private const val ACTION_SHARE_CRASH_LOG = "$ID.$NAME.SEND_CRASH_LOG"
private const val ACTION_CANCEL_RESTORE = "$ID.$NAME.CANCEL_RESTORE"
private const val ACTION_CANCEL_LIBRARY_UPDATE = "$ID.$NAME.CANCEL_LIBRARY_UPDATE"
private const val ACTION_MARK_AS_READ = "$ID.$NAME.MARK_AS_READ"
private const val ACTION_OPEN_CHAPTER = "$ID.$NAME.ACTION_OPEN_CHAPTER"
private const val ACTION_DOWNLOAD_CHAPTER = "$ID.$NAME.ACTION_DOWNLOAD_CHAPTER"
private const val ACTION_RESUME_DOWNLOADS = "$ID.$NAME.ACTION_RESUME_DOWNLOADS"
private const val ACTION_PAUSE_DOWNLOADS = "$ID.$NAME.ACTION_PAUSE_DOWNLOADS"
private const val ACTION_CLEAR_DOWNLOADS = "$ID.$NAME.ACTION_CLEAR_DOWNLOADS"
private const val ACTION_DISMISS_NOTIFICATION = "$ID.$NAME.ACTION_DISMISS_NOTIFICATION"
private const val EXTRA_FILE_LOCATION = "$ID.$NAME.FILE_LOCATION"
private const val EXTRA_URI = "$ID.$NAME.URI"
private const val EXTRA_NOTIFICATION_ID = "$ID.$NAME.NOTIFICATION_ID"
private const val EXTRA_GROUP_ID = "$ID.$NAME.EXTRA_GROUP_ID"
private const val EXTRA_MANGA_ID = "$ID.$NAME.EXTRA_MANGA_ID"
private const val EXTRA_CHAPTER_ID = "$ID.$NAME.EXTRA_CHAPTER_ID"
private const val EXTRA_CHAPTER_URL = "$ID.$NAME.EXTRA_CHAPTER_URL"
/**
* Returns a [PendingIntent] that resumes the download of a chapter
*
* @param context context of application
* @return [PendingIntent]
*/
internal fun resumeDownloadsPendingBroadcast(context: Context): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_RESUME_DOWNLOADS
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that pauses the download queue
*
* @param context context of application
* @return [PendingIntent]
*/
internal fun pauseDownloadsPendingBroadcast(context: Context): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_PAUSE_DOWNLOADS
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns a [PendingIntent] that clears the download queue
*
* @param context context of application
* @return [PendingIntent]
*/
internal fun clearDownloadsPendingBroadcast(context: Context): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_CLEAR_DOWNLOADS
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that starts a service which dismissed the notification
*
* @param context context of application
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun dismissNotificationPendingBroadcast(context: Context, notificationId: Int): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_DISMISS_NOTIFICATION
putExtra(EXTRA_NOTIFICATION_ID, notificationId)
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that starts a service which dismissed the notification
*
* @param context context of application
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun dismissNotification(context: Context, notificationId: Int, groupId: Int? = null) {
/*
Group notifications always have at least 2 notifications:
- Group summary notification
- Single manga notification
If the single notification is dismissed by the system, ie by a user swipe or tapping on the notification,
it will auto dismiss the group notification if there's no other single updates.
When programmatically dismissing this notification, the group notification is not automatically dismissed.
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val groupKey = context.notificationManager.activeNotifications.find {
it.id == notificationId
}?.groupKey
if (groupId != null && groupId != 0 && groupKey != null && groupKey.isNotEmpty()) {
val notifications = context.notificationManager.activeNotifications.filter {
it.groupKey == groupKey
}
if (notifications.size == 2) {
context.notificationManager.cancel(groupId)
return
}
}
}
context.notificationManager.cancel(notificationId)
}
/**
* Returns [PendingIntent] that starts a service which cancels the notification and starts a share activity
*
* @param context context of application
* @param path location path of file
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun shareImagePendingBroadcast(context: Context, path: String, notificationId: Int): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_SHARE_IMAGE
putExtra(EXTRA_FILE_LOCATION, path)
putExtra(EXTRA_NOTIFICATION_ID, notificationId)
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that starts a service which removes an image from disk
*
* @param context context of application
* @param path location path of file
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun deleteImagePendingBroadcast(context: Context, path: String, notificationId: Int): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_DELETE_IMAGE
putExtra(EXTRA_FILE_LOCATION, path)
putExtra(EXTRA_NOTIFICATION_ID, notificationId)
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that starts a reader activity containing chapter.
*
* @param context context of application
* @param manga manga of chapter
* @param chapter chapter that needs to be opened
*/
internal fun openChapterPendingActivity(context: Context, manga: Manga, chapter: Chapter): PendingIntent {
val newIntent = ReaderActivity.newIntent(context, manga, chapter)
return PendingIntent.getActivity(context, manga.id.hashCode(), newIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that opens the manga info controller.
*
* @param context context of application
* @param manga manga of chapter
*/
internal fun openChapterPendingActivity(context: Context, manga: Manga, groupId: Int): PendingIntent {
val newIntent =
Intent(context, MainActivity::class.java).setAction(MainActivity.SHORTCUT_MANGA)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtra(MangaController.MANGA_EXTRA, manga.id)
.putExtra("notificationId", manga.id.hashCode())
.putExtra("groupId", groupId)
return PendingIntent.getActivity(context, manga.id.hashCode(), newIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that marks a chapter as read and deletes it if preferred
*
* @param context context of application
* @param manga manga of chapter
*/
internal fun markAsReadPendingBroadcast(
context: Context,
manga: Manga,
chapters: Array<Chapter>,
groupId: Int
): PendingIntent {
val newIntent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_MARK_AS_READ
putExtra(EXTRA_CHAPTER_URL, chapters.map { it.url }.toTypedArray())
putExtra(EXTRA_MANGA_ID, manga.id)
putExtra(EXTRA_NOTIFICATION_ID, manga.id.hashCode())
putExtra(EXTRA_GROUP_ID, groupId)
}
return PendingIntent.getBroadcast(context, manga.id.hashCode(), newIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that downloads chapters
*
* @param context context of application
* @param manga manga of chapter
*/
internal fun downloadChaptersPendingBroadcast(
context: Context,
manga: Manga,
chapters: Array<Chapter>,
groupId: Int
): PendingIntent {
val newIntent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_DOWNLOAD_CHAPTER
putExtra(EXTRA_CHAPTER_URL, chapters.map { it.url }.toTypedArray())
putExtra(EXTRA_MANGA_ID, manga.id)
putExtra(EXTRA_NOTIFICATION_ID, manga.id.hashCode())
putExtra(EXTRA_GROUP_ID, groupId)
}
return PendingIntent.getBroadcast(context, manga.id.hashCode(), newIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that starts a service which stops the library update
*
* @param context context of application
* @return [PendingIntent]
*/
internal fun cancelLibraryUpdatePendingBroadcast(context: Context): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_CANCEL_LIBRARY_UPDATE
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that opens the extensions controller.
*
* @param context context of application
* @return [PendingIntent]
*/
internal fun openExtensionsPendingActivity(context: Context): PendingIntent {
val intent = Intent(context, MainActivity::class.java).apply {
action = MainActivity.SHORTCUT_EXTENSIONS
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
}
return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that starts a share activity for a backup file.
*
* @param context context of application
* @param uri uri of backup file
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun shareBackupPendingBroadcast(context: Context, uri: Uri, notificationId: Int): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_SHARE_BACKUP
putExtra(EXTRA_URI, uri)
putExtra(EXTRA_NOTIFICATION_ID, notificationId)
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that opens the error log file in an external viewer
*
* @param context context of application
* @param uri uri of error log file
* @return [PendingIntent]
*/
internal fun openErrorLogPendingActivity(context: Context, uri: Uri): PendingIntent {
val intent = Intent().apply {
action = Intent.ACTION_VIEW
setDataAndType(uri, "text/plain")
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION
}
return PendingIntent.getActivity(context, 0, intent, 0)
}
/**
* Returns [PendingIntent] that starts a share activity for a crash log dump file.
*
* @param context context of application
* @param uri uri of file
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun shareCrashLogPendingBroadcast(context: Context, uri: Uri, notificationId: Int): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_SHARE_CRASH_LOG
putExtra(EXTRA_URI, uri)
putExtra(EXTRA_NOTIFICATION_ID, notificationId)
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
/**
* Returns [PendingIntent] that cancels a backup restore job.
*
* @param context context of application
* @param notificationId id of notification
* @return [PendingIntent]
*/
internal fun cancelRestorePendingBroadcast(context: Context, notificationId: Int): PendingIntent {
val intent = Intent(context, NotificationReceiver::class.java).apply {
action = ACTION_CANCEL_RESTORE
putExtra(EXTRA_NOTIFICATION_ID, notificationId)
}
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
}
}
| app/src/main/java/eu/kanade/tachiyomi/data/notification/NotificationReceiver.kt | 1184200635 |
package xyz.javecs.tools.text2expr.templates
import org.yaml.snakeyaml.Yaml
import xyz.javecs.tools.text2expr.utils.read
private val printValue = "<if(value)><value><endif>"
internal data class Templates(var templates: List<RuleTemplate> = ArrayList<RuleTemplate>())
internal data class RuleTemplate(var rule: String = "", var template: String = "")
internal class TemplateLoader(path: String = "rule-template.yml", val defaultTemplate: String = printValue) {
private val config = Yaml().loadAs(read(path), Templates::class.java)
fun templateOf(rule: String): String {
val item = config.templates.find { it.rule == rule }
return if (item == null) defaultTemplate else read(item.template)
}
}
| src/main/kotlin/xyz/javecs/tools/text2expr/templates/TemplateLoader.kt | 2907850443 |
package com.neva.javarel.resource.api
import com.google.common.collect.ImmutableList
import org.apache.commons.io.FilenameUtils
class ResourceDescriptor(val uri: String) {
val protocol: String
val path: String
val baseName: String
val name: String
val extension: String
val parts: List<String>
init {
var parts = uri.split(ResourceMapper.PROTOCOL_SEPARATOR)
if (parts.size != 2) {
throw IllegalArgumentException("Resource descriptor URI '$uri' should contain " + "protocol separator '${ResourceMapper.PROTOCOL_SEPARATOR}'")
}
this.protocol = parts[0]
this.path = parts[1]
this.parts = ImmutableList.copyOf(path.split(ResourceMapper.PATH_SEPARATOR))
this.baseName = FilenameUtils.getBaseName(parts[1])
this.name = FilenameUtils.getName(parts[1])
this.extension = FilenameUtils.getExtension(parts[1])
}
override fun toString(): String {
return uri
}
}
| resource/src/main/kotlin/com/neva/javarel/resource/api/ResourceDescriptor.kt | 587565622 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package vulkan.templates
import org.lwjgl.generator.*
import vulkan.*
val EXT_texture_compression_astc_hdr = "EXTTextureCompressionAstcHdr".nativeClassVK("EXT_texture_compression_astc_hdr", type = "device", postfix = "EXT") {
documentation =
"""
This extension adds support for textures compressed using the Adaptive Scalable Texture Compression (ASTC) High Dynamic Range (HDR) profile.
When this extension is enabled, the HDR profile is supported for all ASTC formats listed in <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#appendix-compressedtex-astc">ASTC Compressed Image Formats</a>.
<h5>Promotion to Vulkan 1.3</h5>
This extension has been partially promoted. Functionality in this extension is included in core Vulkan 1.3, with the EXT suffix omitted. However, the feature is made optional in Vulkan 1.3. The original type, enum and command names are still available as aliases of the core functionality.
<h5>VK_EXT_texture_compression_astc_hdr</h5>
<dl>
<dt><b>Name String</b></dt>
<dd>{@code VK_EXT_texture_compression_astc_hdr}</dd>
<dt><b>Extension Type</b></dt>
<dd>Device extension</dd>
<dt><b>Registered Extension Number</b></dt>
<dd>67</dd>
<dt><b>Revision</b></dt>
<dd>1</dd>
<dt><b>Extension and Version Dependencies</b></dt>
<dd><ul>
<li>Requires support for Vulkan 1.0</li>
<li>Requires {@link KHRGetPhysicalDeviceProperties2 VK_KHR_get_physical_device_properties2} to be enabled for any device-level functionality</li>
</ul></dd>
<dt><b>Deprecation state</b></dt>
<dd><ul>
<li><em>Promoted</em> to <a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#versions-1.3-promotions">Vulkan 1.3</a></li>
</ul></dd>
<dt><b>Contact</b></dt>
<dd><ul>
<li>Jan-Harald Fredriksen <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_texture_compression_astc_hdr]%20@janharaldfredriksen-arm%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_EXT_texture_compression_astc_hdr%20extension*">janharaldfredriksen-arm</a></li>
</ul></dd>
</dl>
<h5>Other Extension Metadata</h5>
<dl>
<dt><b>Last Modified Date</b></dt>
<dd>2019-05-28</dd>
<dt><b>Interactions and External Dependencies</b></dt>
<dd><ul>
<li>Promoted to Vulkan 1.3 Core</li>
</ul></dd>
<dt><b>IP Status</b></dt>
<dd>No known issues.</dd>
<dt><b>Contributors</b></dt>
<dd><ul>
<li>Jan-Harald Fredriksen, Arm</li>
</ul></dd>
</dl>
"""
IntConstant(
"The extension specification version.",
"EXT_TEXTURE_COMPRESSION_ASTC_HDR_SPEC_VERSION".."1"
)
StringConstant(
"The extension name.",
"EXT_TEXTURE_COMPRESSION_ASTC_HDR_EXTENSION_NAME".."VK_EXT_texture_compression_astc_hdr"
)
EnumConstant(
"Extends {@code VkStructureType}.",
"STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXTURE_COMPRESSION_ASTC_HDR_FEATURES_EXT".."1000066000"
)
EnumConstant(
"Extends {@code VkFormat}.",
"FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT".."1000066000",
"FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT".."1000066001",
"FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT".."1000066002",
"FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT".."1000066003",
"FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT".."1000066004",
"FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT".."1000066005",
"FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT".."1000066006",
"FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT".."1000066007",
"FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT".."1000066008",
"FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT".."1000066009",
"FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT".."1000066010",
"FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT".."1000066011",
"FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT".."1000066012",
"FORMAT_ASTC_12x12_SFLOAT_BLOCK_EXT".."1000066013"
)
} | modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/EXT_texture_compression_astc_hdr.kt | 513783666 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package vulkan.templates
import org.lwjgl.generator.*
import vulkan.*
val EXT_filter_cubic = "EXTFilterCubic".nativeClassVK("EXT_filter_cubic", type = "device", postfix = "EXT") {
documentation =
"""
{@code VK_EXT_filter_cubic} extends {@code VK_IMG_filter_cubic}.
It documents cubic filtering of other image view types. It adds new structures that <b>can</b> be added to the {@code pNext} chain of ##VkPhysicalDeviceImageFormatInfo2 and ##VkImageFormatProperties2 that <b>can</b> be used to determine which image types and which image view types support cubic filtering.
<h5>VK_EXT_filter_cubic</h5>
<dl>
<dt><b>Name String</b></dt>
<dd>{@code VK_EXT_filter_cubic}</dd>
<dt><b>Extension Type</b></dt>
<dd>Device extension</dd>
<dt><b>Registered Extension Number</b></dt>
<dd>171</dd>
<dt><b>Revision</b></dt>
<dd>3</dd>
<dt><b>Extension and Version Dependencies</b></dt>
<dd><ul>
<li>Requires support for Vulkan 1.0</li>
</ul></dd>
<dt><b>Contact</b></dt>
<dd><ul>
<li>Bill Licea-Kane <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_filter_cubic]%20@wwlk%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_EXT_filter_cubic%20extension*">wwlk</a></li>
</ul></dd>
</dl>
<h5>Other Extension Metadata</h5>
<dl>
<dt><b>Last Modified Date</b></dt>
<dd>2019-12-13</dd>
<dt><b>Contributors</b></dt>
<dd><ul>
<li>Bill Licea-Kane, Qualcomm Technologies, Inc.</li>
<li>Andrew Garrard, Samsung</li>
<li>Daniel Koch, NVIDIA</li>
<li>Donald Scorgie, Imagination Technologies</li>
<li>Graeme Leese, Broadcom</li>
<li>Jan-Herald Fredericksen, ARM</li>
<li>Jeff Leger, Qualcomm Technologies, Inc.</li>
<li>Tobias Hector, AMD</li>
<li>Tom Olson, ARM</li>
<li>Stuart Smith, Imagination Technologies</li>
</ul></dd>
</dl>
"""
IntConstant(
"The extension specification version.",
"EXT_FILTER_CUBIC_SPEC_VERSION".."3"
)
StringConstant(
"The extension name.",
"EXT_FILTER_CUBIC_EXTENSION_NAME".."VK_EXT_filter_cubic"
)
EnumConstant(
"Extends {@code VkFilter}.",
"FILTER_CUBIC_EXT".."1000015000"
)
EnumConstant(
"Extends {@code VkFormatFeatureFlagBits}.",
"FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_EXT".enum(0x00002000)
)
EnumConstant(
"Extends {@code VkStructureType}.",
"STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_VIEW_IMAGE_FORMAT_INFO_EXT".."1000170000",
"STRUCTURE_TYPE_FILTER_CUBIC_IMAGE_VIEW_IMAGE_FORMAT_PROPERTIES_EXT".."1000170001"
)
} | modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/EXT_filter_cubic.kt | 403450060 |
package i_introduction._1_Java_To_Kotlin_Converter
import util.TODO
fun todoTask1(collection: Collection<Int>): Nothing = TODO(
"""
Task 1.
Rewrite JavaCode1.task1 in Kotlin.
In IntelliJ, you can just copy-paste the code and agree to automatically convert it to Kotlin,
but only for this task!
""",
references = { JavaCode1().task1(collection) })
fun task1(collection: Collection<Int>): String {
val sb = StringBuilder()
sb.append("{")
val iterator = collection.iterator()
while (iterator.hasNext()) {
val element = iterator.next()
sb.append(element)
if (iterator.hasNext()) {
sb.append(", ")
}
}
sb.append("}")
return sb.toString()
}
| src/i_introduction/_1_Java_To_Kotlin_Converter/JavaToKotlinConverter.kt | 2068839847 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.trackedentity.internal
import dagger.Reusable
import io.reactivex.Completable
import javax.inject.Inject
import org.hisp.dhis.android.core.arch.handlers.internal.IdentifiableDataHandlerParams
import org.hisp.dhis.android.core.organisationunit.internal.OrganisationUnitModuleDownloader
import org.hisp.dhis.android.core.relationship.internal.RelationshipItemRelatives
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstance
@Reusable
internal class TrackedEntityInstancePersistenceCallFactory @Inject constructor(
private val trackedEntityInstanceHandler: TrackedEntityInstanceHandler,
private val uidsHelper: TrackedEntityInstanceUidHelper,
private val organisationUnitDownloader: OrganisationUnitModuleDownloader
) {
fun persistTEIs(
trackedEntityInstances: List<TrackedEntityInstance>,
params: IdentifiableDataHandlerParams,
relatives: RelationshipItemRelatives
): Completable {
return persistTEIsInternal(trackedEntityInstances, params, relatives)
}
fun persistRelationships(trackedEntityInstances: List<TrackedEntityInstance>): Completable {
val params = IdentifiableDataHandlerParams(
hasAllAttributes = false,
overwrite = false,
asRelationship = true
)
return persistTEIsInternal(trackedEntityInstances, params, relatives = null)
}
private fun persistTEIsInternal(
trackedEntityInstances: List<TrackedEntityInstance>,
params: IdentifiableDataHandlerParams,
relatives: RelationshipItemRelatives?
): Completable {
return Completable.defer {
trackedEntityInstanceHandler.handleMany(
trackedEntityInstances, params, relatives
)
if (uidsHelper.hasMissingOrganisationUnitUids(trackedEntityInstances)) {
organisationUnitDownloader.refreshOrganisationUnits()
} else {
Completable.complete()
}
}
}
}
| core/src/main/java/org/hisp/dhis/android/core/trackedentity/internal/TrackedEntityInstancePersistenceCallFactory.kt | 1094344593 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.