content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.vanilla.packet.codec.play
import io.netty.handler.codec.CodecException
import io.netty.handler.codec.DecoderException
import org.lanternpowered.server.data.io.store.item.WritableBookItemTypeObjectSerializer
import org.lanternpowered.server.data.io.store.item.WrittenBookItemTypeObjectSerializer
import org.lanternpowered.server.network.buffer.ByteBuffer
import org.lanternpowered.server.network.packet.PacketDecoder
import org.lanternpowered.server.network.packet.CodecContext
import org.lanternpowered.server.network.vanilla.packet.type.play.ClientModifyBookPacket
import org.spongepowered.api.data.type.HandTypes
object ClientModifyBookDecoder : PacketDecoder<ClientModifyBookPacket> {
override fun decode(ctx: CodecContext, buf: ByteBuffer): ClientModifyBookPacket {
val rawItemStack = buf.readRawItemStack()
val sign = buf.readBoolean()
val handType = if (buf.readVarInt() == 0) HandTypes.MAIN_HAND.get() else HandTypes.OFF_HAND.get()
if (rawItemStack == null)
throw DecoderException("Modified book may not be null!")
val dataView = rawItemStack.dataView ?: throw DecoderException("Modified book data view (nbt tag) may not be null!")
val pages = dataView.getStringList(WritableBookItemTypeObjectSerializer.PAGES)
.orElseThrow { DecoderException("Edited book pages missing!") }
if (sign) {
val author = dataView.getString(WrittenBookItemTypeObjectSerializer.AUTHOR)
.orElseThrow { CodecException("Signed book author missing!") }
val title = dataView.getString(WrittenBookItemTypeObjectSerializer.TITLE)
.orElseThrow { CodecException("Signed book title missing!") }
return ClientModifyBookPacket.Sign(handType, pages, author, title)
}
return ClientModifyBookPacket.Edit(handType, pages)
}
}
| src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/ClientModifyBookDecoder.kt | 1561988176 |
// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers
import com.google.cloud.spanner.Value
import com.google.type.Date
import org.wfanet.measurement.gcloud.common.toCloudDate
import org.wfanet.measurement.gcloud.spanner.bufferUpdateMutation
import org.wfanet.measurement.gcloud.spanner.set
import org.wfanet.measurement.internal.kingdom.ExchangeStep
import org.wfanet.measurement.internal.kingdom.ExchangeWorkflow
internal fun SpannerWriter.TransactionScope.updateExchangeStepsToReady(
steps: List<ExchangeWorkflow.Step>,
recurringExchangeId: Long,
date: Date
) {
for (step in steps) {
transactionContext.bufferUpdateMutation("ExchangeSteps") {
set("RecurringExchangeId" to recurringExchangeId)
set("Date" to date.toCloudDate())
set("StepIndex" to step.stepIndex.toLong())
set("State" to ExchangeStep.State.READY)
set("UpdateTime" to Value.COMMIT_TIMESTAMP)
}
}
}
internal fun SpannerWriter.TransactionScope.updateExchangeStepState(
exchangeStep: ExchangeStep,
recurringExchangeId: Long,
state: ExchangeStep.State
) {
// TODO(yunyeng): Add logger and log exceptional cases like this.
if (exchangeStep.state == state) return
require(!exchangeStep.state.isTerminal) {
"ExchangeStep with StepIndex: ${exchangeStep.stepIndex} is in a terminal state."
}
transactionContext.bufferUpdateMutation("ExchangeSteps") {
set("RecurringExchangeId" to recurringExchangeId)
set("Date" to exchangeStep.date.toCloudDate())
set("StepIndex" to exchangeStep.stepIndex.toLong())
set("State" to state)
set("UpdateTime" to Value.COMMIT_TIMESTAMP)
}
}
internal val ExchangeStep.State.isTerminal: Boolean
get() =
when (this) {
ExchangeStep.State.BLOCKED,
ExchangeStep.State.READY,
ExchangeStep.State.READY_FOR_RETRY,
ExchangeStep.State.IN_PROGRESS -> false
ExchangeStep.State.SUCCEEDED,
ExchangeStep.State.FAILED,
ExchangeStep.State.UNRECOGNIZED,
ExchangeStep.State.STATE_UNSPECIFIED -> true
}
| src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/writers/UpdateExchangeStep.kt | 447134230 |
/*
* 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.
*
*/
@file:JvmName("ClassLoaderx")
package debop4k.core.utils
import java.security.AccessController
import java.security.PrivilegedAction
fun getClassLoader(clazz: Class<*>): ClassLoader {
if (System.getSecurityManager() == null) {
return clazz.classLoader
} else {
return AccessController.doPrivileged(PrivilegedAction { clazz.classLoader })
}
}
fun getDefaultClassLoader(): ClassLoader {
var cl = getContextClassLoader()
// TODO: Caller 를 참고해야 한다..
// if (cl == null) {
// val callerClass = Thread.currentThread().javaClass
// cl = callerClass.classLoader
// }
return cl
}
fun getContextClassLoader(): ClassLoader {
if (System.getSecurityManager() != null) {
return Thread.currentThread().contextClassLoader
} else {
return AccessController.doPrivileged(PrivilegedAction { Thread.currentThread().contextClassLoader })
}
}
fun getSystemClassLoader(): ClassLoader {
if (System.getSecurityManager() != null) {
return ClassLoader.getSystemClassLoader()
} else {
return AccessController.doPrivileged(PrivilegedAction { ClassLoader.getSystemClassLoader() })
}
} | debop4k-core/src/main/kotlin/debop4k/core/utils/ClassLoaderx.kt | 2364949022 |
package nl.hannahsten.texifyidea.psi
import com.intellij.openapi.util.TextRange
import com.intellij.psi.AbstractElementManipulator
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.util.PsiTreeUtil
import nl.hannahsten.texifyidea.LatexLanguage
import nl.hannahsten.texifyidea.psi.impl.LatexEnvironmentImpl
/**
* Enable editing environment content in a separate window (when using language injection).
*/
class LatexEnvironmentManipulator : AbstractElementManipulator<LatexEnvironmentImpl>() {
override fun handleContentChange(
element: LatexEnvironmentImpl,
range: TextRange,
newContent: String
): LatexEnvironmentImpl? {
val oldText = element.text
// For some reason the endoffset of the given range is incorrect: sometimes it excludes the last line, so we calculate it ourselves
val endOffset = oldText.indexOf("\\end{${element.environmentName}}") - 1 // -1 to exclude \n
val newText = oldText.substring(0, range.startOffset) + newContent + oldText.substring(endOffset)
val file = PsiFileFactory.getInstance(element.project)
.createFileFromText("temp.tex", LatexLanguage, newText)
val res =
PsiTreeUtil.findChildOfType(file, LatexEnvironmentImpl::class.java) ?: return null
element.replace(res)
return element
}
}
| src/nl/hannahsten/texifyidea/psi/LatexEnvironmentManipulator.kt | 3722991854 |
package voice.app.misc
import android.os.Build
import android.os.StrictMode
object StrictModeInit {
fun init() {
StrictMode.setThreadPolicy(threadPolicy())
StrictMode.setVmPolicy(vmPolicy())
}
private fun vmPolicy(): StrictMode.VmPolicy = StrictMode.VmPolicy.Builder()
.detectActivityLeaks()
.detectLeakedClosableObjects()
.detectLeakedRegistrationObjects()
.detectFileUriExposure()
.detectCleartextNetwork()
.detectContentUriWithoutPermission()
.detectUntaggedSockets()
.apply {
if (Build.VERSION.SDK_INT >= 29) {
detectCredentialProtectedWhileLocked()
}
if (Build.VERSION.SDK_INT >= 28) {
detectNonSdkApiUsage()
}
}
.penaltyLog()
.build()
private fun threadPolicy(): StrictMode.ThreadPolicy = StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyFlashScreen()
.build()
}
| app/src/main/kotlin/voice/app/misc/StrictModeInit.kt | 4221389705 |
package me.ykrank.s1next.data.api.model
import com.fasterxml.jackson.annotation.*
import com.google.common.base.Objects
import com.github.ykrank.androidtools.ui.adapter.StableIdModel
import com.github.ykrank.androidtools.ui.adapter.model.DiffSameItem
import paperparcel.PaperParcel
import paperparcel.PaperParcelable
import java.util.regex.Pattern
/**
* Created by ykrank on 2017/1/5.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@PaperParcel
class Note : PaperParcelable, DiffSameItem, StableIdModel {
@JsonProperty("author")
var author: String? = null
@JsonProperty("authorid")
var authorId: String? = null
@JsonProperty("dateline")
var dateline: Long = 0
@JsonProperty("id")
var id: String? = null
@JsonIgnore
private var isNew: Boolean = false
@JsonIgnore
var note: String? = null
//eg forum.php?mod=redirect&goto=findpost&ptid=1220112&pid=1
@JsonIgnore
var url: String? = null
@JsonIgnore
var content: String? = null
@JsonCreator
constructor(@JsonProperty("note") note: String) {
this.note = note
//eg <a href="home.php?mod=space&uid=1">someone</a> 回复了您的帖子 <a href="forum.php?mod=redirect&goto=findpost&ptid=1220112&pid=1" target="_blank">【Android】 s1Next-鹅版-v0.7.2(群522433035)</a> <a href="forum.php?mod=redirect&goto=findpost&pid=34692327&ptid=1220112" target="_blank" class="lit">查看</a>
var pattern = Pattern.compile("<a href=\"(forum\\.php\\?mod=redirect&goto=findpost.+?)\"")
var matcher = pattern.matcher(note)
if (matcher.find()) {
url = matcher.group(1)
}
pattern = Pattern.compile("target=\"_blank\">(.+)</a> ")
matcher = pattern.matcher(note)
if (matcher.find()) {
content = matcher.group(1)
}
}
fun isNew(): Boolean {
return isNew
}
fun setNew(aNew: Boolean) {
isNew = aNew
}
@JsonSetter("new")
fun setNew(aNew: Int) {
isNew = aNew > 0
}
override fun isSameItem(o: Any): Boolean {
if (this === o) return true
return if (o !is Note) false else Objects.equal(id, o.id)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Note
if (author != other.author) return false
if (authorId != other.authorId) return false
if (dateline != other.dateline) return false
if (id != other.id) return false
if (isNew != other.isNew) return false
if (note != other.note) return false
if (url != other.url) return false
if (content != other.content) return false
return true
}
override fun hashCode(): Int {
var result = author?.hashCode() ?: 0
result = 31 * result + (authorId?.hashCode() ?: 0)
result = 31 * result + dateline.hashCode()
result = 31 * result + (id?.hashCode() ?: 0)
result = 31 * result + isNew.hashCode()
result = 31 * result + (note?.hashCode() ?: 0)
result = 31 * result + (url?.hashCode() ?: 0)
result = 31 * result + (content?.hashCode() ?: 0)
return result
}
companion object {
@JvmField
val CREATOR = PaperParcelNote.CREATOR
}
}
| app/src/main/java/me/ykrank/s1next/data/api/model/Note.kt | 865166123 |
package com.cout970.statistics.gui
import com.cout970.statistics.Statistics
import com.cout970.statistics.data.ItemIdentifier
import com.cout970.statistics.network.ClientEventPacket
import com.cout970.statistics.network.GuiPacket
import com.cout970.statistics.tileentity.TileInventoryDetector
import net.minecraft.client.gui.Gui
import net.minecraft.client.gui.GuiTextField
import net.minecraft.client.renderer.GlStateManager
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.init.Blocks
import net.minecraft.item.EnumDyeColor
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.nbt.NBTTagList
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import net.minecraftforge.common.util.Constants
import org.lwjgl.input.Keyboard
import org.lwjgl.input.Mouse
import java.awt.Color
/**
* Created by cout970 on 06/08/2016.
*/
class GuiInventoryDetector(val cont: ContainerInventoryDetector) : GuiBase(cont) {
lateinit var text: GuiTextField
var offset = 0
var count = 0
var newLimit = -1
override fun initGui() {
super.initGui()
text = object : GuiTextField(0, fontRendererObj, guiLeft + 80 - 2, guiTop + 67 + 8, 90, 18) {
override fun setFocused(isFocusedIn: Boolean) {
super.setFocused(isFocusedIn)
if (!isFocusedIn) {
var amount = cont.tile!!.limit
try {
val i = Integer.parseInt(text)
if (i >= 0) {
amount = i
}
} catch (e: Exception) {
}
text = amount.toString()
cont.tile!!.limit = amount
newLimit = amount
Statistics.NETWORK.sendToServer(ClientEventPacket(cont.tile!!.world.provider.dimension, cont.tile!!.pos, 0, amount))
}
}
}
text.text = cont.tile!!.limit.toString()
}
override fun updateScreen() {
super.updateScreen()
text.updateCursorCounter()
}
override fun drawGuiContainerBackgroundLayer(partialTicks: Float, mouseX: Int, mouseY: Int) {
if (cont.tile!!.limit != newLimit) {
newLimit = cont.tile!!.limit
text.text = cont.tile!!.limit.toString()
}
val tile = cont.tile!!
val start = guiTop + 67
//background
Gui.drawRect(guiLeft, guiTop + 67, guiLeft + xSize, guiTop + 100, 0x7F4C4C4C.toInt())
//active/disable
val item = ItemStack(Blocks.STAINED_GLASS_PANE, 1, if (tile.active) 5 else 14)
drawStack(item, guiLeft + 9, start + 9)
//item
Gui.drawRect(guiLeft + 35, start + 8, guiLeft + 53, start + 26, 0x7FFFFFFF.toInt())
Gui.drawRect(guiLeft + 35 - 1, start + 8 - 1, guiLeft + 53 + 1, start + 26 + 1, 0x7F000000.toInt())
synchronized(tile) {
val selected = tile.itemCache
if (selected != null) {
drawStack(selected.stack.copy().apply { stackSize = 1 }, guiLeft + 9 + 18 + 9, start + 9)
}
}
//comparator
drawBox(guiLeft + 59, start + 11, 6 + 8, 8 + 4, 0x3FFFFFFF.toInt())
drawCenteredString(fontRendererObj, tile.operation.toString(), guiLeft + 65, start + 13, Color.WHITE.rgb)
//text
text.drawTextBox()
//items
val move = -20
Gui.drawRect(guiLeft, guiTop + 123 + move, guiLeft + xSize, guiTop + 125 + 54 + move, 0x4F4C4C4C.toInt())
synchronized(tile) {
var index = 0
val allItems = tile.items.keys.sortedBy { it.stack.item.registryName.toString() }
val dye = EnumDyeColor.byMetadata(0)
for (i in allItems) {
if (index / 9 < 3 + offset && index / 9 - offset >= 0) {
val x = index % 9 * 18 + 7
val y = (index / 9 - offset) * 18 + 125 + move
val stack = i.stack.copy().apply { stackSize = 1 }
if (tile.getItem(index) == tile.itemCache) {
if (stack.item != Item.getItemFromBlock(Blocks.STAINED_GLASS_PANE)) {
GlStateManager.pushMatrix()
GlStateManager.translate(0.0, 0.0, -20.0)
drawStack(ItemStack(Blocks.STAINED_GLASS_PANE, 1, dye.metadata), guiLeft + x, guiTop + y)
GlStateManager.popMatrix()
} else {
Gui.drawRect(guiLeft + x - 1, guiTop + y - 1, guiLeft + x + 17, guiTop + y + 17, dye.mapColor.colorValue or 0x5F000000.toInt())
}
}
drawStack(stack, guiLeft + x, guiTop + y)
}
index++
}
count = index
}
}
override fun drawGuiContainerForegroundLayer(mouseX: Int, mouseY: Int) {
if (inside(guiLeft + 9 + 18 + 9 - 1, guiTop + 67 + 9 - 1, 18, 18, mouseX, mouseY)) {
if (cont.tile!!.amount != -1) {
drawHoveringText(listOf("Amount: " + cont.tile!!.amount.toString()), mouseX - guiLeft, mouseY - guiTop)
}
}
if (inside(guiLeft + 8, guiTop + 67 + 8, 18, 18, mouseX, mouseY)) {
drawHoveringText(listOf(cont.tile!!.active.toString()), mouseX - guiLeft, mouseY - guiTop)
}
super.drawGuiContainerForegroundLayer(mouseX, mouseY)
}
fun drawBox(x: Int, y: Int, sizeX: Int, sizeY: Int, color: Int = 0x7F4C4C4C.toInt()) {
Gui.drawRect(x, y, x + sizeX, y + sizeY, color)
}
override fun handleMouseInput() {
super.handleMouseInput()
val dwheel = Mouse.getDWheel()
if (dwheel < 0) {
if (count / 9 > 3 + offset) {
offset++
}
} else if (dwheel > 0) {
if (offset > 0) {
offset--
}
}
}
override fun mouseClicked(mouseX: Int, mouseY: Int, mouseButton: Int) {
text.mouseClicked(mouseX, mouseY, mouseButton)
if (mouseButton == 0) {
if (inside(guiLeft + 59, guiTop + 67 + 11, 6 + 8, 8 + 4, mouseX, mouseY)) {
Statistics.NETWORK.sendToServer(ClientEventPacket(cont.tile!!.world.provider.dimension, cont.tile!!.pos, 1, cont.tile!!.operation.ordinal + 1))
}
}
val move = -20
val tile = cont.tile!!
start@for (x in 0 until 9) {
for (y in 0 until 3) {
if (inside(guiLeft + x * 18 + 6, guiTop + y * 18 + 125 + move, 18, 18, mouseX, mouseY)) {
val index = x + (y + offset) * 9
if (mouseButton == 0) {
if (index < count && tile.getItem(index) != tile.itemCache) {
Statistics.NETWORK.sendToServer(ClientEventPacket(cont.tile!!.world.provider.dimension, cont.tile!!.pos, 2, index))
}
} else {
if (tile.getItem(index) == tile.itemCache) {
Statistics.NETWORK.sendToServer(ClientEventPacket(cont.tile!!.world.provider.dimension, cont.tile!!.pos, 2, -1))
}
}
break@start
}
}
}
super.mouseClicked(mouseX, mouseY, mouseButton)
}
override fun keyTyped(typedChar: Char, keyCode: Int) {
text.textboxKeyTyped(typedChar, keyCode)
if (keyCode == Keyboard.KEY_DOWN) {
if (count / 9 > 3 + offset) {
offset++
}
} else if (keyCode == Keyboard.KEY_UP) {
if (offset > 0) {
offset--
}
}
super.keyTyped(typedChar, keyCode)
}
}
class ContainerInventoryDetector(world: World, pos: BlockPos, player: EntityPlayer) : ContainerBase(world, pos, player) {
val tile by lazy {
val t = world.getTileEntity(pos)
if (t is TileInventoryDetector) {
t
} else {
null
}
}
override fun readPacket(pkt: GuiPacket) {
if (tile != null) {
val nbt = pkt.nbt!!
val map = mutableMapOf<ItemIdentifier, Int>()
nbt.getTagList("Items", Constants.NBT.TAG_COMPOUND).forEach {
val item = ItemIdentifier.deserializeNBT(it)
val size = it.getInteger("Extra")
map.put(item, size)
}
synchronized(tile!!) {
tile!!.operation = TileInventoryDetector.Operation.values()[nbt.getInteger("Operation")]
tile!!.active = nbt.getBoolean("Active")
if (!nbt.getCompoundTag("Cache").hasNoTags()) {
tile!!.itemCache = ItemIdentifier.deserializeNBT(nbt.getCompoundTag("Cache"))
} else {
tile!!.itemCache = null
}
tile!!.limit = nbt.getInteger("Limit")
tile!!.amount = nbt.getInteger("Amount")
tile!!.items.clear()
tile!!.items.putAll(map)
}
}
}
override fun writePacket(): GuiPacket? = GuiPacket(NBTTagCompound().apply {
setTag("Items", encodeItems(tile!!.items))
setTag("Cache", tile!!.itemCache?.serializeNBT() ?: NBTTagCompound())
setInteger("Limit", tile!!.limit)
setInteger("Amount", tile!!.amount)
setInteger("Operation", tile!!.operation.ordinal)
setBoolean("Active", tile!!.getRedstoneLevel() > 0)
})
private fun encodeItems(map: Map<ItemIdentifier, Int>): NBTTagList {
//items
val itemList = NBTTagList()
for ((key, value) in map) {
itemList.appendTag(key.serializeNBT().apply { setInteger("Extra", value) })
}
return itemList
}
} | src/main/kotlin/com/cout970/statistics/gui/InventoryDetector.kt | 3438673815 |
package com.duopoints.android.fragments.registration
import android.text.TextUtils
import com.duopoints.android.Calls
import com.duopoints.android.fragments.base.BasePresenter
import com.duopoints.android.rest.models.geo.City
import com.duopoints.android.rest.models.geo.Country
import com.duopoints.android.rest.models.geo.wrappers.CityWrapper
import com.duopoints.android.rest.models.geo.wrappers.CountryWrapper
import com.duopoints.android.rest.models.post.UserReg
import com.duopoints.android.utils.ReactiveUtils
import io.reactivex.functions.Consumer
import java.util.regex.Pattern
class RegPresenter internal constructor(regFrag: RegFrag) : BasePresenter<RegFrag>(regFrag) {
private val chars = Pattern.compile("\\w+", Pattern.UNICODE_CASE)
fun loadCountries() {
Calls.geoService.allCountries
.map<ArrayList<Country>>(CountryWrapper::geonames)
.compose(ReactiveUtils.workMaybeInBackgroundDeliverToMain())
.subscribe(view::countriesLoaded, Throwable::printStackTrace)
}
fun loadCities(countryID: Int) {
Calls.geoService.getCities(countryID)
.map<ArrayList<City>>(CityWrapper::geonames)
.compose(ReactiveUtils.workMaybeInBackgroundDeliverToMain())
.subscribe(view::citiesLoaded, Throwable::printStackTrace)
}
fun regUser(userReg: UserReg) {
Calls.userService.registerUser(userReg)
.compose(ReactiveUtils.workMaybeInBackgroundDeliverToMain())
.subscribe(Consumer(view::userRegistered),
Consumer {
view.failedUserReg()
it.printStackTrace()
})
}
fun inputValidation(input: String): String? {
return if (TextUtils.isEmpty(input) || !chars.matcher(input).matches()) null else input
}
fun countryValidation(country: Any?): String? {
return if (country == null) null else (country as Country).countryName
}
fun cityValidation(city: Any?): String? {
return if (city == null) null else (city as City).name
}
} | app/src/main/java/com/duopoints/android/fragments/registration/RegPresenter.kt | 3776053063 |
/*
* 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.google.mlkit.md.objectdetection
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.view.View
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import com.google.mlkit.md.R
/** Represents a detected object by drawing a circle dot at the center of object's bounding box. */
class StaticObjectDotView @JvmOverloads constructor(context: Context, selected: Boolean = false) : View(context) {
private val paint: Paint = Paint().apply {
style = Paint.Style.FILL
}
private val unselectedDotRadius: Int =
context.resources.getDimensionPixelOffset(R.dimen.static_image_dot_radius_unselected)
private val radiusOffsetRange: Int
private var currentRadiusOffset: Float = 0.toFloat()
init {
val selectedDotRadius = context.resources.getDimensionPixelOffset(R.dimen.static_image_dot_radius_selected)
radiusOffsetRange = selectedDotRadius - unselectedDotRadius
currentRadiusOffset = (if (selected) radiusOffsetRange else 0).toFloat()
}
fun playAnimationWithSelectedState(selected: Boolean) {
val radiusOffsetAnimator: ValueAnimator =
if (selected) {
ValueAnimator.ofFloat(0f, radiusOffsetRange.toFloat())
.setDuration(DOT_SELECTION_ANIMATOR_DURATION_MS).apply {
startDelay = DOT_DESELECTION_ANIMATOR_DURATION_MS
}
} else {
ValueAnimator.ofFloat(radiusOffsetRange.toFloat(), 0f)
.setDuration(DOT_DESELECTION_ANIMATOR_DURATION_MS)
}
radiusOffsetAnimator.interpolator = FastOutSlowInInterpolator()
radiusOffsetAnimator.addUpdateListener { animation ->
currentRadiusOffset = animation.animatedValue as Float
invalidate()
}
radiusOffsetAnimator.start()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val cx = width / 2f
val cy = height / 2f
paint.color = Color.WHITE
canvas.drawCircle(cx, cy, unselectedDotRadius + currentRadiusOffset, paint)
}
companion object {
private const val DOT_SELECTION_ANIMATOR_DURATION_MS: Long = 116
private const val DOT_DESELECTION_ANIMATOR_DURATION_MS: Long = 67
}
}
| android/material-showcase/app/src/main/java/com/google/mlkit/md/objectdetection/StaticObjectDotView.kt | 2743486974 |
package com.hartwig.hmftools.teal
import com.hartwig.hmftools.teal.ReadGroup.Companion.suppAlignmentPositions
import htsjdk.samtools.SAMRecord
import htsjdk.samtools.SAMTag
import junit.framework.TestCase
import kotlin.test.*
class ReadGroupTest
{
@Test
fun testSuppAlignmentPositions()
{
var saString = "16,59998,+,64S38M49S,55,0;"
var sas = suppAlignmentPositions(true, saString)
TestCase.assertEquals(sas!!.size, 1)
TestCase.assertEquals(sas[0].chromosome, "16")
TestCase.assertEquals(sas[0].position, 59998)
saString = "16,59998,+,64S38M49S,55,0;15,42243201,+,108S35M8S,9,0;,"
sas = suppAlignmentPositions(true, saString)
TestCase.assertEquals(sas!!.size, 2)
TestCase.assertEquals(sas[0].chromosome, "16")
TestCase.assertEquals(sas[0].position, 59998)
TestCase.assertEquals(sas[1].chromosome, "15")
TestCase.assertEquals(sas[1].position, 42243201)
}
@Test
fun testReadGroupIsComplete()
{
val rg = ReadGroup("ReadGroup")
var record = SAMRecord(null)
record.readName = rg.name
record.referenceName = "1"
record.alignmentStart = 100
record.mateReferenceName = "2"
record.mateAlignmentStart = 200
record.readPairedFlag = true
record.firstOfPairFlag = true
rg.mutableReads.add(record)
TestCase.assertFalse(rg.isComplete())
record = SAMRecord(null)
record.readName = rg.name
record.referenceName = "2"
record.alignmentStart = 200
record.mateReferenceName = "1"
record.mateAlignmentStart = 100
record.readPairedFlag = true
record.firstOfPairFlag = false
rg.mutableReads.add(record)
TestCase.assertTrue(rg.isComplete())
TestCase.assertTrue(rg.invariant())
}
@Test
fun testReadGroupIsCompleteWithSupplementary()
{
val rg = ReadGroup("ReadGroup")
var record = SAMRecord(null)
val cigarRead1 = "64S38M49S"
val cigarSupplRead1 = "13S43M26S"
val cigarSupplRead2 = "66M43S"
record.readName = rg.name
record.referenceName = "1"
record.alignmentStart = 100
record.mateReferenceName = "2"
record.mateAlignmentStart = 200
record.readPairedFlag = true
record.firstOfPairFlag = true
record.readNegativeStrandFlag = true
rg.mutableReads.add(record)
TestCase.assertFalse(rg.isComplete())
record = SAMRecord(null)
record.readName = rg.name
record.referenceName = "2"
record.alignmentStart = 200
record.mateReferenceName = "1"
record.mateAlignmentStart = 100
record.readPairedFlag = true
record.firstOfPairFlag = false
record.readNegativeStrandFlag = false
record.cigarString = cigarRead1
record.setAttribute(SAMTag.SA.name, "3,300,+,${cigarSupplRead1},55,0;4,400,-,${cigarSupplRead2},55,0;,")
rg.mutableReads.add(record)
TestCase.assertFalse(rg.isComplete())
// add supplementary
record = SAMRecord(null)
record.readName = rg.name
record.referenceName = "3"
record.alignmentStart = 300
record.mateReferenceName = "1"
record.mateAlignmentStart = 100
record.readPairedFlag = true
record.firstOfPairFlag = false
record.supplementaryAlignmentFlag = true
record.readNegativeStrandFlag = false
record.cigarString = cigarSupplRead1
record.setAttribute(SAMTag.SA.name, "2,200,+,${cigarRead1},55,0;")
rg.mutableSupplementaryReads.add(record)
// we still missing one supplementary read
TestCase.assertFalse(rg.isComplete())
record = SAMRecord(null)
record.readName = rg.name
record.referenceName = "4"
record.alignmentStart = 400
record.mateReferenceName = "1"
record.mateAlignmentStart = 100
record.readPairedFlag = true
record.firstOfPairFlag = false
record.supplementaryAlignmentFlag = true
record.readNegativeStrandFlag = true
record.cigarString = cigarSupplRead2
record.setAttribute(SAMTag.SA.name, "2,200,+,${cigarRead1},55,0;")
rg.mutableSupplementaryReads.add(record)
TestCase.assertTrue(rg.isComplete())
TestCase.assertTrue(rg.invariant())
}
} | teal/src/test/kotlin/com/hartwig/hmftools/teal/ReadGroupTest.kt | 2729334961 |
package com.lasthopesoftware.bluewater.client.connection.selected.GivenASelectedLibrary
import androidx.test.core.app.ApplicationProvider
import com.lasthopesoftware.AndroidContext
import com.lasthopesoftware.bluewater.client.browsing.library.access.session.ProvideSelectedLibraryId
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.connection.BuildingConnectionStatus
import com.lasthopesoftware.bluewater.client.connection.ConnectionProvider
import com.lasthopesoftware.bluewater.client.connection.IConnectionProvider
import com.lasthopesoftware.bluewater.client.connection.okhttp.OkHttpFactory
import com.lasthopesoftware.bluewater.client.connection.selected.SelectedConnection
import com.lasthopesoftware.bluewater.client.connection.selected.SelectedConnection.BuildingSessionConnectionStatus.BuildingConnection
import com.lasthopesoftware.bluewater.client.connection.selected.SelectedConnection.BuildingSessionConnectionStatus.BuildingSessionComplete
import com.lasthopesoftware.bluewater.client.connection.selected.SelectedConnection.BuildingSessionConnectionStatus.GettingLibrary
import com.lasthopesoftware.bluewater.client.connection.selected.SelectedConnectionReservation
import com.lasthopesoftware.bluewater.client.connection.session.ManageConnectionSessions
import com.lasthopesoftware.bluewater.client.connection.url.IUrlProvider
import com.lasthopesoftware.bluewater.shared.promises.extensions.DeferredProgressingPromise
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.lasthopesoftware.resources.FakeMessageBus
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import java.util.concurrent.Future
class WhenRetrievingTheSelectedConnectionOnBuildComplete : AndroidContext() {
companion object {
private val fakeMessageSender = lazy { FakeMessageBus(ApplicationProvider.getApplicationContext()) }
private val urlProvider = mockk<IUrlProvider>()
private var connectionProvider: IConnectionProvider? = null
private var secondConnectionProvider: IConnectionProvider? = null
}
override fun before() {
val deferredConnectionProvider = DeferredProgressingPromise<BuildingConnectionStatus, IConnectionProvider?>()
val libraryConnections = mockk<ManageConnectionSessions>()
every { libraryConnections.promiseLibraryConnection(LibraryId(2)) } returns deferredConnectionProvider
val libraryIdentifierProvider = mockk<ProvideSelectedLibraryId>()
every { libraryIdentifierProvider.selectedLibraryId } returns Promise(LibraryId(2))
SelectedConnectionReservation().use {
val sessionConnection = SelectedConnection(fakeMessageSender.value, libraryIdentifierProvider, libraryConnections)
deferredConnectionProvider.sendProgressUpdates(
BuildingConnectionStatus.GettingLibrary,
)
val futureConnectionProvider = sessionConnection.promiseSessionConnection().toFuture()
var futureSecondConnectionProvider: Future<IConnectionProvider?>? = null
deferredConnectionProvider.updates {
if (it == BuildingConnectionStatus.BuildingConnectionComplete) {
futureSecondConnectionProvider = sessionConnection.promiseSessionConnection().toFuture()
}
}
deferredConnectionProvider.sendProgressUpdates(
BuildingConnectionStatus.BuildingConnection,
BuildingConnectionStatus.BuildingConnectionComplete
)
deferredConnectionProvider.sendResolution(ConnectionProvider(urlProvider, OkHttpFactory))
connectionProvider = futureConnectionProvider.get()
secondConnectionProvider = futureSecondConnectionProvider?.get()
}
}
@Test
fun thenTheConnectionIsCorrect() {
assertThat(connectionProvider?.urlProvider).isEqualTo(urlProvider)
}
@Test
fun thenTheSecondConnectionIsCorrect() {
assertThat(secondConnectionProvider).isEqualTo(connectionProvider)
}
@Test
fun thenGettingLibraryIsBroadcast() {
assertThat(
fakeMessageSender.value.recordedIntents
.map { i -> i.getIntExtra(SelectedConnection.buildSessionBroadcastStatus, -1) })
.containsExactly(GettingLibrary, BuildingConnection, BuildingSessionComplete)
}
}
| projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/connection/selected/GivenASelectedLibrary/WhenRetrievingTheSelectedConnectionOnBuildComplete.kt | 929535929 |
package email.schaal.ocreader.api
import email.schaal.ocreader.database.model.User
import retrofit2.http.GET
import retrofit2.http.Headers
import retrofit2.http.Path
interface OCSAPI {
@Headers("OCS-APIRequest: true")
@GET("ocs/v1.php/cloud/users/{userId}?format=json")
suspend fun user(@Path("userId") userId: String): User
} | app/src/main/java/email/schaal/ocreader/api/OCSAPI.kt | 2064726994 |
package test.createinstance
import com.nhaarman.expect.expect
import com.nhaarman.mockitokotlin2.internal.createInstance
import org.junit.Test
import test.TestBase
class NullCasterTest : TestBase() {
@Test
fun createInstance() {
/* When */
val result = createInstance(String::class)
/* Then */
expect(result).toBeNull()
}
@Test
fun kotlinAcceptsNullValue() {
/* Given */
val s: String = createInstance(String::class)
/* When */
acceptNonNullableString(s)
}
private fun acceptNonNullableString(@Suppress("UNUSED_PARAMETER") s: String) {
}
}
| tests/src/test/kotlin/test/createinstance/NullCasterTest.kt | 728348052 |
package com.didichuxing.doraemonkit
import android.content.Context
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.didichuxing.doraemonkit.util.LifecycleListenerUtil
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2019-12-31-10:56
* 描 述:全局的fragment 生命周期回调
* 修订历史:
* ================================================
*/
class DoKitFragmentLifecycleCallbacks : FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentAttached(fm: FragmentManager, fragment: Fragment, context: Context) {
super.onFragmentAttached(fm, fragment, context)
for (listener in LifecycleListenerUtil.LIFECYCLE_LISTENERS) {
listener.onFragmentAttached(fragment)
}
}
override fun onFragmentDetached(fm: FragmentManager, fragment: Fragment) {
super.onFragmentDetached(fm, fragment)
for (listener in LifecycleListenerUtil.LIFECYCLE_LISTENERS) {
listener.onFragmentDetached(fragment)
}
}
companion object {
private const val TAG = "DokitFragmentLifecycleCallbacks"
}
}
| Android/dokit/src/main/java/com/didichuxing/doraemonkit/DoKitFragmentLifecycleCallbacks.kt | 3028989276 |
package ca.six.demo.cleanviper.router.core
import java.util.HashMap
interface IRouter {
fun registerRoute(map: HashMap<String, Station>)
} | CleanViper/app/src/main/java/ca/six/demo/cleanviper/router/core/IRouter.kt | 127786203 |
package i_introduction._2_Named_Arguments
import i_introduction._1_Java_To_Kotlin_Converter.task1
import util.TODO
import util.doc2
// default values for arguments
fun bar(i: Int, s: String = "", b: Boolean = true) {}
fun usage() {
// named arguments
bar(1, b = false)
}
fun todoTask2(): Nothing = TODO(
"""
Task 2.
Print out the collection contents surrounded by curly braces using the library function 'joinToString'.
Specify only 'prefix' and 'postfix' arguments.
Don't forget to remove the 'todoTask2()' invocation which throws an exception.
""",
documentation = doc2(),
references = { collection: Collection<Int> -> task1(collection); collection.joinToString() })
fun task2(collection: Collection<Int>): String {
return task2Impl(collection)
}
private fun task2Impl(collection: Collection<Int>) =
collection.joinToString(separator = ", ", prefix = "{", postfix = "}") | src/i_introduction/_2_Named_Arguments/n02NamedArguments.kt | 1862549662 |
package nl.sogeti.android.gpstracker.ng.base.dagger
import android.content.ContentResolver
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.os.AsyncTask
import dagger.Module
import dagger.Provides
import nl.sogeti.android.gpstracker.ng.base.location.GpsLocationFactory
import nl.sogeti.android.gpstracker.ng.base.location.LocationFactory
import nl.sogeti.android.gpstracker.ng.common.controllers.gpsstatus.GpsStatusControllerFactory
import java.util.concurrent.Executor
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
class SystemModule {
@Provides
fun gpsStatusControllerFactory(application: Context): GpsStatusControllerFactory {
return GpsStatusControllerFactory(application)
}
@Provides
fun uriBuilder() = Uri.Builder()
@Provides
@Singleton
@Computation
fun computationExecutor(): Executor = AsyncTask.THREAD_POOL_EXECUTOR
@Provides
@Singleton
@DiskIO
fun diskExecutor(): Executor = ThreadPoolExecutor(1, 2, 10L, TimeUnit.SECONDS, LinkedBlockingQueue())
@Provides
@Singleton
@NetworkIO
fun networkExecutor(): Executor = ThreadPoolExecutor(1, 16, 30L, TimeUnit.SECONDS, LinkedBlockingQueue())
@Provides
fun packageManager(application: Context): PackageManager = application.packageManager
@Provides
fun locationFactory(application: Context): LocationFactory = GpsLocationFactory(application)
@Provides
fun contentResolver(application: Context): ContentResolver = application.contentResolver
}
| studio/base/src/main/java/nl/sogeti/android/gpstracker/ng/base/dagger/SystemModule.kt | 2228113816 |
package io.gitlab.arturbosch.detekt.rules
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.internal.DefaultRuleSetProvider
import io.gitlab.arturbosch.detekt.test.TestConfig
import org.assertj.core.api.Assertions.assertThat
import org.reflections.Reflections
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class RuleProviderConfigSpec : Spek({
describe("RuleProvider config test") {
it("should test if the config has been passed to all rules") {
val config = TestConfig()
val reflections = Reflections("io.gitlab.arturbosch.detekt.rules")
val providers = reflections.getSubTypesOf(DefaultRuleSetProvider::class.java)
providers.forEach {
val provider = it.getDeclaredConstructor().newInstance()
val ruleSet = provider.instance(config)
ruleSet.rules.forEach { baseRule ->
val rule = baseRule as? Rule
if (rule != null) {
assertThat(rule.ruleSetConfig)
.withFailMessage("No config was passed to ${rule.javaClass.name}")
.isEqualTo(config)
}
}
}
}
}
})
| detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/RuleProviderConfigSpec.kt | 2710843437 |
/*
* Copyright (C) 2021 pedroSG94.
*
* 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.pedro.rtmp.rtmp.message.command
import com.pedro.rtmp.rtmp.chunk.ChunkStreamId
import com.pedro.rtmp.rtmp.chunk.ChunkType
import com.pedro.rtmp.rtmp.message.BasicHeader
import com.pedro.rtmp.rtmp.message.MessageType
/**
* Created by pedro on 21/04/21.
*/
class CommandAmf0(name: String = "", commandId: Int = 0, timestamp: Int = 0, streamId: Int = 0, basicHeader: BasicHeader =
BasicHeader(ChunkType.TYPE_0, ChunkStreamId.OVER_CONNECTION.mark)): Command(name, commandId, timestamp, streamId, basicHeader = basicHeader) {
override fun getType(): MessageType = MessageType.COMMAND_AMF0
} | rtmp/src/main/java/com/pedro/rtmp/rtmp/message/command/CommandAmf0.kt | 4098598279 |
/*
* Copyright (C) 2017 Andrzej Ressel ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.jereksel.libresubstratum.domain
import dagger.Provides
import javax.inject.Inject
import javax.inject.Named
@Named("group")
class MetricsGroup
@Inject constructor(
@Named("volatile") private val volatileMetrics: Metrics,
@Named("persistent") private val persistentMetrics: Metrics
): Metrics {
val metricsList = listOf(volatileMetrics, persistentMetrics)
override fun userEnteredTheme(themeId: String) {
metricsList.forEach { it.userEnteredTheme(themeId) }
}
override fun userCompiledOverlay(themeId: String, targetApp: String) {
metricsList.forEach { it.userCompiledOverlay(themeId, targetApp) }
}
override fun userEnabledOverlay(overlayId: String) {
metricsList.forEach { it.userEnabledOverlay(overlayId) }
}
override fun userDisabledOverlay(overlayId: String) {
metricsList.forEach { it.userDisabledOverlay(overlayId) }
}
override fun logOverlayServiceType(overlayService: OverlayService) {
metricsList.forEach { it.logOverlayServiceType(overlayService) }
}
override fun getMetrics(): Map<String, String> {
return metricsList
.map { it.getMetrics() }
.map { it.entries }
.flatten()
.map { Pair(it.key, it.value) }
.toMap()
}
}
| app/src/main/kotlin/com/jereksel/libresubstratum/domain/MetricsGroup.kt | 3238652643 |
package io.gitlab.arturbosch.detekt.core
import io.github.detekt.test.utils.resourceUrl
import io.github.detekt.tooling.api.spec.ProcessingSpec
import io.gitlab.arturbosch.detekt.core.config.loadConfiguration
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
internal class WorkaroundConfigurationKtSpec : Spek({
describe("with all rules activated by default") {
val config by memoized {
ProcessingSpec {
config { resources = listOf(resourceUrl("/configs/empty.yml")) }
rules { activateAllRules = true }
}.let { spec ->
spec.workaroundConfiguration(spec.loadConfiguration())
}
}
it("should override active to true by default") {
val actual = config.subConfig("comments")
.subConfig("UndocumentedPublicClass")
.valueOrDefault("active", false)
assertThat(actual).isEqualTo(true)
}
it("should override maxIssues to 0 by default") {
assertThat(config.subConfig("build").valueOrDefault("maxIssues", -1)).isEqualTo(0)
}
it("should keep config from default") {
val actual = config.subConfig("style")
.subConfig("MaxLineLength")
.valueOrDefault("maxLineLength", -1)
assertThat(actual).isEqualTo(120)
}
}
describe("fail fast override") {
val config by memoized {
ProcessingSpec {
config { resources = listOf(resourceUrl("/configs/fail-fast-will-override-here.yml")) }
rules { activateAllRules = true }
}.let { spec ->
spec.workaroundConfiguration(spec.loadConfiguration())
}
}
it("should override config when specified") {
val actual = config.subConfig("style")
.subConfig("MaxLineLength")
.valueOrDefault("maxLineLength", -1)
assertThat(actual).isEqualTo(100)
}
it("should override active when specified") {
val actual = config.subConfig("comments")
.subConfig("CommentOverPrivateMethod")
.valueOrDefault("active", true)
assertThat(actual).isEqualTo(false)
}
it("should override maxIssues when specified") {
assertThat(config.subConfig("build").valueOrDefault("maxIssues", -1)).isEqualTo(1)
}
}
describe("auto correct config") {
context("when specified it respects all autoCorrect values of rules and rule sets") {
val config by memoized {
ProcessingSpec {
config { resources = listOf(resourceUrl("/configs/config-with-auto-correct.yml")) }
rules { autoCorrect = true }
}.let { spec ->
spec.workaroundConfiguration(spec.loadConfiguration())
}
}
val style by memoized { config.subConfig("style") }
val comments by memoized { config.subConfig("comments") }
it("is disabled for rule sets") {
assertThat(style.valueOrNull<Boolean>("autoCorrect")).isTrue()
assertThat(comments.valueOrNull<Boolean>("autoCorrect")).isFalse()
}
it("is disabled for rules") {
assertThat(style.subConfig("MagicNumber").valueOrNull<Boolean>("autoCorrect")).isTrue()
assertThat(style.subConfig("MagicString").valueOrNull<Boolean>("autoCorrect")).isFalse()
assertThat(comments.subConfig("ClassDoc").valueOrNull<Boolean>("autoCorrect")).isTrue()
assertThat(comments.subConfig("FunctionDoc").valueOrNull<Boolean>("autoCorrect")).isFalse()
}
}
mapOf(
ProcessingSpec {
config { resources = listOf(resourceUrl("/configs/config-with-auto-correct.yml")) }
}.let { spec ->
spec.workaroundConfiguration(spec.loadConfiguration())
} to "when not specified all autoCorrect values are overridden to false",
ProcessingSpec {
config { resources = listOf(resourceUrl("/configs/config-with-auto-correct.yml")) }
rules { autoCorrect = false }
}.let { spec ->
spec.workaroundConfiguration(spec.loadConfiguration())
} to "when specified as false, all autoCorrect values are overridden to false",
ProcessingSpec {
config {
useDefaultConfig = true
resources = listOf(resourceUrl("/configs/config-with-auto-correct.yml"))
}
rules {
autoCorrect = false
activateAllRules = true
}
}.let { spec ->
spec.workaroundConfiguration(spec.loadConfiguration())
} to "regardless of other cli options, autoCorrect values are overridden to false"
).forEach { (config, testContext) ->
context(testContext) {
val style = config.subConfig("style")
val comments = config.subConfig("comments")
it("is disabled for rule sets") {
assertThat(style.valueOrNull<Boolean>("autoCorrect")).isFalse()
assertThat(comments.valueOrNull<Boolean>("autoCorrect")).isFalse()
}
it("is disabled for rules") {
assertThat(style.subConfig("MagicNumber").valueOrNull<Boolean>("autoCorrect")).isFalse()
assertThat(style.subConfig("MagicString").valueOrNull<Boolean>("autoCorrect")).isFalse()
assertThat(comments.subConfig("ClassDoc").valueOrNull<Boolean>("autoCorrect")).isFalse()
assertThat(comments.subConfig("FunctionDoc").valueOrNull<Boolean>("autoCorrect")).isFalse()
}
}
}
}
})
| detekt-core/src/test/kotlin/io/gitlab/arturbosch/detekt/core/WorkaroundConfigurationKtSpec.kt | 2437769540 |
package net.nemerosa.ontrack.service
import net.nemerosa.ontrack.extension.api.support.TestExtensionFeature
import net.nemerosa.ontrack.extension.api.support.TestPropertyType
import net.nemerosa.ontrack.model.events.Event
import net.nemerosa.ontrack.model.events.EventCannotRenderEntityException
import net.nemerosa.ontrack.model.events.EventRenderer
import net.nemerosa.ontrack.model.structure.*
import net.nemerosa.ontrack.model.structure.NameDescription.Companion.nd
import net.nemerosa.ontrack.model.support.NameValue
import net.nemerosa.ontrack.model.events.EventFactoryImpl
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class EventFactoryImplTest {
private val factory = EventFactoryImpl()
private val testPropertyType = TestPropertyType(TestExtensionFeature())
@Test
fun newProject() {
val e = factory.newProject(project())
assertNull(e.signature)
assertEquals(e.entities.size, 1)
assertEquals("New project P.", e.renderText())
assertEquals("""New project <a href="#/project/1">P</a>.""", e.render(testRenderer))
}
@Test
fun deleteProject() {
val e = factory.deleteProject(project())
assertNull(e.signature)
assertEquals(e.entities.size, 0)
assertEquals("Project P has been deleted.", e.renderText())
assertEquals("""Project <i class="project">P</i> has been deleted.""", e.render(testRenderer))
}
@Test
fun newBuild() {
val e = factory.newBuild(build())
assertEquals("user", e.signature?.user?.name)
assertEquals(e.entities.size, 3)
assertEquals("New build 1 for branch B in P.", e.renderText())
assertEquals("""New build <a href="#/build/100">1</a> for branch <a href="#/branch/10">B</a> in <a href="#/project/1">P</a>.""", e.render(testRenderer))
}
@Test
fun updateBuild() {
val e = factory.updateBuild(build())
assertNull(e.signature)
assertEquals(e.entities.size, 3)
assertEquals("Build 1 for branch B in P has been updated.", e.renderText())
}
@Test
fun deleteBuild() {
val e = factory.deleteBuild(build())
assertNull(e.signature)
assertEquals(e.entities.size, 2)
assertEquals("Build 1 for branch B in P has been deleted.", e.renderText())
}
@Test
fun deletePromotionLevel() {
val e = factory.deletePromotionLevel(promotionLevel())
assertNull(e.signature)
assertEquals(e.entities.size, 2)
assertEquals("Promotion level COPPER for branch B in P has been deleted.", e.renderText())
}
@Test
fun reorderPromotionLevels() {
val e = factory.reorderPromotionLevels(branch())
assertNull(e.signature)
assertEquals(e.entities.size, 2)
assertEquals("Promotion levels for branch B in P have been reordered.", e.renderText())
}
@Test
fun imageValidationStamp() {
val e = factory.imageValidationStamp(validationStamp())
assertNull(e.signature)
assertEquals(e.entities.size, 3)
assertEquals("Image for validation stamp SMOKE for branch B in P has changed.", e.renderText())
}
@Test
fun updateValidationStamp() {
val e = factory.updateValidationStamp(validationStamp())
assertNull(e.signature)
assertEquals(e.entities.size, 3)
assertEquals("Validation stamp SMOKE for branch B in P has been updated.", e.renderText())
}
@Test
fun deleteValidationStamp() {
val e = factory.deleteValidationStamp(validationStamp())
assertNull(e.signature)
assertEquals(e.entities.size, 2)
assertEquals("Validation stamp SMOKE for branch B in P has been deleted.", e.renderText())
}
@Test
fun reorderValidationStamps() {
val e = factory.reorderValidationStamps(branch())
assertNull(e.signature)
assertEquals(e.entities.size, 2)
assertEquals("Validation stamps for branch B in P have been reordered.", e.renderText())
}
@Test
fun newPromotionRun() {
val e = factory.newPromotionRun(promotionRun())
assertEquals("user", e.signature?.user?.name)
assertEntities(
e,
ProjectEntityType.PROJECT,
ProjectEntityType.BRANCH,
ProjectEntityType.BUILD,
ProjectEntityType.PROMOTION_LEVEL,
ProjectEntityType.PROMOTION_RUN
)
assertEquals("Build 1 has been promoted to COPPER for branch B in P.", e.renderText())
assertEquals("""Build <a href="#/build/100">1</a> has been promoted to <a href="#/promotionLevel/100">COPPER</a> for branch <a href="#/branch/10">B</a> in <a href="#/project/1">P</a>.""", e.render(testRenderer))
}
@Test
fun deletePromotionRun() {
val e = factory.deletePromotionRun(promotionRun())
assertNull(e.signature)
assertEntities(
e,
ProjectEntityType.PROJECT,
ProjectEntityType.BRANCH,
ProjectEntityType.BUILD,
ProjectEntityType.PROMOTION_LEVEL,
ProjectEntityType.PROMOTION_RUN
)
assertEquals("Promotion COPPER of build 1 has been deleted for branch B in P.", e.renderText())
}
@Test
fun newValidationRun() {
val e = factory.newValidationRun(validationRun())
assertEquals("user", e.signature?.user?.name)
assertEquals(e.entities.size, 5)
assertEquals("Build 1 has run for SMOKE with status Failed in branch B in P.", e.renderText())
assertEquals("""Build <a href="#/build/100">1</a> has run for <a href="#/validationStamp/100">SMOKE</a> with status <i class="status">Failed</i> in branch <a href="#/branch/10">B</a> in <a href="#/project/1">P</a>.""", e.render(testRenderer))
}
@Test
fun newValidationRunStatus() {
val e = factory.newValidationRunStatus(validationRun())
assertEquals("user", e.signature?.user?.name)
assertEquals(e.entities.size, 5)
assertEquals("Status for SMOKE validation #1 for build 1 in branch B of P has changed to Failed.", e.renderText())
assertEquals("""Status for <a href="#/validationStamp/100">SMOKE</a> validation <a href="#/validationRun/1000">#1</a> for build <a href="#/build/100">1</a> in branch <a href="#/branch/10">B</a> of <a href="#/project/1">P</a> has changed to <i class="status">Failed</i>.""", e.render(testRenderer))
}
@Test
fun propertyChange_on_promotion_level() {
val e = factory.propertyChange(promotionLevel(), testPropertyType)
assertNull(e.signature)
assertEquals(e.entities.size, 2)
assertEquals("Configuration value property has changed for promotion level COPPER.", e.renderText())
}
@Test
fun propertyDelete_on_promotion_level() {
val e = factory.propertyDelete(promotionLevel(), testPropertyType)
assertNull(e.signature)
assertEquals(e.entities.size, 2)
assertEquals("Configuration value property has been removed from promotion level COPPER.", e.renderText())
}
@Test
fun propertyChange_on_project() {
val e = factory.propertyChange(project(), testPropertyType)
assertNull(e.signature)
assertEquals(e.entities.size, 1)
assertEquals("Configuration value property has changed for project P.", e.renderText())
}
@Test
fun propertyDelete_on_project() {
val e = factory.propertyDelete(project(), testPropertyType)
assertNull(e.signature)
assertEquals(e.entities.size, 1)
assertEquals("Configuration value property has been removed from project P.", e.renderText())
}
private fun promotionRun(): PromotionRun {
val branch = branch()
return PromotionRun.of(
Build.of(branch, nd("1", "Build"), Signature.of("user")).withId(ID.of(100)),
PromotionLevel.of(branch, nd("COPPER", "")).withId(ID.of(100)),
Signature.of("user"),
""
).withId(ID.of(1000))
}
private fun promotionLevel(): PromotionLevel = PromotionLevel.of(branch(), nd("COPPER", "")).withId(ID.of(100))
private fun validationRun(): ValidationRun {
val branch = branch()
return ValidationRun.of(
Build.of(branch, nd("1", "Build"), Signature.of("user")).withId(ID.of(100)),
ValidationStamp.of(branch, nd("SMOKE", "")).withId(ID.of(100)),
1,
Signature.of("user"),
ValidationRunStatusID.STATUS_FAILED,
""
).withId(ID.of(1000))
}
private fun validationStamp(): ValidationStamp = ValidationStamp.of(branch(), nd("SMOKE", "")).withId(ID.of(100))
private fun build(): Build = Build.of(branch(), nd("1", "Build"), Signature.of("user")).withId(ID.of(100))
private fun branch(): Branch = Branch.of(project(), nd("B", "Branch")).withId(ID.of(10))
private fun project(): Project = Project.of(nd("P", "Project")).withId(ID.of(1))
private val testRenderer: EventRenderer = object : EventRenderer {
override fun render(e: ProjectEntity, event: Event): String {
return when (e) {
is Project -> link(e.name, "project/${e.id}")
is Branch -> link(e.name, "branch/${e.id}")
is PromotionLevel -> link(e.name, "promotionLevel/${e.id}")
is ValidationStamp -> link(e.name, "validationStamp/${e.id}")
is Build -> link(e.name, "build/${e.id}")
is ValidationRun -> link("#${e.runOrder}", "validationRun/${e.id}")
else -> throw EventCannotRenderEntityException(e.entityDisplayName, e)
}
}
override fun render(valueKey: String, value: NameValue, event: Event): String =
"""<i class="$valueKey">${value.value}</i>"""
override fun renderLink(text: NameValue, link: NameValue, event: Event): String =
"""<a href="${link.value}">${text.value}</a>"""
private fun link(name: String, uri: String): String = """<a href="#/$uri">$name</a>"""
}
private fun assertEntities(e: Event, vararg types: ProjectEntityType) {
assertEquals(
types.toSet(),
e.entities.map { it.key }.toSet()
)
assertEquals(
types.toSet(),
e.entities.map { it.value.projectEntityType }.toSet()
)
}
}
| ontrack-service/src/test/java/net/nemerosa/ontrack/service/EventFactoryImplTest.kt | 1365618907 |
/**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.shell.view
import com.mycollab.vaadin.mvp.IModule
import com.mycollab.vaadin.mvp.PageView
/**
* @author MyCollab Ltd
* @since 5.0.8
*/
interface MainView : PageView {
fun display()
fun addModule(module: IModule)
}
| mycollab-web/src/main/java/com/mycollab/shell/view/MainView.kt | 1774555273 |
package net.nemerosa.ontrack.extension.av.properties.yaml
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.fasterxml.jackson.module.kotlin.readValues
import java.io.StringWriter
class Yaml {
private val yamlFactory = YAMLFactory().apply {
enable(YAMLGenerator.Feature.LITERAL_BLOCK_STYLE)
}
private val mapper = ObjectMapper(yamlFactory).apply {
registerModule(KotlinModule.Builder().build())
}
/**
* Reads some Yaml as a list of documents
*/
fun read(content: String): List<ObjectNode> {
val parser = yamlFactory.createParser(content)
return mapper
.readValues<ObjectNode>(parser)
.readAll()
}
fun write(json: List<ObjectNode>): String {
val writer = StringWriter()
json.forEach {
val generator = yamlFactory.createGenerator(writer)
generator.writeObject(it)
writer.append('\n')
}
return writer.toString()
}
} | ontrack-extension-auto-versioning/src/main/java/net/nemerosa/ontrack/extension/av/properties/yaml/Yaml.kt | 626422359 |
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.owncloud.android.databinding.PredefinedStatusBinding
import com.owncloud.android.lib.resources.users.PredefinedStatus
class PredefinedStatusListAdapter(
private val clickListener: PredefinedStatusClickListener,
val context: Context
) : RecyclerView.Adapter<PredefinedStatusViewHolder>() {
internal var list: List<PredefinedStatus> = emptyList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PredefinedStatusViewHolder {
val itemBinding = PredefinedStatusBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return PredefinedStatusViewHolder(itemBinding)
}
override fun onBindViewHolder(holder: PredefinedStatusViewHolder, position: Int) {
holder.bind(list[position], clickListener, context)
}
override fun getItemCount(): Int {
return list.size
}
}
| app/src/main/java/com/owncloud/android/ui/adapter/PredefinedStatusListAdapter.kt | 918488497 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.configurationStore.statistic.eventLog.FeatureUsageSettingsEvents
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ex.DecodeDefaultsUtil
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.openapi.components.*
import com.intellij.openapi.components.StateStorage.SaveSession
import com.intellij.openapi.components.StateStorageChooserEx.Resolution
import com.intellij.openapi.components.impl.ComponentManagerImpl
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.SaveSessionAndFile
import com.intellij.openapi.components.impl.stores.StoreUtil
import com.intellij.openapi.components.impl.stores.UnknownMacroNotification
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.InvalidDataException
import com.intellij.openapi.util.JDOMExternalizable
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import com.intellij.ui.AppUIUtil
import com.intellij.util.ArrayUtilRt
import com.intellij.util.SmartList
import com.intellij.util.SystemProperties
import com.intellij.util.containers.SmartHashSet
import com.intellij.util.containers.isNullOrEmpty
import com.intellij.util.lang.CompoundRuntimeException
import com.intellij.util.messages.MessageBus
import com.intellij.util.xmlb.XmlSerializerUtil
import gnu.trove.THashMap
import org.jdom.Element
import org.jetbrains.annotations.TestOnly
import java.io.IOException
import java.nio.file.Paths
import java.util.*
import java.util.concurrent.TimeUnit
import com.intellij.openapi.util.Pair as JBPair
internal val LOG = Logger.getInstance(ComponentStoreImpl::class.java)
internal val deprecatedComparator = Comparator<Storage> { o1, o2 ->
val w1 = if (o1.deprecated) 1 else 0
val w2 = if (o2.deprecated) 1 else 0
w1 - w2
}
private class PersistenceStateAdapter(val component: Any) : PersistentStateComponent<Any> {
override fun getState() = component
override fun loadState(state: Any) {
XmlSerializerUtil.copyBean(state, component)
}
}
private val NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD_DEFAULT = TimeUnit.MINUTES.toSeconds(4).toInt()
private var NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD = NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD_DEFAULT
@TestOnly
internal fun restoreDefaultNotRoamableComponentSaveThreshold() {
NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD = NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD_DEFAULT
}
@TestOnly
internal fun setRoamableComponentSaveThreshold(thresholdInSeconds: Int) {
NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD = thresholdInSeconds
}
abstract class ComponentStoreImpl : IComponentStore {
private val components = Collections.synchronizedMap(THashMap<String, ComponentInfo>())
internal open val project: Project?
get() = null
open val loadPolicy: StateLoadPolicy
get() = StateLoadPolicy.LOAD
override abstract val storageManager: StateStorageManager
internal fun getComponents(): Map<String, ComponentInfo> {
return components
}
override fun initComponent(component: Any, isService: Boolean) {
var componentName = ""
try {
@Suppress("DEPRECATION")
if (component is PersistentStateComponent<*>) {
componentName = initPersistenceStateComponent(component, StoreUtil.getStateSpec(component), isService)
}
else if (component is JDOMExternalizable) {
componentName = ComponentManagerImpl.getComponentName(component)
@Suppress("DEPRECATION")
initJdomExternalizable(component, componentName)
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
LOG.error("Cannot init $componentName component state", e)
return
}
}
override fun initPersistencePlainComponent(component: Any, key: String) {
initPersistenceStateComponent(PersistenceStateAdapter(component),
StateAnnotation(key, FileStorageAnnotation(StoragePathMacros.WORKSPACE_FILE, false)),
isService = false)
}
private fun initPersistenceStateComponent(component: PersistentStateComponent<*>, stateSpec: State, isService: Boolean): String {
val componentName = stateSpec.name
val info = doAddComponent(componentName, component, stateSpec)
if (initComponent(info, null, false) && isService) {
// if not service, so, component manager will check it later for all components
project?.let {
val app = ApplicationManager.getApplication()
if (!app.isHeadlessEnvironment && !app.isUnitTestMode && it.isInitialized) {
notifyUnknownMacros(this, it, componentName)
}
}
}
return componentName
}
override final fun save(readonlyFiles: MutableList<SaveSessionAndFile>, isForce: Boolean) {
val errors: MutableList<Throwable> = SmartList<Throwable>()
beforeSaveComponents(errors)
val externalizationSession = if (components.isEmpty()) null else SaveSessionProducerManager()
if (externalizationSession != null) {
saveComponents(isForce, externalizationSession, errors)
}
afterSaveComponents(errors)
try {
saveAdditionalComponents(isForce)
}
catch (e: Throwable) {
errors.add(e)
}
if (externalizationSession != null) {
doSave(externalizationSession, readonlyFiles, errors)
}
CompoundRuntimeException.throwIfNotEmpty(errors)
}
protected open fun saveAdditionalComponents(isForce: Boolean) {
}
protected open fun beforeSaveComponents(errors: MutableList<Throwable>) {
}
protected open fun afterSaveComponents(errors: MutableList<Throwable>) {
}
private fun saveComponents(isForce: Boolean, session: SaveSessionProducerManager, errors: MutableList<Throwable>): MutableList<Throwable>? {
val isUseModificationCount = Registry.`is`("store.save.use.modificationCount", true)
val names = ArrayUtilRt.toStringArray(components.keys)
Arrays.sort(names)
val timeLogPrefix = "Saving"
val timeLog = if (LOG.isDebugEnabled) StringBuilder(timeLogPrefix) else null
// well, strictly speaking each component saving takes some time, but +/- several seconds doesn't matter
val nowInSeconds: Int = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()).toInt()
for (name in names) {
val start = if (timeLog == null) 0 else System.currentTimeMillis()
try {
val info = components.get(name)!!
var currentModificationCount = -1L
if (info.isModificationTrackingSupported) {
currentModificationCount = info.currentModificationCount
if (currentModificationCount == info.lastModificationCount) {
LOG.debug { "${if (isUseModificationCount) "Skip " else ""}$name: modificationCount ${currentModificationCount} equals to last saved" }
if (isUseModificationCount) {
continue
}
}
}
if (info.lastSaved != -1) {
if (isForce || (nowInSeconds - info.lastSaved) > NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD) {
info.lastSaved = nowInSeconds
}
else {
LOG.debug { "Skip $name: was already saved in last ${TimeUnit.SECONDS.toMinutes(NOT_ROAMABLE_COMPONENT_SAVE_THRESHOLD_DEFAULT.toLong())} minutes (lastSaved ${info.lastSaved}, now: $nowInSeconds)" }
continue
}
}
commitComponent(session, info, name)
info.updateModificationCount(currentModificationCount)
}
catch (e: Throwable) {
errors.add(Exception("Cannot get $name component state", e))
}
timeLog?.let {
val duration = System.currentTimeMillis() - start
if (duration > 10) {
it.append("\n").append(name).append(" took ").append(duration).append(" ms: ").append((duration / 60000)).append(" min ").append(
((duration % 60000) / 1000)).append("sec")
}
}
}
if (timeLog != null && timeLog.length > timeLogPrefix.length) {
LOG.debug(timeLog.toString())
}
return errors
}
@TestOnly
override fun saveApplicationComponent(component: PersistentStateComponent<*>) {
val stateSpec = StoreUtil.getStateSpec(component)
LOG.info("saveApplicationComponent is called for ${stateSpec.name}")
val externalizationSession = SaveSessionProducerManager()
commitComponent(externalizationSession, ComponentInfoImpl(component, stateSpec), null)
val absolutePath = Paths.get(storageManager.expandMacros(findNonDeprecated(stateSpec.storages).path)).toAbsolutePath().toString()
runUndoTransparentWriteAction {
val errors: MutableList<Throwable> = SmartList<Throwable>()
try {
VfsRootAccess.allowRootAccess(absolutePath)
val isSomethingChanged = externalizationSession.save(errors = errors)
if (!isSomethingChanged) {
LOG.info("saveApplicationComponent is called for ${stateSpec.name} but nothing to save")
}
}
finally {
VfsRootAccess.disallowRootAccess(absolutePath)
}
CompoundRuntimeException.throwIfNotEmpty(errors)
}
}
private fun commitComponent(session: SaveSessionProducerManager, info: ComponentInfo, componentName: String?) {
val component = info.component
@Suppress("DEPRECATION")
if (component is JDOMExternalizable) {
val effectiveComponentName = componentName ?: ComponentManagerImpl.getComponentName(component)
storageManager.getOldStorage(component, effectiveComponentName, StateStorageOperation.WRITE)?.let {
session.getProducer(it)?.setState(component, effectiveComponentName, component)
}
return
}
val state = (component as PersistentStateComponent<*>).state ?: return
val stateSpec = info.stateSpec!!
val effectiveComponentName = componentName ?: stateSpec.name
val stateStorageChooser = component as? StateStorageChooserEx
val storageSpecs = getStorageSpecs(component, stateSpec, StateStorageOperation.WRITE)
for (storageSpec in storageSpecs) {
@Suppress("IfThenToElvis")
var resolution = if (stateStorageChooser == null) Resolution.DO else stateStorageChooser.getResolution(storageSpec, StateStorageOperation.WRITE)
if (resolution == Resolution.SKIP) {
continue
}
val storage = storageManager.getStateStorage(storageSpec)
if (resolution == Resolution.DO) {
resolution = storage.getResolution(component, StateStorageOperation.WRITE)
if (resolution == Resolution.SKIP) {
continue
}
}
session.getProducer(storage)?.setState(component, effectiveComponentName, if (storageSpec.deprecated || resolution == Resolution.CLEAR) null else state)
}
}
protected open fun doSave(saveSession: SaveExecutor, readonlyFiles: MutableList<SaveSessionAndFile> = arrayListOf(), errors: MutableList<Throwable>) {
saveSession.save(readonlyFiles, errors)
return
}
private fun initJdomExternalizable(@Suppress("DEPRECATION") component: JDOMExternalizable, componentName: String): String? {
doAddComponent(componentName, component, null)
if (loadPolicy != StateLoadPolicy.LOAD) {
return null
}
try {
getDefaultState(component, componentName, Element::class.java)?.let { component.readExternal(it) }
}
catch (e: Throwable) {
LOG.error(e)
}
val element = storageManager.getOldStorage(component, componentName, StateStorageOperation.READ)?.getState(component, componentName,
Element::class.java, null,
false) ?: return null
try {
component.readExternal(element)
}
catch (e: InvalidDataException) {
LOG.error(e)
return null
}
return componentName
}
private fun doAddComponent(name: String, component: Any, stateSpec: State?): ComponentInfo {
val newInfo = createComponentInfo(component, stateSpec)
val existing = components.put(name, newInfo)
if (existing != null && existing.component !== component) {
components.put(name, existing)
LOG.error("Conflicting component name '$name': ${existing.component.javaClass} and ${component.javaClass}")
return existing
}
return newInfo
}
private fun initComponent(info: ComponentInfo, changedStorages: Set<StateStorage>?, reloadData: Boolean): Boolean {
if (loadPolicy == StateLoadPolicy.NOT_LOAD) {
return false
}
@Suppress("UNCHECKED_CAST")
if (doInitComponent(info.stateSpec!!, info.component as PersistentStateComponent<Any>, changedStorages, reloadData)) {
// if component was initialized, update lastModificationCount
info.updateModificationCount()
return true
}
return false
}
private fun doInitComponent(stateSpec: State,
component: PersistentStateComponent<Any>,
changedStorages: Set<StateStorage>?,
reloadData: Boolean): Boolean {
val name = stateSpec.name
@Suppress("UNCHECKED_CAST")
val stateClass: Class<Any> = if (component is PersistenceStateAdapter) component.component::class.java as Class<Any>
else ComponentSerializationUtil.getStateClass<Any>(component.javaClass)
if (!stateSpec.defaultStateAsResource && LOG.isDebugEnabled && getDefaultState(component, name, stateClass) != null) {
LOG.error("$name has default state, but not marked to load it")
}
val defaultState = if (stateSpec.defaultStateAsResource) getDefaultState(component, name, stateClass) else null
if (loadPolicy == StateLoadPolicy.LOAD) {
val storageChooser = component as? StateStorageChooserEx
for (storageSpec in getStorageSpecs(component, stateSpec, StateStorageOperation.READ)) {
if (storageChooser?.getResolution(storageSpec, StateStorageOperation.READ) == Resolution.SKIP) {
continue
}
val storage = storageManager.getStateStorage(storageSpec)
val stateGetter = createStateGetter(isUseLoadedStateAsExistingForComponent(storage, name), storage, component, name, stateClass,
reloadData = reloadData)
var state = stateGetter.getState(defaultState)
if (state == null) {
if (changedStorages != null && changedStorages.contains(storage)) {
// state will be null if file deleted
// we must create empty (initial) state to reinit component
state = deserializeState(Element("state"), stateClass, null)!!
}
else {
FeatureUsageSettingsEvents.logDefaultConfigurationState(name, stateSpec, stateClass, project)
continue
}
}
try {
component.loadState(state)
}
finally {
val stateAfterLoad = stateGetter.close()
(stateAfterLoad ?: state).let {
FeatureUsageSettingsEvents.logConfigurationState(name, stateSpec, it, project)
}
}
return true
}
}
// we load default state even if isLoadComponentState false - required for app components (for example, at least one color scheme must exists)
if (defaultState == null) {
component.noStateLoaded()
}
else {
component.loadState(defaultState)
}
return true
}
// todo fix FacetManager
// use.loaded.state.as.existing used in upsource
private fun isUseLoadedStateAsExistingForComponent(storage: StateStorage, name: String): Boolean {
return isUseLoadedStateAsExisting(storage) &&
name != "AntConfiguration" &&
name != "ProjectModuleManager" /* why after loadState we get empty state on getState, test CMakeWorkspaceContentRootsTest */ &&
name != "FacetManager" &&
name != "ProjectRunConfigurationManager" && /* ProjectRunConfigurationManager is used only for IPR, avoid relatively cost call getState */
name != "NewModuleRootManager" /* will be changed only on actual user change, so, to speed up module loading, skip it */ &&
name != "DeprecatedModuleOptionManager" /* doesn't make sense to check it */ &&
SystemProperties.getBooleanProperty("use.loaded.state.as.existing", true)
}
protected open fun isUseLoadedStateAsExisting(storage: StateStorage): Boolean = (storage as? XmlElementStorage)?.roamingType != RoamingType.DISABLED
protected open fun getPathMacroManagerForDefaults(): PathMacroManager? = null
private fun <T : Any> getDefaultState(component: Any, componentName: String, stateClass: Class<T>): T? {
val url = DecodeDefaultsUtil.getDefaults(component, componentName) ?: return null
try {
val element = JDOMUtil.load(url)
getPathMacroManagerForDefaults()?.expandPaths(element)
return deserializeState(element, stateClass, null)
}
catch (e: Throwable) {
throw IOException("Error loading default state from $url", e)
}
}
protected open fun <T> getStorageSpecs(component: PersistentStateComponent<T>,
stateSpec: State,
operation: StateStorageOperation): List<Storage> {
val storages = stateSpec.storages
if (storages.size == 1 || component is StateStorageChooserEx) {
return storages.toList()
}
if (storages.isEmpty()) {
if (stateSpec.defaultStateAsResource) {
return emptyList()
}
throw AssertionError("No storage specified")
}
return storages.sortByDeprecated()
}
final override fun isReloadPossible(componentNames: Set<String>): Boolean = !componentNames.any { isNotReloadable(it) }
private fun isNotReloadable(name: String): Boolean {
val component = components.get(name)?.component ?: return false
return component !is PersistentStateComponent<*> || !StoreUtil.getStateSpec(component).reloadable
}
fun getNotReloadableComponents(componentNames: Collection<String>): Collection<String> {
var notReloadableComponents: MutableSet<String>? = null
for (componentName in componentNames) {
if (isNotReloadable(componentName)) {
if (notReloadableComponents == null) {
notReloadableComponents = LinkedHashSet()
}
notReloadableComponents.add(componentName)
}
}
return notReloadableComponents ?: emptySet()
}
override final fun reloadStates(componentNames: Set<String>, messageBus: MessageBus) {
runBatchUpdate(messageBus) {
reinitComponents(componentNames)
}
}
override final fun reloadState(componentClass: Class<out PersistentStateComponent<*>>) {
val stateSpec = StoreUtil.getStateSpecOrError(componentClass)
val info = components.get(stateSpec.name) ?: return
(info.component as? PersistentStateComponent<*>)?.let {
initComponent(info, emptySet(), true)
}
}
private fun reloadState(componentName: String, changedStorages: Set<StateStorage>): Boolean {
val info = components.get(componentName) ?: return false
if (info.component !is PersistentStateComponent<*>) {
return false
}
val changedStoragesEmpty = changedStorages.isEmpty()
initComponent(info, if (changedStoragesEmpty) null else changedStorages, changedStoragesEmpty)
return true
}
/**
* null if reloaded
* empty list if nothing to reload
* list of not reloadable components (reload is not performed)
*/
fun reload(changedStorages: Set<StateStorage>): Collection<String>? {
if (changedStorages.isEmpty()) {
return emptySet()
}
val componentNames = SmartHashSet<String>()
for (storage in changedStorages) {
try {
// we must update (reload in-memory storage data) even if non-reloadable component will be detected later
// not saved -> user does own modification -> new (on disk) state will be overwritten and not applied
storage.analyzeExternalChangesAndUpdateIfNeed(componentNames)
}
catch (e: Throwable) {
LOG.error(e)
}
}
if (componentNames.isEmpty) {
return emptySet()
}
val notReloadableComponents = getNotReloadableComponents(componentNames)
reinitComponents(componentNames, changedStorages, notReloadableComponents)
return if (notReloadableComponents.isEmpty()) null else notReloadableComponents
}
// used in settings repository plugin
/**
* You must call it in batch mode (use runBatchUpdate)
*/
fun reinitComponents(componentNames: Set<String>,
changedStorages: Set<StateStorage> = emptySet(),
notReloadableComponents: Collection<String> = emptySet()) {
for (componentName in componentNames) {
if (!notReloadableComponents.contains(componentName)) {
reloadState(componentName, changedStorages)
}
}
}
@TestOnly
fun removeComponent(name: String) {
components.remove(name)
}
}
internal fun executeSave(session: SaveSession, readonlyFiles: MutableList<SaveSessionAndFile>, errors: MutableList<Throwable>) {
try {
session.save()
}
catch (e: ReadOnlyModificationException) {
LOG.warn(e)
readonlyFiles.add(SaveSessionAndFile(e.session ?: session, e.file))
}
catch (e: Exception) {
errors.add(e)
}
}
private fun findNonDeprecated(storages: Array<Storage>) = storages.firstOrNull { !it.deprecated } ?: throw AssertionError(
"All storages are deprecated")
enum class StateLoadPolicy {
LOAD, LOAD_ONLY_DEFAULT, NOT_LOAD
}
internal fun Array<out Storage>.sortByDeprecated(): List<Storage> {
if (size < 2) {
return toList()
}
if (!first().deprecated) {
val othersAreDeprecated = (1 until size).any { get(it).deprecated }
if (othersAreDeprecated) {
return toList()
}
}
return sortedWith(deprecatedComparator)
}
private fun notifyUnknownMacros(store: IComponentStore, project: Project, componentName: String) {
val substitutor = store.storageManager.macroSubstitutor ?: return
val immutableMacros = substitutor.getUnknownMacros(componentName)
if (immutableMacros.isEmpty()) {
return
}
val macros = LinkedHashSet(immutableMacros)
AppUIUtil.invokeOnEdt(Runnable {
var notified: MutableList<String>? = null
val manager = NotificationsManager.getNotificationsManager()
for (notification in manager.getNotificationsOfType(UnknownMacroNotification::class.java, project)) {
if (notified == null) {
notified = SmartList<String>()
}
notified.addAll(notification.macros)
}
if (!notified.isNullOrEmpty()) {
macros.removeAll(notified!!)
}
if (macros.isEmpty()) {
return@Runnable
}
LOG.debug("Reporting unknown path macros $macros in component $componentName")
doNotify(macros, project, Collections.singletonMap(substitutor, store))
}, project.disposed)
}
interface SaveExecutor {
/**
* @return was something really saved
*/
fun save(readonlyFiles: MutableList<SaveSessionAndFile> = SmartList(), errors: MutableList<Throwable>): Boolean
}
private class SaveSessionProducerManager : SaveExecutor {
private val sessions = LinkedHashMap<StateStorage, StateStorage.SaveSessionProducer>()
fun getProducer(storage: StateStorage): StateStorage.SaveSessionProducer? {
var session = sessions.get(storage)
if (session == null) {
session = storage.createSaveSessionProducer() ?: return null
sessions.put(storage, session)
}
return session
}
override fun save(readonlyFiles: MutableList<SaveSessionAndFile>, errors: MutableList<Throwable>): Boolean {
if (sessions.isEmpty()) {
return false
}
var changed = false
for (session in sessions.values) {
val saveSession = session.createSaveSession() ?: continue
executeSave(saveSession, readonlyFiles, errors)
changed = true
}
return changed
}
} | platform/configuration-store-impl/src/ComponentStoreImpl.kt | 2879485929 |
package com.groupdocs.ui.modules.upload
import com.groupdocs.ui.config.ApplicationConfig
import com.groupdocs.ui.model.UploadResponse
import com.groupdocs.ui.util.InternalServerException
import io.javalin.Javalin
import kotlinx.coroutines.runBlocking
import org.koin.java.KoinJavaComponent.inject
import java.io.BufferedInputStream
fun Javalin.uploadModule() {
val controller: UploadController by inject(UploadController::class.java)
val appConfig: ApplicationConfig by inject(ApplicationConfig::class.java)
post("/comparison/uploadDocument") { ctx ->
val isUploadEnabled = appConfig.common.upload
if (!isUploadEnabled) {
throw InternalServerException("Files uploading is disabled!")
}
runBlocking {
val urlParam = ctx.formParam("url")
val response: UploadResponse = if (urlParam == null) {
ctx.uploadedFile("file")?.let { uploadedFile ->
BufferedInputStream(uploadedFile.content).use { inputStream ->
return@let controller.uploadDisk(uploadedFile.filename, inputStream)
}
} ?: throw InternalServerException("Incorrect request!")
} else {
controller.uploadUrl(urlParam)
}
ctx.json(response)
}
}
} | Demos/Javalin/src/main/kotlin/com/groupdocs/ui/modules/upload/UploadModule.kt | 3124320588 |
package de.xikolo.controllers.dialogs
import android.app.Dialog
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import com.yatatsu.autobundle.AutoBundleField
import de.xikolo.R
import de.xikolo.controllers.dialogs.base.BaseDialogFragment
import de.xikolo.models.Item
class OpenExternalContentDialog : BaseDialogFragment() {
companion object {
val TAG: String = OpenExternalContentDialog::class.java.simpleName
}
@AutoBundleField(required = false)
var type: String = Item.TYPE_LTI
var listener: ExternalContentDialogListener? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val message = if (type == Item.TYPE_LTI) {
getString(
R.string.dialog_external_content_message_lti,
getString(R.string.app_name)
)
} else {
getString(R.string.dialog_external_content_message_peer)
}
val yes = if (type == Item.TYPE_LTI) R.string.dialog_external_content_yes_lti else R.string.dialog_external_content_yes_peer
val yesAlways = if (type == Item.TYPE_LTI) R.string.dialog_external_content_yes_always_lti else R.string.dialog_external_content_yes_always_peer
val builder = AlertDialog.Builder(requireActivity())
builder.setMessage(message)
.setTitle(R.string.dialog_external_content_title)
.setPositiveButton(yes) { _, _ ->
listener?.onOpen(this)
}
.setNegativeButton(R.string.dialog_negative) { _, _ ->
dialog?.cancel()
}
.setNeutralButton(yesAlways) { _, _ ->
listener?.onOpenAlways(this)
}
.setCancelable(true)
val dialog = builder.create()
dialog.setCanceledOnTouchOutside(true)
return dialog
}
interface ExternalContentDialogListener {
fun onOpen(dialog: DialogFragment)
fun onOpenAlways(dialog: DialogFragment)
}
}
| app/src/main/java/de/xikolo/controllers/dialogs/OpenExternalContentDialog.kt | 3434097873 |
/*
* Created by Orchextra
*
* Copyright (C) 2017 Gigigo Mobile Services SL
*
* 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.gigigo.orchextra.core.data.datasources.network.models
data class ApiConfiguration(
val geofences: List<ApiGeofence>?,
val beaconRegions: List<ApiRegion>?,
val eddystoneRegions: List<ApiRegion>?,
val customFields: Map<String, ApiCustomField>?,
val requestWaitTime: Long?,
val vuforia: ApiVuforia?)
data class ApiGeofence(
val code: String?,
val point: ApiPoint?,
val radius: Int?,
val notifyOnEntry: Boolean?,
val notifyOnExit: Boolean?,
val stayTime: Int?)
data class ApiRegion(
val code: String?,
val uuid: String?,
val major: Int?,
val namespace: String?,
val notifyOnEntry: Boolean?,
val notifyOnExit: Boolean?)
data class ApiCustomField(
val type: String?,
val label: String?)
data class ApiVuforia(
val licenseKey: String?,
val clientAccessKey: String?,
val clientSecretKey: String?) | core/src/main/java/com/gigigo/orchextra/core/data/datasources/network/models/ApiConfiguration.kt | 3796291335 |
package com.github.mibac138.argparser.reader
import org.junit.Assert.assertNotNull
import org.junit.Test
/**
* Created by mibac138 on 10-04-2017.
*/
class ArgumentStringTest {
@Test fun testNotRequired() {
assertNotNull(ArgumentString.Companion)
}
} | core/src/test/kotlin/com/github/mibac138/argparser/reader/ArgumentStringTest.kt | 3547709999 |
package com.soywiz.korge.i18n
fun String.toTextSource(): TextSource = ConstantTextSource(this)
| korge/src/commonMain/kotlin/com/soywiz/korge/i18n/TextSourceExt.kt | 1168890524 |
package de.saschahlusiak.freebloks.network.message
import de.saschahlusiak.freebloks.network.*
import de.saschahlusiak.freebloks.utils.hexString
import de.saschahlusiak.freebloks.utils.ubyteArrayOf
import org.junit.Assert
import org.junit.Assert.assertArrayEquals
import org.junit.Test
class MessageRequestUndoTest {
@Test
fun test_marshal() {
val expected = MessageRequestUndo()
val expectedBytes = ubyteArrayOf(0x0c, 0x00, 0x05, 0x09, 0xe3)
val bytes = expected.toByteArray()
println(bytes.hexString())
assertArrayEquals(expectedBytes, bytes)
val msg = Message.from(bytes) as MessageRequestUndo
Assert.assertEquals(expected, msg)
}
}
| game/src/test/java/de/saschahlusiak/freebloks/network/message/MessageRequestUndoTest.kt | 2416308148 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.passivedata
import android.app.Application
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore
import androidx.hilt.work.HiltWorkerFactory
import androidx.work.Configuration
import com.example.passivedata.PassiveDataRepository.Companion.PREFERENCES_FILENAME
import dagger.hilt.android.HiltAndroidApp
import javax.inject.Inject
/**
* Application class, needed to enable dependency injection with Hilt. It also is used to initialize
* WorkManager.
*/
@HiltAndroidApp
class MainApplication : Application(), Configuration.Provider {
@Inject lateinit var workerFactory: HiltWorkerFactory
override fun getWorkManagerConfiguration() =
Configuration.Builder()
.setWorkerFactory(workerFactory)
.build()
}
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(PREFERENCES_FILENAME)
const val TAG = "Passive Data Sample"
| health-services/PassiveData/app/src/main/java/com/example/passivedata/MainApplication.kt | 4115564282 |
/*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.test.cache
import android.graphics.Bitmap
import android.graphics.Bitmap.Config.ARGB_8888
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.panpf.sketch.Sketch
import com.github.panpf.sketch.cache.CountBitmap
import com.github.panpf.sketch.test.utils.newSketch
import com.github.panpf.sketch.util.toHexString
import com.github.panpf.tools4j.test.ktx.assertThrow
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class CountBitmapTest {
@Test
fun testCacheKey() {
val sketch = newSketch()
createCountBitmap(sketch, "image1", 100, 100).apply {
Assert.assertEquals("image1", cacheKey)
}
createCountBitmap(sketch, "image2", 100, 100).apply {
Assert.assertEquals("image2", cacheKey)
}
}
@Test
fun testBitmap() {
val sketch = newSketch()
createCountBitmap(sketch, "image1", 100, 100).apply {
Assert.assertEquals(100, bitmap!!.width)
Assert.assertEquals(100, bitmap!!.height)
}
createCountBitmap(sketch, "image1", 120, 300).apply {
Assert.assertEquals(120, bitmap!!.width)
Assert.assertEquals(300, bitmap!!.height)
}
createCountBitmap(sketch, "image1", 120, 300).apply {
Assert.assertNotNull(bitmap)
runBlocking(Dispatchers.Main) {
setIsPending(true)
setIsPending(false)
}
Assert.assertNotNull(bitmap)
}
}
@Test
fun testIsRecycled() {
val sketch = newSketch()
createCountBitmap(sketch, "image1", 100, 100).apply {
runBlocking(Dispatchers.Main) {
Assert.assertFalse(isRecycled)
setIsDisplayed(true)
Assert.assertFalse(isRecycled)
setIsDisplayed(false)
Assert.assertTrue(isRecycled)
}
}
}
@Test
fun testByteCount() {
val sketch = newSketch()
createCountBitmap(sketch, "image1", 100, 100).apply {
runBlocking(Dispatchers.Main) {
Assert.assertEquals(100 * 100 * 4, byteCount)
setIsDisplayed(true)
Assert.assertEquals(100 * 100 * 4, byteCount)
setIsDisplayed(false)
Assert.assertEquals(0, byteCount)
}
}
}
@Test
fun testToString() {
val sketch = newSketch()
createCountBitmap(sketch, "image1", 100, 100).apply {
val bitmapLogString = "Bitmap(100x100,ARGB_8888,@${this.bitmap!!.toHexString()})"
Assert.assertEquals("CountBitmap($bitmapLogString,0/0/0,'image1')", toString())
}
createCountBitmap(sketch, "image1", 200, 100).apply {
val bitmapLogString = "Bitmap(200x100,ARGB_8888,@${this.bitmap!!.toHexString()})"
Assert.assertEquals("CountBitmap($bitmapLogString,0/0/0,'image1')", toString())
}
createCountBitmap(sketch, "image2", 100, 100).apply {
val bitmapLogString = "Bitmap(100x100,ARGB_8888,@${this.bitmap!!.toHexString()})"
Assert.assertEquals("CountBitmap($bitmapLogString,0/0/0,'image2')", toString())
}
createCountBitmap(sketch, "image2", 100, 100).apply {
runBlocking(Dispatchers.Main) {
setIsPending(true)
}
val bitmapLogString = "Bitmap(100x100,ARGB_8888,@${this.bitmap!!.toHexString()})"
Assert.assertEquals("CountBitmap($bitmapLogString,1/0/0,'image2')", toString())
}
createCountBitmap(sketch, "image2", 100, 100).apply {
setIsCached(true)
val bitmapLogString = "Bitmap(100x100,ARGB_8888,@${this.bitmap!!.toHexString()})"
Assert.assertEquals("CountBitmap($bitmapLogString,0/1/0,'image2')", toString())
}
createCountBitmap(sketch, "image2", 100, 100).apply {
runBlocking(Dispatchers.Main) {
setIsDisplayed(true)
}
val bitmapLogString = "Bitmap(100x100,ARGB_8888,@${this.bitmap!!.toHexString()})"
Assert.assertEquals("CountBitmap($bitmapLogString,0/0/1,'image2')", toString())
}
createCountBitmap(sketch, "image2", 100, 100).apply {
runBlocking(Dispatchers.Main) {
setIsPending(true)
}
setIsCached(true)
val bitmapLogString = "Bitmap(100x100,ARGB_8888,@${this.bitmap!!.toHexString()})"
Assert.assertEquals("CountBitmap($bitmapLogString,1/1/0,'image2')", toString())
}
createCountBitmap(sketch, "image2", 100, 100).apply {
runBlocking(Dispatchers.Main) {
setIsPending(true)
}
setIsCached(true)
runBlocking(Dispatchers.Main) {
setIsDisplayed(true)
}
val bitmapLogString = "Bitmap(100x100,ARGB_8888,@${this.bitmap!!.toHexString()})"
Assert.assertEquals("CountBitmap($bitmapLogString,1/1/1,'image2')", toString())
}
}
@Test
fun testSetIsDisplayed() {
val sketch = newSketch()
createCountBitmap(sketch, "image1", 100, 100).apply {
assertThrow(IllegalStateException::class) {
setIsDisplayed(true)
}
assertThrow(IllegalStateException::class) {
getDisplayedCount()
}
runBlocking(Dispatchers.Main) {
Assert.assertFalse(isRecycled)
Assert.assertEquals(0, getDisplayedCount())
setIsDisplayed(true)
Assert.assertFalse(isRecycled)
Assert.assertEquals(1, getDisplayedCount())
setIsDisplayed(true)
Assert.assertFalse(isRecycled)
Assert.assertEquals(2, getDisplayedCount())
setIsDisplayed(false)
Assert.assertFalse(isRecycled)
Assert.assertEquals(1, getDisplayedCount())
setIsDisplayed(false)
Assert.assertTrue(isRecycled)
Assert.assertEquals(0, getDisplayedCount())
setIsDisplayed(false)
Assert.assertTrue(isRecycled)
Assert.assertEquals(0, getDisplayedCount())
}
}
}
@Test
fun testSetIsCached() {
val sketch = newSketch()
createCountBitmap(sketch, "image1", 100, 100).apply {
Assert.assertFalse(isRecycled)
Assert.assertEquals(0, getCachedCount())
setIsCached(true)
Assert.assertFalse(isRecycled)
Assert.assertEquals(1, getCachedCount())
setIsCached(true)
Assert.assertFalse(isRecycled)
Assert.assertEquals(2, getCachedCount())
setIsCached(false)
Assert.assertFalse(isRecycled)
Assert.assertEquals(1, getCachedCount())
setIsCached(false)
Assert.assertTrue(isRecycled)
Assert.assertEquals(0, getCachedCount())
setIsCached(false)
Assert.assertTrue(isRecycled)
Assert.assertEquals(0, getCachedCount())
}
}
@Test
fun testSetIsPending() {
val sketch = newSketch()
createCountBitmap(sketch, "image1", 100, 100).apply {
assertThrow(IllegalStateException::class) {
setIsPending(true)
}
assertThrow(IllegalStateException::class) {
getPendingCount()
}
runBlocking(Dispatchers.Main) {
Assert.assertFalse(isRecycled)
Assert.assertEquals(0, getPendingCount())
setIsPending(true)
Assert.assertFalse(isRecycled)
Assert.assertEquals(1, getPendingCount())
setIsPending(true)
Assert.assertFalse(isRecycled)
Assert.assertEquals(2, getPendingCount())
setIsPending(false)
Assert.assertFalse(isRecycled)
Assert.assertEquals(1, getPendingCount())
setIsPending(false)
Assert.assertFalse(isRecycled)
Assert.assertEquals(0, getPendingCount())
setIsPending(false)
Assert.assertFalse(isRecycled)
Assert.assertEquals(0, getPendingCount())
}
}
}
@Test
fun testRecycled() {
val sketch = newSketch()
createCountBitmap(sketch, "image1", 100, 100).apply {
Assert.assertFalse(isRecycled)
bitmap!!.recycle()
assertThrow(IllegalStateException::class) {
setIsCached(true)
}
}
}
private fun createCountBitmap(
sketch: Sketch,
cacheKey: String,
width: Int,
height: Int,
): CountBitmap = CountBitmap(
cacheKey = cacheKey,
bitmap = Bitmap.createBitmap(width, height, ARGB_8888),
bitmapPool = sketch.bitmapPool,
disallowReuseBitmap = false,
)
} | sketch/src/androidTest/java/com/github/panpf/sketch/test/cache/CountBitmapTest.kt | 2692121707 |
package org.wikipedia.notifications
import io.reactivex.rxjava3.core.Observable
import org.wikipedia.auth.AccountUtil
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.mwapi.MwQueryResponse
import org.wikipedia.page.PageTitle
import org.wikipedia.settings.Prefs
import org.wikipedia.util.DateUtil
import java.util.*
import java.util.concurrent.TimeUnit
object AnonymousNotificationHelper {
private const val NOTIFICATION_DURATION_DAYS = 7L
fun onEditSubmitted() {
if (!AccountUtil.isLoggedIn) {
Prefs.lastAnonEditTime = Date().time
}
}
fun observableForAnonUserInfo(wikiSite: WikiSite): Observable<MwQueryResponse> {
return if (Date().time - Prefs.lastAnonEditTime < TimeUnit.DAYS.toMillis(NOTIFICATION_DURATION_DAYS)) {
ServiceFactory.get(wikiSite).userInfo
} else {
Observable.just(MwQueryResponse())
}
}
fun shouldCheckAnonNotifications(response: MwQueryResponse): Boolean {
if (isWithinAnonNotificationTime()) {
return false
}
val hasMessages = response.query?.userInfo?.messages == true
if (hasMessages) {
if (!response.query?.userInfo?.name.isNullOrEmpty()) {
Prefs.lastAnonUserWithMessages = response.query?.userInfo?.name
}
}
return hasMessages
}
fun anonTalkPageHasRecentMessage(response: MwQueryResponse, title: PageTitle): Boolean {
response.query?.firstPage()?.revisions?.firstOrNull()?.timeStamp?.let {
if (Date().time - DateUtil.iso8601DateParse(it).time < TimeUnit.DAYS.toMillis(NOTIFICATION_DURATION_DAYS)) {
Prefs.hasAnonymousNotification = true
Prefs.lastAnonNotificationTime = Date().time
Prefs.lastAnonNotificationLang = title.wikiSite.languageCode
return true
}
}
return false
}
fun isWithinAnonNotificationTime(): Boolean {
return Date().time - Prefs.lastAnonNotificationTime < TimeUnit.DAYS.toMillis(NOTIFICATION_DURATION_DAYS)
}
}
| app/src/main/java/org/wikipedia/notifications/AnonymousNotificationHelper.kt | 360426852 |
package ws.osiris.aws
import com.amazonaws.services.lambda.AWSLambda
import com.amazonaws.services.lambda.AWSLambdaClientBuilder
import com.amazonaws.services.lambda.model.InvocationType
import com.amazonaws.services.lambda.model.InvokeRequest
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent
import com.google.gson.Gson
import org.slf4j.LoggerFactory
import java.nio.ByteBuffer
import kotlin.math.pow
/**
* The number of retries if the keep-alive call fails with access denied.
*
* Retrying is necessary because policy updates aren't visible immediately after the stack is updated.
*/
private const val RETRIES = 7
/**
* Lambda that invokes other lambdas with keep-alive messages.
*
* It is triggered by a CloudWatch event containing the ARN of the lambda to keep alive and
* the number of instances that should be kept alive.
*/
class KeepAliveLambda {
private val lambdaClient: AWSLambda = AWSLambdaClientBuilder.defaultClient()
private val gson: Gson = Gson()
fun handle(trigger: KeepAliveTrigger) {
log.debug("Triggering keep-alive, count: {}, function: {}", trigger.instanceCount, trigger.functionArn)
// The lambda expects a request from API Gateway of this type - this fakes it
val requestEvent = APIGatewayProxyRequestEvent().apply {
resource = KEEP_ALIVE_RESOURCE
headers = mapOf(KEEP_ALIVE_SLEEP to trigger.sleepTimeMs.toString())
}
val json = gson.toJson(requestEvent)
val payloadBuffer = ByteBuffer.wrap(json.toByteArray())
val invokeRequest = InvokeRequest().apply {
functionName = trigger.functionArn
invocationType = InvocationType.Event.name
payload = payloadBuffer
}
/**
* Invokes multiple copies of the function, retrying if access is denied.
*
* The retry is necessary because policy updates aren't visible immediately after the stack is updated.
*/
tailrec fun invokeFunctions(attemptCount: Int = 1) {
try {
repeat(trigger.instanceCount) {
lambdaClient.invoke(invokeRequest)
}
log.debug("Keep-alive complete")
return
} catch (e: Exception) {
if (attemptCount == RETRIES) throw e
// Back off retrying - sleep for 2, 4, 8, 16, ...
val sleep = 1000L * (2.0.pow(attemptCount)).toLong()
log.debug("Exception triggering keep-alive: {} {}, sleeping for {}ms", e.javaClass.name, e.message, sleep)
Thread.sleep(sleep)
}
invokeFunctions(attemptCount + 1)
}
invokeFunctions()
}
companion object {
private val log = LoggerFactory.getLogger(KeepAliveLambda::class.java)
}
}
/**
* Message sent from the CloudWatch event to trigger keep-alive calls.
*/
class KeepAliveTrigger(var functionArn: String = "", var instanceCount: Int = 0, var sleepTimeMs: Int = 200)
| aws/src/main/kotlin/ws/osiris/aws/KeepAlive.kt | 1480414792 |
package ch.schulealtendorf.psa.web
import ch.schulealtendorf.psa.configuration.test.PsaWebMvcTest
import ch.schulealtendorf.psa.configuration.test.formContent
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
internal class UserManagementControllerTest : PsaWebMvcTest() {
@Test
internal fun getChangePasswordPageWhenUnauthorized() {
mockMvc.perform(get("/user/change-pw"))
.andExpect(status().is3xxRedirection)
}
@Test
internal fun getChangePasswordPageWhenAuthorized() {
mockMvc.perform(
get("/user/change-pw")
.with(user(ADMIN_USER))
).andExpect(status().isOk)
}
@Test
internal fun changePasswordWhenInvalidPassword() {
val form = ChangePasswordForm("pass", "pass")
mockMvc.perform(
post("/user/change-pw")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.formContent(form)
.with(user(ADMIN_USER))
).andExpect(status().is3xxRedirection)
.andExpect { assertThat(it.response.redirectedUrl).contains("/user/change-pw") }
.andExpect(flash().attributeExists("pwValidationErrors"))
}
@Test
internal fun changePasswordWhenValidPassword() {
val validPassword = "Psa123456$"
val form = ChangePasswordForm(validPassword, validPassword)
mockMvc.perform(
post("/user/change-pw")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.formContent(form)
.with(user(ADMIN_USER))
).andExpect(status().is3xxRedirection)
.andExpect { assertThat(it.response.redirectedUrl).contains("/app") }
}
}
| app/psa-web/src/test/kotlin/ch/schulealtendorf/psa/web/UserManagementControllerTest.kt | 4208590859 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.paging
import androidx.arch.core.executor.ArchTaskExecutor
import androidx.lifecycle.LiveData
import androidx.paging.LoadState.Error
import androidx.paging.LoadState.Loading
import androidx.paging.LoadType.REFRESH
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.Executor
@Suppress("DEPRECATION")
internal class LivePagedList<Key : Any, Value : Any>(
private val coroutineScope: CoroutineScope,
initialKey: Key?,
private val config: PagedList.Config,
private val boundaryCallback: PagedList.BoundaryCallback<Value>?,
private val pagingSourceFactory: () -> PagingSource<Key, Value>,
private val notifyDispatcher: CoroutineDispatcher,
private val fetchDispatcher: CoroutineDispatcher
) : LiveData<PagedList<Value>>(
InitialPagedList(
coroutineScope = coroutineScope,
notifyDispatcher = notifyDispatcher,
backgroundDispatcher = fetchDispatcher,
config = config,
initialLastKey = initialKey
)
) {
private var currentData: PagedList<Value>
private var currentJob: Job? = null
private val callback = { invalidate(true) }
private val refreshRetryCallback = Runnable { invalidate(true) }
init {
currentData = value!!
currentData.setRetryCallback(refreshRetryCallback)
}
override fun onActive() {
super.onActive()
invalidate(false)
}
private fun invalidate(force: Boolean) {
// work is already ongoing, not forcing, so skip invalidate
if (currentJob != null && !force) return
currentJob?.cancel()
currentJob = coroutineScope.launch(fetchDispatcher) {
currentData.pagingSource.unregisterInvalidatedCallback(callback)
val pagingSource = pagingSourceFactory()
pagingSource.registerInvalidatedCallback(callback)
if (pagingSource is LegacyPagingSource) {
pagingSource.setPageSize(config.pageSize)
}
withContext(notifyDispatcher) {
currentData.setInitialLoadState(REFRESH, Loading)
}
@Suppress("UNCHECKED_CAST")
val lastKey = currentData.lastKey as Key?
val params = config.toRefreshLoadParams(lastKey)
when (val initialResult = pagingSource.load(params)) {
is PagingSource.LoadResult.Invalid -> {
currentData.setInitialLoadState(
REFRESH,
LoadState.NotLoading(false)
)
pagingSource.invalidate()
}
is PagingSource.LoadResult.Error -> {
currentData.setInitialLoadState(
REFRESH,
Error(initialResult.throwable)
)
}
is PagingSource.LoadResult.Page -> {
val pagedList = PagedList.create(
pagingSource,
initialResult,
coroutineScope,
notifyDispatcher,
fetchDispatcher,
boundaryCallback,
config,
lastKey
)
onItemUpdate(currentData, pagedList)
currentData = pagedList
postValue(pagedList)
}
}
}
}
private fun onItemUpdate(previous: PagedList<Value>, next: PagedList<Value>) {
previous.setRetryCallback(null)
next.setRetryCallback(refreshRetryCallback)
}
}
/**
* Constructs a `LiveData<PagedList>`, from this [DataSource.Factory], convenience for
* [LivePagedListBuilder].
*
* No work (such as loading) is done immediately, the creation of the first [PagedList] is deferred
* until the [LiveData] is observed.
*
* @param config Paging configuration.
* @param initialLoadKey Initial load key passed to the first [PagedList] / [PagingSource].
* @param boundaryCallback The boundary callback for listening to [PagedList] load state.
* @param fetchExecutor [Executor] for fetching data from [PagingSource]s.
*
* @see LivePagedListBuilder
*/
@Suppress("DEPRECATION")
@Deprecated(
message = "PagedList is deprecated and has been replaced by PagingData",
replaceWith = ReplaceWith(
"""Pager(
PagingConfig(
config.pageSize,
config.prefetchDistance,
config.enablePlaceholders,
config.initialLoadSizeHint,
config.maxSize
),
initialLoadKey,
this.asPagingSourceFactory(fetchExecutor.asCoroutineDispatcher())
).liveData""",
"androidx.paging.Pager",
"androidx.paging.PagingConfig",
"androidx.paging.liveData",
"kotlinx.coroutines.asCoroutineDispatcher"
)
)
fun <Key : Any, Value : Any> DataSource.Factory<Key, Value>.toLiveData(
config: PagedList.Config,
initialLoadKey: Key? = null,
boundaryCallback: PagedList.BoundaryCallback<Value>? = null,
fetchExecutor: Executor = ArchTaskExecutor.getIOThreadExecutor()
): LiveData<PagedList<Value>> {
return LivePagedListBuilder(this, config)
.setInitialLoadKey(initialLoadKey)
.setBoundaryCallback(boundaryCallback)
.setFetchExecutor(fetchExecutor)
.build()
}
/**
* Constructs a `LiveData<PagedList>`, from this `DataSource.Factory`, convenience for
* [LivePagedListBuilder].
*
* No work (such as loading) is done immediately, the creation of the first [PagedList] is deferred
* until the [LiveData] is observed.
*
* @param pageSize Page size.
* @param initialLoadKey Initial load key passed to the first [PagedList] / [PagingSource].
* @param boundaryCallback The boundary callback for listening to [PagedList] load state.
* @param fetchExecutor Executor for fetching data from DataSources.
*
* @see LivePagedListBuilder
*/
@Suppress("DEPRECATION")
@Deprecated(
message = "PagedList is deprecated and has been replaced by PagingData",
replaceWith = ReplaceWith(
"""Pager(
PagingConfig(pageSize),
initialLoadKey,
this.asPagingSourceFactory(fetchExecutor.asCoroutineDispatcher())
).liveData""",
"androidx.paging.Pager",
"androidx.paging.PagingConfig",
"androidx.paging.liveData",
"kotlinx.coroutines.asCoroutineDispatcher"
)
)
fun <Key : Any, Value : Any> DataSource.Factory<Key, Value>.toLiveData(
pageSize: Int,
initialLoadKey: Key? = null,
boundaryCallback: PagedList.BoundaryCallback<Value>? = null,
fetchExecutor: Executor = ArchTaskExecutor.getIOThreadExecutor()
): LiveData<PagedList<Value>> {
return LivePagedListBuilder(this, Config(pageSize))
.setInitialLoadKey(initialLoadKey)
.setBoundaryCallback(boundaryCallback)
.setFetchExecutor(fetchExecutor)
.build()
}
/**
* Constructs a `LiveData<PagedList>`, from this PagingSource factory, convenience for
* [LivePagedListBuilder].
*
* No work (such as loading) is done immediately, the creation of the first [PagedList] is deferred
* until the [LiveData] is observed.
*
* @param config Paging configuration.
* @param initialLoadKey Initial load key passed to the first [PagedList] / [PagingSource].
* @param boundaryCallback The boundary callback for listening to [PagedList] load state.
* @param coroutineScope Set the [CoroutineScope] that page loads should be launched within. The
* set [coroutineScope] allows a [PagingSource] to cancel running load operations when the results
* are no longer needed - for example, when the containing activity is destroyed.
*
* Defaults to [GlobalScope].
* @param fetchDispatcher [CoroutineDispatcher] for fetching data from [PagingSource]s.
*
* @see LivePagedListBuilder
*/
@OptIn(DelicateCoroutinesApi::class)
@Suppress("DEPRECATION")
@Deprecated(
message = "PagedList is deprecated and has been replaced by PagingData",
replaceWith = ReplaceWith(
"""Pager(
PagingConfig(
config.pageSize,
config.prefetchDistance,
config.enablePlaceholders,
config.initialLoadSizeHint,
config.maxSize
),
initialLoadKey,
this
).liveData""",
"androidx.paging.Pager",
"androidx.paging.PagingConfig",
"androidx.paging.liveData"
)
)
fun <Key : Any, Value : Any> (() -> PagingSource<Key, Value>).toLiveData(
config: PagedList.Config,
initialLoadKey: Key? = null,
boundaryCallback: PagedList.BoundaryCallback<Value>? = null,
coroutineScope: CoroutineScope = GlobalScope,
fetchDispatcher: CoroutineDispatcher = ArchTaskExecutor.getIOThreadExecutor()
.asCoroutineDispatcher()
): LiveData<PagedList<Value>> {
return LivePagedList(
coroutineScope,
initialLoadKey,
config,
boundaryCallback,
this,
ArchTaskExecutor.getMainThreadExecutor().asCoroutineDispatcher(),
fetchDispatcher
)
}
/**
* Constructs a `LiveData<PagedList>`, from this PagingSource factory, convenience for
* [LivePagedListBuilder].
*
* No work (such as loading) is done immediately, the creation of the first [PagedList] is deferred
* until the [LiveData] is observed.
*
* @param pageSize Page size.
* @param initialLoadKey Initial load key passed to the first [PagedList] / [PagingSource].
* @param boundaryCallback The boundary callback for listening to [PagedList] load state.
* @param coroutineScope Set the [CoroutineScope] that page loads should be launched within. The
* set [coroutineScope] allows a [PagingSource] to cancel running load operations when the results
* are no longer needed - for example, when the containing activity is destroyed.
*
* Defaults to [GlobalScope].
* @param fetchDispatcher [CoroutineDispatcher] for fetching data from [PagingSource]s.
*
* @see LivePagedListBuilder
*/
@OptIn(DelicateCoroutinesApi::class)
@Suppress("DEPRECATION")
@Deprecated(
message = "PagedList is deprecated and has been replaced by PagingData",
replaceWith = ReplaceWith(
"""Pager(
PagingConfig(pageSize),
initialLoadKey,
this
).liveData""",
"androidx.paging.Pager",
"androidx.paging.PagingConfig",
"androidx.paging.liveData"
)
)
fun <Key : Any, Value : Any> (() -> PagingSource<Key, Value>).toLiveData(
pageSize: Int,
initialLoadKey: Key? = null,
boundaryCallback: PagedList.BoundaryCallback<Value>? = null,
coroutineScope: CoroutineScope = GlobalScope,
fetchDispatcher: CoroutineDispatcher = ArchTaskExecutor.getIOThreadExecutor()
.asCoroutineDispatcher()
): LiveData<PagedList<Value>> {
return LivePagedList(
coroutineScope,
initialLoadKey,
PagedList.Config.Builder().setPageSize(pageSize).build(),
boundaryCallback,
this,
ArchTaskExecutor.getMainThreadExecutor().asCoroutineDispatcher(),
fetchDispatcher
)
}
| paging/paging-runtime/src/main/java/androidx/paging/LivePagedList.kt | 806217448 |
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.tensorflow.rule.attribute
import org.nd4j.ir.OpNamespace
import org.nd4j.samediff.frameworkimport.argDescriptorType
import org.nd4j.samediff.frameworkimport.findOp
import org.nd4j.samediff.frameworkimport.ir.IRAttribute
import org.nd4j.samediff.frameworkimport.isNd4jTensorName
import org.nd4j.samediff.frameworkimport.isOutputFrameworkAttributeName
import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder
import org.nd4j.samediff.frameworkimport.process.MappingProcess
import org.nd4j.samediff.frameworkimport.rule.MappingRule
import org.nd4j.samediff.frameworkimport.rule.attribute.AttributeValueType
import org.nd4j.samediff.frameworkimport.rule.attribute.ListAttributeValueLookupToIndex
import org.nd4j.samediff.frameworkimport.tensorflow.ir.TensorflowIRAttr
import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowAttributeName
import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowTensorName
import org.nd4j.samediff.frameworkimport.tensorflow.ir.tensorflowAttributeValueTypeFor
import org.tensorflow.framework.*
@MappingRule("tensorflow","listattributevaluelookuptoindex","attribute")
class TensorflowListAttributeValueLookupToIndex(mappingNamesToPerform: Map<String, String>, transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>>) : ListAttributeValueLookupToIndex<GraphDef, OpDef, NodeDef, OpDef.AttrDef, AttrValue, TensorProto, DataType>(mappingNamesToPerform, transformerArgs) {
override fun createIRAttribute(name: String, attrDef: OpDef.AttrDef, attributeValueType: AttrValue): IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType> {
return TensorflowIRAttr(inputAttributeValue = attributeValueType, inputAttributeDef = attrDef)
}
override fun convertAttributesReverse(allInputArguments: List<OpNamespace.ArgDescriptor>, inputArgumentsToProcess: List<OpNamespace.ArgDescriptor>): List<IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType>> {
TODO("Not yet implemented")
}
override fun isInputFrameworkTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!!
return isTensorflowTensorName(name, opDef)
}
override fun isNd4jTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return isNd4jTensorName(name,nd4jOpDescriptor)
}
override fun isInputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!!
return isTensorflowAttributeName(name, opDef)
}
override fun isOutputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return isOutputFrameworkAttributeName(name,nd4jOpDescriptor)
}
override fun argDescriptorType(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): OpNamespace.ArgDescriptor.ArgType {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName())
return argDescriptorType(name,nd4jOpDescriptor)
}
override fun attributeValueTypeFor(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): AttributeValueType {
val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!!
return tensorflowAttributeValueTypeFor(attributeName = name, opDef = opDef)
}
} | nd4j/samediff-import/samediff-import-tensorflow/src/main/kotlin/org/nd4j/samediff/frameworkimport/tensorflow/rule/attribute/TensorflowListAttributeValueLookupToIndex.kt | 3761570265 |
package abi44_0_0.host.exp.exponent.modules.universal
import android.content.Context
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat
import abi44_0_0.expo.modules.interfaces.permissions.PermissionsResponseListener
import host.exp.exponent.di.NativeModuleDepsProvider
import host.exp.exponent.kernel.ExperienceKey
import host.exp.exponent.kernel.services.ExpoKernelServiceRegistry
import abi44_0_0.expo.modules.adapters.react.permissions.PermissionsService
import abi44_0_0.expo.modules.core.ModuleRegistry
import javax.inject.Inject
class ScopedPermissionsService(context: Context, val experienceKey: ExperienceKey) : PermissionsService(context) {
// This variable cannot be lateinit, cause the Location module gets permissions before this module is initialized.
@Inject
var mExpoKernelServiceRegistry: ExpoKernelServiceRegistry? = null
override fun onCreate(moduleRegistry: ModuleRegistry) {
super.onCreate(moduleRegistry)
NativeModuleDepsProvider.instance.inject(ScopedPermissionsService::class.java, this)
}
// We override this to inject scoped permissions even if the device doesn't support the runtime permissions.
override fun askForManifestPermissions(permissions: Array<out String>, listener: PermissionsResponseListener) {
delegateRequestToActivity(permissions, listener)
}
// We override this to scoped permissions in the headless mode.
override fun getManifestPermissionFromContext(permission: String): Int {
val globalPermissions = ContextCompat.checkSelfPermission(context, permission)
return mExpoKernelServiceRegistry?.permissionsKernelService?.getPermissions(globalPermissions, context.packageManager, permission, experienceKey)
?: PackageManager.PERMISSION_DENIED
}
}
| android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/universal/ScopedPermissionsService.kt | 333101610 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.toml.completion
import org.intellij.lang.annotations.Language
import org.rust.FileTreeBuilder
import org.rust.fileTree
import org.rust.lang.core.completion.RsCompletionTestBase
class RsCfgFeatureCompletionProviderTest : RsCompletionTestBase() {
fun `test simple in literal`() = doSingleCompletionByFileTree({
toml("Cargo.toml", """
[features]
foo = []
""")
rust("main.rs", """
#[cfg(feature = "/*caret*/")]
fn foo() {}
""")
}, """
#[cfg(feature = "foo")]
fn foo() {}
""")
fun `test simple without literal`() = doSingleCompletionByFileTree({
toml("Cargo.toml", """
[features]
foo = []
""")
rust("main.rs", """
#[cfg(feature = /*caret*/)]
fn foo() {}
""")
}, """
#[cfg(feature = "foo")]
fn foo() {}
""")
fun `test complex in literal`() = doSingleCompletionByFileTree({
toml("Cargo.toml", """
[features]
foo = []
bar = []
qux = []
""")
rust("main.rs", """
#[cfg(any(feature = "foo", feature = "b/*caret*/", feature = "qux"))]
fn foo() {}
""")
}, """
#[cfg(any(feature = "foo", feature = "bar", feature = "qux"))]
fn foo() {}
""")
fun `test complex without literal`() = doSingleCompletionByFileTree({
toml("Cargo.toml", """
[features]
foo = []
bar = []
qux = []
""")
rust("main.rs", """
#[cfg(any(feature = "foo", feature = b/*caret*/, feature = "qux"))]
fn foo() {}
""")
}, """
#[cfg(any(feature = "foo", feature = "bar", feature = "qux"))]
fn foo() {}
""")
private fun doSingleCompletionByFileTree(builder: FileTreeBuilder.() -> Unit, @Language("Rust") after: String) {
completionFixture.doSingleCompletionByFileTree(fileTree(builder), after, forbidAstLoading = false)
}
}
| toml/src/test/kotlin/org/rust/toml/completion/RsCfgFeatureCompletionProviderTest.kt | 2975981472 |
import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException
/**
* Created by widemos on 26/5/17.
*/
fun main(args: Array<String>) {
// Conectar
var conexion: Connection? = null
try {
val controlador = "org.sqlite.JDBC"
val cadenaconex = "jdbc:sqlite:corredores.sqlite"
Class.forName(controlador)
conexion = DriverManager.getConnection(cadenaconex)
} catch (ex: ClassNotFoundException) {
println("No se ha podido cargar el driver JDBC")
} catch (ex: SQLException) {
println("Error de conexión")
}
// Leer datos
val lista = ArrayList<Corredor>()
try {
val st = conexion?.createStatement()
val sql = "SELECT * FROM corredores"
val rs = st?.executeQuery(sql)
while (rs!!.next()) {
val c = Corredor(
rs.getLong("id"),
rs.getString("nombre"),
rs.getInt("dorsal"),
rs.getInt("categoria")
)
lista.add(c)
}
} catch (ex: SQLException) {
println("Error al recuperar los datos")
}
// Mostrar los datos
println("Recuperados: ${lista.size} registros")
for (corredor in lista) {
println(corredor)
}
// Desconectar
conexion?.close()
}
| 03_ejemplos/EjemploSQLite/src/app.kt | 2964357301 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.newProject.ui
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionToolbarPosition
import com.intellij.openapi.options.ConfigurationException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.ToolbarDecorator
import com.intellij.ui.components.JBList
import com.intellij.ui.components.Link
import com.intellij.ui.dsl.builder.Panel
import com.intellij.ui.dsl.gridLayout.VerticalAlign
import com.intellij.util.ui.JBUI
import org.rust.cargo.project.settings.ui.RustProjectSettingsPanel
import org.rust.cargo.toolchain.tools.Cargo
import org.rust.cargo.toolchain.tools.cargo
import org.rust.ide.newProject.ConfigurationData
import org.rust.ide.newProject.RsCustomTemplate
import org.rust.ide.newProject.RsGenericTemplate
import org.rust.ide.newProject.RsProjectTemplate
import org.rust.ide.newProject.state.RsUserTemplatesState
import org.rust.ide.notifications.showBalloon
import org.rust.openapiext.UiDebouncer
import org.rust.openapiext.fullWidthCell
import org.rust.stdext.unwrapOrThrow
import javax.swing.DefaultListModel
import javax.swing.JList
import javax.swing.ListSelectionModel
import kotlin.math.min
class RsNewProjectPanel(
private val showProjectTypeSelection: Boolean,
private val updateListener: (() -> Unit)? = null
) : Disposable {
private val rustProjectSettings = RustProjectSettingsPanel(updateListener = updateListener)
private val cargo: Cargo?
get() = rustProjectSettings.data.toolchain?.cargo()
private val defaultTemplates: List<RsProjectTemplate> = listOf(
RsGenericTemplate.CargoBinaryTemplate,
RsGenericTemplate.CargoLibraryTemplate,
RsCustomTemplate.ProcMacroTemplate,
RsCustomTemplate.WasmPackTemplate
)
private val userTemplates: List<RsCustomTemplate>
get() = RsUserTemplatesState.getInstance().templates.map {
RsCustomTemplate(it.name, it.url)
}
private val templateListModel: DefaultListModel<RsProjectTemplate> =
JBList.createDefaultListModel(defaultTemplates + userTemplates)
private val templateList: JBList<RsProjectTemplate> = JBList(templateListModel).apply {
selectionMode = ListSelectionModel.SINGLE_SELECTION
selectedIndex = 0
addListSelectionListener { update() }
cellRenderer = object : ColoredListCellRenderer<RsProjectTemplate>() {
override fun customizeCellRenderer(
list: JList<out RsProjectTemplate>,
value: RsProjectTemplate,
index: Int,
selected: Boolean,
hasFocus: Boolean
) {
icon = value.icon
append(value.name)
if (value is RsCustomTemplate) {
append(" ")
append(value.shortLink, SimpleTextAttributes.GRAYED_ATTRIBUTES)
}
}
}
}
private val selectedTemplate: RsProjectTemplate
get() = templateList.selectedValue
private val templateToolbar: ToolbarDecorator = ToolbarDecorator.createDecorator(templateList)
.setToolbarPosition(ActionToolbarPosition.BOTTOM)
.setPreferredSize(JBUI.size(0, 125))
.disableUpDownActions()
.setAddAction {
AddUserTemplateDialog().show()
updateTemplatesList()
}
.setRemoveAction {
val customTemplate = selectedTemplate as? RsCustomTemplate ?: return@setRemoveAction
RsUserTemplatesState.getInstance().templates
.removeIf { it.name == customTemplate.name }
updateTemplatesList()
}
.setRemoveActionUpdater { selectedTemplate !in defaultTemplates }
private var needInstallCargoGenerate = false
@Suppress("DialogTitleCapitalization")
private val downloadCargoGenerateLink = Link("Install cargo-generate using Cargo") {
val cargo = cargo ?: return@Link
object : Task.Modal(null, "Installing cargo-generate", true) {
var exitCode: Int = Int.MIN_VALUE
override fun onFinished() {
if (exitCode != 0) {
templateList.showBalloon("Failed to install cargo-generate", MessageType.ERROR, this@RsNewProjectPanel)
}
update()
}
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
cargo.installCargoGenerate(this@RsNewProjectPanel, listener = object : ProcessAdapter() {
override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) {
indicator.text = "Installing using Cargo..."
indicator.text2 = event.text.trim()
}
override fun processTerminated(event: ProcessEvent) {
exitCode = event.exitCode
}
}).unwrapOrThrow()
}
}.queue()
}.apply { isVisible = false }
private val updateDebouncer = UiDebouncer(this)
val data: ConfigurationData get() = ConfigurationData(rustProjectSettings.data, selectedTemplate)
fun attachTo(panel: Panel) = with(panel) {
rustProjectSettings.attachTo(this)
if (showProjectTypeSelection) {
groupRowsRange(title = "Project Template", indent = false) {
row {
resizableRow()
fullWidthCell(templateToolbar.createPanel())
.verticalAlign(VerticalAlign.FILL)
}
row {
cell(downloadCargoGenerateLink)
}
}
}
update()
}
fun update() {
updateDebouncer.run(
onPooledThread = {
when (selectedTemplate) {
is RsGenericTemplate -> false
is RsCustomTemplate -> cargo?.checkNeedInstallCargoGenerate() ?: false
}
},
onUiThread = { needInstall ->
downloadCargoGenerateLink.isVisible = needInstall
needInstallCargoGenerate = needInstall
updateListener?.invoke()
}
)
}
private fun updateTemplatesList() {
val index: Int = templateList.selectedIndex
with(templateListModel) {
removeAllElements()
defaultTemplates.forEach(::addElement)
userTemplates.forEach(::addElement)
}
templateList.selectedIndex = min(index, templateList.itemsCount - 1)
}
@Throws(ConfigurationException::class)
fun validateSettings() {
rustProjectSettings.validateSettings()
if (needInstallCargoGenerate) {
@Suppress("DialogTitleCapitalization")
throw ConfigurationException("cargo-generate is needed to create a project from a custom template")
}
}
override fun dispose() {
Disposer.dispose(rustProjectSettings)
}
}
| src/main/kotlin/org/rust/ide/newProject/ui/RsNewProjectPanel.kt | 1863432147 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.project.model
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.WritingAccessProvider
class RsGeneratedSourcesWritingAccessProvider(private val project: Project) : WritingAccessProvider() {
override fun requestWriting(files: Collection<VirtualFile>): Collection<VirtualFile> {
val cargoProjects = project.cargoProjects
return files.filter { cargoProjects.isGeneratedFile(it) }
}
override fun isPotentiallyWritable(file: VirtualFile): Boolean {
return !project.cargoProjects.isGeneratedFile(file)
}
}
| src/main/kotlin/org/rust/cargo/project/model/RsGeneratedSourcesWritingAccessProvider.kt | 3536335977 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.toml.inspections
import org.rust.stdext.intersects
import org.rust.toml.isDependencyKey
import org.rust.toml.stringValue
import org.toml.lang.psi.*
import org.toml.lang.psi.ext.TomlLiteralKind
import org.toml.lang.psi.ext.kind
import org.toml.lang.psi.ext.name
abstract class CargoDependencyCrateVisitor: TomlVisitor() {
abstract fun visitDependency(dependency: DependencyCrate)
override fun visitKeyValue(element: TomlKeyValue) {
val table = element.parent as? TomlTable ?: return
val depTable = DependencyTable.fromTomlTable(table) ?: return
if (depTable !is DependencyTable.General) return
val segment = element.key.segments.firstOrNull() ?: return
val name = segment.name ?: return
val value = element.value ?: return
if (value is TomlLiteral && value.kind is TomlLiteralKind.String) {
visitDependency(DependencyCrate(name, segment, mapOf("version" to value)))
} else if (value is TomlInlineTable) {
val pkg = value.getPackageKeyValue()
val (originalNameElement, originalName) = when {
pkg != null -> pkg.value to pkg.value?.stringValue
else -> segment to name
}
if (originalName != null && originalNameElement != null) {
visitDependency(DependencyCrate(originalName, originalNameElement, collectProperties(value)))
}
}
}
override fun visitTable(element: TomlTable) {
val depTable = DependencyTable.fromTomlTable(element) ?: return
if (depTable !is DependencyTable.Specific) return
visitDependency(DependencyCrate(depTable.crateName, depTable.crateNameElement, collectProperties(element)))
}
}
private fun collectProperties(owner: TomlKeyValueOwner): Map<String, TomlValue> {
return owner.entries.mapNotNull {
val name = it.key.name ?: return@mapNotNull null
val value = it.value ?: return@mapNotNull null
name to value
}.toMap()
}
data class DependencyCrate(
val crateName: String,
val crateNameElement: TomlElement,
val properties: Map<String, TomlValue>
) {
/**
* Is this crate from another source than crates.io?
*/
fun isForeign(): Boolean = properties.keys.intersects(FOREIGN_PROPERTIES)
companion object {
private val FOREIGN_PROPERTIES = listOf("git", "path", "registry")
}
}
private sealed class DependencyTable {
object General : DependencyTable()
data class Specific(val crateName: String, val crateNameElement: TomlElement) : DependencyTable()
companion object {
fun fromTomlTable(table: TomlTable): DependencyTable? {
val key = table.header.key ?: return null
val segments = key.segments
val dependencyNameIndex = segments.indexOfFirst { it.isDependencyKey }
return when {
// [dependencies], [x86.dev-dependencies], etc.
dependencyNameIndex == segments.lastIndex -> General
// [dependencies.crate]
dependencyNameIndex != -1 -> {
val pkg = table.getPackageKeyValue()
val (nameElement, name) = when {
pkg != null -> pkg.value to pkg.value?.stringValue
else -> {
val segment = segments.getOrNull(dependencyNameIndex + 1)
segment to segment?.name
}
}
if (nameElement != null && name != null) {
Specific(name, nameElement)
} else {
null
}
}
else -> null
}
}
}
}
/**
* Return the `package` key from a table, if present.
* Example:
*
* ```
* [dependencies.foo]
* <selection>package = "bar"</selection>
*
* [dependencies]
* foo = { <selection>package = "bar"</selection> }
* ```
*/
private fun TomlKeyValueOwner.getPackageKeyValue(): TomlKeyValue? = entries.firstOrNull {
it.key.segments.firstOrNull()?.name == "package"
}
| toml/src/main/kotlin/org/rust/toml/inspections/CargoDependencyCrateVisitor.kt | 2971945077 |
/*
* Copyright (C) 2017 Mantas Varnagiris.
*
* 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.
*/
package com.mvcoding.expensius.model.extensions
import com.mvcoding.expensius.model.RemoteFilter
import com.mvcoding.expensius.model.ReportPeriod
import com.mvcoding.expensius.model.ReportPeriod.MONTH
import org.joda.time.DateTimeConstants
fun anInterval(reportPeriod: ReportPeriod = MONTH) = reportPeriod.interval(System.currentTimeMillis() - DateTimeConstants.MILLIS_PER_DAY.toLong() * 30 * anInt(1000))
fun aRemoteFilter(reportPeriod: ReportPeriod = MONTH) = RemoteFilter(aUserId(), anInterval(reportPeriod))
fun RemoteFilter.withInterval(interval: org.joda.time.Interval) = copy(interval = interval) | models/src/test/kotlin/com/mvcoding/expensius/model/extensions/RemoteFilterExtensions.kt | 4131192382 |
package nl.rsdt.japp.jotial.maps.movement
import android.content.SharedPreferences
import android.graphics.BitmapFactory
import android.graphics.Color
import android.location.Location
import android.os.Bundle
import android.util.Pair
import android.view.View
import com.google.android.gms.location.LocationListener
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.LocationSource
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.gms.maps.model.PolylineOptions
import com.google.android.material.snackbar.Snackbar
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import nl.rsdt.japp.R
import nl.rsdt.japp.application.Japp
import nl.rsdt.japp.application.JappPreferences
import nl.rsdt.japp.jotial.data.bodies.AutoUpdateTaakPostBody
import nl.rsdt.japp.jotial.data.structures.area348.AutoInzittendeInfo
import nl.rsdt.japp.jotial.io.AppData
import nl.rsdt.japp.jotial.maps.deelgebied.Deelgebied
import nl.rsdt.japp.jotial.maps.locations.LocationProviderService
import nl.rsdt.japp.jotial.maps.management.MarkerIdentifier
import nl.rsdt.japp.jotial.maps.misc.AnimateMarkerTool
import nl.rsdt.japp.jotial.maps.misc.LatLngInterpolator
import nl.rsdt.japp.jotial.maps.wrapper.ICameraPosition
import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap
import nl.rsdt.japp.jotial.maps.wrapper.IMarker
import nl.rsdt.japp.jotial.maps.wrapper.IPolyline
import nl.rsdt.japp.jotial.net.apis.AutoApi
import nl.rsdt.japp.service.LocationService
import nl.rsdt.japp.service.ServiceManager
import org.acra.ktx.sendWithAcra
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.collections.ArrayList
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 2-8-2016
* Description...
*/
class MovementManager : ServiceManager.OnBindCallback<LocationService.LocationBinder>, LocationListener, SharedPreferences.OnSharedPreferenceChangeListener {
private val MAX_SIZE_LONG_TAIL = 60
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
if (key == JappPreferences.TAIL_LENGTH){
smallTailPoints.maxSize = JappPreferences.tailLength
smallTail?.points = smallTailPoints
hourTailPoints.maxSize = JappPreferences.tailLength
hourTail?.points = hourTailPoints
hourTailPoints.onremoveCallback = ::addToLongTail
}
if (key == JappPreferences.GPS_ACCURACY || key == JappPreferences.GPS_INTERVAL || key == JappPreferences.GPS_FASTEST_INTERVAL){
gpsAccuracy = JappPreferences.gpsAccuracy
fastestInterval = JappPreferences.gpsFastestInterval
locationInterval = JappPreferences.gpsInterval
request?.let {service?.removeRequest(it)}
request = LocationProviderService.LocationRequest(accuracy = gpsAccuracy, fastestInterval = fastestInterval, interval = locationInterval)
request?.let {service?.addRequest(it)}
}
}
private var gpsAccuracy = JappPreferences.gpsAccuracy
private var fastestInterval: Long = JappPreferences.gpsInterval
private var locationInterval: Long = JappPreferences.gpsFastestInterval
private var service: LocationService? = null
private var jotiMap: IJotiMap? = null
private var marker: IMarker? = null
private var smallTail: IPolyline? = null
private val smallTailPoints: TailPoints<LatLng> = TailPoints(JappPreferences.tailLength)
private var hourTail: IPolyline? = null
private val hourTailPoints: TailPoints<LatLng> = TailPoints(MAX_SIZE_LONG_TAIL)
private var bearing: Float = 0f
private var lastLocation: Location? = null
private var lastHourLocationTime: Long = System.currentTimeMillis()
private var activeSession: FollowSession? = null
private var deelgebied: Deelgebied? = null
private var snackBarView: View? = null
private var request: LocationProviderService.LocationRequest? = null
private var listener: LocationService.OnResolutionRequiredListener? = null
fun addToLongTail(location: LatLng, addedOn: Long){
if (lastHourLocationTime - addedOn > 60 * 60 * 1000){
lastHourLocationTime = addedOn
hourTailPoints.add(location)
hourTail?.points = hourTailPoints
}
}
fun setListener(listener: LocationService.OnResolutionRequiredListener) {
this.listener = listener
}
fun setSnackBarView(snackBarView: View) {
this.snackBarView = snackBarView
}
fun newSession(jotiMap: IJotiMap,before: ICameraPosition, zoom: Float, aoa: Float): FollowSession? {
if (activeSession != null) {
activeSession!!.end()
activeSession = null
}
activeSession = FollowSession(jotiMap,before, zoom, aoa)
return activeSession
}
fun onCreate(savedInstanceState: Bundle?) {
val list:ArrayList<Pair<LatLng,Long>>? = AppData.getObject<ArrayList<Pair<LatLng,Long>>>(
STORAGE_KEY,
object : TypeToken<ArrayList<Pair<LatLng,Long>>>() {}.type)
if (list != null) {
smallTailPoints.setPoints(list)
smallTail?.points = smallTailPoints
}
JappPreferences.visiblePreferences.registerOnSharedPreferenceChangeListener(this)
}
fun onSaveInstanceState(saveInstanceState: Bundle?) {
save()
}
override fun onLocationChanged(l: Location) {
Japp.lastLocation = l
var location = Japp.lastLocation?:l
var nextLocation = Japp.lastLocation?:l
do {
onNewLocation(location)
location = nextLocation
nextLocation = Japp.lastLocation?:l
} while(location != nextLocation)
}
fun onNewLocation(location: Location){
val ldeelgebied = deelgebied
if (marker != null) {
if (lastLocation != null) {
bearing = lastLocation!!.bearingTo(location)
/**
* Animate the marker to the new position
*/
AnimateMarkerTool.animateMarkerToICS(marker, LatLng(location.latitude, location.longitude), LatLngInterpolator.Linear(), 1000)
marker?.setRotation(bearing)
} else {
marker?.position = LatLng(location.latitude, location.longitude)
}
smallTailPoints.add(LatLng(location.latitude, location.longitude))
smallTail?.points = smallTailPoints
}
val refresh = if (ldeelgebied != null) {
if (!ldeelgebied.containsLocation(location)) {
true
} else {
false
}
} else {
true
}
if (refresh) {
deelgebied = Deelgebied.resolveOnLocation(location)
if (deelgebied != null && snackBarView != null) {
Snackbar.make(snackBarView!!, """Welkom in deelgebied ${deelgebied?.name}""", Snackbar.LENGTH_LONG).show()
val coordinatesSmall: List<LatLng> = smallTailPoints
smallTail?.remove()
hourTail?.remove()
smallTail = jotiMap!!.addPolyline(
PolylineOptions()
.width(3f)
.color(getTailColor()?:Color.BLUE)
.addAll(coordinatesSmall))
val coordinatesHour: List<LatLng> = smallTailPoints
hourTail = jotiMap!!.addPolyline(
PolylineOptions()
.width(3f)
.color(getTailColor()?:Color.BLUE)
.addAll(coordinatesHour))
}
}
/**
* Make the marker visible
*/
if (marker?.isVisible == false) {
marker?.isVisible = true
}
updateAutoTaak(location)
if (activeSession != null) {
activeSession!!.onLocationChanged(location)
}
lastLocation = location
}
private fun getTailColor(): Int? {
val color = deelgebied?.color
return if (color != null)
Color.rgb(255 - Color.red(color), 255 - Color.green(color), 255 - Color.blue(color))
else
null
}
private fun updateAutoTaak(location: Location) {
if (JappPreferences.autoTaak) {
val autoApi = Japp.getApi(AutoApi::class.java)
autoApi.getInfoById(JappPreferences.accountKey, JappPreferences.accountId).enqueue(object : Callback<AutoInzittendeInfo> {
override fun onFailure(call: Call<AutoInzittendeInfo>, t: Throwable) {
t.sendWithAcra()
}
override fun onResponse(call: Call<AutoInzittendeInfo>, response: Response<AutoInzittendeInfo>) {
val newTaak = """${deelgebied?.name}${Japp.getString(R.string.automatisch)}"""
if (deelgebied != null && newTaak.toLowerCase() != response.body()?.taak?.toLowerCase()) {
val body: AutoUpdateTaakPostBody = AutoUpdateTaakPostBody.default
body.setTaak(newTaak)
autoApi.updateTaak(body).enqueue(object : Callback<Void> {
override fun onFailure(call: Call<Void>, t: Throwable) {
t.sendWithAcra()
}
override fun onResponse(call: Call<Void>, response: Response<Void>) {
if (response.isSuccessful) {
Snackbar.make(snackBarView!!, """taak upgedate: ${deelgebied?.name}""", Snackbar.LENGTH_LONG).show()
}
}
})
}
}
})
}
}
override fun onBind(binder: LocationService.LocationBinder) {
val service = binder.instance
service.setListener(listener)
service.add(this)
request?.let { service.removeRequest(it) }
request = LocationProviderService.LocationRequest(accuracy = gpsAccuracy, fastestInterval = fastestInterval, interval = locationInterval)
request?.let {service.addRequest(it)}
this.service = service
}
fun postResolutionResultToService(code: Int) {
service?.handleResolutionResult(code)
}
fun requestLocationSettingRequest() {
service?.restartLocationUpdates()
}
fun onMapReady(jotiMap: IJotiMap) {
this.jotiMap = jotiMap
val identifier = MarkerIdentifier.Builder()
.setType(MarkerIdentifier.TYPE_ME)
.add("icon", R.drawable.me.toString())
.create()
marker = jotiMap.addMarker(Pair(
MarkerOptions()
.position(LatLng(52.021818, 6.059603))
.visible(false)
.flat(true)
.title(Gson().toJson(identifier)), BitmapFactory.decodeResource(Japp.instance!!.resources, R.drawable.me)))
smallTail = jotiMap.addPolyline(
PolylineOptions()
.width(3f)
.color(getTailColor()?:Color.BLUE))
hourTail = jotiMap.addPolyline(
PolylineOptions()
.width(3f)
.color(getTailColor()?:Color.BLUE))
if (smallTailPoints.isNotEmpty()) {
smallTail!!.points = smallTailPoints
val last = smallTailPoints.size - 1
marker?.position = smallTailPoints[last]
marker?.isVisible = true
}
}
inner class FollowSession(private val jotiMap: IJotiMap, private val before: ICameraPosition, zoom: Float, aoa: Float) : LocationSource.OnLocationChangedListener {
private var zoom = 19f
private var aoa = 45f
init {
this.zoom = zoom
this.aoa = aoa
/**
* Enable controls.
*/
jotiMap.uiSettings.setAllGesturesEnabled(true)
jotiMap.uiSettings.setCompassEnabled(true)
jotiMap.setOnCameraMoveStartedListener(GoogleMap.OnCameraMoveStartedListener { i ->
if (i == GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE) {
val position = jotiMap.previousCameraPosition
setZoom(position.zoom)
setAngleOfAttack(position.tilt)
}
})
}
private fun setZoom(zoom: Float) {
this.zoom = zoom
}
private fun setAngleOfAttack(aoa: Float) {
this.aoa = aoa
}
override fun onLocationChanged(location: Location) {
/**
* Animate the camera to the new position
*/
if (JappPreferences.followNorth()) {
jotiMap.cameraToLocation(true, location, zoom, aoa, 0f)
} else {
jotiMap.cameraToLocation(true, location, zoom, aoa, bearing)
}
}
fun end() {
/**
* Save the settings of the session to the release_preferences
*/
JappPreferences.followZoom = zoom
JappPreferences.setFollowAoa(aoa)
/**
* Disable controls
*/
jotiMap.uiSettings.setCompassEnabled(false)
/**
* Remove callback
*/
jotiMap.setOnCameraMoveStartedListener(null)
/**
* Move the camera to the before position
*/
//googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(before));
activeSession = null
}
}
fun onResume() {
request?.let { service?.addRequest(it) }
}
fun onPause() {
request?.let { service?.removeRequest(it) }
}
private fun save() {
val list1 = smallTailPoints.toArrayList()
val list2 = hourTailPoints.toArrayList()
val list3 = ArrayList<Pair<LatLng, Long>>()
list3.addAll(list2)
list3.addAll(list1)
list3.sortBy { it.second }
AppData.saveObjectAsJsonInBackground(list3, STORAGE_KEY)
}
fun onDestroy() {
marker?.remove()
smallTail?.remove()
smallTail = null
smallTailPoints.clear()
hourTail?.remove()
hourTailPoints.clear()
hourTail = null
if (jotiMap != null) {
jotiMap = null
}
if (marker != null) {
marker?.remove()
marker = null
}
if (lastLocation != null) {
lastLocation = null
}
if (activeSession != null) {
activeSession = null
}
if (service != null) {
service?.setListener(null)
service?.remove(this)
service = null
}
snackBarView = null
}
companion object {
private val STORAGE_KEY = "TAIL"
private val BUNDLE_KEY = "MovementManager"
}
}
class TailPoints<T>(maxSize:Int) : List<T>{
private var list: ArrayList<T> = ArrayList()
private var addedOn: MutableMap<T,Long> = HashMap()
private var currentFirst = 0
var onremoveCallback: (T, Long) -> Unit= {element, timeAdded -> }
internal var maxSize:Int = maxSize
set(value) {
rearrangeList()
if (value < list.size){
val toRemove = list.subList(value, list.size)
for (el in toRemove){
addedOn.remove(el)
}
list.removeAll(toRemove)
}
field = value
}
private fun toListIndex(tailIndex: Int):Int{
return (currentFirst + tailIndex) % maxSize
}
private fun toTailIndex(listIndex:Int ): Int{
return when {
listIndex > currentFirst -> listIndex - currentFirst
listIndex < currentFirst -> listIndex + currentFirst
else -> 0
}
}
private fun incrementCurrentFirst() {
currentFirst++
if (currentFirst >= maxSize){
currentFirst = 0
}
}
private fun rearrangeList(){
val first = list.subList(currentFirst, list.size)
val second = list.subList(0, currentFirst)
val result = ArrayList<T>()
result.addAll(first)
result.addAll(second)
currentFirst = 0
list = result
}
override fun iterator(): kotlin.collections.Iterator<T> {
return Iterator(0)
}
override val size: Int
get() = list.size
override fun contains(element: T): Boolean {
return list.contains(element)
}
override fun containsAll(elements: Collection<T>): Boolean {
return list.containsAll(elements)
}
override fun get(index: Int): T {
return list[toListIndex(index)]
}
override fun indexOf(element: T): Int {
return toTailIndex(list.indexOf(element))
}
override fun isEmpty(): Boolean {
return list.isEmpty()
}
override fun lastIndexOf(element: T): Int {
return toTailIndex(list.lastIndexOf(element))
}
override fun subList(fromIndex: Int, toIndex: Int): List<T> {
val fromIndexList = toListIndex(fromIndex)
val toIndexList = toListIndex(toIndex)
return when {
fromIndexList == toIndexList -> listOf()
fromIndexList < toIndexList -> list.subList(fromIndexList, toIndexList)
else -> {
val result = list.subList(0, toIndexList)
result.addAll(list.subList(fromIndexList, maxSize))
result
}
}
}
override fun listIterator(): ListIterator<T> {
return Iterator(0)
}
override fun listIterator(index: Int): ListIterator<T> {
return Iterator(index)
}
fun toArrayList():ArrayList<Pair<T, Long>>{
rearrangeList()
return ArrayList(list.map {Pair(it, addedOn[it]!!)})
}
fun add(element: T): Boolean {
if (list.contains(element)){
return false
}
addedOn[element] = System.currentTimeMillis()
return if (list.size < maxSize){
assert(currentFirst == 0) {currentFirst}
list.add(element)
} else {
onremoveCallback(list[currentFirst], addedOn[list[currentFirst]]!!)
addedOn.remove(list[currentFirst])
list[currentFirst] = element
incrementCurrentFirst()
true
}
}
fun clear() {
list.clear()
addedOn.clear()
currentFirst = 0
}
fun setPoints(list: List<Pair<T,Long>>) {
clear()
if (list.size <= maxSize) {
this.list.addAll(list.map { it.first })
list.forEach{ addedOn[it.first] = it.second }
}else{
val overflow = list.size - maxSize
val sublist = list.subList(overflow, list.size)
this.list.addAll(sublist.map { it.first })
sublist.forEach { addedOn[it.first] = it.second }
}
assert(this.list.size <= maxSize)
}
inner class Iterator(private var currentIndex: Int): ListIterator<T> {
override fun hasNext(): Boolean {
return currentIndex + 1 < size
}
override fun next(): T {
val nextE = get(currentIndex)
currentIndex++
return nextE
}
override fun hasPrevious(): Boolean {
return currentIndex - 1 > maxSize
}
override fun nextIndex(): Int {
return currentIndex + 1
}
override fun previous(): T {
val prevE = get(currentIndex)
currentIndex--
return prevE
}
override fun previousIndex(): Int {
return currentIndex - 1
}
}
}
| app/src/main/java/nl/rsdt/japp/jotial/maps/movement/MovementManager.kt | 3482002918 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.datastore.rxjava2
import android.annotation.SuppressLint
import android.content.Context
import androidx.datastore.core.DataMigration
import androidx.datastore.migrations.SharedPreferencesMigration
import androidx.datastore.migrations.SharedPreferencesView
import io.reactivex.Single
import kotlinx.coroutines.rx2.await
@JvmDefaultWithCompatibility
/**
* Client implemented migration interface.
**/
public interface RxSharedPreferencesMigration<T> {
/**
* Whether or not the migration should be run. This can be used to skip a read from the
* SharedPreferences.
*
* @param currentData the most recently persisted data
* @return a Single indicating whether or not the migration should be run.
*/
public fun shouldMigrate(currentData: T): Single<Boolean> {
return Single.just(true)
}
/**
* Maps SharedPreferences into T. Implementations should be idempotent
* since this may be called multiple times. See [DataMigration.migrate] for more
* information. The method accepts a SharedPreferencesView which is the view of the
* SharedPreferences to migrate from (limited to [keysToMigrate] and a T which represent
* the current data. The function must return the migrated data.
*
* If SharedPreferences is empty or does not contain any keys which you specified, this
* callback will not run.
*
* @param sharedPreferencesView the current state of the SharedPreferences
* @param currentData the most recently persisted data
* @return a Single of the updated data
*/
public fun migrate(sharedPreferencesView: SharedPreferencesView, currentData: T): Single<T>
}
/**
* RxSharedPreferencesMigrationBuilder for the RxSharedPreferencesMigration.
*/
@SuppressLint("TopLevelBuilder")
public class RxSharedPreferencesMigrationBuilder<T>
/**
* Construct a RxSharedPreferencesMigrationBuilder.
*
* @param context the Context used for getting the SharedPreferences.
* @param sharedPreferencesName the name of the SharedPreference from which to migrate.
* @param rxSharedPreferencesMigration the user implemented migration for this SharedPreference.
*/
constructor(
private val context: Context,
private val sharedPreferencesName: String,
private val rxSharedPreferencesMigration: RxSharedPreferencesMigration<T>
) {
private var keysToMigrate: Set<String>? = null
/**
* Set the list of keys to migrate. The keys will be mapped to datastore.Preferences with
* their same values. If the key is already present in the new Preferences, the key
* will not be migrated again. If the key is not present in the SharedPreferences it
* will not be migrated.
*
* This method is optional and if keysToMigrate is not set, all keys will be migrated from the
* existing SharedPreferences.
*
* @param keys the keys to migrate
* @return this
*/
@Suppress("MissingGetterMatchingBuilder")
public fun setKeysToMigrate(vararg keys: String): RxSharedPreferencesMigrationBuilder<T> =
apply {
keysToMigrate = setOf(*keys)
}
/**
* Build and return the DataMigration instance.
*
* @return the DataMigration.
*/
public fun build(): DataMigration<T> {
return if (keysToMigrate == null) {
SharedPreferencesMigration(
context = context,
sharedPreferencesName = sharedPreferencesName,
migrate = { spView, curData ->
rxSharedPreferencesMigration.migrate(spView, curData).await()
},
shouldRunMigration = { curData ->
rxSharedPreferencesMigration.shouldMigrate(curData).await()
}
)
} else {
SharedPreferencesMigration(
context = context,
sharedPreferencesName = sharedPreferencesName,
migrate = { spView, curData ->
rxSharedPreferencesMigration.migrate(spView, curData).await()
},
keysToMigrate = keysToMigrate!!,
shouldRunMigration = { curData ->
rxSharedPreferencesMigration.shouldMigrate(curData).await()
}
)
}
}
}
| datastore/datastore-rxjava2/src/main/java/androidx/datastore/rxjava2/RxSharedPreferencesMigration.kt | 726870373 |
package org.thoughtcrime.securesms.badges.self.none
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.plusAssign
import io.reactivex.rxjava3.kotlin.subscribeBy
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.components.settings.app.subscription.MonthlyDonationRepository
import org.thoughtcrime.securesms.util.livedata.Store
class BecomeASustainerViewModel(subscriptionsRepository: MonthlyDonationRepository) : ViewModel() {
private val store = Store(BecomeASustainerState())
val state: LiveData<BecomeASustainerState> = store.stateLiveData
private val disposables = CompositeDisposable()
init {
disposables += subscriptionsRepository.getSubscriptions().subscribeBy(
onError = { Log.w(TAG, "Could not load subscriptions.") },
onSuccess = { subscriptions ->
store.update {
it.copy(badge = subscriptions.firstOrNull()?.badge)
}
}
)
}
override fun onCleared() {
disposables.clear()
}
companion object {
private val TAG = Log.tag(BecomeASustainerViewModel::class.java)
}
class Factory(private val subscriptionsRepository: MonthlyDonationRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return modelClass.cast(BecomeASustainerViewModel(subscriptionsRepository))!!
}
}
}
| app/src/main/java/org/thoughtcrime/securesms/badges/self/none/BecomeASustainerViewModel.kt | 3730700405 |
/*
* 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.compose.material.ripple
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.RippleDrawable
import android.os.Build
import android.view.View
import android.view.animation.AnimationUtils
import androidx.annotation.DoNotInline
import androidx.annotation.RequiresApi
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.geometry.toRect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toAndroidRect
import androidx.compose.ui.graphics.toArgb
import java.lang.reflect.Method
/**
* Empty [View] that hosts a [RippleDrawable] as its background. This is needed as
* [RippleDrawable]s cannot currently be drawn directly to a [android.graphics.RenderNode]
* (b/184760109), so instead we rely on [View]'s internal implementation to draw to the
* background [android.graphics.RenderNode].
*
* A [RippleContainer] is used to manage and assign RippleHostViews when needed - see
* [RippleContainer.getRippleHostView].
*/
internal class RippleHostView(
context: Context
) : View(context) {
/**
* View related configuration
*/
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
setMeasuredDimension(0, 0)
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
// noop
}
override fun refreshDrawableState() {
// We don't want the View to manage the drawable state, so avoid updating the ripple's
// state (via View.mBackground) when we lose window focus, or other events.
}
/**
* A [RippleDrawable] cannot be dynamically changed between bounded / unbounded states - as a
* result we need to create a new instance when we need to draw a different type.
* Alternatively we could maintain both a bounded and unbounded instance, but we would still
* need to reset state for both, and change what the view's background is - so it doesn't
* help us out that much.
*/
private var ripple: UnprojectedRipple? = null
private var bounded: Boolean? = null
/**
* The last time in millis that we called [setRippleState], needed to ensure that we don't
* instantly fade out if [setRippleState] is called on the exact same millisecond twice.
*/
private var lastRippleStateChangeTimeMillis: Long? = null
private var resetRippleRunnable: Runnable? = null
/**
* Creates a new [UnprojectedRipple] and assigns it to [ripple].
*
* @param bounded whether the [UnprojectedRipple] is bounded (fills the bounds of the
* containing canvas, or unbounded (starts from the center of the canvas and fills outwards
* in a circle that may go outside the bounds of the canvas).
*/
private fun createRipple(bounded: Boolean) {
ripple = UnprojectedRipple(bounded).apply {
// Set the ripple to be the view's background - this will internally set the ripple's
// Drawable.Callback callback to equal this view so there is no need to manage this
// separately.
background = this
}
}
/**
* Callback invoked when the underlying [RippleDrawable] requests to be
* invalidated - this callback should end up triggering a re-draw in the owning ripple instance.
*/
private var onInvalidateRipple: (() -> Unit)? = null
/**
* Pass through any drawable invalidations to the owning ripple instance - the normal
* [View.invalidate] circuitry won't trigger a re-draw / re-composition inside of Compose out
* of the box.
*/
override fun invalidateDrawable(who: Drawable) {
onInvalidateRipple?.invoke()
}
/**
* Adds and starts drawing a ripple with the provided properties.
*
* @param onInvalidateRipple callback invoked when the ripple requests an invalidation
*/
fun addRipple(
interaction: PressInteraction.Press,
bounded: Boolean,
size: Size,
radius: Int,
color: Color,
alpha: Float,
onInvalidateRipple: () -> Unit
) {
// Create a new ripple if there is no existing ripple, or bounded has changed.
// (Since this.bounded is initialized to `null`, technically the first check isn't
// needed, but it might not survive refactoring).
if (ripple == null || bounded != this.bounded) {
createRipple(bounded)
this.bounded = bounded
}
val ripple = ripple!!
this.onInvalidateRipple = onInvalidateRipple
updateRippleProperties(size, radius, color, alpha)
if (bounded) {
// Bounded ripples should animate from the press position
ripple.setHotspot(interaction.pressPosition.x, interaction.pressPosition.y)
} else {
// Unbounded ripples should animate from the center of the ripple - in the framework
// this change in spec was never made, so they currently animate from the press
// position into a circle that starts at the center of the ripple, instead of
// starting directly at the center.
ripple.setHotspot(
ripple.bounds.centerX().toFloat(),
ripple.bounds.centerY().toFloat()
)
}
setRippleState(pressed = true)
}
/**
* Removes the most recent ripple, causing it to start the 'end' animation. Note that this is
* separate from immediately cancelling existing ripples - see [disposeRipple].
*/
fun removeRipple() {
setRippleState(pressed = false)
}
/**
* Update the underlying [RippleDrawable] with the new properties. Note that changes to
* [size] or [radius] while a ripple is animating will cause the animation to move to the UI
* thread, so it is important to also provide the correct values in [addRipple].
*/
fun updateRippleProperties(
size: Size,
radius: Int,
color: Color,
alpha: Float
) {
val ripple = ripple ?: return
// NOTE: if adding new properties here, make sure they are guarded with an equality check
// (either here or internally in RippleDrawable). Many properties invalidate the ripple when
// changed, which will lead to a call to updateRippleProperties again, which will cause
// another invalidation, etc.
ripple.trySetRadius(radius)
ripple.setColor(color, alpha)
val newBounds = size.toRect().toAndroidRect()
// Drawing the background causes the view to update the bounds of the drawable
// based on the view's bounds, so we need to adjust the view itself to match the
// canvas' bounds.
// These setters will no-op if there is no change, so no need for us to check for equality
left = newBounds.left
top = newBounds.top
right = newBounds.right
bottom = newBounds.bottom
ripple.bounds = newBounds
}
/**
* Remove existing callbacks and clear any currently drawing ripples.
*/
fun disposeRipple() {
onInvalidateRipple = null
if (resetRippleRunnable != null) {
removeCallbacks(resetRippleRunnable)
resetRippleRunnable!!.run()
} else {
ripple?.state = RestingState
}
val ripple = ripple ?: return
ripple.setVisible(false, false)
unscheduleDrawable(ripple)
}
/**
* Calls [RippleDrawable.setState] depending on [pressed]. Also makes sure that the fade out
* will not happen instantly if the enter and exit events happen to occur on the same
* millisecond.
*/
private fun setRippleState(pressed: Boolean) {
val currentTime = AnimationUtils.currentAnimationTimeMillis()
resetRippleRunnable?.let { runnable ->
removeCallbacks(runnable)
runnable.run()
}
val timeSinceLastStateChange = currentTime - (lastRippleStateChangeTimeMillis ?: 0)
// When fading out, if the exit happens on the same millisecond (as returned by
// currentAnimationTimeMillis), RippleForeground will instantly fade out without showing
// the minimum duration ripple. Handle this specific case by posting the exit event to
// make sure it is shown for its minimum time, if the last state change was recent.
// Since it is possible for currentAnimationTimeMillis to be different between here, and
// when it is called inside RippleForeground, we post for any small difference just to be
// safe.
if (!pressed && timeSinceLastStateChange < MinimumRippleStateChangeTime) {
resetRippleRunnable = Runnable {
ripple?.state = RestingState
resetRippleRunnable = null
}
postDelayed(resetRippleRunnable, ResetRippleDelayDuration)
} else {
val state = if (pressed) PressedState else RestingState
ripple?.state = state
}
lastRippleStateChangeTimeMillis = currentTime
}
companion object {
/**
* Minimum time between moving to [PressedState] and [RestingState] - for values smaller
* than this it is possible that the value of [AnimationUtils.currentAnimationTimeMillis]
* might be different between where we check in [setRippleState], and where it is checked
* inside [RippleDrawable] - so even if it appears different here, it might be the same
* value inside [RippleDrawable]. As a result if the time is smaller than this, we post
* the resting state change to be safe.
*/
private const val MinimumRippleStateChangeTime = 5L
/**
* Delay between moving to [PressedState] and [RestingState], to ensure that the move to
* [RestingState] happens on a new value for [AnimationUtils.currentAnimationTimeMillis],
* so the ripple will cleanly animate out instead of instantly cancelling.
*
* The actual value of this number doesn't matter, provided it is long enough that it is
* guaranteed to happen on another frame / value for
* [AnimationUtils.currentAnimationTimeMillis], and that it is short enough that it will
* happen before the minimum ripple duration (225ms).
*/
private const val ResetRippleDelayDuration = 50L
private val PressedState = intArrayOf(
android.R.attr.state_pressed,
android.R.attr.state_enabled
)
private val RestingState = intArrayOf()
}
}
/**
* [RippleDrawable] that always returns `false` for [isProjected], so that it will always be drawn
* in the owning [View]'s RenderNode, and not an ancestor node. This is only meaningful if the
* owning [View]'s drawing is not clipped, which it won't be in Compose, so we can always return
* `false` and just draw outside of the bounds if we need to.
*/
private class UnprojectedRipple(private val bounded: Boolean) : RippleDrawable(
// Temporary default color that we will override later
/* color */ ColorStateList.valueOf(android.graphics.Color.BLACK),
/* content */null,
// The color of the mask here doesn't matter - we just need a mask to draw the bounded ripple
// against
/* mask */ if (bounded) ColorDrawable(android.graphics.Color.WHITE) else null
) {
/**
* Store the ripple color so we can compare it later, as there is no way to get the currently
* set color on the RippleDrawable itself.
*/
private var rippleColor: Color? = null
/**
* Store the ripple radius so we can compare it later - [getRadius] is only available on M+,
* and we don't want to use reflection to read this below that.
*/
private var rippleRadius: Int? = null
/**
* Set a new [color] with [alpha] for this [RippleDrawable].
*/
fun setColor(color: Color, alpha: Float) {
val newColor = calculateRippleColor(color, alpha)
if (rippleColor != newColor) {
rippleColor = newColor
setColor(ColorStateList.valueOf(newColor.toArgb()))
}
}
private var projected = false
/**
* Return false (other than when calculating dirty bounds, see [getDirtyBounds]) to ensure
* that this [RippleDrawable] will be drawn inside the owning [View]'s RenderNode, and not an
* ancestor that supports projection.
*/
override fun isProjected(): Boolean {
return projected
}
/**
* On older API levels [isProjected] is used to control whether the dirty bounds (and hence
* how the ripple is clipped) are bounded / unbounded. Since we turn off projection for this
* ripple, if the ripple is unbounded we temporarily set isProjected to return true, so the
* super implementation will return us the correct bounds for an unbounded ripple.
*/
override fun getDirtyBounds(): Rect {
if (!bounded) {
projected = true
}
val bounds = super.getDirtyBounds()
projected = false
return bounds
}
/**
* Compat wrapper for [setRadius] which is only available on [Build.VERSION_CODES.M] and
* above. This will try to call setMaxRadius below that if possible.
*/
fun trySetRadius(radius: Int) {
if (rippleRadius != radius) {
rippleRadius = radius
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
try {
if (!setMaxRadiusFetched) {
setMaxRadiusFetched = true
setMaxRadiusMethod = RippleDrawable::class.java.getDeclaredMethod(
"setMaxRadius",
Int::class.javaPrimitiveType
)
}
setMaxRadiusMethod?.invoke(this, radius)
} catch (e: Exception) {
// Fail silently
}
} else {
MRadiusHelper.setRadius(this, radius)
}
}
}
/**
* Calculates the resulting [Color] from [color] with [alpha] applied, accounting for
* differences in [RippleDrawable]'s behavior on different API levels.
*/
private fun calculateRippleColor(color: Color, alpha: Float): Color {
// On API 21-27 the ripple animation is split into two sections - an overlay and an
// animation on top - and 50% of the original alpha is used for both. Since these sections
// don't always overlap, the actual alpha of the animation in parts can be 50% of the
// original amount, so to ensure that the contrast is correct, and make the ripple alpha
// match more closely with the provided value, we double it first.
// Note that this is also consistent with MDC behavior.
val transformedAlpha = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
alpha * 2
} else {
// Note: above 28 the ripple alpha is clamped to 50%, so this might not be the
// _actual_ alpha that is used in the ripple.
alpha
}.coerceAtMost(1f)
return color.copy(alpha = transformedAlpha)
}
/**
* Separate class to avoid verification errors for methods introduced in M.
*/
@RequiresApi(Build.VERSION_CODES.M)
private object MRadiusHelper {
/**
* Sets the [radius] for the given [ripple].
*/
@DoNotInline
fun setRadius(ripple: RippleDrawable, radius: Int) {
ripple.radius = radius
}
}
companion object {
/**
* Cache RippleDrawable#setMaxRadius to avoid retrieving it more times than necessary
*/
private var setMaxRadiusMethod: Method? = null
private var setMaxRadiusFetched = false
}
}
| compose/material/material-ripple/src/androidMain/kotlin/androidx/compose/material/ripple/RippleHostView.android.kt | 2371480316 |
/*
* 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.wear.compose.foundation
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.Placeable
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontSynthesis
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints
import kotlin.math.roundToInt
import kotlin.math.sqrt
/**
* [basicCurvedText] is a component allowing developers to easily write curved text following
* the curvature a circle (usually at the edge of a circular screen).
* [basicCurvedText] can be only created within the [CurvedLayout] since it's not a not a
* composable.
*
* @sample androidx.wear.compose.foundation.samples.CurvedAndNormalText
*
* @param text The text to display
* @param modifier The [CurvedModifier] to apply to this curved text.
* @param angularDirection Specify if the text is laid out clockwise or anti-clockwise, and if
* those needs to be reversed in a Rtl layout.
* If not specified, it will be inherited from the enclosing [curvedRow] or [CurvedLayout]
* See [CurvedDirection.Angular].
* @param overflow How visual overflow should be handled.
* @param style A @Composable factory to provide the style to use. This composable SHOULDN'T
* generate any compose nodes.
*/
public fun CurvedScope.basicCurvedText(
text: String,
modifier: CurvedModifier = CurvedModifier,
angularDirection: CurvedDirection.Angular? = null,
overflow: TextOverflow = TextOverflow.Clip,
style: @Composable () -> CurvedTextStyle = { CurvedTextStyle() }
) = add(CurvedTextChild(
text,
curvedLayoutDirection.copy(overrideAngular = angularDirection).absoluteClockwise(),
style,
overflow
), modifier)
/**
* [basicCurvedText] is a component allowing developers to easily write curved text following
* the curvature a circle (usually at the edge of a circular screen).
* [basicCurvedText] can be only created within the [CurvedLayout] since it's not a not a
* composable.
*
* @sample androidx.wear.compose.foundation.samples.CurvedAndNormalText
*
* @param text The text to display
* @param style A style to use.
* @param modifier The [CurvedModifier] to apply to this curved text.
* @param angularDirection Specify if the text is laid out clockwise or anti-clockwise, and if
* those needs to be reversed in a Rtl layout.
* If not specified, it will be inherited from the enclosing [curvedRow] or [CurvedLayout]
* See [CurvedDirection.Angular].
* @param overflow How visual overflow should be handled.
*/
public fun CurvedScope.basicCurvedText(
text: String,
style: CurvedTextStyle,
modifier: CurvedModifier = CurvedModifier,
angularDirection: CurvedDirection.Angular? = null,
overflow: TextOverflow = TextOverflow.Clip,
) = basicCurvedText(text, modifier, angularDirection, overflow) { style }
internal class CurvedTextChild(
val text: String,
val clockwise: Boolean = true,
val style: @Composable () -> CurvedTextStyle = { CurvedTextStyle() },
val overflow: TextOverflow
) : CurvedChild() {
private lateinit var delegate: CurvedTextDelegate
private lateinit var actualStyle: CurvedTextStyle
// We create a compose-ui node so that we can attach a11y info.
private lateinit var placeable: Placeable
@Composable
override fun SubComposition() {
actualStyle = DefaultCurvedTextStyles + style()
// Avoid recreating the delegate if possible, as it's expensive
delegate = remember { CurvedTextDelegate() }
delegate.UpdateFontIfNeeded(
actualStyle.fontFamily,
actualStyle.fontWeight,
actualStyle.fontStyle,
actualStyle.fontSynthesis
)
// Empty compose-ui node to attach a11y info.
Box(Modifier.semantics { contentDescription = text })
}
override fun CurvedMeasureScope.initializeMeasure(
measurables: Iterator<Measurable>
) {
delegate.updateIfNeeded(
text,
clockwise,
actualStyle.fontSize.toPx()
)
// Size the compose-ui node reasonably.
// We make the bounding rectangle sizes as the text, but cut the width (if needed) to the
// point at which the circle crosses the middle of the side
val height = delegate.textHeight.roundToInt()
val maxWidth = sqrt(height * (radius - height / 4))
val width = delegate.textWidth.coerceAtMost(maxWidth).roundToInt()
// Measure the corresponding measurable.
placeable = measurables.next().measure(Constraints(
minWidth = width, maxWidth = width, minHeight = height, maxHeight = height
))
}
override fun doEstimateThickness(maxRadius: Float): Float = delegate.textHeight
override fun doRadialPosition(
parentOuterRadius: Float,
parentThickness: Float
): PartialLayoutInfo {
val measureRadius = parentOuterRadius - delegate.baseLinePosition
return PartialLayoutInfo(
delegate.textWidth / measureRadius,
parentOuterRadius,
delegate.textHeight,
measureRadius
)
}
private var parentSweepRadians: Float = 0f
override fun doAngularPosition(
parentStartAngleRadians: Float,
parentSweepRadians: Float,
centerOffset: Offset
): Float {
this.parentSweepRadians = parentSweepRadians
return super.doAngularPosition(parentStartAngleRadians, parentSweepRadians, centerOffset)
}
override fun DrawScope.draw() {
with(delegate) {
doDraw(
layoutInfo!!,
parentSweepRadians,
overflow,
actualStyle.color,
actualStyle.background
)
}
}
override fun (Placeable.PlacementScope).placeIfNeeded() =
// clockwise doesn't matter, we have no content in placeable.
place(placeable, layoutInfo!!, parentSweepRadians, clockwise = false)
}
internal expect class CurvedTextDelegate() {
var textWidth: Float
var textHeight: Float
var baseLinePosition: Float
fun updateIfNeeded(
text: String,
clockwise: Boolean,
fontSizePx: Float
)
@Composable
fun UpdateFontIfNeeded(
fontFamily: FontFamily?,
fontWeight: FontWeight?,
fontStyle: FontStyle?,
fontSynthesis: FontSynthesis?
)
fun DrawScope.doDraw(
layoutInfo: CurvedLayoutInfo,
parentSweepRadians: Float,
overflow: TextOverflow,
color: Color,
background: Color
)
}
| wear/compose/compose-foundation/src/commonMain/kotlin/androidx/wear/compose/foundation/BasicCurvedText.kt | 854912142 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.glfw.templates
import org.lwjgl.generator.*
import org.lwjgl.glfw.*
import org.lwjgl.system.macosx.*
val GLFWNativeNSGL = "GLFWNativeNSGL".nativeClass(packageName = GLFW_PACKAGE, nativeSubPath = "macosx", prefix = "GLFW", binding = GLFW_BINDING_DELEGATE) {
documentation = "Native bindings to the GLFW library's NSGL native access functions."
id(
"GetNSGLContext",
"""
Returns the ${code("NSOpenGLContext")} of the specified GLFW window.
Note: This function may be called from any thread. Access is not synchronized.
""",
GLFWwindow.IN("window", "the GLFW window"),
returnDoc = "The ${code("NSOpenGLContext")} of the specified window, or nil if an error occurred.",
since = "version 3.0"
)
} | modules/templates/src/main/kotlin/org/lwjgl/glfw/templates/GLFWNativeNSGL.kt | 2121983647 |
package org.edx.mobile.view
import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import org.edx.mobile.BuildConfig.VERSION_NAME
import org.edx.mobile.R
import org.edx.mobile.base.BaseFragment
import org.edx.mobile.databinding.FragmentCourseDatesPageBinding
import org.edx.mobile.exception.ErrorMessage
import org.edx.mobile.http.HttpStatus
import org.edx.mobile.http.HttpStatusException
import org.edx.mobile.http.notifications.FullScreenErrorNotification
import org.edx.mobile.http.notifications.SnackbarErrorNotification
import org.edx.mobile.interfaces.OnDateBlockListener
import org.edx.mobile.model.CourseDatesCalendarSync
import org.edx.mobile.model.api.EnrolledCoursesResponse
import org.edx.mobile.model.course.CourseBannerInfoModel
import org.edx.mobile.model.course.CourseComponent
import org.edx.mobile.module.analytics.Analytics
import org.edx.mobile.util.*
import org.edx.mobile.view.adapters.CourseDatesAdapter
import org.edx.mobile.view.dialog.AlertDialogFragment
import org.edx.mobile.viewModel.CourseDateViewModel
import org.edx.mobile.viewModel.ViewModelFactory
class CourseDatesPageFragment : OfflineSupportBaseFragment(), BaseFragment.PermissionListener {
private lateinit var errorNotification: FullScreenErrorNotification
private lateinit var binding: FragmentCourseDatesPageBinding
private lateinit var viewModel: CourseDateViewModel
private var onDateItemClick: OnDateBlockListener = object : OnDateBlockListener {
override fun onClick(link: String, blockId: String) {
val component = courseManager.getComponentByIdFromAppLevelCache(courseData.courseId, blockId)
if (blockId.isNotEmpty() && component != null) {
environment.router.showCourseUnitDetail(this@CourseDatesPageFragment,
REQUEST_SHOW_COURSE_UNIT_DETAIL, courseData, null, blockId, false)
environment.analyticsRegistry.trackDatesCourseComponentTapped(courseData.courseId, component.id, component.type.toString().toLowerCase(), link)
} else {
showOpenInBrowserDialog(link)
if (blockId.isNotEmpty()) {
environment.analyticsRegistry.trackUnsupportedComponentTapped(courseData.courseId, blockId, link)
}
}
}
}
private var courseData: EnrolledCoursesResponse = EnrolledCoursesResponse()
private var isSelfPaced: Boolean = true
private var isDeepLinkEnabled: Boolean = false
private lateinit var calendarTitle: String
private lateinit var accountName: String
private lateinit var keyValMap: Map<String, CharSequence>
private var isCalendarExist: Boolean = false
private lateinit var loaderDialog: AlertDialogFragment
companion object {
@JvmStatic
fun makeArguments(courseData: EnrolledCoursesResponse): Bundle {
val courseBundle = Bundle()
courseBundle.putSerializable(Router.EXTRA_COURSE_DATA, courseData)
return courseBundle
}
}
override fun isShowingFullScreenError(): Boolean {
return errorNotification.isShowing
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_course_dates_page, container, false)
return binding.root
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_SHOW_COURSE_UNIT_DETAIL && resultCode == Activity.RESULT_OK
&& data != null) {
val outlineComp: CourseComponent? = courseManager.getCourseDataFromAppLevelCache(courseData.courseId)
outlineComp?.let {
navigateToCourseUnit(data, courseData, outlineComp)
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
permissionListener = this
viewModel = ViewModelProvider(this, ViewModelFactory()).get(CourseDateViewModel::class.java)
courseData = arguments?.getSerializable(Router.EXTRA_COURSE_DATA) as EnrolledCoursesResponse
isSelfPaced = courseData.course.isSelfPaced
calendarTitle = CalendarUtils.getCourseCalendarTitle(environment, courseData.course.name)
accountName = CalendarUtils.getUserAccountForSync(environment)
keyValMap = mapOf(
AppConstants.PLATFORM_NAME to environment.config.platformName,
AppConstants.COURSE_NAME to calendarTitle
)
errorNotification = FullScreenErrorNotification(binding.swipeContainer)
loaderDialog = AlertDialogFragment.newInstance(R.string.title_syncing_calendar, R.layout.alert_dialog_progress)
binding.swipeContainer.setOnRefreshListener {
// Hide the progress bar as swipe layout has its own progress indicator
binding.loadingIndicator.loadingIndicator.visibility = View.GONE
errorNotification.hideError()
viewModel.fetchCourseDates(courseID = courseData.courseId, forceRefresh = true, showLoader = false, isSwipeRefresh = true)
}
UiUtils.setSwipeRefreshLayoutColors(binding.swipeContainer)
initObserver()
}
override fun onResume() {
super.onResume()
viewModel.fetchCourseDates(courseID = courseData.courseId, forceRefresh = false, showLoader = true, isSwipeRefresh = false)
}
private fun initObserver() {
viewModel.showLoader.observe(viewLifecycleOwner, Observer { showLoader ->
binding.loadingIndicator.loadingIndicator.visibility = if (showLoader) View.VISIBLE else View.GONE
})
viewModel.bannerInfo.observe(viewLifecycleOwner, Observer {
initDatesBanner(it)
})
viewModel.syncLoader.observe(viewLifecycleOwner, Observer { syncLoader ->
if (syncLoader) {
loaderDialog.isCancelable = false
loaderDialog.showNow(childFragmentManager, null)
} else {
checkIfCalendarExists()
dismissLoader()
}
})
viewModel.courseDates.observe(viewLifecycleOwner, Observer { dates ->
if (dates.courseDateBlocks.isNullOrEmpty()) {
viewModel.setError(ErrorMessage.COURSE_DATES_CODE, HttpStatus.NO_CONTENT, getString(R.string.course_dates_unavailable_message))
} else {
dates.organiseCourseDates()
binding.rvDates.apply {
layoutManager = LinearLayoutManager(context)
adapter = CourseDatesAdapter(dates.courseDatesMap, onDateItemClick)
}
val outdatedCalenderId = CalendarUtils.isCalendarOutOfDate(
requireContext(),
accountName,
calendarTitle,
dates.courseDateBlocks
)
if (outdatedCalenderId != -1L) {
showCalendarOutOfDateDialog(outdatedCalenderId)
}
}
})
viewModel.resetCourseDates.observe(viewLifecycleOwner, Observer { resetCourseDates ->
if (resetCourseDates != null) {
if (!CalendarUtils.isCalendarExists(contextOrThrow, accountName, calendarTitle)) {
showShiftDateSnackBar(true)
}
}
})
viewModel.errorMessage.observe(viewLifecycleOwner, Observer { errorMsg ->
if (errorMsg != null) {
if (errorMsg.throwable is HttpStatusException) {
when (errorMsg.throwable.statusCode) {
HttpStatus.UNAUTHORIZED -> {
environment.router?.forceLogout(contextOrThrow,
environment.analyticsRegistry,
environment.notificationDelegate)
return@Observer
}
else ->
errorNotification.showError(contextOrThrow, errorMsg.throwable, -1, null)
}
} else {
when (errorMsg.errorCode) {
ErrorMessage.COURSE_DATES_CODE ->
errorNotification.showError(contextOrThrow, errorMsg.throwable, -1, null)
ErrorMessage.BANNER_INFO_CODE ->
initDatesBanner(null)
ErrorMessage.COURSE_RESET_DATES_CODE ->
showShiftDateSnackBar(false)
}
}
}
})
viewModel.swipeRefresh.observe(viewLifecycleOwner, Observer { enableSwipeListener ->
binding.swipeContainer.isRefreshing = enableSwipeListener
})
}
private fun showCalendarOutOfDateDialog(calendarId: Long) {
val alertDialogFragment = AlertDialogFragment.newInstance(getString(R.string.title_calendar_out_of_date),
getString(R.string.message_calendar_out_of_date),
getString(R.string.label_update_now),
{ _: DialogInterface?, _: Int ->
trackCalendarEvent(Analytics.Events.CALENDAR_SYNC_UPDATE, Analytics.Values.CALENDAR_SYNC_UPDATE)
val newCalId = CalendarUtils.createOrUpdateCalendar(
context = contextOrThrow,
accountName = accountName,
calendarTitle = calendarTitle
)
viewModel.addOrUpdateEventsInCalendar(
contextOrThrow,
newCalId,
courseData.courseId,
courseData.course.name,
isDeepLinkEnabled,
true
)
},
getString(R.string.label_remove_course_calendar),
{ _: DialogInterface?, _: Int ->
trackCalendarEvent(Analytics.Events.CALENDAR_SYNC_REMOVE, Analytics.Values.CALENDAR_SYNC_REMOVE)
deleteCalendar(calendarId)
binding.switchSync.isChecked = false
})
alertDialogFragment.isCancelable = false
alertDialogFragment.show(childFragmentManager, null)
}
/**
* Initialized dates info banner on CourseDatesPageFragment
*
* @param courseBannerInfo object of course deadline info
*/
private fun initDatesBanner(courseBannerInfo: CourseBannerInfoModel?) {
if (courseBannerInfo == null || courseBannerInfo.hasEnded) {
binding.banner.containerLayout.visibility = View.GONE
binding.syncCalendarContainer.visibility = View.GONE
return
}
ConfigUtil.checkCalendarSyncEnabled(environment.config, object : ConfigUtil.OnCalendarSyncListener {
override fun onCalendarSyncResponse(response: CourseDatesCalendarSync) {
if (!response.disabledVersions.contains(VERSION_NAME) && ((response.isSelfPlacedEnable && isSelfPaced) || (response.isInstructorPlacedEnable && !isSelfPaced))) {
binding.syncCalendarContainer.visibility = View.VISIBLE
isDeepLinkEnabled = response.isDeepLinkEnabled
initializedSyncContainer()
}
}
})
CourseDateUtil.setupCourseDatesBanner(view = binding.banner.root, isCourseDatePage = true, courseId = courseData.courseId,
enrollmentMode = courseData.mode, isSelfPaced = isSelfPaced, screenName = Analytics.Screens.PLS_COURSE_DATES,
analyticsRegistry = environment.analyticsRegistry, courseBannerInfoModel = courseBannerInfo,
clickListener = View.OnClickListener { viewModel.resetCourseDatesBanner(courseID = courseData.courseId) })
}
private fun initializedSyncContainer() {
checkIfCalendarExists()
binding.switchSync.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
if (!CalendarUtils.permissions.any { permission -> PermissionsUtil.checkPermissions(permission, contextOrThrow) }) {
askCalendarPermission()
} else if (isCalendarExist.not()) {
askForCalendarSync()
}
} else if (CalendarUtils.hasPermissions(context = contextOrThrow)) {
val calendarId = CalendarUtils.getCalendarId(context = contextOrThrow, accountName = accountName, calendarTitle = calendarTitle)
if (calendarId != -1L) {
askCalendarRemoveDialog(calendarId)
}
}
trackCalendarEvent(if (isChecked) Analytics.Events.CALENDAR_TOGGLE_ON else Analytics.Events.CALENDAR_TOGGLE_OFF,
if (isChecked) Analytics.Values.CALENDAR_TOGGLE_ON else Analytics.Values.CALENDAR_TOGGLE_OFF)
}
}
private fun checkIfCalendarExists() {
isCalendarExist = CalendarUtils.isCalendarExists(context = contextOrThrow, accountName = accountName, calendarTitle = calendarTitle)
binding.switchSync.isChecked = isCalendarExist
}
private fun askCalendarPermission() {
val title: String = ResourceUtil.getFormattedString(resources, R.string.title_request_calendar_permission, AppConstants.PLATFORM_NAME, environment.config.platformName).toString()
val message: String = ResourceUtil.getFormattedString(resources, R.string.message_request_calendar_permission, AppConstants.PLATFORM_NAME, environment.config.platformName).toString()
val alertDialog = AlertDialogFragment.newInstance(title, message, getString(R.string.label_ok),
{ _: DialogInterface, _: Int ->
PermissionsUtil.requestPermissions(PermissionsUtil.CALENDAR_PERMISSION_REQUEST, CalendarUtils.permissions, this@CourseDatesPageFragment)
},
getString(R.string.label_do_not_allow),
{ _: DialogInterface?, _: Int ->
trackCalendarEvent(Analytics.Events.CALENDAR_ACCESS_DONT_ALLOW, Analytics.Values.CALENDAR_ACCESS_DONT_ALLOW)
binding.switchSync.isChecked = false
})
alertDialog.isCancelable = false
alertDialog.show(childFragmentManager, null)
}
private fun askForCalendarSync() {
val title: String = ResourceUtil.getFormattedString(resources, R.string.title_add_course_calendar, AppConstants.COURSE_NAME, calendarTitle).toString()
val message: String = ResourceUtil.getFormattedString(resources, R.string.message_add_course_calendar, keyValMap).toString()
val alertDialog = AlertDialogFragment.newInstance(title, message, getString(R.string.label_ok),
{ _: DialogInterface, _: Int ->
trackCalendarEvent(Analytics.Events.CALENDAR_ADD_OK, Analytics.Values.CALENDAR_ADD_OK)
insertCalendarEvent()
},
getString(R.string.label_cancel),
{ _: DialogInterface?, _: Int ->
trackCalendarEvent(Analytics.Events.CALENDAR_ADD_CANCEL, Analytics.Values.CALENDAR_ADD_CANCEL)
binding.switchSync.isChecked = false
})
alertDialog.isCancelable = false
alertDialog.show(childFragmentManager, null)
}
private fun showShiftDateSnackBar(isSuccess: Boolean) {
val snackbarErrorNotification = SnackbarErrorNotification(binding.root)
snackbarErrorNotification.showError(
if (isSuccess) R.string.assessment_shift_dates_success_msg else R.string.course_dates_reset_unsuccessful,
0, 0, SnackbarErrorNotification.COURSE_DATE_MESSAGE_DURATION, null)
environment.analyticsRegistry.trackPLSCourseDatesShift(courseData.courseId, courseData.mode, Analytics.Screens.PLS_COURSE_DATES, isSuccess)
}
private fun insertCalendarEvent() {
val calendarId: Long = CalendarUtils.createOrUpdateCalendar(
context = contextOrThrow,
accountName = accountName,
calendarTitle = calendarTitle
)
// if app unable to create the Calendar for the course
if (calendarId == -1L) {
Toast.makeText(
contextOrThrow,
getString(R.string.adding_calendar_error_message),
Toast.LENGTH_SHORT
).show()
binding.switchSync.isChecked = false
return
}
viewModel.addOrUpdateEventsInCalendar(
contextOrThrow,
calendarId,
courseData.courseId,
courseData.course.name,
isDeepLinkEnabled,
false
)
}
private fun dismissLoader() {
loaderDialog.dismiss()
if (viewModel.areEventsUpdated) {
showCalendarUpdatedSnackbar()
trackCalendarEvent(
Analytics.Events.CALENDAR_UPDATE_SUCCESS,
Analytics.Values.CALENDAR_UPDATE_SUCCESS
)
} else {
calendarAddedSuccessDialog()
trackCalendarEvent(
Analytics.Events.CALENDAR_ADD_SUCCESS,
Analytics.Values.CALENDAR_ADD_SUCCESS
)
}
}
private fun calendarAddedSuccessDialog() {
isCalendarExist = true
if (environment.courseCalendarPrefs.isSyncAlertPopupDisabled(courseData.course.name.replace(" ", "_"))) {
showAddCalendarSuccessSnackbar()
} else {
environment.courseCalendarPrefs.setSyncAlertPopupDisabled(courseData.course.name.replace(" ", "_"), true)
val message: String = ResourceUtil.getFormattedString(resources, R.string.message_for_alert_after_course_calendar_added, AppConstants.COURSE_NAME, calendarTitle).toString()
AlertDialogFragment.newInstance(null, message, getString(R.string.label_done),
{ _: DialogInterface, _: Int ->
trackCalendarEvent(Analytics.Events.CALENDAR_CONFIRMATION_DONE, Analytics.Values.CALENDAR_CONFIRMATION_DONE)
},
getString(R.string.label_view_events),
{ _: DialogInterface?, _: Int ->
trackCalendarEvent(Analytics.Events.CALENDAR_VIEW_EVENTS, Analytics.Values.CALENDAR_VIEW_EVENTS)
CalendarUtils.openCalendarApp(this)
}).show(childFragmentManager, null)
}
}
private fun showAddCalendarSuccessSnackbar() {
val snackbarErrorNotification = SnackbarErrorNotification(binding.root)
snackbarErrorNotification.showError(R.string.message_after_course_calendar_added,
0, R.string.label_close, SnackbarErrorNotification.COURSE_DATE_MESSAGE_DURATION) { snackbarErrorNotification.hideError() }
}
private fun askCalendarRemoveDialog(calendarId: Long) {
val title: String = ResourceUtil.getFormattedString(resources, R.string.title_remove_course_calendar, AppConstants.COURSE_NAME, calendarTitle).toString()
val message: String = ResourceUtil.getFormattedString(resources, R.string.message_remove_course_calendar, keyValMap).toString()
val alertDialog = AlertDialogFragment.newInstance(title, message, getString(R.string.label_remove),
{ _: DialogInterface, _: Int ->
trackCalendarEvent(Analytics.Events.CALENDAR_REMOVE_OK, Analytics.Values.CALENDAR_REMOVE_OK)
deleteCalendar(calendarId)
},
getString(R.string.label_cancel),
{ _: DialogInterface?, _: Int ->
trackCalendarEvent(Analytics.Events.CALENDAR_REMOVE_CANCEL, Analytics.Values.CALENDAR_REMOVE_CANCEL)
binding.switchSync.isChecked = true
})
alertDialog.isCancelable = false
alertDialog.show(childFragmentManager, null)
}
private fun deleteCalendar(calendarId: Long) {
CalendarUtils.deleteCalendar(context = contextOrThrow, calendarId = calendarId)
isCalendarExist = false
showCalendarRemovedSnackbar()
trackCalendarEvent(Analytics.Events.CALENDAR_REMOVE_SUCCESS, Analytics.Values.CALENDAR_REMOVE_SUCCESS)
}
private fun showOpenInBrowserDialog(link: String) {
AlertDialogFragment.newInstance(null, getString(R.string.assessment_not_available),
getString(R.string.assessment_view_on_web), { _: DialogInterface, _: Int -> BrowserUtil.open(activity, link, true) },
getString(R.string.label_cancel), null).show(childFragmentManager, null)
}
override fun onPermissionGranted(permissions: Array<out String>?, requestCode: Int) {
askForCalendarSync()
trackCalendarEvent(Analytics.Events.CALENDAR_ACCESS_OK, Analytics.Values.CALENDAR_ACCESS_OK)
}
override fun onPermissionDenied(permissions: Array<out String>?, requestCode: Int) {
binding.switchSync.isChecked = false
trackCalendarEvent(Analytics.Events.CALENDAR_ACCESS_DONT_ALLOW, Analytics.Values.CALENDAR_ACCESS_DONT_ALLOW)
}
private fun trackCalendarEvent(eventName: String, biValue: String) {
environment.analyticsRegistry.trackCalendarEvent(
eventName,
biValue,
courseData.courseId,
courseData.mode,
isSelfPaced,
viewModel.getSyncingCalendarTime()
)
viewModel.resetSyncingCalendarTime()
}
}
| OpenEdXMobile/src/main/java/org/edx/mobile/view/CourseDatesPageFragment.kt | 2789846478 |
package com.felipecosta.microservice.server.pagecontroller
import com.felipecosta.microservice.server.Request
import com.felipecosta.microservice.server.renderer.Renderer
import com.felipecosta.microservice.server.renderer.impl.DefaultRenderer
abstract class PageController(private val renderer: Renderer = DefaultRenderer()) {
var output: String = ""
abstract fun doGet(request: Request)
fun render(output: Any = emptyMap<String, Any>(), template: String = "", text: String = "") {
this.output = if (text.isNotBlank()) text else renderer.render(output, template)
}
}
| server/src/main/kotlin/com/felipecosta/microservice/server/pagecontroller/PageController.kt | 4068937403 |
package com.felipecosta.microservice.server
import com.felipecosta.microservice.server.frontcontroller.FrontCommand
import com.felipecosta.microservice.server.renderer.Renderer
import com.felipecosta.microservice.server.renderer.impl.DefaultRenderer
import io.mockk.clearAllMocks
import io.mockk.mockk
import io.mockk.slot
import io.mockk.verify
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import kotlin.test.assertEquals
import kotlin.test.assertTrue
@TestInstance(value = TestInstance.Lifecycle.PER_CLASS)
class ServerPutActionTest {
private val putHandlerSlotCaptor = slot<PutHandler<FrontCommand>>()
private val mockFrontCommand = mockk<FrontCommand>(relaxed = true)
private val mockServerHandler = mockk<ServerHandler>(relaxed = true)
private val mockRenderer = mockk<Renderer>(relaxed = true)
@BeforeEach
fun setUp() {
clearAllMocks()
}
@Test
fun givenServerItShouldAssertEmptyServerHandler() {
val serviceHandler = server {
}.serverHandler
assertTrue { EmptyServerHandler::class.java.isAssignableFrom(serviceHandler.javaClass) }
}
@Test
fun givenServerWithHandlerItShouldAssertHandler() {
val serviceHandler = server {
handler { mockServerHandler }
}.serverHandler
assertEquals(mockServerHandler, serviceHandler)
}
@Test
fun givenServerWithVerbItShouldAssertHandler() {
server {
handler { mockServerHandler }
+(map put "/" to { mockFrontCommand })
}
verify { mockServerHandler.put(capture(putHandlerSlotCaptor)) }
assertTrue { putHandlerSlotCaptor.isCaptured }
}
@Test
fun givenServerWithVerbItShouldAssertHandlerPath() {
server {
handler { mockServerHandler }
+(map put "/" to { mockFrontCommand })
}
verify { mockServerHandler.put(capture(putHandlerSlotCaptor)) }
assertEquals(PutPath("/"), putHandlerSlotCaptor.captured.putPath)
}
@Test
fun givenServerWithVerbItShouldAssertHandlerFrontCommand() {
server {
handler { mockServerHandler }
+(map put "/" to { mockFrontCommand })
}
verify { mockServerHandler.put(capture(putHandlerSlotCaptor)) }
assertEquals(mockFrontCommand, putHandlerSlotCaptor.captured.action())
}
@Test
fun givenServerWithVerbItShouldAssertHandlerDefaultRenderer() {
server {
handler { mockServerHandler }
+(map put "/" to { mockFrontCommand })
}
verify { mockServerHandler.put(capture(putHandlerSlotCaptor)) }
assertTrue { DefaultRenderer::class.java.isAssignableFrom(putHandlerSlotCaptor.captured.renderer.javaClass) }
}
@Test
fun givenServerWithVerbItShouldAssertHandlerCustomRenderer() {
server {
handler { mockServerHandler }
+(map put "/" to { mockFrontCommand } with mockRenderer)
}
verify { mockServerHandler.put(capture(putHandlerSlotCaptor)) }
assertEquals(mockRenderer, putHandlerSlotCaptor.captured.renderer)
}
@Test
fun givenServerWithMultipleVerbsItShouldAssertHandlerMultipleTimes() {
server {
handler { mockServerHandler }
+(map put "/" to { mockFrontCommand })
+(map put "/hello" to { mockFrontCommand })
}
verify(exactly = 2) { mockServerHandler.put(capture(putHandlerSlotCaptor)) }
}
} | server/src/test/kotlin/com/felipecosta/microservice/server/ServerPutActionTest.kt | 1552417589 |
package org.jmailen.gradle.kotlinter.functional
import org.gradle.testkit.runner.TaskOutcome.SUCCESS
import org.gradle.testkit.runner.TaskOutcome.UP_TO_DATE
import org.jmailen.gradle.kotlinter.functional.utils.resolve
import org.jmailen.gradle.kotlinter.functional.utils.settingsFile
import org.jmailen.gradle.kotlinter.tasks.InstallHookTask
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import java.io.File
abstract class InstallHookTaskTest(
private val taskName: String,
private val hookFile: String,
) : WithGradleTest.Kotlin() {
private lateinit var projectRoot: File
@BeforeEach
fun setup() {
projectRoot = testProjectDir.apply {
resolve("settings.gradle") { writeText(settingsFile) }
resolve("build.gradle") {
writeText(
"""
plugins {
id("kotlin")
id("org.jmailen.kotlinter")
}
""".trimIndent(),
)
}
build("wrapper")
}
}
@Test
fun `installs hook in project without hook directory`() {
File(testProjectDir, ".git").apply { mkdir() }
build(taskName).apply {
assertEquals(SUCCESS, task(":$taskName")?.outcome)
testProjectDir.apply {
resolve(".git/hooks/$hookFile") {
assertTrue(readText().contains("${'$'}GRADLEW formatKotlin"))
assertTrue(canExecute())
}
}
}
}
@Test
fun `installs hook in project with existing hook`() {
val existingHook =
"""
#!/bin/bash
This is some existing hook
""".trimIndent()
File(testProjectDir, ".git/hooks").apply { mkdirs() }
File(testProjectDir, ".git/hooks/$hookFile").apply {
writeText(existingHook)
}
build(taskName).apply {
assertEquals(SUCCESS, task(":$taskName")?.outcome)
testProjectDir.apply {
resolve(".git/hooks/$hookFile") {
val hookContents = readText()
assertTrue(hookContents.startsWith(existingHook))
assertTrue(hookContents.contains("${'$'}GRADLEW formatKotlin"))
}
}
}
}
@Test
fun `updates previously installed kotlinter hook`() {
val placeholder = "Not actually the hook, just a placeholder"
File(testProjectDir, ".git/hooks").apply { mkdirs() }
File(testProjectDir, ".git/hooks/$hookFile").apply {
writeText(
"""
${InstallHookTask.startHook}
$placeholder
${InstallHookTask.endHook}
""".trimIndent(),
)
}
build(taskName).apply {
assertEquals(SUCCESS, task(":$taskName")?.outcome)
testProjectDir.apply {
resolve(".git/hooks/$hookFile") {
val hookContents = readText()
assertTrue(hookContents.contains("${'$'}GRADLEW formatKotlin"))
assertFalse(hookContents.contains(placeholder))
}
}
}
}
@Test
fun `up-to-date when after hook installed`() {
File(testProjectDir, ".git").apply { mkdir() }
lateinit var hookContent: String
build(taskName).apply {
assertEquals(SUCCESS, task(":$taskName")?.outcome)
testProjectDir.apply {
resolve(".git/hooks/$hookFile") {
hookContent = readText()
println(hookContent)
assertTrue(hookContent.contains("${'$'}GRADLEW formatKotlin"))
assertTrue(canExecute())
}
}
}
build(taskName).apply {
assertEquals(UP_TO_DATE, task(":$taskName")?.outcome)
testProjectDir.apply {
resolve(".git/hooks/$hookFile") {
assertEquals(hookContent, readText())
}
}
}
}
}
class InstallPrePushHookTaskTest : InstallHookTaskTest("installKotlinterPrePushHook", "pre-push")
| src/test/kotlin/org/jmailen/gradle/kotlinter/functional/InstallHookTaskTest.kt | 506970392 |
package me.proxer.app.news
import io.reactivex.Single
import io.reactivex.rxkotlin.plusAssign
import me.proxer.app.base.PagedContentViewModel
import me.proxer.app.util.extension.toInstantBP
import me.proxer.library.api.PagingLimitEndpoint
import me.proxer.library.entity.notifications.NewsArticle
/**
* @author Ruben Gees
*/
class NewsViewModel : PagedContentViewModel<NewsArticle>() {
override val itemsOnPage = 15
override val dataSingle: Single<List<NewsArticle>>
get() = super.dataSingle.doOnSuccess {
if (page == 0) {
it.firstOrNull()?.date?.toInstantBP()?.let { date ->
preferenceHelper.lastNewsDate = date
}
}
}
override val endpoint: PagingLimitEndpoint<List<NewsArticle>>
get() = api.notifications.news()
.markAsRead(page == 0)
init {
disposables += bus.register(NewsNotificationEvent::class.java).subscribe()
}
}
| src/main/kotlin/me/proxer/app/news/NewsViewModel.kt | 1922959308 |
package ru.fantlab.android.provider.storage.smiles
import ru.fantlab.android.App
import ru.fantlab.android.data.dao.model.Smile
import java.io.IOException
object SmileManager {
private const val PATH = "smiles.json"
private var ALL_SMILES: List<Smile>? = null
fun load() {
try {
val stream = App.instance.assets.open(PATH)
val smiles = SmileLoader.loadSmiles(stream)
ALL_SMILES = smiles
stream.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
fun getAll(): List<Smile>? {
return ALL_SMILES
}
} | app/src/main/kotlin/ru/fantlab/android/provider/storage/smiles/SmileManager.kt | 3337990924 |
package ru.fantlab.android.data.dao.model
import android.os.Parcelable
import androidx.annotation.Keep
import kotlinx.android.parcel.Parcelize
@Keep
@Parcelize
data class Smile(
val id: String,
val description: String
) : Parcelable | app/src/main/kotlin/ru/fantlab/android/data/dao/model/Smile.kt | 3758125908 |
package utils
import org.w3c.fetch.RequestInit
import org.w3c.xhr.XMLHttpRequest
import kotlin.browser.window
import kotlin.js.Json
import kotlin.js.Promise
import kotlin.js.json
fun <T> makeRequest(method: String, url: String, body: Any? = null, parse: (dynamic) -> T): Promise<T?> {
return Promise { resolve, reject ->
window.fetch(url, object: RequestInit {
override var method: String? = method
override var headers: dynamic = json("Content-Type" to "application/json")
override var body: dynamic = if (body != null) {
JSON.stringify(body)
} else {
null
}
}).then { r ->
if (method != "DELETE") {
r.json().then { obj ->
resolve(parse(obj))
}
} else {
resolve(null)
}
}
}
}
fun makeSyncRequest(method: String, url: String, body: Any? = null): dynamic? {
val xhr = XMLHttpRequest()
xhr.open(method, url, false)
xhr.setRequestHeader("Content-Type", "application/json")
if (body != null) {
xhr.send(JSON.stringify(body))
} else {
xhr.send()
}
return JSON.parse(xhr.responseText) as dynamic
} | examples/kotlin-react/src/utils/HttpUtil.kt | 1851224823 |
package ru.fantlab.android.ui.modules.search
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.ArrayAdapter
import com.evernote.android.state.State
import com.google.android.material.tabs.TabLayout
import com.google.zxing.integration.android.IntentIntegrator
import kotlinx.android.synthetic.main.search_layout.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.FragmentPagerAdapterModel
import ru.fantlab.android.data.dao.TabsCountStateModel
import ru.fantlab.android.helper.AnimHelper
import ru.fantlab.android.helper.ViewHelper
import ru.fantlab.android.ui.adapter.FragmentsPagerAdapter
import ru.fantlab.android.ui.base.BaseActivity
import shortbread.Shortcut
import java.text.NumberFormat
import java.util.*
@Shortcut(id = "search", icon = R.drawable.sb_search, shortLabelRes = R.string.search, rank = 1)
class SearchActivity : BaseActivity<SearchMvp.View, SearchPresenter>(), SearchMvp.View {
@State var tabsCountSet: HashSet<TabsCountStateModel> = LinkedHashSet<TabsCountStateModel>()
private val numberFormat = NumberFormat.getNumberInstance()
private val adapter: ArrayAdapter<String> by lazy {
ArrayAdapter(this, android.R.layout.simple_list_item_1, presenter.getHints())
}
override fun layout(): Int = R.layout.search_layout
override fun isTransparent(): Boolean = false
override fun canBack(): Boolean = true
override fun providePresenter(): SearchPresenter = SearchPresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
title = ""
pager.adapter = FragmentsPagerAdapter(supportFragmentManager, FragmentPagerAdapterModel.buildForSearch(this))
tabs.setupWithViewPager(pager)
searchEditText.setAdapter(adapter)
searchEditText.setOnItemClickListener { _, _, _, _ -> presenter.onSearchClicked(pager, searchEditText) }
searchEditText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
val text = s.toString()
AnimHelper.animateVisibility(clear, text.isNotEmpty())
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
})
if (!tabsCountSet.isEmpty()) {
tabsCountSet.forEach { setupTab(count = it.count, index = it.tabIndex) }
}
if (savedInstanceState == null && intent != null) {
if (intent.hasExtra("search")) {
searchEditText.setText(intent.getStringExtra("search"))
presenter.onSearchClicked(pager, searchEditText)
}
}
tabs.addOnTabSelectedListener(object : TabLayout.ViewPagerOnTabSelectedListener(pager) {
override fun onTabReselected(tab: TabLayout.Tab) {
super.onTabReselected(tab)
onScrollTop(tab.position)
}
})
search.setOnClickListener { onSearchClicked() }
clear.setOnClickListener { searchEditText.setText("") }
scan_barcode.setOnClickListener { onScanBarcodeClicked() }
searchEditText.setOnEditorActionListener { _, _, _ ->
onSearchClicked()
true
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
result?.let {
if (result.contents == null) {
showMessage("Result", getString(R.string.scan_canceled))
} else {
searchEditText.setText(result.contents)
presenter.onSearchClicked(pager, searchEditText, true)
pager.currentItem = 2
}
}
}
fun onSearchClicked() {
presenter.onSearchClicked(pager, searchEditText)
}
private fun onScanBarcodeClicked() {
val integrator = IntentIntegrator(this)
with(integrator) {
setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)
setPrompt(getString(R.string.scan))
setCameraId(0)
setBeepEnabled(false)
setBarcodeImageEnabled(false)
initiateScan()
}
}
override fun onNotifyAdapter(query: String?) {
if (query == null)
adapter.notifyDataSetChanged()
else
adapter.add(query)
}
override fun onSetCount(count: Int, index: Int) {
tabsCountSet.add(TabsCountStateModel(count = count, tabIndex = index))
setupTab(count, index)
}
private fun setupTab(count: Int, index: Int) {
val textView = ViewHelper.getTabTextView(tabs, index)
when (index) {
0 -> textView.text = String.format("%s(%s)", getString(R.string.authors), numberFormat.format(count.toLong()))
1 -> textView.text = String.format("%s(%s)", getString(R.string.works), numberFormat.format(count.toLong()))
2 -> textView.text = String.format("%s(%s)", getString(R.string.editions), numberFormat.format(count.toLong()))
3 -> textView.text = String.format("%s(%s)", getString(R.string.awards), numberFormat.format(count.toLong()))
}
}
} | app/src/main/kotlin/ru/fantlab/android/ui/modules/search/SearchActivity.kt | 526172514 |
package reagent.rxjava2
import kotlinx.coroutines.experimental.runBlocking
import org.junit.Assert.fail
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertSame
import io.reactivex.Maybe as RxMaybe
class MaybeRxToReagentTest {
@Test fun complete() = runBlocking {
val value = RxMaybe.empty<Any>()
.toReagent()
.produce()
assertNull(value)
}
@Test fun item() = runBlocking {
val value = RxMaybe.just("Hello")
.toReagent()
.produce()
assertEquals("Hello", value)
}
@Test fun error() = runBlocking {
val exception = RuntimeException("Oops!")
try {
RxMaybe.error<Any>(exception)
.toReagent()
.produce()
fail()
} catch (t: Throwable) {
assertSame(exception, t)
}
}
}
| reagent-rxjava2/src/test/kotlin/reagent/rxjava2/MaybeRxToReagentTest.kt | 2294157504 |
package reagent.operator
import reagent.runTest
import reagent.source.observableOf
import reagent.source.test.emptyActualObservable
import reagent.source.test.toActualObservable
import reagent.tester.testObservable
import kotlin.test.Test
import kotlin.test.fail
class ObservableFilterTest {
@Test fun filter() = runTest {
observableOf("Hello", "World")
.filter { it == "Hello" }
.testObservable {
item("Hello")
complete()
}
}
@Test fun filterEmpty() = runTest {
emptyActualObservable<Nothing>()
.filter { fail() }
.testObservable {
complete()
}
}
@Test fun filterError() = runTest {
val exception = RuntimeException("Oops!")
exception.toActualObservable<Nothing>()
.filter { fail() }
.testObservable {
error(exception)
}
}
@Test fun filterThrowing() = runTest {
val exception = RuntimeException("Oops!")
observableOf("Hello", "World")
.filter { throw exception }
.testObservable {
error(exception)
}
}
}
| reagent/common/src/test/kotlin/reagent/operator/ObservableFilterTest.kt | 2050174297 |
package com.revbingo.spiff.parser
import com.revbingo.spiff.instructions.Instruction
import com.revbingo.spiff.parser.gen.ParseException
import com.revbingo.spiff.parser.gen.SpiffTreeParser
import java.io.InputStream
import java.util.*
interface InstructionParser {
@Throws(ParseException::class)
fun parse(): List<Instruction>
}
class SpiffParser(private val input: InputStream) : InstructionParser {
@Throws(ParseException::class)
override fun parse(): List<Instruction> {
val parser = SpiffTreeParser(input)
val rootNode = parser.adf()
val visitor = SpiffVisitor()
return rootNode.jjtAccept(visitor, ArrayList<Instruction>())
}
}
| src/main/java/com/revbingo/spiff/parser/SpiffParser.kt | 3116090653 |
/**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen.checks
import com.felipebz.flr.api.AstNode
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.annotations.*
import org.sonar.plugins.plsqlopen.api.matchers.MethodMatcher
@Rule(priority = Priority.MINOR)
@ConstantRemediation("5min")
@RuleInfo(scope = RuleInfo.Scope.MAIN)
@ActivatedByDefault
class DbmsOutputPutCheck : AbstractBaseCheck() {
override fun init() {
subscribeTo(PlSqlGrammar.METHOD_CALL)
}
override fun visitNode(node: AstNode) {
val put = MethodMatcher.create()
.schema("sys").schemaIsOptional()
.packageName("dbms_output")
.name("put")
.addParameter()
val putLine = MethodMatcher.create()
.schema("sys").schemaIsOptional()
.packageName("dbms_output")
.name("put_line")
.addParameter()
if (!put.matches(node) && !putLine.matches(node)) {
return
}
addIssue(node, getLocalizedMessage())
}
}
| zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/DbmsOutputPutCheck.kt | 1493034200 |
package tk.zielony.carbonsamples.feature
import android.os.Bundle
import android.util.TypedValue
import kotlinx.android.synthetic.main.activity_autosizetext.*
import tk.zielony.carbonsamples.SampleAnnotation
import tk.zielony.carbonsamples.R
import tk.zielony.carbonsamples.ThemedActivity
@SampleAnnotation(layoutId = R.layout.activity_autosizetext, titleId = R.string.autoSizeTextActivity_title)
class AutoSizeTextActivity : ThemedActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initToolbar()
autoSizeText.addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
textSize.setTextSize(TypedValue.COMPLEX_UNIT_PX, autoSizeText.textSize)
textSize.text = "${autoSizeText.textSize / resources.displayMetrics.scaledDensity}sp"
}
}
}
| samples/src/main/java/tk/zielony/carbonsamples/feature/AutoSizeTextActivity.kt | 2915929322 |
package io.propa.framework.common
/**
* Created by gbaldeck on 5/7/2017.
*/
internal fun String.camelToDashCase(): String {
return this.replace(Regex("([a-z])([A-Z])"), {
result ->
val (g1: String, g2: String) = result.destructured
"$g1-$g2"
})
}
internal fun String.getProperTagName(): String =
if (this.indexOf("-") > 0)
this.toLowerCase()
else
throwPropaException("The chosen tag name '$this' is not in the correct custom tag format.")
fun jsObjectOf(vararg pairs: Pair<String, dynamic>): dynamic{
val obj: dynamic = Any()
pairs.forEach {
(key, value) ->
obj[key] = value
}
return obj
}
fun jsObjectOf(map: Map<String, dynamic>): dynamic = jsObjectOf(*map.toList().toTypedArray())
fun <T> assertSafeCast(obj: Any): T{
@Suppress("UNCHECKED_CAST")
return obj as T
}
fun isNullOrUndefined(value: dynamic) = value === undefined || value === null
| src/main/kotlin/io/propa/framework/common/Common.kt | 3042651585 |
package com.google.firebase.example.perf.kotlin
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.example.perf.kotlin.model.ItemCache
import com.google.firebase.example.perf.kotlin.model.User
import com.google.firebase.ktx.Firebase
import com.google.firebase.perf.FirebasePerformance
import com.google.firebase.perf.ktx.performance
import com.google.firebase.perf.ktx.trace
import com.google.firebase.perf.metrics.AddTrace
import com.google.firebase.remoteconfig.ktx.remoteConfig
import devrel.firebase.google.com.firebaseoptions.R
import java.io.DataOutputStream
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
class MainActivity : AppCompatActivity() {
// [START perf_traced_create]
@AddTrace(name = "onCreateTrace", enabled = true /* optional */)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
// [END perf_traced_create]
fun basicTrace() {
val cache = ItemCache()
// [START perf_basic_trace_start]
val myTrace = Firebase.performance.newTrace("test_trace")
myTrace.start()
// [END perf_basic_trace_start]
// [START perf_basic_trace_increment]
val item = cache.fetch("item")
if (item != null) {
myTrace.incrementMetric("item_cache_hit", 1)
} else {
myTrace.incrementMetric("item_cache_miss", 1)
}
// [END perf_basic_trace_increment]
// [START perf_basic_trace_stop]
myTrace.stop()
// [END perf_basic_trace_stop]
}
fun traceCustomAttributes() {
// [START perf_trace_custom_attrs]
Firebase.performance.newTrace("test_trace").trace {
// Update scenario.
putAttribute("experiment", "A")
// Reading scenario.
val experimentValue = getAttribute("experiment")
// Delete scenario.
removeAttribute("experiment")
// Read attributes.
val traceAttributes = this.attributes
}
// [END perf_trace_custom_attrs]
}
fun disableWithConfig() {
// [START perf_disable_with_config]
// Setup remote config
val config = Firebase.remoteConfig
// You can uncomment the following two statements to permit more fetches when
// validating your app, but you should comment out or delete these lines before
// distributing your app in production.
// val configSettings = remoteConfigSettings {
// minimumFetchIntervalInSeconds = 3600
// }
// config.setConfigSettingsAsync(configSettings)
// Load in-app defaults from an XML file that sets perf_disable to false until you update
// values in the Firebase Console
// Observe the remote config parameter "perf_disable" and disable Performance Monitoring if true
config.setDefaultsAsync(R.xml.remote_config_defaults)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Firebase.performance.isPerformanceCollectionEnabled = !config.getBoolean("perf_disable")
} else {
// An error occurred while setting default parameters
}
}
// [END perf_disable_with_config]
}
fun activateConfig() {
// [START perf_activate_config]
// Remote Config fetches and activates parameter values from the service
val config = Firebase.remoteConfig
config.fetch(3600)
.continueWithTask { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
config.activate()
}
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Parameter values successfully activated
// ...
} else {
// Handle errors
}
}
// [END perf_activate_config]
}
@Throws(Exception::class)
fun manualNetworkTrace() {
val data = "badgerbadgerbadgerbadgerMUSHROOM!".toByteArray()
// [START perf_manual_network_trace]
val url = URL("https://www.google.com")
val metric = Firebase.performance.newHttpMetric("https://www.google.com",
FirebasePerformance.HttpMethod.GET)
metric.trace {
val conn = url.openConnection() as HttpURLConnection
conn.doOutput = true
conn.setRequestProperty("Content-Type", "application/json")
try {
val outputStream = DataOutputStream(conn.outputStream)
outputStream.write(data)
} catch (ignored: IOException) {
}
// Set HttpMetric attributes
setRequestPayloadSize(data.size.toLong())
setHttpResponseCode(conn.responseCode)
printStreamContent(conn.inputStream)
conn.disconnect()
}
// [END perf_manual_network_trace]
}
fun piiExamples() {
val trace = Firebase.performance.newTrace("trace")
val user = User()
// [START perf_attr_no_pii]
trace.putAttribute("experiment", "A")
// [END perf_attr_no_pii]
// [START perf_attr_pii]
trace.putAttribute("email", user.getEmailAddress())
// [END perf_attr_pii]
}
private fun printStreamContent(stream: InputStream) {
// Unimplemented
// ...
}
}
| perf/app/src/main/java/com/google/firebase/example/perf/kotlin/MainActivity.kt | 98365002 |
package com.habitrpg.wearos.habitica.models.user
import com.habitrpg.shared.habitica.models.AvatarItems
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
class Items: AvatarItems {
override var gear: Gear? = null
override var currentMount: String? = null
override var currentPet: String? = null
} | wearos/src/main/java/com/habitrpg/wearos/habitica/models/user/Items.kt | 4064814167 |
/*
* Copyright (C) 2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xproc.lang.fileTypes
import com.intellij.ide.FileIconPatcher
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import com.intellij.psi.xml.XmlFile
import uk.co.reecedunn.intellij.plugin.xproc.lang.XProc
import uk.co.reecedunn.intellij.plugin.xproc.resources.XProcIcons
import javax.swing.Icon
class XProcFileIconPatcher : FileIconPatcher {
override fun patchIcon(baseIcon: Icon, file: VirtualFile?, flags: Int, project: Project?): Icon = when {
project == null || file == null -> baseIcon
else -> {
(PsiManager.getInstance(project).findFile(file) as? XmlFile)?.rootTag?.let {
if (it.namespace == XProc.NAMESPACE) {
XProcIcons.FileType
} else {
null
}
} ?: baseIcon
}
}
}
| src/lang-xproc/main/uk/co/reecedunn/intellij/plugin/xproc/lang/fileTypes/XProcFileIconPatcher.kt | 2166999560 |
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.policies.federatedcompute
/** Data policy. */
val AppLaunchPredictionMetricsPolicy_FederatedCompute =
flavoredPolicies(
name = "AppLaunchPredictionMetricsPolicy_FederatedCompute",
policyType = MonitorOrImproveUserExperienceWithFederatedCompute,
) {
description =
"""
To measure and improve the quality of app prediction based on user’s app launches.
ALLOWED EGRESSES: FederatedCompute.
ALLOWED USAGES: Federated analytics, federated learning.
"""
.trimIndent()
consentRequiredForCollectionOrStorage(Consent.UsageAndDiagnosticsCheckbox)
presubmitReviewRequired(OwnersApprovalOnly)
checkpointMaxTtlDays(720)
target(PERSISTED_ECHO_APP_LAUNCH_METRICS_EVENT_GENERATED_DTD, Duration.ofDays(2)) {
retention(StorageMedium.RAM)
retention(StorageMedium.DISK)
"id" { rawUsage(UsageType.JOIN) }
"timestampMillis" {
ConditionalUsage.TruncatedToDays.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"packageName" {
ConditionalUsage.Top2000PackageNamesWith2000Wau.whenever(UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"launchLocationId" { rawUsage(UsageType.ANY) }
"predictionUiSurfaceId" { rawUsage(UsageType.ANY) }
"predictionSourceId" { rawUsage(UsageType.ANY) }
"predictionRank" { rawUsage(UsageType.ANY) }
}
}
| src/com/google/android/as/oss/assets/federatedcompute/AppLaunchPredictionMetricsPolicy_FederatedCompute.kt | 128036790 |
package com.habitrpg.android.habitica.helpers
import com.habitrpg.common.habitica.helpers.HealthFormatter
import io.kotest.matchers.shouldBe
import java.util.Locale
import org.junit.jupiter.api.Test
class HealthFormatterTest {
@Test
fun shouldRoundValuesGreaterThanOneDown() {
49.0 shouldBe HealthFormatter.format(49.9)
9.0 shouldBe HealthFormatter.format(9.9999)
1.0 shouldBe HealthFormatter.format(1.9)
1.0 shouldBe HealthFormatter.format(1.0001)
"49" shouldBe HealthFormatter.formatToString(49.9, Locale.US)
"9" shouldBe HealthFormatter.formatToString(9.9999, Locale.US)
"1" shouldBe HealthFormatter.formatToString(1.9, Locale.US)
"1" shouldBe HealthFormatter.formatToString(1.0001, Locale.US)
}
@Test
fun shouldRoundValuesBetweenZeroAndOneUpToOneDecimalPlace() {
1.0 shouldBe HealthFormatter.format(0.99)
0.2 shouldBe HealthFormatter.format(0.11)
0.1 shouldBe HealthFormatter.format(0.0001)
"1" shouldBe HealthFormatter.formatToString(0.99, Locale.US)
"0.2" shouldBe HealthFormatter.formatToString(0.11, Locale.US)
"0.1" shouldBe HealthFormatter.formatToString(0.0001, Locale.US)
}
@Test
fun shouldRoundNegativeValuesDown() {
-1.0 shouldBe HealthFormatter.format(-0.1)
-2.0 shouldBe HealthFormatter.format(-2.0)
"-1" shouldBe HealthFormatter.formatToString(-0.1, Locale.US)
"-2" shouldBe HealthFormatter.formatToString(-2.0, Locale.US)
}
@Test
fun shouldLeaveAcceptableValuesAsTheyAre() {
20.0 shouldBe HealthFormatter.format(20)
0.0 shouldBe HealthFormatter.format(0)
0.9 shouldBe HealthFormatter.format(0.9)
"20" shouldBe HealthFormatter.formatToString(20, Locale.US)
"0" shouldBe HealthFormatter.formatToString(0, Locale.US)
"0.9" shouldBe HealthFormatter.formatToString(0.9, Locale.US)
}
}
| Habitica/src/test/java/com/habitrpg/android/habitica/helpers/HealthFormatterTest.kt | 1764122138 |
package de.westnordost.streetcomplete.util
import org.junit.Test
import org.junit.Assert.*
class ReverseIteratorTest {
@Test fun reverse() {
val it = ReverseIterator(listOf("a", "b", "c"))
assertEquals("c", it.next())
assertEquals("b", it.next())
assertEquals("a", it.next())
assertFalse(it.hasNext())
}
}
| app/src/test/java/de/westnordost/streetcomplete/util/ReverseIteratorTest.kt | 1992400273 |
package org.stepik.android.domain.step.interactor
import io.reactivex.Maybe
import io.reactivex.Single
import io.reactivex.rxkotlin.Maybes.zip
import io.reactivex.rxkotlin.toObservable
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.exam.interactor.ExamSessionDataInteractor
import org.stepik.android.domain.exam.model.SessionData
import ru.nobird.android.domain.rx.toMaybe
import org.stepik.android.domain.lesson.model.LessonData
import org.stepik.android.domain.lesson.repository.LessonRepository
import org.stepik.android.domain.progress.repository.ProgressRepository
import org.stepik.android.domain.section.repository.SectionRepository
import org.stepik.android.domain.step.model.StepDirectionData
import org.stepik.android.domain.step.model.StepNavigationDirection
import org.stepik.android.domain.unit.repository.UnitRepository
import org.stepik.android.model.Course
import org.stepik.android.model.Lesson
import org.stepik.android.model.Section
import org.stepik.android.model.Step
import org.stepik.android.model.Unit
import org.stepik.android.view.course_content.model.RequiredSection
import ru.nobird.android.domain.rx.filterSingle
import ru.nobird.android.domain.rx.maybeFirst
import java.util.EnumSet
import javax.inject.Inject
class StepNavigationInteractor
@Inject
constructor(
private val sectionRepository: SectionRepository,
private val unitRepository: UnitRepository,
private val lessonRepository: LessonRepository,
private val progressRepository: ProgressRepository,
private val examSessionDataInteractor: ExamSessionDataInteractor
) {
fun getStepNavigationDirections(step: Step, lessonData: LessonData): Single<Set<StepNavigationDirection>> =
if (lessonData.unit == null ||
step.position in 2 until lessonData.lesson.steps.size.toLong()) {
Single.just(EnumSet.noneOf(StepNavigationDirection::class.java))
} else {
StepNavigationDirection
.values()
.toObservable()
.filterSingle { isCanMoveInDirection(it, step, lessonData) }
.reduce(EnumSet.noneOf(StepNavigationDirection::class.java)) { set, direction -> set.add(direction); set }
.map { it as Set<StepNavigationDirection> }
}
fun getStepDirectionData(direction: StepNavigationDirection, step: Step, lessonData: LessonData): Maybe<StepDirectionData> =
when {
lessonData.unit == null ||
lessonData.section == null ||
lessonData.course == null ||
!isDirectionCompliesStepPosition(direction, step, lessonData.lesson) ->
Maybe.empty()
isDirectionCompliesUnitPosition(direction, lessonData.unit, lessonData.section) ->
unitRepository
.getUnit(lessonData.section.units[
when (direction) {
StepNavigationDirection.NEXT ->
lessonData.unit.position
StepNavigationDirection.PREV ->
lessonData.unit.position - 2
}
])
.flatMap { unit ->
lessonRepository
.getLesson(unit.lesson)
.map { lesson ->
lessonData.copy(unit = unit, lesson = lesson)
}
}
else ->
getSlicedSections(direction, lessonData.section, lessonData.course)
.flatMapMaybe { sections ->
sections
.firstOrNull() { it.units.isNotEmpty() }
.toMaybe()
}
.flatMap { section ->
val unitId =
when (direction) {
StepNavigationDirection.NEXT ->
section.units.first()
StepNavigationDirection.PREV ->
section.units.last()
}
unitRepository
.getUnit(unitId)
.flatMap { unit ->
lessonRepository
.getLesson(unit.lesson)
.map { lesson ->
lessonData.copy(section = section, unit = unit, lesson = lesson)
}
}
}
}.flatMap {
val requiredSectionSource =
if (it.section?.isRequirementSatisfied == false) {
getRequiredSection(it.section.requiredSection).onErrorReturnItem(RequiredSection.EMPTY)
} else {
Maybe.just(RequiredSection.EMPTY)
}
val examSessionSource =
if (it.section != null) {
examSessionDataInteractor.getSessionData(it.section, DataSourceType.REMOTE).onErrorReturnItem(SessionData.EMPTY)
} else {
Single.just(SessionData.EMPTY)
}
zip(
requiredSectionSource,
examSessionSource.toMaybe()
) { requiredSection, examSessionData ->
StepDirectionData(lessonData = it, requiredSection = requiredSection, examSessionData = examSessionData)
}
}
private fun getRequiredSection(sectionId: Long): Maybe<RequiredSection> =
sectionRepository
.getSection(sectionId, DataSourceType.CACHE)
.flatMap { section ->
progressRepository
.getProgresses(listOfNotNull(section.progress), primarySourceType = DataSourceType.REMOTE)
.maybeFirst()
.map { progress ->
RequiredSection(section, progress)
}
}
private fun isCanMoveInDirection(direction: StepNavigationDirection, step: Step, lessonData: LessonData): Single<Boolean> =
when {
lessonData.unit == null ||
lessonData.section == null ||
lessonData.course == null ||
!isDirectionCompliesStepPosition(direction, step, lessonData.lesson) ->
Single.just(false)
isDirectionCompliesUnitPosition(direction, lessonData.unit, lessonData.section) ->
Single.just(true)
else ->
getSlicedSections(direction, lessonData.section, lessonData.course)
.map { sections ->
sections.any { it.units.isNotEmpty() } || direction == StepNavigationDirection.NEXT
}
}
private fun isDirectionCompliesStepPosition(direction: StepNavigationDirection, step: Step, lesson: Lesson): Boolean =
direction == StepNavigationDirection.PREV && step.position == 1L ||
direction == StepNavigationDirection.NEXT && step.position == lesson.steps.size.toLong()
private fun isDirectionCompliesUnitPosition(direction: StepNavigationDirection, unit: Unit, section: Section): Boolean =
direction == StepNavigationDirection.PREV && unit.position > 1 ||
direction == StepNavigationDirection.NEXT && unit.position < section.units.size
private fun getSlicedSections(direction: StepNavigationDirection, section: Section, course: Course): Single<List<Section>> {
val sectionIds = course.sections ?: return Single.just(emptyList())
val range =
when (direction) {
StepNavigationDirection.NEXT ->
(section.position until sectionIds.size)
StepNavigationDirection.PREV ->
(0 until section.position - 1)
}
return sectionRepository
.getSections(sectionIds.slice(range))
.map { sections ->
when (direction) {
StepNavigationDirection.NEXT ->
sections
StepNavigationDirection.PREV ->
sections.asReversed()
}
}
}
} | app/src/main/java/org/stepik/android/domain/step/interactor/StepNavigationInteractor.kt | 3829118000 |
package nl.sugcube.dirtyarrows.bow
import nl.sugcube.dirtyarrows.DirtyArrows
import nl.sugcube.dirtyarrows.bow.ability.*
import org.bukkit.event.EventHandler
import org.bukkit.event.HandlerList
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerQuitEvent
import java.util.logging.Level
/**
* Tracks all bow effects. Iterates over all registered bow types.
*
* @author SugarCaney
*/
open class BowManager(private val plugin: DirtyArrows): Iterable<BowType>, Listener {
/**
* Contains all available bows.
*/
private val bows = HashMap<BowType, BowAbility>()
/**
* Keeps track of all scheduled task IDs. Mapped from each bow type.
*/
private val tasks = HashMap<BowType, Int>()
/**
* Get all bow types that are registered.
*/
val registeredTypes: Set<BowType>
get() = bows.keys
/**
* Loads all enabled bows. Re-evaluates on second call.
*/
fun reload() = with(plugin) {
// Remove all registered bows, to overwrite with new ones.
unload()
loadAbilities()
plugin.server.pluginManager.registerEvents(this@BowManager, plugin)
bows.forEach { (bowType, ability) ->
plugin.server.pluginManager.registerEvents(ability, plugin)
// Cache task ID to be canceled on reload.
val taskId = plugin.server.scheduler.scheduleSyncRepeatingTask(plugin, ability, 0L, 1L)
tasks[bowType] = taskId
}
logger.log(Level.INFO, "Loaded ${bows.size} bows.")
}
/**
* Adds all enabled bow ability implementations to [bows].
*/
private fun loadAbilities() {
ExplodingBow(plugin).load()
LightningBow(plugin).load()
CluckyBow(plugin).load()
EnderBow(plugin).load()
TreeBow(plugin, TreeBow.Tree.OAK).load()
TreeBow(plugin, TreeBow.Tree.SPRUCE).load()
TreeBow(plugin, TreeBow.Tree.BIRCH).load()
TreeBow(plugin, TreeBow.Tree.JUNGLE).load()
TreeBow(plugin, TreeBow.Tree.ACACIA).load()
TreeBow(plugin, TreeBow.Tree.DARK_OAK).load()
BattyBow(plugin).load()
NuclearBow(plugin).load()
EnlightenedBow(plugin).load()
RangedBow(plugin).load()
MachineBow(plugin).load()
VenomousBow(plugin).load()
DisorientingBow(plugin).load()
SwapBow(plugin).load()
DrainBow(plugin).load()
FlintAndBow(plugin).load()
DisarmingBow(plugin).load()
WitherBow(plugin).load()
FireyBow(plugin).load()
SlowBow(plugin).load()
LevelBow(plugin).load()
UndeadBow(plugin).load()
WoodmanBow(plugin).load()
StarvationBow(plugin).load()
MultiBow(plugin).load()
BombBow(plugin).load()
DropBow(plugin).load()
AirstrikeBow(plugin).load()
MagmaticBow(plugin).load()
AquaticBow(plugin).load()
PullBow(plugin).load()
ParalyzeBow(plugin).load()
ClusterBow(plugin).load()
AirshipBow(plugin).load()
IronBow(plugin).load()
CurseBow(plugin).load()
RoundBow(plugin).load()
FrozenBow(plugin).load()
DrillBow(plugin).load()
MusicBow(plugin).load()
HomingBow(plugin).load()
InterdimensionalBow(plugin).load()
SingularityBow(plugin).load()
PushyBow(plugin).load()
RainbowBow(plugin).load()
LaserBow(plugin).load()
GrapplingBow(plugin).load()
BouncyBow(plugin).load()
MiningBow(plugin).load()
UpBow(plugin).load()
ShearBow(plugin).load()
UndyingBow(plugin).load()
FireworkBow(plugin).load()
BridgeBow(plugin).load()
MeteorBow(plugin).load()
DraggyBow(plugin).load()
BabyBow(plugin).load()
SmokyBow(plugin).load()
InvincibilityBow(plugin).load()
BlockyBow(plugin).load()
AcceleratingBow(plugin).load()
FarmersBow(plugin).load()
BowBow(plugin).load()
MineBow(plugin).load()
BlasterBow(plugin).load()
}
/**
* Adds the given ability for this bow type if it is enabled in the configuration file.
*/
private fun BowAbility.load() {
if (type.isEnabled(plugin)) {
bows[type] = this
}
}
/**
* Unregisters all bows.
*/
fun unload() = with(plugin) {
if (bows.isEmpty()) return
// Unregister event handlers.
bows.entries.forEach { (bowType, ability) ->
HandlerList.unregisterAll(ability)
tasks[bowType]?.let { server.scheduler.cancelTask(it) }
}
HandlerList.unregisterAll(this@BowManager)
bows.clear()
tasks.clear()
}
/**
* Get the ability implementation for the bow with the given type.
*/
fun implementation(bowType: BowType) = bows[bowType]
/**
* Adds the given bow type when it is enabled in the config.
*/
private fun addIfEnabled(bowType: BowType, ability: BowAbility) {
if (plugin.config.getBoolean(bowType.enabledNode)) {
bows[bowType] = ability
}
}
/**
* @see implementation
*/
operator fun get(bowType: BowType) = implementation(bowType)
override fun iterator() = bows.keys.iterator()
@EventHandler
fun playerQuits(event: PlayerQuitEvent) {
val player = event.player
bows.values.forEach { it.removeFromCostRequirementsCache(player) }
}
} | src/main/kotlin/nl/sugcube/dirtyarrows/bow/BowManager.kt | 494322029 |
package nl.sugcube.dirtyarrows.util
import kotlin.math.ceil
import kotlin.math.roundToInt
import kotlin.random.Random
/**
* Rolls whether a hit should be critical.
*/
fun rollCritical(chance: Double = 0.25) = Random.nextDouble() < chance
/**
* Calculates the amount of extra bonus damage (additive) that must be added for a critical hit.
*/
fun criticalDamage(baseDamage: Double): Double {
val max = (baseDamage / 2.0).roundToInt() + 1
return Random.nextInt(0, max).toDouble()
}
/**
* Calculates how many damage an arrow should do, based on vanilla behaviour.
*
* @param arrowVelocity
* How quickly the arrow flies (velocity length).
* @param criticalHitChance
* How much chance there is for the damage to be critical.
* @param powerLevel
* The power level enchantment of the bow, or 0 for now power level.
* @return The damage to deal.
*/
fun arrowDamage(arrowVelocity: Double, criticalHitChance: Double = 0.25, powerLevel: Int = 0): Double {
val baseDamage = ceil(2.0 * arrowVelocity)
val powerMultiplier = powerDamageMultiplier(powerLevel)
val criticalDamage = if (rollCritical(criticalHitChance)) criticalDamage(baseDamage) else 0.0
return (baseDamage + criticalDamage) * powerMultiplier
}
/**
* With how much to multiply arrow damage given the power enchantment level.
*/
fun powerDamageMultiplier(powerLevel: Int = 0) = when (powerLevel) {
0 -> 1.0
else -> 1 + 0.5 * (powerLevel + 1)
} | src/main/kotlin/nl/sugcube/dirtyarrows/util/Combat.kt | 2014833843 |
package com.vmenon.mpo.my_library.presentation.di.dagger
import com.vmenon.mpo.common.framework.di.dagger.CommonFrameworkComponent
import com.vmenon.mpo.my_library.presentation.fragment.EpisodeDetailsFragment
import com.vmenon.mpo.my_library.presentation.fragment.LibraryFragment
import com.vmenon.mpo.my_library.presentation.fragment.SubscribedShowsFragment
import com.vmenon.mpo.my_library.presentation.viewmodel.SubscribedShowsViewModel
import com.vmenon.mpo.my_library.presentation.viewmodel.EpisodeDetailsViewModel
import com.vmenon.mpo.my_library.presentation.viewmodel.LibraryViewModel
import com.vmenon.mpo.my_library.framework.di.dagger.LibraryFrameworkComponent
import com.vmenon.mpo.player.framework.di.dagger.PlayerFrameworkComponent
import dagger.Component
@Component(
dependencies = [
CommonFrameworkComponent::class,
PlayerFrameworkComponent::class,
LibraryFrameworkComponent::class
],
modules = [LibraryModule::class]
)
@LibraryScope
interface LibraryComponent {
@Component.Builder
interface Builder {
fun commonFrameworkComponent(component: CommonFrameworkComponent): Builder
fun playerFrameworkComponent(component: PlayerFrameworkComponent): Builder
fun libraryFrameworkComponent(component: LibraryFrameworkComponent): Builder
fun build(): LibraryComponent
}
fun inject(fragment: LibraryFragment)
fun inject(viewModel: LibraryViewModel)
fun inject(fragment: EpisodeDetailsFragment)
fun inject(viewModel: EpisodeDetailsViewModel)
fun inject(fragment: SubscribedShowsFragment)
fun inject(viewModel: SubscribedShowsViewModel)
}
| my_library_presentation/src/main/java/com/vmenon/mpo/my_library/presentation/di/dagger/LibraryComponent.kt | 1132112474 |
package org.walleth.walletconnect
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.*
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types.newParameterizedType
import kotlinx.android.synthetic.main.activity_list_nofab.*
import kotlinx.android.synthetic.main.item_wc_app.view.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.koin.android.ext.android.inject
import org.ligi.kaxt.setVisibility
import org.walleth.R
import org.walleth.base_activities.BaseSubActivity
import org.walleth.data.AppDatabase
val list = """
[
{
"name": "Example dApp",
"url": "https://example.walletconnect.org",
"icon": "https://example.walletconnect.org/favicon.ico",
"networks": ["1","4","5","100"]
},
{
"name": "ENS",
"url": "https://app.ens.domains",
"icon": "https://app.ens.domains/favicon-32x32.png",
"networks": ["1","4","5","3"]
},
{
"name": "Etherscan",
"url": "https://etherscan.io",
"icon": "https://etherscan.io/images/brandassets/etherscan-logo-circle.png",
"networks" : ["1"]
},
{
"name": "Etherscan",
"url": "https://goerli.etherscan.io",
"icon": "https://etherscan.io/images/brandassets/etherscan-logo-circle.png",
"networks" : ["5"]
},
{
"name": "Gnosis safe",
"url": "https://gnosis-safe.io/app",
"networks": ["1"],
"icon": "https://gnosis-safe.io/app/favicon.ico"
},
{
"name": "Gnosis safe",
"url": "https://rinkeby.gnosis-safe.io/app/",
"networks": ["4"],
"icon": "https://rinkeby.gnosis-safe.io/app/favicon.ico"
},
{
"name": "ReMix IDE",
"networks": [ "*" ],
"url": "http://remix.ethereum.org",
"icon": "https://raw.githubusercontent.com/ethereum/remix-ide/master/favicon.ico"
},
{
"name": "uniswap",
"url": "https://app.uniswap.org",
"networks": ["1"],
"icon": "https://app.uniswap.org/./favicon.png"
},
{
"name": "zkSync",
"url": "https://rinkeby.zksync.io",
"networks": ["1"],
"icon": "https://rinkeby.zksync.io/_nuxt/icons/icon_64x64.3fdd8f.png"
},
{
"name": "zkSync",
"url": "https://wallet zksync.io",
"networks": ["4"],
"icon": "https://rinkeby.zksync.io/_nuxt/icons/icon_64x64.3fdd8f.png"
},
{
"name": "Other Apps",
"url": "https://walletconnect.org/apps",
"icon": "https://example.walletconnect.org/favicon.ico"
}
]
""".trimIndent()
data class WalletConnectApp(val name: String, val url: String, val icon: String?, val networks: List<String>?)
data class WalletConnectEnhancedApp(val name: String, val url: String, val icon: String?, val networks: String?)
class WalletConnectListApps : BaseSubActivity() {
val moshi: Moshi by inject()
val appDatabase: AppDatabase by inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list_nofab)
supportActionBar?.subtitle = "WalletConnect Apps"
val adapter: JsonAdapter<List<WalletConnectApp>> = moshi.adapter(newParameterizedType(List::class.java, WalletConnectApp::class.java))
lifecycleScope.launch(Dispatchers.Default) {
val list = adapter.fromJson(list)!!.map {
val networks = it.networks?.map { network ->
val chainId = network.toBigIntegerOrNull()
when {
(chainId != null) -> appDatabase.chainInfo.getByChainId(chainId)?.name
(network == "*") -> "All networks"
else -> "Unknown"
}
}?.joinToString(", ")
WalletConnectEnhancedApp(it.name, it.url, it.icon, networks)
}
lifecycleScope.launch(Dispatchers.Main) {
recycler_view.layoutManager = LinearLayoutManager(this@WalletConnectListApps)
recycler_view.adapter = WalletConnectAdapter(list)
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_manage_wc, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.menu_input_text -> true.also {
showWalletConnectURLInputAlert()
}
else -> super.onOptionsItemSelected(item)
}
}
class WalletConnectAppViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
fun bind(app: WalletConnectEnhancedApp) {
view.app_name.text = app.name
view.app_networks.text = app.networks
view.app_networks.setVisibility(app.networks != null)
app.icon?.let {
view.session_icon.load(it)
}
view.session_card.setOnClickListener {
view.context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(app.url)).apply {
flags += Intent.FLAG_ACTIVITY_NEW_TASK
})
}
}
}
class WalletConnectAdapter(private val allFunctions: List<WalletConnectEnhancedApp>) : RecyclerView.Adapter<WalletConnectAppViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = WalletConnectAppViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_wc_app, parent, false))
override fun getItemCount() = allFunctions.size
override fun onBindViewHolder(holder: WalletConnectAppViewHolder, position: Int) {
holder.bind(allFunctions[position])
}
}
| app/src/main/java/org/walleth/walletconnect/WalletConnectListApps.kt | 3835945454 |
package info.hzvtc.hipixiv.vm.fragment
import android.content.Intent
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.StaggeredGridLayoutManager
import android.util.Log
import com.google.gson.Gson
import com.like.LikeButton
import info.hzvtc.hipixiv.R
import info.hzvtc.hipixiv.adapter.*
import info.hzvtc.hipixiv.adapter.events.*
import info.hzvtc.hipixiv.data.Account
import info.hzvtc.hipixiv.databinding.FragmentListBinding
import info.hzvtc.hipixiv.net.ApiService
import info.hzvtc.hipixiv.pojo.illust.Illust
import info.hzvtc.hipixiv.pojo.illust.IllustResponse
import info.hzvtc.hipixiv.util.AppMessage
import info.hzvtc.hipixiv.util.AppUtil
import info.hzvtc.hipixiv.view.fragment.BaseFragment
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.net.SocketTimeoutException
import javax.inject.Inject
class IllustViewModel @Inject constructor(val apiService: ApiService,val gson: Gson) :
BaseFragmentViewModel<BaseFragment<FragmentListBinding>, FragmentListBinding>(),ViewModelData<IllustResponse>{
var contentType : IllustAdapter.Type = IllustAdapter.Type.ILLUST
var obsNewData : Observable<IllustResponse>? = null
lateinit var account: Account
private var allowLoadMore = true
private var errorIndex = 0
private lateinit var adapter : IllustAdapter
override fun initViewModel() {
if(contentType == IllustAdapter.Type.MANGA){
val layoutManger = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
mBind.recyclerView.layoutManager = layoutManger
}else{
val layoutManger = GridLayoutManager(mView.context,2)
layoutManger.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup(){
override fun getSpanSize(pos: Int): Int =
if(adapter.getFull(pos)) 1 else layoutManger.spanCount
}
mBind.recyclerView.layoutManager = layoutManger
}
adapter = IllustAdapter(mView.context,contentType)
adapter.setItemClick(
itemClick = object : ItemClick {
override fun itemClick(illust: Illust) {
val intent = Intent(mView.getString(R.string.activity_content))
intent.putExtra(mView.getString(R.string.extra_json),gson.toJson(illust))
intent.putExtra(getString(R.string.extra_type),mView.getString(R.string.extra_type_illust))
ActivityCompat.startActivity(mView.context, intent, null)
}
}
)
adapter.setItemLike(itemLike = object : ItemLike {
override fun like(id: Int, itemIndex: Int,isRank: Boolean, likeButton: LikeButton) {
postLikeOrUnlike(id, itemIndex,true,isRank,likeButton)
}
override fun unlike(id: Int,itemIndex : Int,isRank: Boolean,likeButton: LikeButton) {
postLikeOrUnlike(id,itemIndex,false,isRank,likeButton)
}
})
mBind.srLayout.setColorSchemeColors(ContextCompat.getColor(mView.context, R.color.primary))
mBind.srLayout.setOnRefreshListener({ getData(obsNewData) })
mBind.recyclerView.addOnScrollListener(object : OnScrollListener() {
override fun onBottom() {
if(allowLoadMore){
getMoreData()
}
}
override fun scrollUp(dy: Int) {
getParent()?.showFab(false)
}
override fun scrollDown(dy: Int) {
getParent()?.showFab(true)
}
})
mBind.recyclerView.adapter = adapter
}
override fun runView() {
getData(obsNewData)
}
override fun getData(obs : Observable<IllustResponse>?){
if(obs != null){
Observable.just(obs)
.doOnNext({ errorIndex = 0 })
.doOnNext({ if(obs != obsNewData) obsNewData = obs })
.doOnNext({ mBind.srLayout.isRefreshing = true })
.observeOn(Schedulers.io())
.flatMap({ observable -> observable })
.doOnNext({ illustResponse -> adapter.setNewData(illustResponse) })
.observeOn(AndroidSchedulers.mainThread())
.doOnNext({
illustResponse ->
if(illustResponse.ranking.isNotEmpty()) rankingTopClick()
})
.subscribe({
_ -> adapter.updateUI(true)
},{
error ->
mBind.srLayout.isRefreshing = false
adapter.loadError()
processError(error)
},{
mBind.srLayout.isRefreshing = false
})
}
}
override fun getMoreData(){
Observable.just(adapter.nextUrl?:"")
.doOnNext({ errorIndex = 1 })
.doOnNext({ allowLoadMore = false })
.filter({ url -> !url.isNullOrEmpty() })
.observeOn(AndroidSchedulers.mainThread())
.doOnNext({ adapter.setProgress(true) })
.observeOn(Schedulers.io())
.flatMap({ account.obsToken(mView.context) })
.flatMap({ token -> apiService.getIllustNext(token,adapter.nextUrl?:"")})
.doOnNext({ illustResponse -> adapter.addMoreData(illustResponse) })
.observeOn(AndroidSchedulers.mainThread())
.doOnNext({ (content) ->
if (content.size == 0) {
AppMessage.toastMessageLong(mView.getString(R.string.no_more_data), mView.context)
}
})
.doOnNext({ illustResponse ->
if(illustResponse.nextUrl.isNullOrEmpty()){
AppMessage.toastMessageLong(mView.getString(R.string.is_last_data), mView.context)
}
})
.subscribe({
_ ->
adapter.setProgress(false)
adapter.updateUI(false)
},{
error->
adapter.setProgress(false)
allowLoadMore = true
processError(error)
},{
allowLoadMore = true
})
}
private fun postLikeOrUnlike(illustId : Int,position : Int,isLike : Boolean,isRank : Boolean,likeButton: LikeButton){
account.obsToken(mView.context)
.filter({ AppUtil.isNetworkConnected(mView.context) })
.flatMap({
token ->
if(isLike){
return@flatMap apiService.postLikeIllust(token,illustId,"public")
}else{
return@flatMap apiService.postUnlikeIllust(token,illustId)
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
adapter.updateBookmarked(position,isLike,isRank)
},{
error -> processError(error)
adapter.updateBookmarked(position,false,isRank)
likeButton.isLiked = false
},{
if(!AppUtil.isNetworkConnected(mView.context)){
adapter.updateBookmarked(position,false,isRank)
likeButton.isLiked = false
}
})
}
private fun rankingTopClick(){
adapter.setRankingTopClick(object : RankingTopClick {
override fun itemClick(type: RankingType) {
val intent = Intent(mView.getString(R.string.activity_ranking))
intent.putExtra(mView.getString(R.string.extra_string),type.value)
ActivityCompat.startActivity(mView.context, intent, null)
}
})
}
private fun processError(error : Throwable){
Log.e("Error",error.printStackTrace().toString())
if(AppUtil.isNetworkConnected(mView.context)){
val msg = if(error is SocketTimeoutException)
mView.getString(R.string.load_data_timeout)
else
mView.getString(R.string.load_data_failed)
Snackbar.make(getParent()?.getRootView()?:mBind.root.rootView, msg, Snackbar.LENGTH_LONG)
.setAction(mView.getString(R.string.app_dialog_ok),{
if(errorIndex == 0){
getData(obsNewData)
}else if(errorIndex == 1){
getMoreData()
}
}).show()
}
}
}
| app/src/main/java/info/hzvtc/hipixiv/vm/fragment/IllustViewModel.kt | 4009599758 |
package fr.o80.sample.lib.dagger
import javax.inject.Scope
/**
* @author Olivier Perez
*/
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class FeatureScope
| lib/src/main/java/fr/o80/sample/lib/dagger/FeatureScope.kt | 4280990110 |
/*
* ========================LICENSE_START=================================
* AEM Permission Management
* %%
* Copyright (C) 2013 Wunderman Thompson Technology
* %%
* 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.
* =========================LICENSE_END==================================
*/
package com.cognifide.apm.core.endpoints.utils
import com.cognifide.apm.core.endpoints.params.RequestParameter
import com.cognifide.apm.core.endpoints.response.ErrorBody
import com.cognifide.apm.core.endpoints.response.JsonObject
import com.cognifide.apm.core.endpoints.response.ResponseEntity
import com.cognifide.apm.core.utils.ServletUtils
import org.apache.sling.api.SlingHttpServletRequest
import org.apache.sling.api.SlingHttpServletResponse
import org.apache.sling.api.resource.ResourceResolver
import org.apache.sling.models.factory.MissingElementsException
import org.apache.sling.models.factory.ModelFactory
import javax.servlet.http.HttpServletResponse
class RequestProcessor<F>(private val modelFactory: ModelFactory, private val formClass: Class<F>) {
fun process(httpRequest: SlingHttpServletRequest, httpResponse: SlingHttpServletResponse,
process: (form: F, resourceResolver: ResourceResolver) -> ResponseEntity<Any>) {
try {
val form = modelFactory.createModel(httpRequest, formClass)
val response = process(form, httpRequest.resourceResolver)
httpResponse.setStatus(response.statusCode)
ServletUtils.writeJson(httpResponse, body(response.body))
} catch (e: MissingElementsException) {
httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST)
ServletUtils.writeJson(httpResponse, body(ErrorBody("Bad request", toErrors(e))))
} catch (e: Exception) {
httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
ServletUtils.writeJson(httpResponse, body(ErrorBody(e.message ?: "")))
}
}
private fun toErrors(e: MissingElementsException) = e.missingElements.mapNotNull { it.element }
.mapNotNull { it.getAnnotation(RequestParameter::class.java) }
.map { "Missing required parameter: ${it.value}" }
private fun body(body: Any) = if (body is JsonObject) body.toMap() else body
} | app/aem/core/src/main/kotlin/com/cognifide/apm/core/endpoints/utils/RequestProcessor.kt | 3518050137 |
package com.apollographql.apollo3
import com.apollographql.apollo3.api.AnyResponseAdapter
import com.apollographql.apollo3.api.Upload
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.api.ResponseAdapterCache
import com.apollographql.apollo3.api.internal.json.BufferedSinkJsonWriter
import com.apollographql.apollo3.api.internal.json.FileUploadAwareJsonWriter
import com.apollographql.apollo3.api.json.use
import com.benasher44.uuid.uuid4
import okio.Buffer
import okio.BufferedSink
import okio.ByteString
import kotlin.jvm.JvmStatic
/**
* [OperationRequestBodyComposer] is a helper class to create a body from an operation. The body will include serialized
* variables and possibly be multi-part if variables contain uploads.
*/
object OperationRequestBodyComposer {
interface Body {
val operations: ByteString
val contentType: String
val contentLength: Long
fun writeTo(bufferedSink: BufferedSink)
}
/**
* @param operation the instance of the [Operation] to create a body for.
* @param autoPersistQueries write the APQs extension if true
* @param withQueryDocument if false, skip writing the query document. This can be used with APQs to make network requests smaller
* @param responseAdapterCache a [ResponseAdapterCache] containing the custom scalar [ResponseAdapter] to use to serialize variables
*
* @return a [Body] to be sent over HTTP. It will either be of "application/json" type or "multipart/form-data" if variables contain
* [Upload]
*/
@JvmStatic
fun compose(
operation: Operation<*>,
autoPersistQueries: Boolean,
withQueryDocument: Boolean,
responseAdapterCache: ResponseAdapterCache
): Body {
val buffer = Buffer()
val jsonWriter = FileUploadAwareJsonWriter(BufferedSinkJsonWriter(buffer))
jsonWriter.use { writer ->
with(writer) {
beginObject()
name("operationName").value(operation.name())
name("variables")
beginObject()
operation.serializeVariables(this, responseAdapterCache)
endObject()
if (autoPersistQueries) {
name("extensions")
beginObject()
name("persistedQuery")
beginObject()
name("version").value(1)
name("sha256Hash").value(operation.id())
endObject()
endObject()
}
if (!autoPersistQueries || withQueryDocument) {
name("query").value(operation.document())
}
endObject()
}
}
buffer.flush()
val operationByteString = buffer.readByteString()
val uploads = jsonWriter.collectedUploads()
if (uploads.isEmpty()) {
return object : Body {
override val operations = operationByteString
override val contentType = "application/json"
override val contentLength = operationByteString.size.toLong()
override fun writeTo(bufferedSink: BufferedSink) {
bufferedSink.write(operationByteString)
}
}
} else {
return object : Body {
private val boundary = uuid4().toString()
override val operations = operationByteString
override val contentType = "multipart/form-data; boundary=$boundary"
// XXX: support non-chunked multipart
override val contentLength = -1L
override fun writeTo(bufferedSink: BufferedSink) {
bufferedSink.writeUtf8("--$boundary\r\n")
bufferedSink.writeUtf8("Content-Disposition: form-data; name=\"operations\"\r\n")
bufferedSink.writeUtf8("Content-Type: application/json\r\n")
bufferedSink.writeUtf8("Content-Length: ${operationByteString.size}\r\n")
bufferedSink.writeUtf8("\r\n")
bufferedSink.write(operationByteString)
val uploadsMapBuffer = uploads.toMapBuffer()
bufferedSink.writeUtf8("\r\n--$boundary\r\n")
bufferedSink.writeUtf8("Content-Disposition: form-data; name=\"map\"\r\n")
bufferedSink.writeUtf8("Content-Type: application/json\r\n")
bufferedSink.writeUtf8("Content-Length: ${uploadsMapBuffer.size}\r\n")
bufferedSink.writeUtf8("\r\n")
bufferedSink.writeAll(uploadsMapBuffer)
uploads.values.forEachIndexed { index, upload ->
bufferedSink.writeUtf8("\r\n--$boundary\r\n")
bufferedSink.writeUtf8("Content-Disposition: form-data; name=\"$index\"")
if (upload.fileName != null) {
bufferedSink.writeUtf8("; filename=\"${upload.fileName}\"")
}
bufferedSink.writeUtf8("\r\n")
bufferedSink.writeUtf8("Content-Type: ${upload.contentType}\r\n")
val contentLength = upload.contentLength
if (contentLength != -1L) {
bufferedSink.writeUtf8("Content-Length: $contentLength\r\n")
}
bufferedSink.writeUtf8("\r\n")
upload.writeTo(bufferedSink)
}
bufferedSink.writeUtf8("\r\n--$boundary--\r\n")
}
}
}
}
private fun Map<String, Upload>.toMapBuffer(): Buffer {
val buffer = Buffer()
BufferedSinkJsonWriter(buffer).use {
AnyResponseAdapter.toResponse(it, ResponseAdapterCache.DEFAULT, entries.mapIndexed { index, entry ->
index.toString() to listOf(entry.key)
}.toMap())
}
return buffer
}
}
| apollo-runtime-common/src/commonMain/kotlin/com/apollographql/apollo3/OperationRequestBodyComposer.kt | 3886913726 |
package com.gkzxhn.mygithub.extension
import android.util.Base64
import java.io.ByteArrayOutputStream
import java.io.ObjectOutputStream
/**
* Created by 方 on 2017/12/29.
*/
fun List<Any>.base64Encode(): String {
// 实例化一个ByteArrayOutputStream对象,用来装载压缩后的字节文件。
val byteArrayOutputStream = ByteArrayOutputStream()
// 然后将得到的字符数据装载到ObjectOutputStream
val objectOutputStream = ObjectOutputStream(
byteArrayOutputStream)
// writeObject 方法负责写入特定类的对象的状态,以便相应的 readObject 方法可以还原它
objectOutputStream.writeObject(this)
// 最后,用Base64.encode将字节文件转换成Base64编码保存在String中
val SceneListString = String(Base64.encode(
byteArrayOutputStream.toByteArray(), Base64.DEFAULT))
// 关闭objectOutputStream
objectOutputStream.close()
return SceneListString
} | app/src/main/java/com/gkzxhn/mygithub/extension/ListExtensions.kt | 1445153468 |
package com.emedinaa.infosoft2017
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentTransaction
import android.view.MenuItem
import com.emedinaa.infosoft2017.ui.BaseActivityK
import com.emedinaa.infosoft2017.ui.fragmentskt.HomeFragmentK
import com.emedinaa.infosoft2017.ui.fragmentskt.ScheduleFragmentK
import com.emedinaa.infosoft2017.ui.fragmentskt.SpeakersFragmentK
import com.emedinaa.infosoft2017.ui.fragmentskt.SponsorsFragmentK
import kotlinx.android.synthetic.main.activity_main.*
class MainActivityK : BaseActivityK() {
private var itemId=0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
app()
}
/**
* Kotlin when
* https://kotlinlang.org/docs/reference/basic-syntax.html
*/
private fun app() {
val menuItem:MenuItem= bottomNavigation.menu.getItem(0)
itemId= menuItem.itemId
changeFragment(HomeFragmentK.newInstance())
bottomNavigation.setOnNavigationItemSelectedListener {item: MenuItem ->
var fragment:Fragment?=null
var tab=0
itemId= item.itemId
when(item.itemId){
R.id.action_home -> {
tab = 0
fragment= HomeFragmentK.newInstance()
}
R.id.action_speakers -> {
tab =1
fragment= SpeakersFragmentK.newInstance()
}
R.id.action_schedule-> {
tab=2
fragment= ScheduleFragmentK.newInstance()
}
R.id.action_sponsors-> {
tab=3
fragment= SponsorsFragmentK.newInstance()
}
}
changeFragment(fragment!!)
true
}
}
private fun changeFragment(fragment: Fragment){
val fragmenTransaction:FragmentTransaction= supportFragmentManager.beginTransaction()
fragmenTransaction.replace(R.id.frameLayout,fragment,null)
fragmenTransaction.commit()
}
}
| Infosoft2017/app/src/main/java/com/emedinaa/infosoft2017/MainActivityK.kt | 1617448105 |
package com.camerakit.preview
import android.graphics.SurfaceTexture
import android.opengl.Matrix
import androidx.annotation.Keep
import com.camerakit.type.CameraSize
class CameraSurfaceTexture(inputTexture: Int, val outputTexture: Int) : SurfaceTexture(inputTexture) {
var size: CameraSize = CameraSize(0, 0)
set(size) {
field = size
previewInvalidated = true
}
private var previewInvalidated = false
private val transformMatrix: FloatArray = FloatArray(16)
private val extraTransformMatrix: FloatArray = FloatArray(16)
init {
nativeInit(inputTexture, outputTexture)
Matrix.setIdentityM(extraTransformMatrix, 0)
}
override fun updateTexImage() {
if (previewInvalidated) {
nativeSetSize(size.width, size.height)
previewInvalidated = false
}
super.updateTexImage()
getTransformMatrix(transformMatrix)
nativeUpdateTexImage(transformMatrix, extraTransformMatrix)
}
override fun release() {
nativeRelease()
}
fun setRotation(degrees: Int) {
Matrix.setIdentityM(extraTransformMatrix, 0)
Matrix.rotateM(extraTransformMatrix, 0, degrees.toFloat(), 0f, 0f, 1f)
}
// ---
override fun finalize() {
super.finalize()
try {
nativeFinalize()
} catch (e: Exception) {
// ignore
}
}
// ---
@Keep
private var nativeHandle: Long = 0L
private external fun nativeInit(inputTexture: Int, outputTexture: Int)
private external fun nativeSetSize(width: Int, height: Int)
private external fun nativeUpdateTexImage(transformMatrix: FloatArray, extraTransformMatrix: FloatArray)
private external fun nativeFinalize()
private external fun nativeRelease()
companion object {
init {
System.loadLibrary("camerakit")
}
}
}
| camerakit/src/main/java/com/camerakit/preview/CameraSurfaceTexture.kt | 3541703447 |
package com.apollographql.apollo3.compiler
import com.apollographql.apollo3.compiler.TestUtils.checkExpected
import com.apollographql.apollo3.compiler.TestUtils.testParametersForGraphQLFilesIn
import com.apollographql.apollo3.graphql.ast.GraphQLParser
import com.apollographql.apollo3.graphql.ast.Issue
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.io.File
@Suppress("UNUSED_PARAMETER")
@RunWith(Parameterized::class)
class ValidationTest(name: String, private val graphQLFile: File) {
private val separator = "\n------------\n"
private fun List<Issue>.serialize() = joinToString(separator) {
"${it.severity}: ${it.javaClass.simpleName} (${it.sourceLocation.line}:${it.sourceLocation.position})\n${it.message}"
}
@Test
fun testValidation() = checkExpected(graphQLFile) { schema ->
val issues = if (graphQLFile.parentFile.name == "operation") {
GraphQLParser.parseOperations(graphQLFile, schema!!).issues
} else {
// schema is unused there
GraphQLParser.parseSchemaInternal(graphQLFile).issues
}
issues.serialize()
}
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun data() = testParametersForGraphQLFilesIn("src/test/validation/")
}
}
| apollo-compiler/src/test/kotlin/com/apollographql/apollo3/compiler/ValidationTest.kt | 1417678504 |
package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.entities.VersionChange
import java.util.*
class VersionChangeTransaction(
private val versionName: String,
private val versionCode: Int,
private val gitRemote: String?,
private val commitHash: String?) : Transaction<Unit>() {
override fun run() {
val current = database.versionChangeDao.getMostRecentVersionChange()
if (current == null
|| current.versionName != versionName
|| current.versionCode != versionCode
|| current.gitRemote != gitRemote
|| current.commitHash != commitHash) {
database.versionChangeDao.insert(VersionChange(
timestamp = System.currentTimeMillis(),
versionCode = versionCode,
versionName = versionName,
gitRemote = gitRemote,
commitHash = commitHash
))
}
}
} | database/src/main/java/info/nightscout/androidaps/database/transactions/VersionChangeTransaction.kt | 4120017100 |
/*
* Copyright (c) 2020 Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.cryart.sabbathschool.lessons.ui.lessons
import androidx.compose.runtime.snapshotFlow
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.ss.lessons.data.repository.lessons.LessonsRepository
import app.ss.lessons.data.repository.quarterly.QuarterliesRepository
import app.ss.models.LessonPdf
import app.ss.models.PublishingInfo
import app.ss.models.SSQuarterlyInfo
import app.ss.widgets.AppWidgetHelper
import com.cryart.sabbathschool.core.extensions.coroutines.flow.stateIn
import com.cryart.sabbathschool.core.extensions.prefs.SSPrefs
import com.cryart.sabbathschool.core.misc.SSConstants
import com.cryart.sabbathschool.core.response.Result
import com.cryart.sabbathschool.core.response.asResult
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class LessonsViewModel @Inject constructor(
private val repository: QuarterliesRepository,
private val lessonsRepository: LessonsRepository,
private val ssPrefs: SSPrefs,
private val appWidgetHelper: AppWidgetHelper,
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
private val quarterlyIndex: String?
get() = savedStateHandle.get<String>(
SSConstants.SS_QUARTERLY_INDEX_EXTRA
) ?: ssPrefs.getLastQuarterlyIndex()
private val publishingInfo: Flow<Result<PublishingInfo?>> = repository.getPublishingInfo()
.map { it.data }
.asResult()
private val quarterlyInfo: Flow<Result<SSQuarterlyInfo?>> = snapshotFlow { quarterlyIndex }
.flatMapLatest { index ->
index?.run {
repository.getQuarterlyInfo(index)
.map { it.data }
} ?: flowOf(null)
}
.onEach { info ->
info?.run { appWidgetHelper.refreshAll() }
}
.asResult()
private val _selectedPdfs = MutableSharedFlow<Pair<String, List<LessonPdf>>>()
val selectedPdfsFlow: SharedFlow<Pair<String, List<LessonPdf>>> = _selectedPdfs
val uiState: StateFlow<LessonsScreenState> = combine(
publishingInfo,
quarterlyInfo
) { publishingInfo, quarterlyInfo ->
val publishingInfoState = when (publishingInfo) {
is Result.Error -> PublishingInfoState.Error
Result.Loading -> PublishingInfoState.Loading
is Result.Success -> publishingInfo.data?.let {
PublishingInfoState.Success(it)
} ?: PublishingInfoState.Error
}
val quarterlyInfoState = when (quarterlyInfo) {
is Result.Error -> QuarterlyInfoState.Error
Result.Loading -> QuarterlyInfoState.Loading
is Result.Success -> quarterlyInfo.data?.let {
QuarterlyInfoState.Success(it)
} ?: QuarterlyInfoState.Error
}
LessonsScreenState(
isLoading = quarterlyInfoState == QuarterlyInfoState.Loading,
isError = quarterlyInfoState == QuarterlyInfoState.Error,
publishingInfo = publishingInfoState,
quarterlyInfo = quarterlyInfoState
)
}.stateIn(viewModelScope, LessonsScreenState())
private val ssQuarterlyInfo: SSQuarterlyInfo? get() = (uiState.value.quarterlyInfo as? QuarterlyInfoState.Success)?.quarterlyInfo
val quarterlyShareIndex: String get() = ssQuarterlyInfo?.shareIndex() ?: ""
init {
// cache DisplayOptions for read screen launch
ssPrefs.getDisplayOptions { }
}
fun pdfLessonSelected(lessonIndex: String) = viewModelScope.launch {
val resource = lessonsRepository.getLessonInfo(lessonIndex)
if (resource.isSuccessFul) {
val data = resource.data
_selectedPdfs.emit(lessonIndex to (data?.pdfs ?: emptyList()))
}
}
}
| features/lessons/src/main/java/com/cryart/sabbathschool/lessons/ui/lessons/LessonsViewModel.kt | 4136007621 |
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.web.server
import io.mockk.every
import io.mockk.mockk
import java.security.cert.Certificate
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.io.ClassPathResource
import org.springframework.http.client.reactive.ClientHttpConnector
import org.springframework.http.server.reactive.ServerHttpRequestDecorator
import org.springframework.http.server.reactive.SslInfo
import org.springframework.lang.Nullable
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity
import org.springframework.security.config.test.SpringTestContext
import org.springframework.security.config.test.SpringTestContextExtension
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService
import org.springframework.security.core.userdetails.User
import org.springframework.security.web.authentication.preauth.x509.SubjectDnX509PrincipalExtractor
import org.springframework.security.web.server.SecurityWebFilterChain
import org.springframework.security.web.server.authentication.ReactivePreAuthenticatedAuthenticationManager
import org.springframework.test.web.reactive.server.MockServerConfigurer
import org.springframework.test.web.reactive.server.WebTestClient
import org.springframework.test.web.reactive.server.WebTestClientConfigurer
import org.springframework.test.web.reactive.server.expectBody
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.reactive.config.EnableWebFlux
import org.springframework.web.server.ServerWebExchange
import org.springframework.web.server.ServerWebExchangeDecorator
import org.springframework.web.server.WebFilter
import org.springframework.web.server.WebFilterChain
import org.springframework.web.server.adapter.WebHttpHandlerBuilder
import reactor.core.publisher.Mono
/**
* Tests for [ServerX509Dsl]
*
* @author Eleftheria Stein
*/
@ExtendWith(SpringTestContextExtension::class)
class ServerX509DslTests {
@JvmField
val spring = SpringTestContext(this)
private lateinit var client: WebTestClient
@Autowired
fun setup(context: ApplicationContext) {
this.client = WebTestClient
.bindToApplicationContext(context)
.configureClient()
.build()
}
@Test
fun `x509 when configured with defaults then user authenticated with expected username`() {
this.spring
.register(X509DefaultConfig::class.java, UserDetailsConfig::class.java, UsernameController::class.java)
.autowire()
val certificate = loadCert<X509Certificate>("rod.cer")
this.client
.mutateWith(mockX509(certificate))
.get()
.uri("/username")
.exchange()
.expectStatus().isOk
.expectBody<String>().isEqualTo("rod")
}
@EnableWebFluxSecurity
@EnableWebFlux
open class X509DefaultConfig {
@Bean
open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
x509 { }
}
}
}
@Test
fun `x509 when principal extractor customized then custom principal extractor used`() {
this.spring
.register(PrincipalExtractorConfig::class.java, UserDetailsConfig::class.java, UsernameController::class.java)
.autowire()
val certificate = loadCert<X509Certificate>("rodatexampledotcom.cer")
this.client
.mutateWith(mockX509(certificate))
.get()
.uri("/username")
.exchange()
.expectStatus().isOk
.expectBody<String>().isEqualTo("rod")
}
@EnableWebFluxSecurity
@EnableWebFlux
open class PrincipalExtractorConfig {
@Bean
open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
val customPrincipalExtractor = SubjectDnX509PrincipalExtractor()
customPrincipalExtractor.setSubjectDnRegex("CN=(.*?)@example.com(?:,|$)")
return http {
x509 {
principalExtractor = customPrincipalExtractor
}
}
}
}
@Test
fun `x509 when authentication manager customized then custom authentication manager used`() {
this.spring
.register(AuthenticationManagerConfig::class.java, UsernameController::class.java)
.autowire()
val certificate = loadCert<X509Certificate>("rod.cer")
this.client
.mutateWith(mockX509(certificate))
.get()
.uri("/username")
.exchange()
.expectStatus().isOk
.expectBody<String>().isEqualTo("rod")
}
@EnableWebFluxSecurity
@EnableWebFlux
open class AuthenticationManagerConfig {
@Bean
open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
x509 {
authenticationManager = ReactivePreAuthenticatedAuthenticationManager(userDetailsService())
}
}
}
fun userDetailsService(): MapReactiveUserDetailsService {
val user = User.withDefaultPasswordEncoder()
.username("rod")
.password("password")
.roles("USER")
.build()
return MapReactiveUserDetailsService(user)
}
}
@RestController
class UsernameController {
@GetMapping("/username")
fun principal(@AuthenticationPrincipal user: User?): String {
return user!!.username
}
}
@Configuration
open class UserDetailsConfig {
@Bean
open fun userDetailsService(): MapReactiveUserDetailsService {
val user = User.withDefaultPasswordEncoder()
.username("rod")
.password("password")
.roles("USER")
.build()
return MapReactiveUserDetailsService(user)
}
}
private fun mockX509(certificate: X509Certificate): X509Mutator {
return X509Mutator(certificate)
}
private class X509Mutator internal constructor(private var certificate: X509Certificate) : WebTestClientConfigurer, MockServerConfigurer {
override fun afterConfigurerAdded(builder: WebTestClient.Builder,
@Nullable httpHandlerBuilder: WebHttpHandlerBuilder?,
@Nullable connector: ClientHttpConnector?) {
val filter = SetSslInfoWebFilter(certificate)
httpHandlerBuilder!!.filters { filters: MutableList<WebFilter?> -> filters.add(0, filter) }
}
}
private class SetSslInfoWebFilter(var certificate: X509Certificate) : WebFilter {
override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
return chain.filter(decorate(exchange))
}
private fun decorate(exchange: ServerWebExchange): ServerWebExchange {
val decorated: ServerHttpRequestDecorator = object : ServerHttpRequestDecorator(exchange.request) {
override fun getSslInfo(): SslInfo {
val sslInfo: SslInfo = mockk()
every { sslInfo.sessionId } returns "sessionId"
every { sslInfo.peerCertificates } returns arrayOf(certificate)
return sslInfo
}
}
return object : ServerWebExchangeDecorator(exchange) {
override fun getRequest(): org.springframework.http.server.reactive.ServerHttpRequest {
return decorated
}
}
}
}
private fun <T : Certificate> loadCert(location: String): T {
ClassPathResource(location).inputStream.use { inputStream ->
val certFactory = CertificateFactory.getInstance("X.509")
return certFactory.generateCertificate(inputStream) as T
}
}
}
| config/src/test/kotlin/org/springframework/security/config/web/server/ServerX509DslTests.kt | 3470084145 |
/*
* Copyright (c) 2021. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.cryart.sabbathschool.test.di.repository
import app.ss.models.Language
import app.ss.lessons.data.repository.quarterly.QuarterliesRepository
import app.ss.models.PublishingInfo
import app.ss.models.QuarterlyGroup
import app.ss.models.SSQuarterly
import app.ss.models.SSQuarterlyInfo
import com.cryart.sabbathschool.core.response.Resource
import com.cryart.sabbathschool.test.di.mock.QuarterlyMockData
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.flowOf
import javax.inject.Inject
class FakeQuarterliesRepository @Inject constructor(
private val mockData: QuarterlyMockData
) : QuarterliesRepository {
override fun getLanguages(): Flow<Resource<List<Language>>> {
return flowOf(Resource.success(emptyList()))
}
override fun getQuarterlies(languageCode: String?, group: QuarterlyGroup?): Flow<Resource<List<SSQuarterly>>> {
return flowOf(Resource.success(mockData.getQuarterlies(group)))
}
override fun getQuarterlyInfo(index: String): Flow<Resource<SSQuarterlyInfo>> {
return flowOf(
mockData.getQuarterlyInfo(index)?.let {
Resource.success(it)
} ?: Resource.error(Throwable())
)
}
override fun getPublishingInfo(languageCode: String?): Flow<Resource<PublishingInfo>> {
return emptyFlow()
}
}
| libraries/test_utils/src/main/java/com/cryart/sabbathschool/test/di/repository/FakeQuarterliesRepository.kt | 1354220696 |
package arcs.core.crdt
import com.google.common.truth.Truth
fun <T : CrdtData, U : CrdtOperation, V> invariant_mergeWithSelf_producesNoChanges(
model: CrdtModel<T, U, V>
) {
val changes = model.merge(model.data)
Truth.assertThat(changes.modelChange.isEmpty()).isTrue()
Truth.assertThat(changes.otherChange.isEmpty()).isTrue()
}
| javatests/arcs/core/crdt/CrdtInvariants.kt | 686011023 |
/*
* Copyright (c) 2017. All Rights Reserved. Michal Jankowski orbitemobile.pl
*/
package pl.orbitemobile.wspolnoty.activities.contact
import pl.orbitemobile.mvp.MvpPresenter
import pl.orbitemobile.mvp.MvpView
class ContactContract {
abstract class View(layoutId: Int) : MvpView<Presenter>(layoutId)
interface Presenter : MvpPresenter<View> {
fun onPhoneClick()
fun onMailClick()
fun onWebsiteClick()
}
}
| app/src/main/java/pl/orbitemobile/wspolnoty/activities/contact/ContactContract.kt | 1734334448 |
/*
* Copyright 2018 Duncan Casteleyn
*
* 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 be.duncanc.discordmodbot.bot.services
import be.duncanc.discordmodbot.bot.commands.CommandModule
import be.duncanc.discordmodbot.bot.utils.nicknameAndUsername
import be.duncanc.discordmodbot.data.entities.MuteRole
import be.duncanc.discordmodbot.data.repositories.jpa.MuteRolesRepository
import net.dv8tion.jda.api.EmbedBuilder
import net.dv8tion.jda.api.Permission
import net.dv8tion.jda.api.entities.Guild
import net.dv8tion.jda.api.entities.Role
import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent
import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent
import net.dv8tion.jda.api.events.guild.member.GuildMemberRoleAddEvent
import net.dv8tion.jda.api.events.guild.member.GuildMemberRoleRemoveEvent
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import net.dv8tion.jda.api.events.role.RoleDeleteEvent
import net.dv8tion.jda.api.exceptions.PermissionException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional
import java.awt.Color
import java.util.concurrent.TimeUnit
@Component
@Transactional
class MuteRole
@Autowired constructor(
private val muteRolesRepository: MuteRolesRepository,
private val guildLogger: GuildLogger
) : CommandModule(
arrayOf("MuteRole"),
"[Name of the mute role or nothing to remove the role]",
"This command allows you to set the mute role for a guild/server"
) {
override fun commandExec(event: MessageReceivedEvent, command: String, arguments: String?) {
if (event.member?.hasPermission(Permission.MANAGE_ROLES) != true) {
throw PermissionException("You do not have sufficient permissions to set the mute role for this server")
}
val guildId = event.guild.idLong
if (arguments == null) {
muteRolesRepository.deleteById(guildId)
event.channel.sendMessage("Mute role has been removed.")
.queue { it.delete().queueAfter(1, TimeUnit.MINUTES) }
} else {
try {
muteRolesRepository.save(MuteRole(guildId, event.guild.getRolesByName(arguments, false)[0].idLong))
event.channel.sendMessage("Role has been set as mute role.")
.queue { it.delete().queueAfter(1, TimeUnit.MINUTES) }
} catch (exception: IndexOutOfBoundsException) {
throw IllegalArgumentException("Couldn't find any roles with that name.", exception)
}
}
}
override fun onRoleDelete(event: RoleDeleteEvent) {
muteRolesRepository.deleteByRoleIdAndGuildId(event.role.idLong, event.guild.idLong)
}
@Transactional(readOnly = true)
fun getMuteRole(guild: Guild): Role {
val roleId = muteRolesRepository.findById(guild.idLong)
.orElse(null)?.roleId
?: throw IllegalStateException("This guild does not have a mute role set up.")
return guild.getRoleById(roleId)!!
}
override fun onGuildMemberRoleAdd(event: GuildMemberRoleAddEvent) {
val muteRole = muteRolesRepository.findById(event.guild.idLong)
.orElse(null)
if (!(muteRole == null || !event.roles.contains(muteRole.roleId.let { event.guild.getRoleById(it) }))) {
muteRole.mutedUsers.add(event.user.idLong)
muteRolesRepository.save(muteRole)
}
}
override fun onGuildMemberRoleRemove(event: GuildMemberRoleRemoveEvent) {
val muteRole = muteRolesRepository.findById(event.guild.idLong)
.orElse(null)
if (muteRole != null && event.roles.contains(muteRole.roleId.let { event.guild.getRoleById(it) })) {
muteRole.mutedUsers.remove(event.user.idLong)
muteRolesRepository.save(muteRole)
}
}
override fun onGuildMemberRemove(event: GuildMemberRemoveEvent) {
val member = event.member
val muteRole = muteRolesRepository.findById(event.guild.idLong)
.orElse(null)
if (muteRole != null && member != null) {
if (member.roles.contains(muteRole.roleId.let { event.guild.getRoleById(it) })) {
muteRole.mutedUsers.add(event.user.idLong)
muteRolesRepository.save(muteRole)
} else {
muteRole.mutedUsers.remove(event.user.idLong)
muteRolesRepository.save(muteRole)
}
}
}
override fun onGuildMemberJoin(event: GuildMemberJoinEvent) {
val muteRole = muteRolesRepository.findById(event.guild.idLong)
.orElse(null)
if (muteRole?.roleId != null && muteRole.mutedUsers.contains(event.user.idLong)) {
event.guild.addRoleToMember(event.member, event.guild.getRoleById(muteRole.roleId)!!).queue()
val logEmbed = EmbedBuilder()
.setColor(Color.YELLOW)
.setTitle("User automatically muted")
.addField("User", event.member.nicknameAndUsername, true)
.addField("Reason", "Previously muted before leaving the server", false)
guildLogger.log(
guild = event.guild,
associatedUser = event.user,
logEmbed = logEmbed,
actionType = GuildLogger.LogTypeAction.MODERATOR
)
}
}
}
| src/main/kotlin/be/duncanc/discordmodbot/bot/services/MuteRole.kt | 2688266688 |
/*
* Copyright 2019 Poly Forest, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.component.style
import com.acornui.component.UiComponent
object CommonStyleTags {
/**
* Some components may be disabled, when they are, they are expected to add this tag.
*/
val disabled by cssClass()
val toggled by cssClass()
val active by cssClass()
val hidden by cssClass()
val popup by cssClass()
val controlBar by cssClass()
}
var UiComponent.disabledTag: Boolean by CssClassToggle(CommonStyleTags.disabled)
| acornui-core/src/main/kotlin/com/acornui/component/style/CommonStyles.kt | 3229360218 |
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache
import org.gradle.configurationcache.extensions.unsafeLazy
import org.gradle.configurationcache.initialization.ConfigurationCacheStartParameter
import org.gradle.internal.buildtree.BuildActionModelRequirements
import org.gradle.internal.hash.Hasher
import org.gradle.internal.hash.Hashing
import org.gradle.internal.service.scopes.Scopes
import org.gradle.internal.service.scopes.ServiceScope
import org.gradle.util.GradleVersion
import org.gradle.util.internal.GFileUtils.relativePathOf
import java.io.File
@ServiceScope(Scopes.BuildTree::class)
class ConfigurationCacheKey(
private val startParameter: ConfigurationCacheStartParameter,
private val buildActionRequirements: BuildActionModelRequirements
) {
val string: String by unsafeLazy {
Hashing.md5().newHasher().apply {
putCacheKeyComponents()
}.hash().toCompactString()
}
override fun toString() = string
override fun hashCode(): Int = string.hashCode()
override fun equals(other: Any?): Boolean = (other as? ConfigurationCacheKey)?.string == string
private
fun Hasher.putCacheKeyComponents() {
putString(GradleVersion.current().version)
putString(
startParameter.settingsFile?.let {
relativePathOf(it, startParameter.rootDirectory)
} ?: ""
)
putAll(
startParameter.includedBuilds.map {
relativePathOf(it, startParameter.rootDirectory)
}
)
buildActionRequirements.appendKeyTo(this)
// TODO:bamboo review with Adam
// require(buildActionRequirements.isRunsTasks || startParameter.requestedTaskNames.isEmpty())
if (buildActionRequirements.isRunsTasks) {
appendRequestedTasks()
}
}
private
fun Hasher.appendRequestedTasks() {
val requestedTaskNames = startParameter.requestedTaskNames
putAll(requestedTaskNames)
val excludedTaskNames = startParameter.excludedTaskNames
putAll(excludedTaskNames)
val taskNames = requestedTaskNames.asSequence() + excludedTaskNames.asSequence()
val hasRelativeTaskName = taskNames.any { !it.startsWith(':') }
if (hasRelativeTaskName) {
// Because unqualified task names are resolved relative to the selected
// sub-project according to either `projectDirectory` or `currentDirectory`,
// the relative directory information must be part of the key.
val projectDir = startParameter.projectDirectory
if (projectDir != null) {
relativePathOf(
projectDir,
startParameter.rootDirectory
).let { relativeProjectDir ->
putString(relativeProjectDir)
}
} else {
relativeChildPathOrNull(
startParameter.currentDirectory,
startParameter.rootDirectory
)?.let { relativeSubDir ->
putString(relativeSubDir)
}
}
}
}
private
fun Hasher.putAll(list: Collection<String>) {
putInt(list.size)
list.forEach(::putString)
}
/**
* Returns the path of [target] relative to [base] if
* [target] is a child of [base] or `null` otherwise.
*/
private
fun relativeChildPathOrNull(target: File, base: File): String? =
relativePathOf(target, base)
.takeIf { !it.startsWith('.') }
}
| subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/ConfigurationCacheKey.kt | 895866015 |
package com.firebase.hackweek.tank18thscale
class Blinker(private val threshold: Float = 0.5f, private val ti: TankInterface) {
fun blink(happiness: Float) {
if (happiness > this.threshold) {
ti.turnGreen()
}
else {
ti.turnRed()
}
return
}
} | app/src/main/java/com/firebase/hackweek/tank18thscale/Blinker.kt | 891501582 |
actual typealias <!LINE_MARKER("descr='Has expects in common module'")!>Common<!> = Short
fun nativeTest(arg: Common) {
takeCommon(arg)
}
| plugins/kotlin/idea/tests/testData/multiplatform/chainedTypeAliasRefinement/native/native.kt | 1216795900 |
// JS
// PROBLEM: Suspicious 'asDynamic' member invocation
// FIX: Remove 'asDynamic' invocation
fun test(d: dynamic) {
d.<caret>asDynamic().foo()
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/suspiciousAsDynamic/simple.kt | 3817309638 |
fun synthesize(p: SyntheticProperty) {
val v1 = p.syntheticA
p.syntheticA = 1
p.syntheticA += 2
p.syntheticA++
val x = p.syntheticA++
val y = ++p.syntheticA
} | plugins/kotlin/idea/tests/testData/refactoring/rename/javaSetterToOrdinaryMethod/before/synthesize.kt | 1453494472 |
class C(<caret>val v: Int) | plugins/kotlin/idea/tests/testData/intentions/changeVisibility/private/noModifierListValParam.kt | 3346046618 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.