content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package hu.nevermind.demo.data
object Role {
const val Admin: String = "ROLE_ADMIN"
const val User: String = "ROLE_USER"
} | backend/src/main/kotlin/hu/nevermind/demo/data/Role.kt | 1314527970 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.inspection.suppress
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.OVERWRITE
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.SHADOW
import com.demonwav.mcdev.util.findContainingMember
import com.intellij.codeInspection.InspectionSuppressor
import com.intellij.codeInspection.SuppressQuickFix
import com.intellij.codeInspection.visibility.VisibilityInspection
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
class ShadowOverwriteInspectionSuppressor : InspectionSuppressor {
private val SUPPRESSED_INSPECTIONS = setOf(
"UnusedReturnValue",
"SameParameterValue",
"Guava",
VisibilityInspection.SHORT_NAME,
"MethodMayBeStatic"
)
override fun isSuppressedFor(element: PsiElement, toolId: String): Boolean {
if (toolId !in SUPPRESSED_INSPECTIONS) {
return false
}
val member = element.findContainingMember() ?: return false
return member.hasAnnotation(SHADOW) || (member is PsiMethod && member.hasAnnotation(OVERWRITE))
}
override fun getSuppressActions(element: PsiElement?, toolId: String): Array<SuppressQuickFix> =
SuppressQuickFix.EMPTY_ARRAY
}
| src/main/kotlin/platform/mixin/inspection/suppress/ShadowOverwriteInspectionSuppressor.kt | 3441652745 |
/*
* Copyright (C) 2017-2022 Alexey Rochev <[email protected]>
*
* This file is part of Tremotesf.
*
* Tremotesf 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.
*
* Tremotesf is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.equeim.tremotesf.ui.views
import android.content.Context
import android.text.InputType
import android.util.AttributeSet
import androidx.annotation.AttrRes
import androidx.core.content.withStyledAttributes
import com.google.android.material.textfield.MaterialAutoCompleteTextView
import org.equeim.tremotesf.R
class NonFilteringAutoCompleteTextView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
@AttrRes defStyleAttr: Int = androidx.appcompat.R.attr.autoCompleteTextViewStyle
) : MaterialAutoCompleteTextView(context, attrs, defStyleAttr) {
init {
context.withStyledAttributes(
attrs,
R.styleable.NonFilteringAutoCompleteTextView,
defStyleAttr,
0
) {
if (getBoolean(R.styleable.NonFilteringAutoCompleteTextView_readOnly, false)) {
inputType = InputType.TYPE_NULL
}
}
}
override fun performFiltering(text: CharSequence?, keyCode: Int) {}
}
| app/src/main/kotlin/org/equeim/tremotesf/ui/views/NonFilteringAutoCompleteTextView.kt | 4089251802 |
package io.mockk.impl.recording
import io.mockk.impl.instantiation.AbstractInstantiator
import io.mockk.impl.instantiation.AnyValueGenerator
import kotlin.reflect.KClass
interface SignatureValueGenerator {
fun <T : Any> signatureValue(
cls: KClass<T>,
anyValueGeneratorProvider: () -> AnyValueGenerator,
instantiator: AbstractInstantiator,
): T
}
| modules/mockk/src/commonMain/kotlin/io/mockk/impl/recording/SignatureValueGenerator.kt | 2888952382 |
package t.masahide.android.croudia.ui.fragment
import android.os.Bundle
/**
* Created by Masahide on 2016/05/04.
*/
class PublicTimeLineFragment : TimelineFragmentBase() {
companion object {
fun newInstance(): PublicTimeLineFragment {
val fragment = PublicTimeLineFragment()
val args = Bundle()
fragment.arguments = args
return fragment
}
}
} | app/src/main/kotlin/t/masahide/android/croudia/ui/fragment/PublicTimeLineFragment.kt | 1746715558 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2012-2018 DragonBones team and other contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.dragonbones.model
import com.dragonbones.core.*
import com.soywiz.kds.*
import com.soywiz.kds.iterators.*
/**
* - The skin data, typically a armature data instance contains at least one skinData.
* @version DragonBones 3.0
* @language en_US
*/
/**
* - 皮肤数据,通常一个骨架数据至少包含一个皮肤数据。
* @version DragonBones 3.0
* @language zh_CN
*/
class SkinData(pool: SingleObjectPool<SkinData>) : BaseObject(pool) {
/**
* - The skin name.
* @version DragonBones 3.0
* @language en_US
*/
/**
* - 皮肤名称。
* @version DragonBones 3.0
* @language zh_CN
*/
var name: String = ""
/**
* @private
*/
val displays: FastStringMap<FastArrayList<DisplayData?>> = FastStringMap()
/**
* @private
*/
var parent: ArmatureData? = null
override fun _onClear() {
this.displays.fastValueForEach { slotDisplays ->
slotDisplays.fastForEach { display ->
display?.returnToPool()
}
}
this.displays.clear()
this.name = ""
//this.parent = null //
}
/**
* @internal
*/
fun addDisplay(slotName: String, value: DisplayData?) {
if (!(slotName in this.displays)) {
this.displays[slotName] = FastArrayList()
}
if (value != null) {
value.parent = this
}
val slotDisplays = this.displays[slotName] // TODO clear prev
slotDisplays?.add(value)
}
/**
* @private
*/
fun getDisplay(slotName: String, displayName: String): DisplayData? {
getDisplays(slotName)?.fastForEach { display ->
if (display != null && display.name == displayName) {
return display
}
}
return null
}
/**
* @private
*/
fun getDisplays(slotName: String?): FastArrayList<DisplayData?>? = this.displays.getNull(slotName)
override fun toString(): String = "[class dragonBones.SkinData]"
}
| korge-dragonbones/src/commonMain/kotlin/com/dragonbones/model/SkinData.kt | 2215511348 |
/*
* Copyright (c) 2021 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.reviewer
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.StringRes
import com.ichi2.anki.AbstractFlashcardViewer
/**
* The UI of an ease button
*
* Currently contains a some business logic:
* * [nextTime] is used by the API
* * [canPerformClick] is used to determine if the answer is being shown and the button isn't blocked
*/
class EaseButton(private val ease: Int, private val layout: LinearLayout, private val easeTextView: TextView, private val easeTimeView: TextView) {
var height: Int
get() = layout.layoutParams.height
set(value) {
layout.layoutParams.height = value
}
@get:JvmName("canPerformClick")
val canPerformClick
get() = layout.isEnabled && layout.visibility == View.VISIBLE
var nextTime: String
get() = easeTimeView.text.toString()
set(value) {
easeTimeView.text = value
}
fun hideNextReviewTime() {
easeTimeView.visibility = View.GONE
}
fun setButtonScale(scale: Int) {
val params = layout.layoutParams
params.height = params.height * scale / 100
}
fun setVisibility(visibility: Int) {
layout.visibility = visibility
}
fun setColor(color: Int) {
layout.setBackgroundResource(color)
}
fun setListeners(easeHandler: AbstractFlashcardViewer.SelectEaseHandler) {
layout.setOnClickListener { view: View? -> easeHandler.onClick(view) }
layout.setOnTouchListener { view: View?, event: MotionEvent? -> easeHandler.onTouch(view, event) }
}
fun detachFromParent() {
if (layout.parent != null) {
(layout.parent as ViewGroup).removeView(layout)
}
}
fun addTo(toAddTo: LinearLayout) {
toAddTo.addView(layout)
}
fun hide() {
layout.visibility = View.GONE
easeTimeView.text = ""
}
/** Perform a click if the button is visible */
fun performSafeClick() {
if (!canPerformClick) return
layout.performClick()
}
/**
* Makes the button clickable if it is the provided ease, otherwise enabled.
*
* @param currentEase The current ease of the card
*/
fun unblockBasedOnEase(currentEase: Int) {
if (this.ease == currentEase) {
layout.isClickable = true
} else {
layout.isEnabled = true
}
}
/**
* Makes the button not clickable if it is the provided ease, otherwise disable it.
*
* @param currentEase The current ease of the card
*/
fun blockBasedOnEase(currentEase: Int) {
if (this.ease == currentEase) {
layout.isClickable = false
} else {
layout.isEnabled = false
}
}
fun performClickWithVisualFeedback() {
layout.requestFocus()
layout.performClick()
}
fun requestFocus() {
}
fun setup(backgroundColor: Int, textColor: Int, @StringRes easeStringRes: Int) {
layout.visibility = View.VISIBLE
layout.setBackgroundResource(backgroundColor)
easeTextView.setText(easeStringRes)
easeTextView.setTextColor(textColor)
easeTimeView.setTextColor(textColor)
}
}
| AnkiDroid/src/main/java/com/ichi2/anki/reviewer/EaseButton.kt | 4128653696 |
package com.example
import app.cash.sqldelight.ColumnAdapter
import kotlin.Int
import kotlin.String
import kotlin.collections.List
public data class Test(
public val third: String,
public val second: List<Int>?,
) {
public class Adapter(
public val secondAdapter: ColumnAdapter<List<Int>, String>,
)
}
| sqldelight-compiler/src/test/migration-interface-fixtures/alter-table-rename-column/output/com/example/Test.kt | 1964298916 |
package org.pixelndice.table.pixelclient.connection.lobby.client
import org.apache.logging.log4j.LogManager
import org.pixelndice.table.pixelclient.ApplicationBus
import org.pixelndice.table.pixelclient.ds.Account
import org.pixelndice.table.pixelprotocol.Protobuf
private val logger = LogManager.getLogger(StateRunning22TextMessage::class.java)
class StateRunning22TextMessage : State {
override fun process(ctx: Context) {
val packet = ctx.channel.packet
if( packet != null ){
if( packet.payloadCase == Protobuf.Packet.PayloadCase.TEXTMESSAGE){
val textMessage = packet.textMessage
val accountFrom = Account.fromProtobuf(textMessage.from)
val accountTo = Account.fromProtobuf(textMessage.to)
ApplicationBus.post(ApplicationBus.ReceiveTextMessage(accountFrom,textMessage.toAll, accountFrom, textMessage.text))
}else{
logger.error("Expecting TextMessage, instead received $packet")
}
}
}
}
| src/main/kotlin/org/pixelndice/table/pixelclient/connection/lobby/client/StateRunning22TextMessage.kt | 146964701 |
package ru.dageev.compiler.parser.visitor.expression
import ru.dageev.compiler.domain.ClassesContext
import ru.dageev.compiler.domain.node.expression.BinaryExpression
import ru.dageev.compiler.domain.node.expression.Expression
import ru.dageev.compiler.domain.node.expression.Value
import ru.dageev.compiler.domain.scope.Scope
import ru.dageev.compiler.grammar.ElaginBaseVisitor
import ru.dageev.compiler.grammar.ElaginParser
/**
* Created by dageev
* on 15-May-16.
*/
class ExpressionVisitor(scope: Scope, val classesContext: ClassesContext) : ElaginBaseVisitor<Expression>() {
val scope: Scope
val binaryOperationVisitor = BinaryOperationVisitor(this)
init {
this.scope = scope.copy()
}
override fun visitVariableReference(ctx: ElaginParser.VariableReferenceContext): Expression {
return VariableReferenceVisitor(scope, classesContext).visitVariableReference(ctx)
}
override fun visitBooleanValue(ctx: ElaginParser.BooleanValueContext): Value {
return ValueExpressionVisitor().visitBooleanValue(ctx)
}
override fun visitIntegerValue(ctx: ElaginParser.IntegerValueContext): Value {
return ValueExpressionVisitor().visitIntegerValue(ctx);
}
override fun visitMethodCall(ctx: ElaginParser.MethodCallContext): Expression {
return MethodCallExpressionVisitor(scope, classesContext, this).visitMethodCall(ctx)
}
override fun visitSuperCall(ctx: ElaginParser.SuperCallContext): Expression {
return MethodCallExpressionVisitor(scope, classesContext, this).visitSuperCall(ctx)
}
override fun visitConstructorCall(ctx: ElaginParser.ConstructorCallContext): Expression {
return MethodCallExpressionVisitor(scope, classesContext, this).visitConstructorCall(ctx)
}
override fun visitFieldAccessor(ctx: ElaginParser.FieldAccessorContext): Expression {
return FieldAccessExpressionVisitor(scope, classesContext, this).visitFieldAccessor(ctx)
}
override fun visitMultDivExpression(ctx: ElaginParser.MultDivExpressionContext): BinaryExpression {
return ctx.accept(binaryOperationVisitor)
}
override fun visitSumExpression(ctx: ElaginParser.SumExpressionContext): BinaryExpression {
return ctx.accept(binaryOperationVisitor)
}
override fun visitCompareExpression(ctx: ElaginParser.CompareExpressionContext): BinaryExpression {
return ctx.accept(binaryOperationVisitor)
}
override fun visitLogicalExpression(ctx: ElaginParser.LogicalExpressionContext): BinaryExpression {
return ctx.accept(binaryOperationVisitor)
}
override fun visitParenthesis(ctx: ElaginParser.ParenthesisContext): Expression {
return ctx.expression().accept(this)
}
} | src/main/kotlin/ru/dageev/compiler/parser/visitor/expression/ExpressionVisitor.kt | 2661642480 |
package com.fboldog.ext4klaxon;
import com.beust.klaxon.JsonObject
import org.testng.annotations.Test
import java.util.*
import kotlin.test.assertEquals
class DateExtensionTests {
@Test
fun dateValueFromLong() {
val input: Long = java.lang.System.currentTimeMillis() / 1000
val src = JsonObject(mapOf(Pair("long_to_date", input)))
assertEquals(Date(input.times(1000)),src.date("long_to_date"))
}
@Test
fun dateValueFromString() {
val input: String = (java.lang.System.currentTimeMillis() / 1000).toString()
val src = JsonObject(mapOf(Pair("string_to_date", input)))
assertEquals(Date(input.toLong().times(1000)),src.date("string_to_date"))
}
}
| src/test/kotlin/com/fboldog/ext4klaxon/DateExtensionTests.kt | 2775093518 |
import NGramDriver.NGramCounters.REMOVED_BY_KEYWORD
import common.hadoop.extensions.plusAssign
import common.hadoop.extensions.toIntWritable
import org.apache.hadoop.io.IntWritable
import org.apache.hadoop.io.Text
import org.apache.hadoop.mapreduce.Reducer
/**
* Combiner for the problem. It should run at least once.
* Input and Output are the same of the Reducer for the previous reason.
*/
class NGramCombiner : Reducer<Text, IntWritable, Text, IntWritable>() {
override fun reduce(key: Text, values: Iterable<IntWritable>, context: Context) {
val keyword = context.configuration
.get("keyword")
// if key starts with the keyword, than the counter is increase
// based on the number of times it appears in the text, otherwise
// writes the key and the sum of occurrences
if (key.toString().startsWith(keyword)) {
context.getCounter(REMOVED_BY_KEYWORD) += values.sumBy(IntWritable::get).toLong()
} else {
context.write(key, values.sumBy(IntWritable::get).toIntWritable())
}
}
} | 02_n-gram-count/src/main/kotlin/NGramCombiner.kt | 2442190558 |
package org.hildan.minecraft.mining.optimizer.blocks
import org.hildan.minecraft.mining.optimizer.geometry.BlockIndex
import org.hildan.minecraft.mining.optimizer.geometry.Dimensions
import org.hildan.minecraft.mining.optimizer.geometry.Wrapping
import org.hildan.minecraft.mining.optimizer.ore.BlockType
import java.util.*
/**
* An arbitrary group of blocks. It can have any dimension, thus it is different from a minecraft chunk, which is
* 16x256x16.
*/
data class Sample(
/** The dimensions of this sample. */
val dimensions: Dimensions,
/** The blocks of this sample. */
private var blocks: MutableList<BlockType>,
) {
/** The number of dug blocks currently in this sample. */
var dugBlocks = mutableSetOf<BlockIndex>()
private set
/** The number of dug blocks currently in this sample. */
val dugBlocksCount: Int
get() = dugBlocks.size
/** The number of ore blocks currently in this sample. */
var oreBlocksCount = 0
private set
/**
* Creates a new pure sample of the given [dimensions] containing only blocks of the given [initialBlockType].
*/
constructor(dimensions: Dimensions, initialBlockType: BlockType) : this(
dimensions = dimensions,
blocks = MutableList(dimensions.nbPositions) { initialBlockType },
) {
oreBlocksCount = if (initialBlockType.isOre) blocks.size else 0
dugBlocks = if (initialBlockType == BlockType.AIR) blocks.indices.toMutableSet() else mutableSetOf()
}
/**
* Creates a copy of the given [source] Sample.
*/
constructor(source: Sample) : this(source.dimensions, ArrayList(source.blocks)) {
this.oreBlocksCount = source.oreBlocksCount
this.dugBlocks = HashSet(source.dugBlocksCount)
}
/**
* Fills this [Sample] with the given [blockType].
*/
fun fill(blockType: BlockType) {
blocks.fill(blockType)
oreBlocksCount = if (blockType.isOre) blocks.size else 0
dugBlocks = if (blockType == BlockType.AIR) blocks.indices.toMutableSet() else mutableSetOf()
}
/**
* Resets this [Sample] to the same state as the given [sample].
*/
fun resetTo(sample: Sample) {
blocks = ArrayList(sample.blocks)
oreBlocksCount = sample.oreBlocksCount
dugBlocks = HashSet(sample.dugBlocks)
}
/**
* Gets the 6 blocks that are adjacent to this block, with [Wrapping.WRAP_XZ] wrapping. If this block is on the
* floor or ceiling of this sample, less than 6 blocks are returned because part of them is cut off.
*/
private val BlockIndex.neighbours
get() = with(dimensions) { neighbours }
/**
* Returns whether the given [x], [y], [z] coordinates belong to this sample.
*/
fun contains(x: Int, y: Int, z: Int): Boolean = dimensions.contains(x, y, z)
/**
* Gets the type of the block located at the given [x], [y], [z] coordinates.
*/
fun getBlockType(x: Int, y: Int, z: Int): BlockType = getBlockType(getIndex(x, y, z))
/**
* Sets the type of the block located at the given [x], [y], [z] coordinates.
*/
fun setBlockType(x: Int, y: Int, z: Int, type: BlockType) = setBlockType(getIndex(x, y, z), type)
private fun getIndex(x: Int, y: Int, z: Int) = dimensions.getIndex(x, y, z)
/**
* Gets the type of the block located at the given [index].
*/
private fun getBlockType(index: BlockIndex): BlockType = blocks[index]
/**
* Sets the type of the block located at the given [index].
*/
private fun setBlockType(index: BlockIndex, type: BlockType) {
val formerType = blocks[index]
blocks[index] = type
if (!formerType.isOre && type.isOre) {
oreBlocksCount++
} else if (formerType.isOre && !type.isOre) {
oreBlocksCount--
}
if (formerType != BlockType.AIR && type == BlockType.AIR) {
dugBlocks.add(index)
} else if (formerType == BlockType.AIR && type != BlockType.AIR) {
dugBlocks.remove(index)
}
}
/**
* Digs the block at the specified [index].
*/
fun digBlock(index: BlockIndex) {
setBlockType(index, BlockType.AIR)
}
/**
* Digs the block at the specified [x], [y], [z] coordinates.
*/
fun digBlock(x: Int, y: Int, z: Int) = digBlock(getIndex(x, y, z))
fun digVisibleOresRecursively() {
val explored = HashSet(dugBlocks)
val toExplore = explored.flatMapTo(ArrayDeque()) { it.neighbours.asIterable() }
while (toExplore.isNotEmpty()) {
val blockIndex = toExplore.poll()
explored.add(blockIndex)
if (blocks[blockIndex].isOre) {
digBlock(blockIndex)
blockIndex.neighbours.filterNotTo(toExplore) { explored.contains(it) }
}
}
}
override fun toString(): String = "Size: $dimensions Dug: $dugBlocksCount"
}
| src/main/kotlin/org/hildan/minecraft/mining/optimizer/blocks/Sample.kt | 2844651518 |
package de.sudoq.controller.menus
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Espresso.pressBack
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import de.sudoq.R
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
import org.hamcrest.core.IsInstanceOf
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class RecordedContinueTest {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(SplashActivity::class.java)
@Test
fun recordedContinueTest() {
val appCompatButton = onView(
allOf(withId(R.id.button_mainmenu_new_sudoku), withText("New Sudoku"),
childAtPosition(
childAtPosition(
withClassName(`is`("android.widget.ScrollView")),
0),
2)))
appCompatButton.perform(scrollTo(), click())
val appCompatButton2 = onView(
allOf(withId(R.id.button_start), withText("Start"),
childAtPosition(
childAtPosition(
withClassName(`is`("android.widget.ScrollView")),
0),
7)))
appCompatButton2.perform(scrollTo(), click())
pressBack()
pressBack()
val button = onView(
allOf(withId(R.id.button_mainmenu_continue), withText("CONTINUE"),
withParent(withParent(IsInstanceOf.instanceOf(android.widget.ScrollView::class.java))),
isDisplayed()))
button.check(matches(isDisplayed()))
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent)
&& view == parent.getChildAt(position)
}
}
}
}
| sudoq-app/sudoqapp/src/androidTest/java/de/sudoq/controller/menus/RecordedContinueTest.kt | 1180912381 |
/*
* Copyright 2019 Peter Kenji Yamanaka
*
* 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.pyamsoft.padlock.list.info
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.pyamsoft.padlock.Injector
import com.pyamsoft.padlock.PadLockComponent
import com.pyamsoft.padlock.R
import com.pyamsoft.padlock.list.info.LockInfoItem.ViewHolder
import com.pyamsoft.padlock.model.LockState
import com.pyamsoft.padlock.model.list.ActivityEntry
import com.pyamsoft.padlock.model.list.ActivityEntry.Item
import com.pyamsoft.pydroid.core.bus.EventBus
import com.pyamsoft.pydroid.core.bus.Publisher
import timber.log.Timber
import javax.inject.Inject
class LockInfoItem internal constructor(
entry: ActivityEntry.Item,
private val system: Boolean
) : LockInfoBaseItem<Item, LockInfoItem, ViewHolder>(entry) {
override fun getType(): Int = R.id.adapter_lock_info
override fun getLayoutRes(): Int = R.layout.adapter_item_lockinfo
override fun bindView(
holder: ViewHolder,
payloads: List<Any>
) {
super.bindView(holder, payloads)
holder.bind(model, system)
}
override fun unbindView(holder: ViewHolder) {
super.unbindView(holder)
holder.unbind()
}
override fun filterAgainst(query: String): Boolean {
val name = model.name.toLowerCase()
.trim { it <= ' ' }
Timber.d("Filter predicate: '%s' against %s", query, name)
return name.contains(query)
}
override fun getViewHolder(view: View): ViewHolder =
ViewHolder(view)
class ViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
@field:Inject internal lateinit var publisher: EventBus<LockInfoEvent>
@field:Inject internal lateinit var view: LockInfoItemView
init {
Injector.obtain<PadLockComponent>(itemView.context.applicationContext)
.plusLockInfoItemComponent()
.itemView(itemView)
.build()
.inject(this)
}
private fun processModifyDatabaseEntry(
model: ActivityEntry.Item,
system: Boolean,
newLockState: LockState
) {
publisher.publish(LockInfoEvent.from(model, newLockState, null, system))
}
fun bind(
model: ActivityEntry.Item,
system: Boolean
) {
view.bind(model, system)
view.onSwitchChanged {
processModifyDatabaseEntry(model, system, it)
}
}
fun unbind() {
view.unbind()
}
}
}
| padlock/src/main/java/com/pyamsoft/padlock/list/info/LockInfoItem.kt | 1464625219 |
package abi44_0_0.expo.modules.filesystem
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.StatFs
import android.provider.DocumentsContract
import android.util.Base64
import android.util.Log
import androidx.core.content.FileProvider
import androidx.documentfile.provider.DocumentFile
import abi44_0_0.expo.modules.core.ExportedModule
import abi44_0_0.expo.modules.core.ModuleRegistry
import abi44_0_0.expo.modules.core.ModuleRegistryDelegate
import abi44_0_0.expo.modules.core.Promise
import abi44_0_0.expo.modules.core.interfaces.ActivityEventListener
import abi44_0_0.expo.modules.core.interfaces.ActivityProvider
import abi44_0_0.expo.modules.core.interfaces.ExpoMethod
import abi44_0_0.expo.modules.core.interfaces.services.EventEmitter
import abi44_0_0.expo.modules.core.interfaces.services.UIManager
import abi44_0_0.expo.modules.interfaces.filesystem.FilePermissionModuleInterface
import abi44_0_0.expo.modules.interfaces.filesystem.Permission
import java.io.BufferedInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.io.OutputStreamWriter
import java.lang.ClassCastException
import java.lang.Exception
import java.lang.IllegalArgumentException
import java.lang.NullPointerException
import java.math.BigInteger
import java.net.CookieHandler
import java.net.URLConnection
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.math.pow
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Headers
import okhttp3.JavaNetCookieJar
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import okhttp3.ResponseBody
import okio.Buffer
import okio.BufferedSource
import okio.ForwardingSource
import okio.Okio
import okio.Source
import org.apache.commons.codec.binary.Hex
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.io.FileUtils
import org.apache.commons.io.IOUtils
private const val NAME = "ExponentFileSystem"
private val TAG = FileSystemModule::class.java.simpleName
private const val EXDownloadProgressEventName = "expo-file-system.downloadProgress"
private const val EXUploadProgressEventName = "expo-file-system.uploadProgress"
private const val MIN_EVENT_DT_MS: Long = 100
private const val HEADER_KEY = "headers"
private const val DIR_PERMISSIONS_REQUEST_CODE = 5394
// The class needs to be 'open', because it's inherited in expoview
open class FileSystemModule(
context: Context,
private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate()
) : ExportedModule(context), ActivityEventListener {
init {
try {
ensureDirExists(getContext().filesDir)
ensureDirExists(getContext().cacheDir)
} catch (e: IOException) {
e.printStackTrace()
}
}
private inline fun <reified T> moduleRegistry() =
moduleRegistryDelegate.getFromModuleRegistry<T>()
private val uIManager: UIManager by moduleRegistry()
private var client: OkHttpClient? = null
private var dirPermissionsRequest: Promise? = null
private val taskHandlers: MutableMap<String, TaskHandler> = HashMap()
override fun onCreate(moduleRegistry: ModuleRegistry) {
moduleRegistryDelegate.onCreate(moduleRegistry)
}
override fun getName() = NAME
override fun getConstants(): Map<String, Any?> {
return mapOf(
"documentDirectory" to Uri.fromFile(context.filesDir).toString() + "/",
"cacheDirectory" to Uri.fromFile(context.cacheDir).toString() + "/",
"bundleDirectory" to "asset:///",
)
}
@Throws(IOException::class)
private fun Uri.checkIfFileExists() {
val file = this.toFile()
if (!file.exists()) {
throw IOException("Directory for '${file.path}' doesn't exist.")
}
}
@Throws(IOException::class)
private fun Uri.checkIfFileDirExists() {
val file = this.toFile()
val dir = file.parentFile
if (dir == null || !dir.exists()) {
throw IOException("Directory for '${file.path}' doesn't exist. Please make sure directory '${file.parent}' exists before calling downloadAsync.")
}
}
private fun permissionsForPath(path: String?): EnumSet<Permission>? {
val filePermissionModule: FilePermissionModuleInterface by moduleRegistry()
return filePermissionModule.getPathPermissions(context, path)
}
private fun permissionsForUri(uri: Uri) = when {
uri.isSAFUri -> permissionsForSAFUri(uri)
uri.scheme == "content" -> EnumSet.of(Permission.READ)
uri.scheme == "asset" -> EnumSet.of(Permission.READ)
uri.scheme == "file" -> permissionsForPath(uri.path)
uri.scheme == null -> EnumSet.of(Permission.READ)
else -> EnumSet.noneOf(Permission::class.java)
}
private fun permissionsForSAFUri(uri: Uri): EnumSet<Permission> {
val documentFile = getNearestSAFFile(uri)
return EnumSet.noneOf(Permission::class.java).apply {
if (documentFile != null) {
if (documentFile.canRead()) {
add(Permission.READ)
}
if (documentFile.canWrite()) {
add(Permission.WRITE)
}
}
}
}
// For now we only need to ensure one permission at a time, this allows easier error message strings,
// we can generalize this when needed later
@Throws(IOException::class)
private fun ensurePermission(uri: Uri, permission: Permission, errorMsg: String) {
if (permissionsForUri(uri)?.contains(permission) != true) {
throw IOException(errorMsg)
}
}
@Throws(IOException::class)
private fun ensurePermission(uri: Uri, permission: Permission) {
if (permission == Permission.READ) {
ensurePermission(uri, permission, "Location '$uri' isn't readable.")
}
if (permission == Permission.WRITE) {
ensurePermission(uri, permission, "Location '$uri' isn't writable.")
}
ensurePermission(uri, permission, "Location '$uri' doesn't have permission '${permission.name}'.")
}
@Throws(IOException::class)
private fun openAssetInputStream(uri: Uri): InputStream {
// AssetManager expects no leading slash.
val asset = requireNotNull(uri.path).substring(1)
return context.assets.open(asset)
}
@Throws(IOException::class)
private fun openResourceInputStream(resourceName: String?): InputStream {
var resourceId = context.resources.getIdentifier(resourceName, "raw", context.packageName)
if (resourceId == 0) {
// this resource doesn't exist in the raw folder, so try drawable
resourceId = context.resources.getIdentifier(resourceName, "drawable", context.packageName)
if (resourceId == 0) {
throw FileNotFoundException("No resource found with the name '$resourceName'")
}
}
return context.resources.openRawResource(resourceId)
}
@ExpoMethod
fun getInfoAsync(_uriStr: String, options: Map<String?, Any?>, promise: Promise) {
var uriStr = _uriStr
try {
val uri = Uri.parse(uriStr)
var absoluteUri = uri
if (uri.scheme == "file") {
uriStr = parseFileUri(uriStr)
absoluteUri = Uri.parse(uriStr)
}
ensurePermission(absoluteUri, Permission.READ)
if (uri.scheme == "file") {
val file = absoluteUri.toFile()
if (file.exists()) {
promise.resolve(
Bundle().apply {
putBoolean("exists", true)
putBoolean("isDirectory", file.isDirectory)
putString("uri", Uri.fromFile(file).toString())
putDouble("size", getFileSize(file).toDouble())
putDouble("modificationTime", 0.001 * file.lastModified())
options["md5"].takeIf { it == true }?.let { putString("md5", md5(file)) }
}
)
} else {
promise.resolve(
Bundle().apply {
putBoolean("exists", false)
putBoolean("isDirectory", false)
}
)
}
} else if (uri.scheme == "content" || uri.scheme == "asset" || uri.scheme == null) {
try {
val inputStream: InputStream = when (uri.scheme) {
"content" -> context.contentResolver.openInputStream(uri)
"asset" -> openAssetInputStream(uri)
else -> openResourceInputStream(uriStr)
} ?: throw FileNotFoundException()
promise.resolve(
Bundle().apply {
putBoolean("exists", true)
putBoolean("isDirectory", false)
putString("uri", uri.toString())
// NOTE: `.available()` is supposedly not a reliable source of size info, but it's been
// more reliable than querying `OpenableColumns.SIZE` in practice in tests ¯\_(ツ)_/¯
putDouble("size", inputStream.available().toDouble())
if (options.containsKey("md5") && options["md5"] == true) {
val md5bytes = DigestUtils.md5(inputStream)
putString("md5", String(Hex.encodeHex(md5bytes)))
}
}
)
} catch (e: FileNotFoundException) {
promise.resolve(
Bundle().apply {
putBoolean("exists", false)
putBoolean("isDirectory", false)
}
)
}
} else {
throw IOException("Unsupported scheme for location '$uri'.")
}
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject(e)
}
}
@ExpoMethod
fun readAsStringAsync(uriStr: String?, options: Map<String?, Any?>, promise: Promise) {
try {
val uri = Uri.parse(uriStr)
ensurePermission(uri, Permission.READ)
// TODO:Bacon: Add more encoding types to match iOS
val encoding = getEncodingFromOptions(options)
var contents: String?
if (encoding.equals("base64", ignoreCase = true)) {
getInputStream(uri).use { inputStream ->
contents = if (options.containsKey("length") && options.containsKey("position")) {
val length = (options["length"] as Number).toInt()
val position = (options["position"] as Number).toInt()
val buffer = ByteArray(length)
inputStream.skip(position.toLong())
val bytesRead = inputStream.read(buffer, 0, length)
Base64.encodeToString(buffer, 0, bytesRead, Base64.NO_WRAP)
} else {
val inputData = getInputStreamBytes(inputStream)
Base64.encodeToString(inputData, Base64.NO_WRAP)
}
}
} else {
contents = when {
uri.scheme == "file" -> IOUtils.toString(FileInputStream(uri.toFile()))
uri.scheme == "asset" -> IOUtils.toString(openAssetInputStream(uri))
uri.scheme == null -> IOUtils.toString(openResourceInputStream(uriStr))
uri.isSAFUri -> IOUtils.toString(context.contentResolver.openInputStream(uri))
else -> throw IOException("Unsupported scheme for location '$uri'.")
}
}
promise.resolve(contents)
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject(e)
}
}
@ExpoMethod
fun writeAsStringAsync(uriStr: String?, string: String?, options: Map<String?, Any?>, promise: Promise) {
try {
val uri = Uri.parse(uriStr)
ensurePermission(uri, Permission.WRITE)
val encoding = getEncodingFromOptions(options)
getOutputStream(uri).use { out ->
if (encoding == "base64") {
val bytes = Base64.decode(string, Base64.DEFAULT)
out.write(bytes)
} else {
OutputStreamWriter(out).use { writer -> writer.write(string) }
}
}
promise.resolve(null)
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject(e)
}
}
@ExpoMethod
fun deleteAsync(uriStr: String?, options: Map<String?, Any?>, promise: Promise) {
try {
val uri = Uri.parse(uriStr)
val appendedUri = Uri.withAppendedPath(uri, "..")
ensurePermission(appendedUri, Permission.WRITE, "Location '$uri' isn't deletable.")
if (uri.scheme == "file") {
val file = uri.toFile()
if (file.exists()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
FileUtils.forceDelete(file)
} else {
// to be removed once Android SDK 25 support is dropped
forceDelete(file)
}
promise.resolve(null)
} else {
if (options.containsKey("idempotent") && options["idempotent"] as Boolean) {
promise.resolve(null)
} else {
promise.reject(
"ERR_FILESYSTEM_CANNOT_FIND_FILE",
"File '$uri' could not be deleted because it could not be found"
)
}
}
} else if (uri.isSAFUri) {
val file = getNearestSAFFile(uri)
if (file != null && file.exists()) {
file.delete()
promise.resolve(null)
} else {
if (options.containsKey("idempotent") && options["idempotent"] as Boolean) {
promise.resolve(null)
} else {
promise.reject(
"ERR_FILESYSTEM_CANNOT_FIND_FILE",
"File '$uri' could not be deleted because it could not be found"
)
}
}
} else {
throw IOException("Unsupported scheme for location '$uri'.")
}
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject(e)
}
}
@ExpoMethod
fun moveAsync(options: Map<String?, Any?>, promise: Promise) {
try {
if (!options.containsKey("from")) {
promise.reject("ERR_FILESYSTEM_MISSING_PARAMETER", "`FileSystem.moveAsync` needs a `from` path.")
return
}
val fromUri = Uri.parse(options["from"] as String?)
ensurePermission(Uri.withAppendedPath(fromUri, ".."), Permission.WRITE, "Location '$fromUri' isn't movable.")
if (!options.containsKey("to")) {
promise.reject("ERR_FILESYSTEM_MISSING_PARAMETER", "`FileSystem.moveAsync` needs a `to` path.")
return
}
val toUri = Uri.parse(options["to"] as String?)
ensurePermission(toUri, Permission.WRITE)
if (fromUri.scheme == "file") {
val from = fromUri.toFile()
val to = toUri.toFile()
if (from.renameTo(to)) {
promise.resolve(null)
} else {
promise.reject(
"ERR_FILESYSTEM_CANNOT_MOVE_FILE",
"File '$fromUri' could not be moved to '$toUri'"
)
}
} else if (fromUri.isSAFUri) {
val documentFile = getNearestSAFFile(fromUri)
if (documentFile == null || !documentFile.exists()) {
promise.reject("ERR_FILESYSTEM_CANNOT_MOVE_FILE", "File '$fromUri' could not be moved to '$toUri'")
return
}
val output = File(toUri.path)
transformFilesFromSAF(documentFile, output, false)
promise.resolve(null)
} else {
throw IOException("Unsupported scheme for location '$fromUri'.")
}
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject(e)
}
}
@ExpoMethod
fun copyAsync(options: Map<String?, Any?>, promise: Promise) {
try {
if (!options.containsKey("from")) {
promise.reject("ERR_FILESYSTEM_MISSING_PARAMETER", "`FileSystem.moveAsync` needs a `from` path.")
return
}
val fromUri = Uri.parse(options["from"] as String?)
ensurePermission(fromUri, Permission.READ)
if (!options.containsKey("to")) {
promise.reject("ERR_FILESYSTEM_MISSING_PARAMETER", "`FileSystem.moveAsync` needs a `to` path.")
return
}
val toUri = Uri.parse(options["to"] as String?)
ensurePermission(toUri, Permission.WRITE)
when {
fromUri.scheme == "file" -> {
val from = fromUri.toFile()
val to = toUri.toFile()
if (from.isDirectory) {
FileUtils.copyDirectory(from, to)
} else {
FileUtils.copyFile(from, to)
}
promise.resolve(null)
}
fromUri.isSAFUri -> {
val documentFile = getNearestSAFFile(fromUri)
if (documentFile == null || !documentFile.exists()) {
promise.reject("ERR_FILESYSTEM_CANNOT_FIND_FILE", "File '$fromUri' could not be copied because it could not be found")
return
}
val output = File(toUri.path)
transformFilesFromSAF(documentFile, output, true)
promise.resolve(null)
}
fromUri.scheme == "content" -> {
val inputStream = context.contentResolver.openInputStream(fromUri)
val out: OutputStream = FileOutputStream(toUri.toFile())
IOUtils.copy(inputStream, out)
promise.resolve(null)
}
fromUri.scheme == "asset" -> {
val inputStream = openAssetInputStream(fromUri)
val out: OutputStream = FileOutputStream(toUri.toFile())
IOUtils.copy(inputStream, out)
promise.resolve(null)
}
fromUri.scheme == null -> {
// this is probably an asset embedded by the packager in resources
val inputStream = openResourceInputStream(options["from"] as String?)
val out: OutputStream = FileOutputStream(toUri.toFile())
IOUtils.copy(inputStream, out)
promise.resolve(null)
}
else -> {
throw IOException("Unsupported scheme for location '$fromUri'.")
}
}
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject(e)
}
}
@Throws(IOException::class)
private fun transformFilesFromSAF(documentFile: DocumentFile, outputDir: File, copy: Boolean) {
if (!documentFile.exists()) {
return
}
if (!outputDir.exists() && !outputDir.mkdirs()) {
throw IOException("Couldn't create folder in output dir.")
}
if (documentFile.isDirectory) {
for (file in documentFile.listFiles()) {
documentFile.name?.let {
transformFilesFromSAF(file, File(outputDir, it), copy)
}
}
if (!copy) {
documentFile.delete()
}
return
}
documentFile.name?.let {
val newFile = File(outputDir.path, it)
context.contentResolver.openInputStream(documentFile.uri).use { `in` -> FileOutputStream(newFile).use { out -> IOUtils.copy(`in`, out) } }
if (!copy) {
documentFile.delete()
}
}
}
@ExpoMethod
fun makeDirectoryAsync(uriStr: String?, options: Map<String?, Any?>, promise: Promise) {
try {
val uri = Uri.parse(uriStr)
ensurePermission(uri, Permission.WRITE)
if (uri.scheme == "file") {
val file = uri.toFile()
val previouslyCreated = file.isDirectory
val setIntermediates = options.containsKey("intermediates") && options["intermediates"] as Boolean
val success = if (setIntermediates) file.mkdirs() else file.mkdir()
if (success || setIntermediates && previouslyCreated) {
promise.resolve(null)
} else {
promise.reject(
"ERR_FILESYSTEM_CANNOT_CREATE_DIRECTORY",
"Directory '$uri' could not be created or already exists."
)
}
} else {
throw IOException("Unsupported scheme for location '$uri'.")
}
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject(e)
}
}
@ExpoMethod
fun readDirectoryAsync(uriStr: String?, options: Map<String?, Any?>?, promise: Promise) {
try {
val uri = Uri.parse(uriStr)
ensurePermission(uri, Permission.READ)
if (uri.scheme == "file") {
val file = uri.toFile()
val children = file.listFiles()
if (children != null) {
val result = children.map { it.name }
promise.resolve(result)
} else {
promise.reject(
"ERR_FILESYSTEM_CANNOT_READ_DIRECTORY",
"Directory '$uri' could not be read."
)
}
} else if (uri.isSAFUri) {
promise.reject(
"ERR_FILESYSTEM_UNSUPPORTED_SCHEME",
"Can't read Storage Access Framework directory, use StorageAccessFramework.readDirectoryAsync() instead."
)
} else {
throw IOException("Unsupported scheme for location '$uri'.")
}
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject(e)
}
}
@ExpoMethod
fun getTotalDiskCapacityAsync(promise: Promise) {
try {
val root = StatFs(Environment.getDataDirectory().absolutePath)
val blockCount = root.blockCountLong
val blockSize = root.blockSizeLong
val capacity = BigInteger.valueOf(blockCount).multiply(BigInteger.valueOf(blockSize))
// cast down to avoid overflow
val capacityDouble = Math.min(capacity.toDouble(), 2.0.pow(53.0) - 1)
promise.resolve(capacityDouble)
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject("ERR_FILESYSTEM_CANNOT_DETERMINE_DISK_CAPACITY", "Unable to access total disk capacity", e)
}
}
@ExpoMethod
fun getFreeDiskStorageAsync(promise: Promise) {
try {
val external = StatFs(Environment.getDataDirectory().absolutePath)
val availableBlocks = external.availableBlocksLong
val blockSize = external.blockSizeLong
val storage = BigInteger.valueOf(availableBlocks).multiply(BigInteger.valueOf(blockSize))
// cast down to avoid overflow
val storageDouble = Math.min(storage.toDouble(), 2.0.pow(53.0) - 1)
promise.resolve(storageDouble)
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject("ERR_FILESYSTEM_CANNOT_DETERMINE_DISK_CAPACITY", "Unable to determine free disk storage capacity", e)
}
}
@ExpoMethod
fun getContentUriAsync(uri: String, promise: Promise) {
try {
val fileUri = Uri.parse(uri)
ensurePermission(fileUri, Permission.WRITE)
ensurePermission(fileUri, Permission.READ)
fileUri.checkIfFileDirExists()
if (fileUri.scheme == "file") {
val file = fileUri.toFile()
promise.resolve(contentUriFromFile(file).toString())
} else {
promise.reject("ERR_FILESYSTEM_CANNOT_READ_DIRECTORY", "No readable files with the uri '$uri'. Please use other uri.")
}
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject(e)
}
}
private fun contentUriFromFile(file: File): Uri {
val activityProvider: ActivityProvider by moduleRegistry()
val application = activityProvider.currentActivity.application
return FileProvider.getUriForFile(application, "${application.packageName}.FileSystemFileProvider", file)
}
@ExpoMethod
fun readSAFDirectoryAsync(uriStr: String?, options: Map<String?, Any?>?, promise: Promise) {
try {
val uri = Uri.parse(uriStr)
ensurePermission(uri, Permission.READ)
if (uri.isSAFUri) {
val file = DocumentFile.fromTreeUri(context, uri)
if (file == null || !file.exists() || !file.isDirectory) {
promise.reject(
"ERR_FILESYSTEM_CANNOT_READ_DIRECTORY",
"Uri '$uri' doesn't exist or isn't a directory."
)
return
}
val children = file.listFiles()
val result = children.map { it.uri.toString() }
promise.resolve(result)
} else {
throw IOException("The URI '$uri' is not a Storage Access Framework URI. Try using FileSystem.readDirectoryAsync instead.")
}
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject(e)
}
}
@ExpoMethod
fun makeSAFDirectoryAsync(uriStr: String?, dirName: String?, promise: Promise) {
try {
val uri = Uri.parse(uriStr)
ensurePermission(uri, Permission.WRITE)
if (!uri.isSAFUri) {
throw IOException("The URI '$uri' is not a Storage Access Framework URI. Try using FileSystem.makeDirectoryAsync instead.")
}
val dir = getNearestSAFFile(uri)
if (dir != null) {
if (!dir.isDirectory) {
promise.reject("ERR_FILESYSTEM_CANNOT_CREATE_DIRECTORY", "Provided uri '$uri' is not pointing to a directory.")
return
}
}
val newDir = dirName?.let { dir?.createDirectory(it) }
if (newDir == null) {
promise.reject("ERR_FILESYSTEM_CANNOT_CREATE_DIRECTORY", "Unknown error.")
return
}
promise.resolve(newDir.uri.toString())
} catch (e: Exception) {
promise.reject(e)
}
}
@ExpoMethod
fun createSAFFileAsync(uriStr: String?, fileName: String?, mimeType: String?, promise: Promise) {
try {
val uri = Uri.parse(uriStr)
ensurePermission(uri, Permission.WRITE)
if (uri.isSAFUri) {
val dir = getNearestSAFFile(uri)
if (dir == null || !dir.isDirectory) {
promise.reject("ERR_FILESYSTEM_CANNOT_CREATE_FILE", "Provided uri '$uri' is not pointing to a directory.")
return
}
if (mimeType == null || fileName == null) {
promise.reject("ERR_FILESYSTEM_CANNOT_CREATE_FILE", "Parameters fileName and mimeType can not be null.")
return
}
val newFile = dir.createFile(mimeType, fileName)
if (newFile == null) {
promise.reject("ERR_FILESYSTEM_CANNOT_CREATE_FILE", "Unknown error.")
return
}
promise.resolve(newFile.uri.toString())
} else {
throw IOException("The URI '$uri' is not a Storage Access Framework URI.")
}
} catch (e: Exception) {
promise.reject(e)
}
}
@ExpoMethod
fun requestDirectoryPermissionsAsync(initialFileUrl: String?, promise: Promise) {
if (dirPermissionsRequest != null) {
promise.reject("ERR_FILESYSTEM_CANNOT_ASK_FOR_PERMISSIONS", "You have an unfinished permission request.")
return
}
try {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
initialFileUrl
?.let { Uri.parse(it) }
?.let { intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, it) }
}
val activityProvider: ActivityProvider by moduleRegistry()
val activity = activityProvider.currentActivity
if (activity == null) {
promise.reject("ERR_FILESYSTEM_CANNOT_ASK_FOR_PERMISSIONS", "Can't find activity.")
return
}
uIManager.registerActivityEventListener(this)
dirPermissionsRequest = promise
activity.startActivityForResult(intent, DIR_PERMISSIONS_REQUEST_CODE)
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject("ERR_FILESYSTEM_CANNOT_ASK_FOR_PERMISSIONS", "Can't ask for permissions.", e)
}
}
private fun createUploadRequest(url: String, fileUriString: String, options: Map<String, Any>, promise: Promise, decorator: RequestBodyDecorator): Request? {
try {
val fileUri = Uri.parse(fileUriString)
ensurePermission(fileUri, Permission.READ)
fileUri.checkIfFileExists()
if (!options.containsKey("httpMethod")) {
promise.reject("ERR_FILESYSTEM_MISSING_HTTP_METHOD", "Missing HTTP method.", null)
return null
}
val method = options["httpMethod"] as String?
if (!options.containsKey("uploadType")) {
promise.reject("ERR_FILESYSTEM_MISSING_UPLOAD_TYPE", "Missing upload type.", null)
return null
}
val requestBuilder = Request.Builder().url(url)
if (options.containsKey(HEADER_KEY)) {
val headers = options[HEADER_KEY] as Map<String, Any>?
headers?.forEach { (key, value) -> requestBuilder.addHeader(key, value.toString()) }
}
val body = createRequestBody(options, decorator, fileUri.toFile())
return requestBuilder.method(method, body).build()
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject(e)
}
return null
}
private fun createRequestBody(options: Map<String, Any>, decorator: RequestBodyDecorator, file: File): RequestBody? {
val uploadType = UploadType.fromInt((options["uploadType"] as Double).toInt())
return when {
uploadType === UploadType.BINARY_CONTENT -> {
decorator.decorate(RequestBody.create(null, file))
}
uploadType === UploadType.MULTIPART -> {
val bodyBuilder = MultipartBody.Builder().setType(MultipartBody.FORM)
options["parameters"]?.let {
(it as Map<String, Any>)
.forEach { (key, value) -> bodyBuilder.addFormDataPart(key, value.toString()) }
}
val mimeType: String = options["mimeType"]?.let {
it as String
} ?: URLConnection.guessContentTypeFromName(file.name)
val fieldName = options["fieldName"]?.let { it as String } ?: file.name
bodyBuilder.addFormDataPart(fieldName, file.name, decorator.decorate(RequestBody.create(MediaType.parse(mimeType), file)))
bodyBuilder.build()
}
else -> {
throw IllegalArgumentException("ERR_FILESYSTEM_INVALID_UPLOAD_TYPE. " + String.format("Invalid upload type: %s.", options["uploadType"]))
}
}
}
@ExpoMethod
fun uploadAsync(url: String, fileUriString: String, options: Map<String, Any>, promise: Promise) {
val request = createUploadRequest(
url, fileUriString, options, promise,
RequestBodyDecorator { requestBody -> requestBody }
) ?: return
okHttpClient?.let {
it.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.e(TAG, e.message.toString())
promise.reject(e)
}
override fun onResponse(call: Call, response: Response) {
val result = Bundle().apply {
putString("body", response.body()?.string())
putInt("status", response.code())
putBundle("headers", translateHeaders(response.headers()))
}
response.close()
promise.resolve(result)
}
})
} ?: run {
promise.reject(NullPointerException("okHttpClient is null"))
}
}
@ExpoMethod
fun uploadTaskStartAsync(url: String, fileUriString: String, uuid: String, options: Map<String, Any>, promise: Promise) {
val progressListener: CountingRequestListener = object : CountingRequestListener {
private var mLastUpdate: Long = -1
override fun onProgress(bytesWritten: Long, contentLength: Long) {
val eventEmitter: EventEmitter by moduleRegistry()
val uploadProgress = Bundle()
val uploadProgressData = Bundle()
val currentTime = System.currentTimeMillis()
// Throttle events. Sending too many events will block the JS event loop.
// Make sure to send the last event when we're at 100%.
if (currentTime > mLastUpdate + MIN_EVENT_DT_MS || bytesWritten == contentLength) {
mLastUpdate = currentTime
uploadProgressData.putDouble("totalByteSent", bytesWritten.toDouble())
uploadProgressData.putDouble("totalBytesExpectedToSend", contentLength.toDouble())
uploadProgress.putString("uuid", uuid)
uploadProgress.putBundle("data", uploadProgressData)
eventEmitter.emit(EXUploadProgressEventName, uploadProgress)
}
}
}
val request = createUploadRequest(
url,
fileUriString,
options,
promise,
object : RequestBodyDecorator {
override fun decorate(requestBody: RequestBody): RequestBody {
return CountingRequestBody(requestBody, progressListener)
}
}
) ?: return
val call = okHttpClient!!.newCall(request)
taskHandlers[uuid] = TaskHandler(call)
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
if (call.isCanceled) {
promise.resolve(null)
return
}
Log.e(TAG, e.message.toString())
promise.reject(e)
}
override fun onResponse(call: Call, response: Response) {
val result = Bundle()
val body = response.body()
result.apply {
putString("body", body?.string())
putInt("status", response.code())
putBundle("headers", translateHeaders(response.headers()))
}
response.close()
promise.resolve(result)
}
})
}
@ExpoMethod
fun downloadAsync(url: String, uriStr: String?, options: Map<String?, Any?>?, promise: Promise) {
try {
val uri = Uri.parse(uriStr)
ensurePermission(uri, Permission.WRITE)
uri.checkIfFileDirExists()
when {
url.contains(":").not() -> {
val context = context
val resources = context.resources
val packageName = context.packageName
val resourceId = resources.getIdentifier(url, "raw", packageName)
val bufferedSource = Okio.buffer(Okio.source(context.resources.openRawResource(resourceId)))
val file = uri.toFile()
file.delete()
val sink = Okio.buffer(Okio.sink(file))
sink.writeAll(bufferedSource)
sink.close()
val result = Bundle()
result.putString("uri", Uri.fromFile(file).toString())
options?.get("md5").takeIf { it == true }?.let { result.putString("md5", md5(file)) }
promise.resolve(result)
}
"file" == uri.scheme -> {
val requestBuilder = Request.Builder().url(url)
if (options != null && options.containsKey(HEADER_KEY)) {
try {
val headers = options[HEADER_KEY] as Map<String, Any>?
headers?.forEach { (key, value) ->
requestBuilder.addHeader(key, value.toString())
}
} catch (exception: ClassCastException) {
promise.reject("ERR_FILESYSTEM_INVALID_HEADERS", "Invalid headers dictionary. Keys and values should be strings.", exception)
return
}
}
okHttpClient?.newCall(requestBuilder.build())?.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.e(TAG, e.message.toString())
promise.reject(e)
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
val file = uri.toFile()
file.delete()
val sink = Okio.buffer(Okio.sink(file))
sink.writeAll(response.body()!!.source())
sink.close()
val result = Bundle().apply {
putString("uri", Uri.fromFile(file).toString())
putInt("status", response.code())
putBundle("headers", translateHeaders(response.headers()))
if (options?.get("md5") == true) {
putString("md5", md5(file))
}
}
response.close()
promise.resolve(result)
}
}) ?: run {
promise.reject(NullPointerException("okHttpClient is null"))
}
}
else -> throw IOException("Unsupported scheme for location '$uri'.")
}
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject(e)
}
}
@ExpoMethod
fun networkTaskCancelAsync(uuid: String, promise: Promise) {
val taskHandler = taskHandlers[uuid]
taskHandler?.call?.cancel()
promise.resolve(null)
}
@ExpoMethod
fun downloadResumableStartAsync(url: String, fileUriStr: String, uuid: String, options: Map<String?, Any?>, resumeData: String?, promise: Promise) {
try {
val fileUri = Uri.parse(fileUriStr)
fileUri.checkIfFileDirExists()
if (fileUri.scheme != "file") {
throw IOException("Unsupported scheme for location '$fileUri'.")
}
val progressListener: ProgressListener = object : ProgressListener {
var mLastUpdate: Long = -1
override fun update(bytesRead: Long, contentLength: Long, done: Boolean) {
val eventEmitter by moduleRegistry<EventEmitter>()
if (eventEmitter != null) {
val downloadProgress = Bundle()
val downloadProgressData = Bundle()
val totalBytesWritten = bytesRead + (resumeData?.toLong() ?: 0)
val totalBytesExpectedToWrite = contentLength + (resumeData?.toLong() ?: 0)
val currentTime = System.currentTimeMillis()
// Throttle events. Sending too many events will block the JS event loop.
// Make sure to send the last event when we're at 100%.
if (currentTime > mLastUpdate + MIN_EVENT_DT_MS || totalBytesWritten == totalBytesExpectedToWrite) {
mLastUpdate = currentTime
downloadProgressData.putDouble("totalBytesWritten", totalBytesWritten.toDouble())
downloadProgressData.putDouble("totalBytesExpectedToWrite", totalBytesExpectedToWrite.toDouble())
downloadProgress.putString("uuid", uuid)
downloadProgress.putBundle("data", downloadProgressData)
eventEmitter.emit(EXDownloadProgressEventName, downloadProgress)
}
}
}
}
val client = okHttpClient?.newBuilder()
?.addNetworkInterceptor { chain ->
val originalResponse = chain.proceed(chain.request())
originalResponse.newBuilder()
.body(ProgressResponseBody(originalResponse.body(), progressListener))
.build()
}
?.build()
if (client == null) {
promise.reject(NullPointerException("okHttpClient is null"))
return
}
val requestBuilder = Request.Builder()
resumeData.let {
requestBuilder.addHeader("Range", "bytes=$it-")
}
if (options.containsKey(HEADER_KEY)) {
val headers = options[HEADER_KEY] as Map<String, Any>?
headers?.forEach { (key, value) ->
requestBuilder.addHeader(key, value.toString())
}
}
DownloadResumableTask().apply {
val request = requestBuilder.url(url).build()
val call = client.newCall(request)
taskHandlers[uuid] = DownloadTaskHandler(fileUri, call)
val params = DownloadResumableTaskParams(
options, call, fileUri.toFile(), resumeData != null, promise
)
execute(params)
}
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject(e)
}
}
@ExpoMethod
fun downloadResumablePauseAsync(uuid: String, promise: Promise) {
val taskHandler = taskHandlers[uuid]
if (taskHandler == null) {
val e: Exception = IOException("No download object available")
e.message?.let { Log.e(TAG, it) }
promise.reject(e)
return
}
if (taskHandler !is DownloadTaskHandler) {
promise.reject("ERR_FILESYSTEM_CANNOT_FIND_TASK", "Cannot find task.")
return
}
taskHandler.call.cancel()
taskHandlers.remove(uuid)
try {
val file = taskHandler.fileUri.toFile()
val result = Bundle().apply {
putString("resumeData", file.length().toString())
}
promise.resolve(result)
} catch (e: Exception) {
e.message?.let { Log.e(TAG, it) }
promise.reject(e)
}
}
@SuppressLint("WrongConstant")
override fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == DIR_PERMISSIONS_REQUEST_CODE && dirPermissionsRequest != null) {
val result = Bundle()
if (resultCode == Activity.RESULT_OK && data != null) {
val treeUri = data.data
val takeFlags = (
data.flags
and (Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
)
treeUri?.let {
activity.contentResolver.takePersistableUriPermission(it, takeFlags)
}
result.putBoolean("granted", true)
result.putString("directoryUri", treeUri.toString())
} else {
result.putBoolean("granted", false)
}
dirPermissionsRequest?.resolve(result)
uIManager.unregisterActivityEventListener(this)
dirPermissionsRequest = null
}
}
override fun onNewIntent(intent: Intent) = Unit
private class DownloadResumableTaskParams internal constructor(var options: Map<String?, Any?>?, var call: Call, var file: File, var isResume: Boolean, var promise: Promise)
private inner class DownloadResumableTask : AsyncTask<DownloadResumableTaskParams?, Void?, Void?>() {
override fun doInBackground(vararg params: DownloadResumableTaskParams?): Void? {
val call = params[0]?.call
val promise = params[0]?.promise
val file = params[0]?.file
val isResume = params[0]?.isResume
val options = params[0]?.options
return try {
val response = call!!.execute()
val responseBody = response.body()
val input = BufferedInputStream(responseBody!!.byteStream())
val output = FileOutputStream(file, isResume == true)
val data = ByteArray(1024)
var count = 0
while (input.read(data).also { count = it } != -1) {
output.write(data, 0, count)
}
val result = Bundle().apply {
putString("uri", Uri.fromFile(file).toString())
putInt("status", response.code())
putBundle("headers", translateHeaders(response.headers()))
options?.get("md5").takeIf { it == true }?.let { putString("md5", file?.let { md5(it) }) }
}
response.close()
promise?.resolve(result)
null
} catch (e: Exception) {
if (call?.isCanceled == true) {
promise?.resolve(null)
return null
}
e.message?.let { Log.e(TAG, it) }
promise?.reject(e)
null
}
}
}
private open class TaskHandler(val call: Call)
private class DownloadTaskHandler(val fileUri: Uri, call: Call) : TaskHandler(call)
// https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/Progress.java
private class ProgressResponseBody internal constructor(private val responseBody: ResponseBody?, private val progressListener: ProgressListener) : ResponseBody() {
private var bufferedSource: BufferedSource? = null
override fun contentType(): MediaType? = responseBody?.contentType()
override fun contentLength(): Long = responseBody?.contentLength() ?: -1
override fun source(): BufferedSource =
bufferedSource ?: Okio.buffer(source(responseBody!!.source()))
private fun source(source: Source): Source {
return object : ForwardingSource(source) {
var totalBytesRead = 0L
@Throws(IOException::class)
override fun read(sink: Buffer, byteCount: Long): Long {
val bytesRead = super.read(sink, byteCount)
// read() returns the number of bytes read, or -1 if this source is exhausted.
totalBytesRead += if (bytesRead != -1L) bytesRead else 0
progressListener.update(
totalBytesRead,
responseBody?.contentLength()
?: -1,
bytesRead == -1L
)
return bytesRead
}
}
}
}
internal fun interface ProgressListener {
fun update(bytesRead: Long, contentLength: Long, done: Boolean)
}
@get:Synchronized
private val okHttpClient: OkHttpClient?
get() {
if (client == null) {
val builder = OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
val cookieHandler: CookieHandler by moduleRegistry()
builder.cookieJar(JavaNetCookieJar(cookieHandler))
client = builder.build()
}
return client
}
@Throws(IOException::class)
private fun md5(file: File): String {
val inputStream: InputStream = FileInputStream(file)
return inputStream.use {
val md5bytes = DigestUtils.md5(it)
String(Hex.encodeHex(md5bytes))
}
}
@Throws(IOException::class)
private fun ensureDirExists(dir: File) {
if (!(dir.isDirectory || dir.mkdirs())) {
throw IOException("Couldn't create directory '$dir'")
}
}
/**
* Concatenated copy of [email protected]#FileUtils#forceDelete
* Newer version of commons-io uses File#toPath() under the hood that unsupported below Android SDK 26
* See docs for reference https://commons.apache.org/proper/commons-io/javadocs/api-1.4/index.html
*/
@Throws(IOException::class)
private fun forceDelete(file: File) {
if (file.isDirectory) {
val files = file.listFiles() ?: throw IOException("Failed to list contents of $file")
var exception: IOException? = null
for (f in files) {
try {
forceDelete(f)
} catch (ioe: IOException) {
exception = ioe
}
}
if (null != exception) {
throw exception
}
if (!file.delete()) {
throw IOException("Unable to delete directory $file.")
}
} else if (!file.delete()) {
throw IOException("Unable to delete file: $file")
}
}
private fun getFileSize(file: File): Long {
if (!file.isDirectory) {
return file.length()
}
val content = file.listFiles() ?: return 0
val size = content.map { getFileSize(it) }.reduceOrNull { total, itemSize -> total + itemSize } ?: 0
return size
}
private fun getEncodingFromOptions(options: Map<String?, Any?>): String {
return if (options.containsKey("encoding") && options["encoding"] is String) {
(options["encoding"] as String).toLowerCase(Locale.ROOT)
} else {
"utf8"
}
}
@Throws(IOException::class)
private fun getInputStream(uri: Uri) = when {
uri.scheme == "file" -> FileInputStream(uri.toFile())
uri.scheme == "asset" -> openAssetInputStream(uri)
uri.isSAFUri -> context.contentResolver.openInputStream(uri)!!
else -> throw IOException("Unsupported scheme for location '$uri'.")
}
@Throws(IOException::class)
private fun getOutputStream(uri: Uri) = when {
uri.scheme == "file" -> FileOutputStream(uri.toFile())
uri.isSAFUri -> context.contentResolver.openOutputStream(uri)!!
else -> throw IOException("Unsupported scheme for location '$uri'.")
}
private fun getNearestSAFFile(uri: Uri): DocumentFile? {
val file = DocumentFile.fromSingleUri(context, uri)
return if (file != null && file.isFile) {
file
} else DocumentFile.fromTreeUri(context, uri)
}
/**
* Checks if the provided URI is compatible with the Storage Access Framework.
* For more information check out https://developer.android.com/guide/topics/providers/document-provider.
*
* @param uri
* @return whatever the provided URI is SAF URI
*/
// extension functions of Uri class
private fun Uri.toFile() = File(this.path)
private val Uri.isSAFUri: Boolean
get() = scheme == "content" && host?.startsWith("com.android.externalstorage") ?: false
private fun parseFileUri(uriStr: String) = uriStr.substring(uriStr.indexOf(':') + 3)
@Throws(IOException::class)
private fun getInputStreamBytes(inputStream: InputStream): ByteArray {
val bytesResult: ByteArray
val byteBuffer = ByteArrayOutputStream()
val bufferSize = 1024
val buffer = ByteArray(bufferSize)
try {
var len: Int
while (inputStream.read(buffer).also { len = it } != -1) {
byteBuffer.write(buffer, 0, len)
}
bytesResult = byteBuffer.toByteArray()
} finally {
try {
byteBuffer.close()
} catch (ignored: IOException) {
}
}
return bytesResult
}
// Copied out of React Native's `NetworkingModule.java`
private fun translateHeaders(headers: Headers): Bundle {
val responseHeaders = Bundle()
for (i in 0 until headers.size()) {
val headerName = headers.name(i)
// multiple values for the same header
if (responseHeaders[headerName] != null) {
responseHeaders.putString(
headerName,
responseHeaders.getString(headerName) + ", " + headers.value(i)
)
} else {
responseHeaders.putString(headerName, headers.value(i))
}
}
return responseHeaders
}
}
| android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/filesystem/FileSystemModule.kt | 3612978663 |
package com.teamwizardry.librarianlib.facade.text
import com.teamwizardry.librarianlib.math.Matrix4d
import dev.thecodewarrior.bitfont.typesetting.PositionedGlyph
import dev.thecodewarrior.bitfont.typesetting.TextEmbed
import java.awt.Color
public abstract class FacadeTextEmbed: TextEmbed() {
public abstract fun draw(matrix: Matrix4d, glyph: PositionedGlyph, posX: Int, posY: Int, color: Color)
} | modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/text/FacadeTextEmbed.kt | 1378702217 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
@file:JvmName("SerializationUtils")
@file:Suppress("unused")
package org.rust.cargo.project.settings.impl
import com.intellij.util.addOptionTag
import com.intellij.util.xmlb.Constants
import org.jdom.Element
import org.rust.cargo.project.settings.RustProjectSettingsService.MacroExpansionEngine
// Bump this number if Rust project settings changes
const val XML_FORMAT_VERSION: Int = 2
const val VERSION: String = "version"
const val TOOLCHAIN_HOME_DIRECTORY: String = "toolchainHomeDirectory"
const val AUTO_UPDATE_ENABLED: String = "autoUpdateEnabled"
const val EXPLICIT_PATH_TO_STDLIB: String = "explicitPathToStdlib"
const val EXTERNAL_LINTER: String = "externalLinter"
const val RUN_EXTERNAL_LINTER_ON_THE_FLY: String = "runExternalLinterOnTheFly"
const val EXTERNAL_LINTER_ARGUMENTS: String = "externalLinterArguments"
const val COMPILE_ALL_TARGETS: String = "compileAllTargets"
const val USE_OFFLINE: String = "useOffline"
const val MACRO_EXPANSION_ENGINE: String = "macroExpansionEngine"
const val DOCTEST_INJECTION_ENABLED: String = "doctestInjectionEnabled"
const val USE_RUSTFMT: String = "useRustfmt"
const val RUN_RUSTFMT_ON_SAVE: String = "runRustfmtOnSave"
const val USE_SKIP_CHILDREN: String = "useSkipChildren"
// Legacy properties needed for migration
const val USE_CARGO_CHECK_ANNOTATOR: String = "useCargoCheckAnnotator"
const val CARGO_CHECK_ARGUMENTS: String = "cargoCheckArguments"
const val EXPAND_MACROS: String = "expandMacros"
fun Element.updateToCurrentVersion() {
updateToVersionIfNeeded(2) {
renameOption(USE_CARGO_CHECK_ANNOTATOR, RUN_EXTERNAL_LINTER_ON_THE_FLY)
renameOption(CARGO_CHECK_ARGUMENTS, EXTERNAL_LINTER_ARGUMENTS)
if (getOptionValueAsBoolean(EXPAND_MACROS) == false) {
setOptionValue(MACRO_EXPANSION_ENGINE, MacroExpansionEngine.DISABLED)
}
}
check(version == XML_FORMAT_VERSION)
}
private fun Element.updateToVersionIfNeeded(newVersion: Int, update: Element.() -> Unit) {
if (version != newVersion - 1) return
update()
setOptionValue(VERSION, newVersion)
}
private val Element.version: Int get() = getOptionValueAsInt(VERSION) ?: 1
private fun Element.getOptionWithName(name: String): Element? =
children.find { it.getAttribute(Constants.NAME)?.value == name }
private fun Element.getOptionValue(name: String): String? =
getOptionWithName(name)?.getAttributeValue(Constants.VALUE)
private fun Element.getOptionValueAsBoolean(name: String): Boolean? =
getOptionValue(name)?.let {
when (it) {
"true" -> true
"false" -> false
else -> null
}
}
private fun Element.getOptionValueAsInt(name: String): Int? =
getOptionValue(name)?.let { Integer.valueOf(it) }
private fun Element.setOptionValue(name: String, value: Any) {
val option = getOptionWithName(name)
if (option != null) {
option.setAttribute(Constants.VALUE, value.toString())
} else {
addOptionTag(name, value.toString())
}
}
private fun Element.renameOption(oldName: String, newName: String) {
getOptionWithName(oldName)?.setAttribute(Constants.NAME, newName)
}
| src/main/kotlin/org/rust/cargo/project/settings/impl/SerializationUtils.kt | 1038907939 |
package com.mcgars.basekitk.tools.custom
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.os.Build
import android.util.AttributeSet
import android.view.WindowInsets
import com.bluelinelabs.conductor.ChangeHandlerFrameLayout
import com.mcgars.basekitk.R
import com.mcgars.basekitk.tools.colorAttr
import com.mcgars.basekitk.tools.forEach
import com.mcgars.basekitk.tools.getStatusBarHeight
/**
* In some case fitsystem not work correctly, this draw behind
* status bar rect with colorAccent
*/
class StatusBarFrameLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ChangeHandlerFrameLayout(context, attrs, defStyleAttr) {
private var statusBarHeight = 0f
private var paint = Paint().apply {
strokeWidth = 0f
}
init {
// make us to use onDraw method
setWillNotDraw(false)
statusBarHeight = context.getStatusBarHeight().toFloat()
// background color of status bar rect
paint.color = context.colorAttr(R.attr.colorPrimaryDark)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (width > 0) {
canvas.drawRect(0f, 0f, width.toFloat(), statusBarHeight, paint)
}
}
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
forEach {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
it.dispatchApplyWindowInsets(insets)
}
}
return insets
}
} | basekitk/src/main/kotlin/com/mcgars/basekitk/tools/custom/StatusBarFrameLayout.kt | 3241662460 |
package org.tsdes.advanced.dataformat
/**
* Note: by default, in Kotlin a generic T would bind to "Any?", which
* allows nullable types (eg, "String?").
* If we want to prevent null, we need "T: Any"
*/
interface Converter<T: Any> {
fun toXml(obj: T): String
fun fromXml(xml: String): T
fun toJson(obj: T): String
fun fromJson(json: String): T
/*
Transforming strings directly from XML to JSON (and vice-versa) would
be more efficient. But piping together existing methods is very quick
and easy, and perfectly valid solution when performance is not a major
constraint.
Recall that these default methods in this interface could be overwritten
if necessary
*/
fun fromJsonToXml(json: String): String {
val obj = fromJson(json)
return toXml(obj)
}
fun fromXmlToJson(xml: String): String {
val obj = fromXml(xml)
return toJson(obj)
}
} | advanced/data-format/src/main/kotlin/org/tsdes/advanced/dataformat/Converter.kt | 2222468337 |
/*
Copyright 2017-2020 Charles Korn.
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 batect.journeytests
import batect.journeytests.testutils.ApplicationRunner
import batect.journeytests.testutils.itCleansUpAllContainersItCreates
import batect.journeytests.testutils.itCleansUpAllNetworksItCreates
import batect.testutils.createForGroup
import batect.testutils.on
import batect.testutils.runBeforeGroup
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.containsSubstring
import com.natpryce.hamkrest.equalTo
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object SimpleTaskJourneyTests : Spek({
mapOf(
"simple-task-using-dockerfile" to "a simple task that uses a Dockerfile with the command specified on the task in the configuration file",
"simple-task-using-image" to "a simple task that uses an existing image",
"simple-task-using-custom-dockerfile" to "a simple task that uses a Dockerfile in a non-standard location",
"simple-task-dockerfile-command" to "a simple task with the command specified in the Dockerfile",
"simple-task-container-command" to "a simple task with the command specified on the container in the configuration file",
"simple-task-entrypoint-on-container" to "a simple task with an entrypoint specified on the container in the configuration file",
"simple-task-entrypoint-on-task" to "a simple task with an entrypoint specified on the task in the configuration file",
"simple-task-with-environment" to "a simple task with a task-level environment variable",
"container-with-health-check-overrides" to "a task with a dependency container that has a batect-specific health check configuration",
"build-image-dockerignore" to "a task that builds an image with a .dockerignore file",
"simple-task-using-dockerfile-with-add-from-url" to "a simple task that uses a Dockerfile with an ADD command that downloads a file from a URL",
"dependency-container-with-setup-command" to "a simple task that uses a setup command on a dependency container",
"task-container-with-setup-command" to "a simple task that uses a setup command on the task container"
).forEach { (testName, description) ->
describe(description) {
val runner by createForGroup { ApplicationRunner(testName) }
on("running that task") {
val result by runBeforeGroup { runner.runApplication(listOf("the-task")) }
it("prints the output from that task") {
assertThat(result.output, containsSubstring("This is some output from the task\r\n"))
}
it("returns the exit code from that task") {
assertThat(result.exitCode, equalTo(123))
}
itCleansUpAllContainersItCreates { result }
itCleansUpAllNetworksItCreates { result }
}
}
}
})
| app/src/journeyTest/kotlin/batect/journeytests/SimpleTaskJourneyTests.kt | 2544324559 |
/**
* Created by Corwin on 2017/2/1.
*/
private data class Node<T>(val v: T, var previous: Node<T>? = null, var next: Node<T>? = null)
class Deque<T> {
private var head: Node<T>? = null
private var tail: Node<T>? = null
fun push(v: T) {
val node = Node(v, previous = tail, next = null)
tail?.next = node
tail = node
if (head == null) head = tail
}
fun pop() : T {
if (tail == null) {
throw IllegalAccessException("Empty deque.")
}
val value = tail?.v
val p = tail?.previous
p?.next = null
tail?.previous = null
if (head == tail) head = null
tail = p
return value!!
}
fun unshift(v: T) {
val node = Node(v, previous = null, next = head)
head?.previous = node
head = node
if (tail == null) tail = head
}
fun shift() : T {
if (head == null) {
throw IllegalAccessException("Empty deque.")
}
val value = head?.v
val n = head?.next
n?.previous = null
head?.next = null
if (tail == head) tail = null
head = n
return value!!
}
}
| kotlin/linked-list/src/main/kotlin/Deque.kt | 1939604796 |
package net.rayfall.eyesniper2.skrayfall.effectlibsupport
import ch.njol.skript.Skript
import ch.njol.skript.doc.Description
import ch.njol.skript.doc.Name
import ch.njol.skript.lang.Effect
import ch.njol.skript.lang.Expression
import ch.njol.skript.lang.SkriptParser
import ch.njol.skript.util.VisualEffect
import ch.njol.util.Kleenean
import de.slikey.effectlib.effect.AnimatedBallEffect
import de.slikey.effectlib.util.DynamicLocation
import net.rayfall.eyesniper2.skrayfall.Core
import org.bukkit.Location
import org.bukkit.entity.Entity
import org.bukkit.event.Event
@Name("Animated Ball Effect")
@Description("Creates an EffectLib animated ball effect.")
class EffEffectLibAnimatedBallEffect : Effect() {
// (spawn|create|apply) (a|the|an) animated ball (effect|formation) (at|on|for|to)
// %entity/location% with id %string% [with particle %visualeffects%][ off set by %number%,
// %number%(,| and) %number%]
private var targetExpression: Expression<*>? = null
private var idExpression: Expression<String>? = null
private var visualEffectExpression: Expression<VisualEffect>? = null
private var xOffsetExpression: Expression<Number>? = null
private var yOffsetExpression: Expression<Number>? = null
private var zOffsetExpression: Expression<Number>? = null
@Suppress("UNCHECKED_CAST")
override fun init(exp: Array<Expression<*>?>, arg1: Int, arg2: Kleenean, arg3: SkriptParser.ParseResult): Boolean {
targetExpression = exp[0]
idExpression = exp[1] as Expression<String>
visualEffectExpression = exp[2] as? Expression<VisualEffect>
xOffsetExpression = exp[3] as Expression<Number>
yOffsetExpression = exp[4] as Expression<Number>
zOffsetExpression = exp[5] as Expression<Number>
return true
}
override fun toString(arg0: Event?, arg1: Boolean): String {
return ""
}
override fun execute(evt: Event) {
val target = targetExpression?.getSingle(evt)
val id = idExpression?.getSingle(evt)
val baseEffect = AnimatedBallEffect(Core.effectManager)
if (id == null)
{
Skript.warning("Id was null for EffectLib Animated Ball")
return
}
when (target) {
is Entity -> {
baseEffect.setDynamicOrigin(DynamicLocation(target as Entity?))
}
is Location -> {
baseEffect.setDynamicOrigin(DynamicLocation(target as Location?))
}
else -> {
assert(false)
}
}
val particle = EffectLibUtils.getParticleFromVisualEffect(visualEffectExpression?.getSingle(evt))
if (particle != null) {
baseEffect.particle = particle
}
val xOffset = xOffsetExpression?.getSingle(evt)
val yOffset = yOffsetExpression?.getSingle(evt)
val zOffset = zOffsetExpression?.getSingle(evt)
if (xOffset != null && yOffset != null && zOffset != null) {
baseEffect.xOffset = xOffset.toFloat()
baseEffect.yOffset = yOffset.toFloat()
baseEffect.zOffset = zOffset.toFloat()
}
baseEffect.infinite()
baseEffect.start()
val setEffectSuccess = Core.rayfallEffectManager.setEffect(baseEffect, id.replace("\"", ""))
if (!setEffectSuccess) {
baseEffect.cancel()
}
}
} | src/main/java/net/rayfall/eyesniper2/skrayfall/effectlibsupport/EffEffectLibAnimatedBallEffect.kt | 3661204234 |
/*
* 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.work.multiprocess
import android.content.Context
import android.os.Build
import androidx.arch.core.executor.ArchTaskExecutor
import androidx.arch.core.executor.TaskExecutor
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.work.Configuration
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkRequest
import androidx.work.impl.Scheduler
import androidx.work.impl.WorkContinuationImpl
import androidx.work.impl.WorkManagerImpl
import androidx.work.impl.utils.SerialExecutorImpl
import androidx.work.impl.utils.SynchronousExecutor
import androidx.work.impl.utils.taskexecutor.SerialExecutor
import androidx.work.multiprocess.parcelable.ParcelConverters.marshall
import androidx.work.multiprocess.parcelable.ParcelConverters.unmarshall
import androidx.work.multiprocess.parcelable.ParcelableWorkContinuationImpl
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.mockito.Mockito.spy
import java.util.concurrent.Executor
@RunWith(AndroidJUnit4::class)
public class ParcelableWorkContinuationImplTest {
private lateinit var context: Context
private lateinit var workManager: WorkManagerImpl
@Before
public fun setUp() {
if (Build.VERSION.SDK_INT <= 27) {
// Exclude <= API 27, from tests because it causes a SIGSEGV.
return
}
context = ApplicationProvider.getApplicationContext<Context>()
val taskExecutor = object : TaskExecutor() {
override fun executeOnDiskIO(runnable: Runnable) {
runnable.run()
}
override fun isMainThread(): Boolean {
return true
}
override fun postToMainThread(runnable: Runnable) {
runnable.run()
}
}
ArchTaskExecutor.getInstance().setDelegate(taskExecutor)
val scheduler = mock(Scheduler::class.java)
val configuration = Configuration.Builder()
.setExecutor(SynchronousExecutor())
.build()
workManager = spy(
WorkManagerImpl(
context,
configuration,
object : androidx.work.impl.utils.taskexecutor.TaskExecutor {
val executor = Executor {
it.run()
}
val serialExecutor = SerialExecutorImpl(executor)
override fun getMainThreadExecutor(): Executor {
return serialExecutor
}
override fun getSerialTaskExecutor(): SerialExecutor {
return serialExecutor
}
}
)
)
`when`<List<Scheduler>>(workManager.schedulers).thenReturn(listOf(scheduler))
WorkManagerImpl.setDelegate(workManager)
}
@Test
@MediumTest
public fun basicContinuationTest() {
if (Build.VERSION.SDK_INT <= 27) {
// Exclude <= API 27, from tests because it causes a SIGSEGV.
return
}
val first = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
val second = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
val continuation = workManager.beginWith(listOf(first)).then(second)
val parcelable = ParcelableWorkContinuationImpl(continuation as WorkContinuationImpl)
assertOn(parcelable)
}
@Test
@MediumTest
public fun continuationTests2() {
if (Build.VERSION.SDK_INT <= 27) {
// Exclude <= API 27, from tests because it causes a SIGSEGV.
return
}
val first = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
val second = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
val third = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
val continuation = workManager.beginWith(listOf(first, second)).then(third)
val parcelable = ParcelableWorkContinuationImpl(continuation as WorkContinuationImpl)
assertOn(parcelable)
}
@Test
@MediumTest
public fun continuationTest3() {
if (Build.VERSION.SDK_INT <= 27) {
// Exclude <= API 27, from tests because it causes a SIGSEGV.
return
}
val first = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
val second = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
val continuation = workManager.beginUniqueWork(
"test", ExistingWorkPolicy.REPLACE, listOf(first)
).then(second)
val parcelable = ParcelableWorkContinuationImpl(continuation as WorkContinuationImpl)
assertOn(parcelable)
}
@Test
@MediumTest
public fun continuationTest4() {
if (Build.VERSION.SDK_INT <= 27) {
// Exclude <= API 27, from tests because it causes a SIGSEGV.
return
}
val first = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
val second = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
val continuation = workManager.beginUniqueWork(
"test", ExistingWorkPolicy.REPLACE, listOf(first)
).then(second)
val parcelable = ParcelableWorkContinuationImpl(continuation as WorkContinuationImpl)
val continuation2 = parcelable.info.toWorkContinuationImpl(workManager)
equal(
ParcelableWorkContinuationImpl(continuation).info,
ParcelableWorkContinuationImpl(continuation2).info
)
}
@Test
@MediumTest
public fun combineContinuationTests() {
if (Build.VERSION.SDK_INT <= 27) {
// Exclude <= API 27, from tests because it causes a SIGSEGV.
return
}
val first = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
val second = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
val third = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
val continuation1 = workManager.beginWith(listOf(first, second)).then(third)
val fourth = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
val fifth = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
val sixth = OneTimeWorkRequest.Builder(TestWorker::class.java).build()
val continuation2 = workManager.beginWith(listOf(fourth, fifth)).then(sixth)
val continuation = WorkContinuationImpl.combine(listOf(continuation1, continuation2))
val parcelable = ParcelableWorkContinuationImpl(continuation as WorkContinuationImpl)
assertOn(parcelable)
}
// Utilities
private fun assertOn(parcelable: ParcelableWorkContinuationImpl) {
val parcelable2 = unmarshall(marshall(parcelable), ParcelableWorkContinuationImpl.CREATOR)
equal(parcelable.info, parcelable2.info)
}
private fun equal(
first: ParcelableWorkContinuationImpl.WorkContinuationImplInfo,
second: ParcelableWorkContinuationImpl.WorkContinuationImplInfo
) {
assertEquals(first.name, second.name)
assertEquals(first.existingWorkPolicy, second.existingWorkPolicy)
assertRequests(first.work, second.work)
assertEquals(first.parentInfos?.size, first.parentInfos?.size)
first.parentInfos?.forEachIndexed { i, info -> equal(info, second.parentInfos!![i]) }
}
private fun assertRequest(first: WorkRequest, second: WorkRequest) {
assertEquals(first.id, second.id)
assertEquals(first.workSpec, second.workSpec)
assertEquals(first.tags, second.tags)
}
private fun assertRequests(listOne: List<WorkRequest>, listTwo: List<WorkRequest>) {
listOne.forEachIndexed { i, workRequest ->
assertRequest(workRequest, listTwo[i])
}
}
}
| work/work-multiprocess/src/androidTest/java/androidx/work/multiprocess/ParcelableWorkContinuationImplTest.kt | 1718950086 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.bluetooth.integration.testapp.ui.framework
import android.annotation.SuppressLint
import android.bluetooth.BluetoothManager
import android.bluetooth.le.AdvertiseCallback
import android.bluetooth.le.AdvertiseData
import android.bluetooth.le.AdvertiseSettings
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.os.Bundle
import android.os.ParcelUuid
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.bluetooth.integration.testapp.R
import androidx.bluetooth.integration.testapp.databinding.FragmentFwkBinding
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
class FwkFragment : Fragment() {
companion object {
const val TAG = "FwkFragment"
val ServiceUUID: ParcelUuid = ParcelUuid.fromString("0000b81d-0000-1000-8000-00805f9b34fb")
}
private val scanCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult?) {
Log.d(TAG, "onScanResult() called with: callbackType = $callbackType, result = $result")
}
override fun onBatchScanResults(results: MutableList<ScanResult>?) {
Log.d(TAG, "onBatchScanResults() called with: results = $results")
}
override fun onScanFailed(errorCode: Int) {
Log.d(TAG, "onScanFailed() called with: errorCode = $errorCode")
}
}
private val advertiseCallback = object : AdvertiseCallback() {
override fun onStartFailure(errorCode: Int) {
Log.d(TAG, "onStartFailure() called with: errorCode = $errorCode")
}
override fun onStartSuccess(settingsInEffect: AdvertiseSettings?) {
Log.d(TAG, "onStartSuccess() called")
}
}
private var _binding: FragmentFwkBinding? = null
// This property is only valid between onCreateView and onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentFwkBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.buttonNext.setOnClickListener {
findNavController().navigate(R.id.action_FwkFragment_to_BtxFragment)
}
binding.buttonScan.setOnClickListener {
scan()
}
binding.switchAdvertise.setOnClickListener {
if (binding.switchAdvertise.isChecked) startAdvertise()
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
// Permissions are handled by MainActivity requestBluetoothPermissions
@SuppressLint("MissingPermission")
private fun scan() {
Log.d(TAG, "scan() called")
val bluetoothManager =
context?.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager
val bluetoothAdapter = bluetoothManager?.adapter
val bleScanner = bluetoothAdapter?.bluetoothLeScanner
val scanSettings = ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build()
bleScanner?.startScan(null, scanSettings, scanCallback)
Toast.makeText(context, getString(R.string.scan_start_message), Toast.LENGTH_LONG)
.show()
}
// Permissions are handled by MainActivity requestBluetoothPermissions
@SuppressLint("MissingPermission")
private fun startAdvertise() {
Log.d(TAG, "startAdvertise() called")
val bluetoothManager =
context?.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager
val bluetoothAdapter = bluetoothManager?.adapter
val bleAdvertiser = bluetoothAdapter?.bluetoothLeAdvertiser
val advertiseSettings = AdvertiseSettings.Builder()
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
.setTimeout(0)
.build()
val advertiseData = AdvertiseData.Builder()
.addServiceUuid(ServiceUUID)
.setIncludeDeviceName(true)
.build()
bleAdvertiser?.startAdvertising(advertiseSettings, advertiseData, advertiseCallback)
Toast.makeText(context, getString(R.string.advertise_start_message), Toast.LENGTH_LONG)
.show()
}
}
| bluetooth/integration-tests/testapp/src/main/java/androidx/bluetooth/integration/testapp/ui/framework/FwkFragment.kt | 3569171037 |
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import org.elm.lang.core.psi.ElmFunctionParamTag
import org.elm.lang.core.psi.ElmPatternChildTag
import org.elm.lang.core.psi.ElmPsiElementImpl
import org.elm.lang.core.psi.ElmUnionPatternChildTag
/**
* An underscore in a pattern.
*
* e.g. the `_` in `(1, _, 3)`
*/
class ElmAnythingPattern(node: ASTNode) : ElmPsiElementImpl(node), ElmFunctionParamTag, ElmPatternChildTag, ElmUnionPatternChildTag
| src/main/kotlin/org/elm/lang/core/psi/elements/ElmAnythingPattern.kt | 3214676453 |
package net.oddpoet.expect.extension
import net.oddpoet.expect.should
import org.junit.jupiter.api.Test
class FloatExtensionTest {
@Test
fun `test beGreaterThan`() {
2.3f.should.beGreaterThan(1.1f)
2.1f.should.not.beGreaterThan(2.1f)
1f.should.not.beGreaterThan(2f)
}
@Test
fun `test beGreaterThanOrEqualTo`() {
1f.should.beGreaterThanOrEqualTo(1f)
1f.should.beGreaterThanOrEqualTo(0f)
}
@Test
fun `test beLessThan`() {
1f.should.beLessThan(2f)
1f.should.not.beLessThan(1f)
1f.should.not.beLessThan(0f)
}
@Test
fun `test beLessThanOrEqualTo`() {
2f.should.beLessThanOrEqualTo(2f)
2f.should.beLessThanOrEqualTo(3f)
2f.should.not.beLessThanOrEqualTo(1f)
}
@Test
fun `test beBetween`() {
2f.should.beBetween(1f, 3f)
2f.should.beBetween(1f, 2f)
2f.should.beBetween(2f, 3f)
2f.should.not.beBetween(3f, 4f)
}
@Test
fun `test beIn the range`() {
3f.should.beIn(3f..4f)
3f.should.beIn(2.9f..3f)
3f.should.not.beIn(3.00001f..3.1f)
3f.should.not.beIn(2f..2.999999f)
}
@Test
fun `test equalToWithin`() {
2.31231f.should.equalToWithin(2.3f, error = 0.1)
3.14159f.should.not.equalToWithin(3.15f, error = 0.001)
}
}
| src/test/kotlin/net/oddpoet/expect/extension/FloatExtensionTest.kt | 4265411221 |
/**
* Copyright 2017 Goldman Sachs.
* 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.gs.obevo.impl
import com.gs.obevo.api.appdata.ChangeInput
import com.gs.obevo.api.platform.DaConstants
import com.gs.obevo.util.vfs.BasicFileSelector
import com.gs.obevo.util.vfs.FileObject
import org.eclipse.collections.api.set.ImmutableSet
/**
* The strategy for when onboarding is disabled (i.e. the regular prod deployment mode). The main check here is to
* ensure that teams did not leave leftover folders from onboarding and reverse-engineering here.
*/
internal class DisabledOnboardingStrategy : OnboardingStrategy {
override fun handleSuccess(change: ChangeInput) {
// no need to do anything extra upon actual deployment time
}
override fun handleException(change: ChangeInput, exc: Exception) {
// no need to do anything extra upon actual deployment time
}
override fun validateSourceDirs(sourceDirs: Iterable<FileObject>, schemaNames: ImmutableSet<String>) {
for (sourceDir in sourceDirs) {
// Only check for the schema folders under the source dirs to minimize any noise in this check.
// This logic matches DbDirectoryChangesetReader - ideally we should try to share this code logic
val schemaDirs = sourceDir.findFiles(BasicFileSelector({ fileInfo ->
schemaNames.any { schemaName ->
fileInfo.file.name.baseName.equals(schemaName, ignoreCase = true)
}
}))
val onboardFiles = schemaDirs.flatMap { schemaDir ->
schemaDir.findFiles(BasicFileSelector({ fileInfo ->
fileInfo.file.name.baseName.equals(OnboardingStrategy.exceptionDir, ignoreCase = true)
|| fileInfo.file.name.baseName.endsWith(DaConstants.ANALYZE_FOLDER_SUFFIX)
}, true)).toList()
}
if (onboardFiles.isNotEmpty()) {
throw IllegalArgumentException("Directory $sourceDir has the exception folders in it that need to get removed before doing regular deployments: $onboardFiles")
}
}
}
}
| obevo-core/src/main/java/com/gs/obevo/impl/DisabledOnboardingStrategy.kt | 1380068905 |
/*
* Copyright (C) 2017 Juan Ramón González González (https://github.com/jrgonzalezg)
*
* 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.jrgonzalezg.openlibrary.features.books.data.repository
import com.github.jrgonzalezg.openlibrary.domain.Result
import com.github.jrgonzalezg.openlibrary.features.books.data.repository.datasource.CloudBookDataSource
import com.github.jrgonzalezg.openlibrary.features.books.data.repository.datasource.LocalBookDataSource
import com.github.jrgonzalezg.openlibrary.features.books.domain.Book
import com.github.jrgonzalezg.openlibrary.features.books.domain.BookError
import com.github.jrgonzalezg.openlibrary.features.books.domain.BookSummariesError
import com.github.jrgonzalezg.openlibrary.features.books.domain.BookSummary
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.async
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class BookRepository @Inject constructor(private val cloudBookDataSource: CloudBookDataSource,
private val localBookDataSource: LocalBookDataSource) {
fun getBook(key: String): Result<BookError, Book> {
return async(CommonPool) {
val localBook = localBookDataSource.getBook(key).await()
if (localBook.isRight()) {
localBook
} else {
val cloudBook = cloudBookDataSource.getBook(key).await()
if (cloudBook.isRight()) {
localBookDataSource.insertBook(cloudBook.get())
}
cloudBook
}
}
}
fun getBookSummaries(): Result<BookSummariesError, List<BookSummary>> {
return async(CommonPool) {
val localBookSummaries = localBookDataSource.getBookSummaries().await()
if (localBookSummaries.isRight()) {
localBookSummaries
} else {
val cloudBookSummaries = cloudBookDataSource.getBookSummaries().await()
if (cloudBookSummaries.isRight()) {
localBookDataSource.insertBookSummaries(cloudBookSummaries.get())
}
cloudBookSummaries
}
}
}
}
| app/src/main/kotlin/com/github/jrgonzalezg/openlibrary/features/books/data/repository/BookRepository.kt | 3677797528 |
/*
* Copyright 2017 Peter Kenji Yamanaka
*
* 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.pyamsoft.powermanager.trigger.bus
data class TriggerDeleteEvent(val percent: Int)
| powermanager-trigger/src/main/java/com/pyamsoft/powermanager/trigger/bus/TriggerDeleteEvent.kt | 1686073592 |
/*
* Copyright 2017 Peter Kenji Yamanaka
*
* 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.pyamsoft.powermanager.manage
import com.pyamsoft.powermanager.base.preference.DataPreferences
import com.pyamsoft.powermanager.model.PermissionObserver
import io.reactivex.Completable
import io.reactivex.Single
import javax.inject.Inject
internal class DataManageInteractor @Inject internal constructor(val preferences: DataPreferences,
private val permissionObserver: PermissionObserver) : ManageInteractor() {
override fun setManaged(state: Boolean): Single<Boolean> {
return Completable.fromAction { preferences.dataManaged = state }.andThen(Single.just(state))
}
override val isManaged: Single<Pair<Boolean, Boolean>>
get() = Single.fromCallable {
return@fromCallable Pair(permissionObserver.hasPermission(), preferences.dataManaged)
}
}
| powermanager-manage/src/main/java/com/pyamsoft/powermanager/manage/DataManageInteractor.kt | 841532361 |
package at.ac.tuwien.caa.docscan.db.model
import android.os.Parcelable
import androidx.annotation.Keep
import androidx.room.ColumnInfo
import kotlinx.parcelize.Parcelize
@Parcelize
@Keep
data class MetaData(
/**
* Represents the related upload id, this is usually available when a document is created
* from a QR-code, which can be then used for uploads so that a document is associated to
* specific document in the backend already.
*/
@ColumnInfo(name = KEY_RELATED_UPLOAD_ID)
var relatedUploadId: Int? = null,
/**
* Transkribus author related tag
*/
@ColumnInfo(name = KEY_AUTHOR)
var author: String?,
/**
* Transkribus authority related tag
*/
@ColumnInfo(name = KEY_AUTHORITY)
var authority: String?,
/**
* Transkribus authority related tag
*/
@ColumnInfo(name = KEY_HIERARCHY)
var hierarchy: String?,
/**
* Transkribus genre related tag
*/
@ColumnInfo(name = KEY_GENRE)
var genre: String?,
/**
* Transkribus language related tag
*/
@ColumnInfo(name = KEY_LANGUAGE)
var language: String?,
/**
* Transkribus isProjectReadme2020 related tag
*/
@ColumnInfo(name = KEY_IS_PROJECT_README_2020)
var isProjectReadme2020: Boolean,
/**
* Transkribus allowImagePublication related tag
*/
@ColumnInfo(name = KEY_ALLOW_IMAGE_PUBLICATION)
var allowImagePublication: Boolean,
/**
* Transkribus signature related tag
*/
@ColumnInfo(name = KEY_SIGNATURE)
var signature: String?,
/**
* Transkribus url related tag
*/
@ColumnInfo(name = KEY_URL)
var url: String?,
/**
* Transkribus writer related tag
*/
@ColumnInfo(name = KEY_WRITER)
var writer: String?,
/**
* Transkribus description tag (only set from the QR-code)
*/
@ColumnInfo(name = KEY_DESCRIPTION)
var description: String?
) : Parcelable {
companion object {
const val KEY_RELATED_UPLOAD_ID = "related_upload_id"
const val KEY_AUTHOR = "author"
const val KEY_WRITER = "writer"
const val KEY_DESCRIPTION = "description"
const val KEY_GENRE = "genre"
const val KEY_SIGNATURE = "signature"
const val KEY_AUTHORITY = "authority"
const val KEY_HIERARCHY = "hierarchy"
const val KEY_URL = "url"
const val KEY_LANGUAGE = "language"
const val KEY_IS_PROJECT_README_2020 = "is_project_readme_2020"
const val KEY_ALLOW_IMAGE_PUBLICATION = "allow_image_publication"
}
}
| app/src/main/java/at/ac/tuwien/caa/docscan/db/model/MetaData.kt | 3570338321 |
// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.panelmatch.common.certificates
import java.security.PrivateKey
import java.security.cert.X509Certificate
import org.wfanet.panelmatch.common.ExchangeDateKey
/** Manages X509 Certificates and private keys. */
interface CertificateManager {
data class KeyPair(
val x509Certificate: X509Certificate,
val privateKey: PrivateKey,
val certResourceName: String
)
/**
* Retrieves the [X509Certificate] and resource name generated by a party in the exchange.
*
* @param exchange the Exchange that the certificate is scoped for
* @param certResourceName the resource name for the certificate we want to retrieve
* @throws [IllegalArgumentException] if not found
*/
suspend fun getCertificate(
exchange: ExchangeDateKey,
certOwnerName: String,
certResourceName: String
): X509Certificate
/** Grabs the root [X509Certificate] for a party. */
suspend fun getPartnerRootCertificate(partnerName: String): X509Certificate
/** Gets the [PrivateKey] created for the current exchange */
suspend fun getExchangePrivateKey(exchange: ExchangeDateKey): PrivateKey
/** Gets the [X509Certificate] and [PrivateKey] created for the current exchange. */
suspend fun getExchangeKeyPair(exchange: ExchangeDateKey): KeyPair
/**
* Creates an [X509Certificate] and a corresponding [PrivateKey] for [exchange].
*
* After this completes, the same Certificate and PrivateKey can be retrieved by using
* [getCertificate] and [getExchangePrivateKey], respectively.
*
* @return certResourceName compatible with [getCertificate].
*/
suspend fun createForExchange(exchange: ExchangeDateKey): String
}
| src/main/kotlin/org/wfanet/panelmatch/common/certificates/CertificateManager.kt | 230239050 |
package ru.fantlab.android.ui.adapter.viewholder
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.response_row_item.view.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.Response
import ru.fantlab.android.helper.FantlabHelper
import ru.fantlab.android.helper.InputHelper
import ru.fantlab.android.helper.getTimeAgo
import ru.fantlab.android.helper.parseFullDate
import ru.fantlab.android.provider.scheme.LinkParserHelper
import ru.fantlab.android.provider.storage.WorkTypesProvider
import ru.fantlab.android.ui.modules.work.CyclePagerActivity
import ru.fantlab.android.ui.modules.work.WorkPagerActivity
import ru.fantlab.android.ui.widgets.recyclerview.BaseRecyclerAdapter
import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder
class ResponseViewHolder(itemView: View, adapter: BaseRecyclerAdapter<Response, ResponseViewHolder>)
: BaseViewHolder<Response>(itemView, adapter) {
override fun bind(response: Response) {
itemView.avatarLayout.setUrl("https://${LinkParserHelper.HOST_DATA}/images/users/${response.userId}")
itemView.responseUser.text = response.userName.capitalize()
itemView.userInfo.setOnClickListener {
listener?.onOpenContextMenu(response)
}
itemView.date.text = response.dateIso.parseFullDate(true).getTimeAgo()
itemView.authors.text = if (!InputHelper.isEmpty(response.workAuthor)) response.workAuthor else response.workAuthorOrig
itemView.workName.text = if (response.workName.isNotEmpty()) response.workName else response.workNameOrig
itemView.coverLayout.setUrl("https:${response.workImage}", WorkTypesProvider.getCoverByTypeId(response.workTypeId))
itemView.coverLayout.setOnClickListener {
if (response.workTypeId == FantlabHelper.WorkType.WORK_TYPE_CYCLE.id)
CyclePagerActivity.startActivity(itemView.context, response.workId, response.workName, 0)
else
WorkPagerActivity.startActivity(itemView.context, response.workId, response.workName, 0)
}
itemView.responseText.text = response.text
.replace("(\r\n)+".toRegex(), "\n")
.replace("\\[spoiler].*|\\[\\/spoiler]".toRegex(), "")
.replace("\\[.*]".toRegex(), "")
.replace(":\\w+:".toRegex(), "")
if (response.mark == null) {
itemView.rating.visibility = View.GONE
} else {
itemView.rating.text = response.mark.toString()
itemView.rating.visibility = View.VISIBLE
}
response.voteCount.let {
when {
it < 0 -> {
itemView.votes.setDrawables(R.drawable.ic_thumb_down)
itemView.votes.text = response.voteCount.toString()
itemView.votes.visibility = View.VISIBLE
}
it > 0 -> {
itemView.votes.setDrawables(R.drawable.ic_thumb_up)
itemView.votes.text = response.voteCount.toString()
itemView.votes.visibility = View.VISIBLE
}
else -> itemView.votes.visibility = View.GONE
}
}
}
interface OnOpenContextMenu {
fun onOpenContextMenu(userItem: Response)
}
companion object {
private var listener: OnOpenContextMenu? = null
fun newInstance(
viewGroup: ViewGroup,
adapter: BaseRecyclerAdapter<Response, ResponseViewHolder>
): ResponseViewHolder {
return ResponseViewHolder(getView(viewGroup, R.layout.response_row_item), adapter)
}
fun setOnContextMenuListener(listener: ResponseViewHolder.OnOpenContextMenu) {
this.listener = listener
}
}
} | app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/ResponseViewHolder.kt | 3315890958 |
/*
* Copyright 2020 Automate The Planet Ltd.
* Author: Anton Angelov
* 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 tipstricks
import org.apache.tools.ant.util.FileUtils
import org.openqa.selenium.*
import org.openqa.selenium.support.ui.WebDriverWait
import kotlin.Throws
import java.io.IOException
import org.openqa.selenium.chrome.ChromeOptions
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.firefox.FirefoxDriver
import org.openqa.selenium.firefox.FirefoxOptions
import java.io.File
import java.util.HashMap
import java.util.concurrent.TimeUnit
import org.openqa.selenium.firefox.FirefoxProfile
import org.openqa.selenium.firefox.ProfilesIni
import org.openqa.selenium.interactions.Actions
import java.lang.InterruptedException
import org.openqa.selenium.support.ui.ExpectedConditions
import org.testng.Assert
import java.nio.file.Paths
import java.lang.System
import org.testng.annotations.AfterClass
import org.testng.annotations.BeforeClass
import org.testng.annotations.Test
import java.awt.image.BufferedImage
import java.lang.Exception
import java.nio.file.Files
import javax.imageio.ImageIO
class TipsTricksTests {
private lateinit var driver: WebDriver
private lateinit var wait: WebDriverWait
@BeforeClass
@Throws(IOException::class)
fun testSetup() {
System.setProperty("webdriver.chrome.driver", "resources\\chromedriver.exe")
// 5. Execute tests in headless Chrome
val chromeOptions = ChromeOptions()
chromeOptions.addArguments("--headless", "--disable-gpu", "--window-size=1920,1200", "--ignore-certificate-errors")
driver = ChromeDriver(chromeOptions)
// 22. Set HTTP Proxy ChromeDriver
val proxy = Proxy()
proxy.proxyType = Proxy.ProxyType.MANUAL
proxy.isAutodetect = false
proxy.sslProxy = "127.0.0.1:3239"
chromeOptions.setProxy(proxy)
// 23. Set HTTP Proxy with Authentication ChromeDriver
// chromeOptions.addArguments("--proxy-server=http://user:[email protected]:3239");
// 24. tart ChromeDriver with an Packed Extension
chromeOptions.addArguments("load-extension=/pathTo/extension")
// 25. Start ChromeDriver with an Unpacked Extension
chromeOptions.addExtensions(File("local/path/to/extension.crx"))
// 29. Verify File Downloaded ChromeDriver
// String downloadFilepath = "c:\\temp";
val chromePrefs = HashMap<String, Any>()
chromePrefs["profile.default_content_settings.popups"] = 0
chromePrefs["download.default_directory"] = "downloadFilepath"
chromeOptions.setExperimentalOption("prefs", chromePrefs)
chromeOptions.addArguments("--test-type")
chromeOptions.addArguments("start-maximized", "disable-popup-blocking")
// 18.2. Handle SSL Certificate Error ChromeDrive
chromeOptions.addArguments("--ignore-certificate-errors")
// 7. Use Specific Profile in Chrome
chromeOptions.addArguments("user-data-dri=C:\\Users\\Your path to user\\Roaming\\Google\\Chrome\\User Data")
driver = ChromeDriver()
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS)
// 10. Maximize Window
driver.manage().window().maximize()
// 4. Set Page Load Timeout
// driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
wait = WebDriverWait(driver, 30)
// 7. Use Specific Profile in Firefox
val profile = ProfilesIni()
val firefoxProfile = profile.getProfile("xyzProfile")
val firefoxOptions = FirefoxOptions()
// 8. Turn Off JavaScript
firefoxProfile.setPreference("javascript.enabled", false)
// 16. Change User Agent
firefoxProfile.setPreference("general.useragent.override", "Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.1.0.346 Mobile Safari/534.11+")
// 17. Set HTTP Proxy for Browser
firefoxProfile.setPreference("network.proxy.type", 1)
firefoxProfile.setPreference("network.proxy.http", "myproxy.com")
firefoxProfile.setPreference("network.proxy.http_port", 3239)
// 18. Handle SSL Certificate Error FirefoxDriver
firefoxProfile.setAcceptUntrustedCertificates(true)
firefoxProfile.setAssumeUntrustedCertificateIssuer(false)
// 21. Start FirefoxDriver with Plugins
firefoxProfile.addExtension(File("C:\\extensionsLocation\\extension.xpi"))
// 30. Verify File Downloaded FirefoxDriver
val downloadFilepath = "c:\\temp"
firefoxProfile.setPreference("browser.download.folderList", 2)
firefoxProfile.setPreference("browser.download.dir", downloadFilepath)
firefoxProfile.setPreference("browser.download.manager.alertOnEXEOpen", false)
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword, application/binary, application/ris, text/csv, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream")
firefoxOptions.setProfile(firefoxProfile)
val firefoxDriver: WebDriver = FirefoxDriver(firefoxOptions)
}
@AfterClass
fun afterClass() {
driver.quit()
}
@Test
fun takeFullScreenshot_test() {
driver.navigate().to("http://automatetheplanet.com")
takeFullScreenshot("testImage")
}
@Test
fun takeElementScreenshot_test() {
driver.navigate().to("http://automatetheplanet.com")
val element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/header/div/div[2]/div/div[2]/nav")))
takeScreenshotOfElement(element, "testElementImage")
}
// 2. Get HTML Source of WebElement
@get:Test
val htmlSourceOfWebElement: Unit
get() {
driver.navigate().to("http://automatetheplanet.com")
val element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/header/div/div[2]/div/div[2]/nav")))
val sourceHtml = element.getAttribute("innerHTML")
println(sourceHtml)
}
// 3. Execute JavaScript
@Test
fun executeJavaScript() {
driver.navigate().to("http://automatetheplanet.com")
val javascriptExecutor = driver as JavascriptExecutor?
val title = javascriptExecutor!!.executeScript("return document.title") as String
// 4. Visibility of all elements wait
wait.until(ExpectedConditions.visibilityOfAllElements(driver.findElements(By.xpath("//*[@id='tve_editor']/div[2]/div[2]/div/div"))))
println(title)
}
// 6. Check If an Element Is Visible
@Test
fun checkIfElementIsVisible() {
driver.navigate().to("http://automatetheplanet.com")
val element = driver.findElement(By.xpath("/html/body/div[1]/header/div/div[2]/div/div[2]/nav"))
Assert.assertTrue(element.isDisplayed)
}
@Test
fun manageCookies() {
driver.navigate().to("http://automatetheplanet.com")
// get all cookies
val cookies = driver.manage().cookies
for (cookie in cookies) {
println(cookie.name)
}
// get a cookie by name
val fbPixelCookie = driver.manage().getCookieNamed("_fbp")
// create a new cookie by name
val newCookie = Cookie("customName", "customValue")
driver.manage().addCookie(newCookie)
// delete a cookie
driver.manage().deleteCookie(fbPixelCookie)
// delete a cookie by name
driver.manage().deleteCookieNamed("customName")
// delete all cookies
driver.manage().deleteAllCookies()
}
// 11. Drag and Drop
@Test
fun dragAndDrop() {
driver.navigate().to("http://loopj.com/jquery-simple-slider/")
val element = driver.findElement(By.xpath("//*[@id='project']/p[1]/div/div[2]"))
val action = Actions(driver)
action.dragAndDropBy(element, 30, 0).build().perform()
}
// 12. Upload a File
@Test
fun fileUpload() {
driver.navigate().to("https://demos.telerik.com/aspnet-ajax/ajaxpanel/application-scenarios/file-upload/defaultcs.aspx")
val element = driver.findElement(By.id("ctl00_ContentPlaceholder1_RadUpload1file0"))
val filePath = Paths.get(System.getProperty("java.io.tmpdir"), "debugWebDriver.xml").toString()
val destFile = File(filePath)
destFile.createNewFile()
element.sendKeys(filePath)
}
// 13. Handle JavaScript Pop-ups
@Test
fun handleJavaScripPopUps() {
driver.navigate().to("http://www.w3schools.com/js/tryit.asp?filename=tryjs_confirm")
driver.switchTo().frame("iframeResult")
val button = driver.findElement(By.xpath("/html/body/button"))
button.click()
val alert = driver.switchTo().alert()
if (alert.text == "Press a button!") {
alert.accept()
} else {
alert.dismiss()
}
}
// 14. Switch Between Browser Windows or Tabs
@Test
fun movingBetweenTabs() {
driver.navigate().to("https://www.automatetheplanet.com/")
val firstLink = driver.findElement(By.xpath("//*[@id='menu-item-11362']/a"))
val secondLink = driver.findElement(By.xpath("//*[@id='menu-item-6']/a"))
val selectLinkOpenninNewTab = Keys.chord(Keys.CONTROL, Keys.RETURN)
firstLink.sendKeys(selectLinkOpenninNewTab)
secondLink.sendKeys(selectLinkOpenninNewTab)
val windows = driver.windowHandles
val firstTab = windows.toTypedArray()[1] as String
val lastTab = windows.toTypedArray()[2] as String
driver.switchTo().window(lastTab)
Assert.assertEquals("Resources - Automate The Planet", driver.title)
driver.switchTo().window(firstTab)
Assert.assertEquals("Blog - Automate The Planet", driver.title)
}
// 15. Navigation History
@Test
fun navigationHistory() {
driver.navigate().to("https://www.codeproject.com/Articles/1078541/Advanced-WebDriver-Tips-and-Tricks-Part")
driver.navigate().to("http://www.codeproject.com/Articles/1017816/Speed-up-Selenium-Tests-through-RAM-Facts-and-Myth")
driver.navigate().back()
Assert.assertEquals("10 Advanced WebDriver Tips and Tricks - Part 1 - CodeProject", driver.title)
driver.navigate().refresh()
Assert.assertEquals("10 Advanced WebDriver Tips and Tricks - Part 1 - CodeProject", driver.title)
driver.navigate().forward()
Assert.assertEquals("Speed up Selenium Tests through RAM Facts and Myths - CodeProject", driver.title)
}
// 19. Scroll Focus to Control
@Test
fun scrollFocusToControl() {
driver.navigate().to("http://automatetheplanet.com/")
val ourMissionLink = driver.findElement(By.xpath("//*[@id=\"panel-6435-0-0-4\"]/div"))
val jsToBeExecuted = String.format("window.scroll(0, {0});", ourMissionLink.location.getY())
val javascriptExecutor = driver as JavascriptExecutor?
javascriptExecutor!!.executeScript(jsToBeExecuted)
}
// 20. Focus on a Control
@Test
fun focusOnControl() {
driver.navigate().to("http://automatetheplanet.com/")
waitUntilLoaded()
val ourMissionLink = driver.findElement(By.xpath("//*[@id=\"panel-6435-0-0-4\"]/div"))
val action = Actions(driver)
action.moveToElement(ourMissionLink).build().perform()
}
// 26. Assert a Button Enabled or Disabled
@Test
fun assertButtonEnabledDisabled() {
driver.navigate().to("http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_button_disabled")
driver.switchTo().frame("iframeResult")
val button = driver.findElement(By.xpath("/html/body/button"))
Assert.assertFalse(button.isEnabled)
}
// 27. Set and Assert the Value of a Hidden Field
@Test
fun setHiddenField() {
//<input type="hidden" name="country" value="Bulgaria"/>
val theHiddenElem = driver.findElement(By.name("country"))
val javascriptExecutor = driver as JavascriptExecutor?
javascriptExecutor!!.executeScript("arguments[0].value='Germany';", theHiddenElem)
val hiddenFieldValue = theHiddenElem.getAttribute("value")
Assert.assertEquals("Germany", hiddenFieldValue)
}
// 29. Verify File Downloaded ChromeDriver
@Test
fun VerifyFileDownloadChrome() {
val expectedFilePath = Paths.get("c:\\temp\\Testing_Framework_2015_3_1314_2_Free.exe")
try {
driver.navigate().to("https://www.telerik.com/download-trial-file/v2/telerik-testing-framework")
wait.until { x: WebDriver? -> Files.exists(expectedFilePath) }
val bytes = Files.size(expectedFilePath)
Assert.assertEquals(4326192, bytes)
} finally {
if (Files.exists(expectedFilePath)) {
Files.delete(expectedFilePath)
}
}
}
// 1. Taking a Screenshot
fun takeFullScreenshot(fileName: String) {
val srcFile = (driver as TakesScreenshot).getScreenshotAs(OutputType.FILE)
val tempDir = System.getProperty("java.io.tmpdir")
val destFile = File(Paths.get(tempDir, "$fileName.png").toString())
FileUtils.getFileUtils().copyFile(srcFile, destFile)
}
fun takeScreenshotOfElement(element: WebElement, fileName: String) {
val screenshotFile = (driver as TakesScreenshot).getScreenshotAs(OutputType.FILE)
val fullImg = ImageIO.read(screenshotFile)
val point = element.location
val elementWidth = element.size.getWidth()
val elementHeight = element.size.getHeight()
val eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(), elementWidth, elementHeight)
ImageIO.write(eleScreenshot, "png", screenshotFile)
val tempDir = System.getProperty("java.io.tmpdir")
val destFile = File(Paths.get(tempDir, "$fileName.png").toString())
FileUtils.getFileUtils().copyFile(screenshotFile, destFile)
}
// 4. Set Page Load Timeout
private fun waitUntilLoaded() {
wait.until { x: WebDriver? ->
val javascriptExecutor = driver as JavascriptExecutor?
val isReady = javascriptExecutor!!.executeScript("return document.readyState") as String
isReady == "complete"
}
}
// 28. Wait AJAX Call to Complete Using JQuery
private fun waitForAjaxComplete() {
wait.until { x: WebDriver? ->
val javascriptExecutor = driver as JavascriptExecutor?
val isAjaxCallComplete = javascriptExecutor!!.executeScript("return window.jQuery != undefined && jQuery.active == 0") as Boolean
isAjaxCallComplete
}
}
} | kotlin/WebAutomation-Series/src/test/java/tipstricks/TipsTricksTests.kt | 2573257130 |
package xyz.gnarbot.gnar.commands.settings
import net.dv8tion.jda.api.Permission
import xyz.gnarbot.gnar.commands.BotInfo
import xyz.gnarbot.gnar.commands.Category
import xyz.gnarbot.gnar.commands.Command
import xyz.gnarbot.gnar.commands.Context
import xyz.gnarbot.gnar.commands.template.CommandTemplate
import xyz.gnarbot.gnar.commands.template.annotations.Description
@Command(
aliases = ["prefix"],
usage = "(set|reset) [string]",
description = "Set the bot prefix for the server."
)
@BotInfo(
id = 56,
category = Category.SETTINGS,
permissions = [Permission.MANAGE_SERVER]
)
class PrefixCommand : CommandTemplate() {
private val mention = Regex("<@!?(\\d+)>|<#(\\d+)>|<@&(\\d+)>")
@Description("Set the prefix.")
fun set(context: Context, prefix: String) {
if (prefix matches mention) {
context.send().error("The prefix can't be set to a mention.").queue()
return
}
if (context.data.command.prefix == prefix) {
context.send().error("The prefix is already set to `$prefix`.").queue()
return
}
if (prefix == "__" || prefix == "~~" || prefix == "**" || prefix == "`" || prefix == "```" || prefix == "*" || prefix == "_") {
context.send().error("To prevent markdown formatting issues, `$prefix` is not an allowable prefix.").queue()
return
}
context.data.command.prefix = prefix
context.data.save()
context.send().info("The prefix has been set to `${context.data.command.prefix}`.").queue()
}
@Description("Reset to the default prefix.")
fun reset(context: Context) {
if (context.data.command.prefix == null) {
context.send().error("The prefix is already set to the default.").queue()
return
}
context.data.command.prefix = null
context.data.save()
context.send().info("The prefix has been reset to `${context.bot.configuration.prefix}`.").queue()
}
override fun onWalkFail(context: Context, args: Array<String>, depth: Int) {
onWalkFail(context, args, depth, null, buildString {
append("Default prefix will still be valid.\n")
val prefix = context.data.command.prefix
append("Current prefix: `").append(prefix).append('`')
})
}
} | src/main/kotlin/xyz/gnarbot/gnar/commands/settings/PrefixCommand.kt | 4292605109 |
package ktx.assets.async
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.assets.AssetDescriptor
import com.badlogic.gdx.assets.AssetLoaderParameters
import com.badlogic.gdx.assets.loaders.resolvers.ClasspathFileHandleResolver
import com.badlogic.gdx.audio.Music
import com.badlogic.gdx.audio.Sound
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3NativesLoader
import com.badlogic.gdx.backends.lwjgl3.audio.OpenALLwjgl3Audio
import com.badlogic.gdx.graphics.Cubemap
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.ParticleEffect
import com.badlogic.gdx.graphics.g2d.PolygonRegion
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.graphics.g3d.Model
import com.badlogic.gdx.graphics.glutils.ShaderProgram
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.ui.Button
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.badlogic.gdx.utils.I18NBundle
import com.badlogic.gdx.utils.Logger
import com.nhaarman.mockitokotlin2.mock
import io.kotlintest.matchers.shouldThrow
import kotlinx.coroutines.runBlocking
import ktx.assets.TextAssetLoader
import ktx.async.AsyncTest
import org.junit.After
import org.junit.AfterClass
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNotSame
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestName
import java.util.IdentityHashMap
import com.badlogic.gdx.graphics.g3d.particles.ParticleEffect as ParticleEffect3D
/**
* [AssetStorage] has 3 main variants of asset loading: [AssetStorage.load], [AssetStorage.loadAsync]
* and [AssetStorage.loadSync]. To test each one, a common abstract test suite is provided.
*
* This test suite ensures that each method supports loading of every default asset type
* and performs basic asset loading logic tests.
*
* Note that variants consuming [String] path and reified asset types could not be easily tested,
* as they cannot be invoked in abstract methods. However, since all of them are just aliases and
* contain no logic other than [AssetDescriptor] or [Identifier] initiation, the associated loading
* methods are still tested.
*
* See also: [AssetStorageTest].
*/
abstract class AbstractAssetStorageLoadingTest : AsyncTest() {
@get:Rule
var testName = TestName()
/**
* Must be overridden with the tested loading method variant.
* Blocks the current thread until the selected asset is loaded.
*/
protected abstract fun <T> AssetStorage.testLoad(
path: String,
type: Class<T>,
parameters: AssetLoaderParameters<T>?
): T
private inline fun <reified T> AssetStorage.testLoad(
path: String,
parameters: AssetLoaderParameters<T>? = null
): T = testLoad(path, T::class.java, parameters)
// --- Asset support tests:
@Test
fun `should load text assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
// When:
val asset = storage.testLoad<String>(path)
// Then:
assertEquals("Content.", asset)
assertTrue(storage.isLoaded<String>(path))
assertSame(asset, storage.get<String>(path))
assertEquals(1, storage.getReferenceCount<String>(path))
assertEquals(emptyList<String>(), storage.getDependencies<String>(path))
}
@Test
fun `should load text assets with parameters`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
// When:
val asset = storage.testLoad(path, parameters = TextAssetLoader.TextAssetLoaderParameters("UTF-8"))
// Then:
assertEquals("Content.", asset)
assertTrue(storage.isLoaded<String>(path))
assertSame(asset, storage.get<String>(path))
assertEquals(1, storage.getReferenceCount<String>(path))
assertEquals(emptyList<String>(), storage.getDependencies<String>(path))
}
@Test
fun `should unload text assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
storage.testLoad<String>(path)
// When:
runBlocking { storage.unload<String>(path) }
// Then:
assertFalse(storage.isLoaded<String>(path))
assertEquals(0, storage.getReferenceCount<String>(path))
}
@Test
fun `should load BitmapFont assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "com/badlogic/gdx/utils/arial-15.fnt"
val dependency = "com/badlogic/gdx/utils/arial-15.png"
// When:
val asset = storage.testLoad<BitmapFont>(path)
// Then:
assertTrue(storage.isLoaded<BitmapFont>(path))
assertSame(asset, storage.get<BitmapFont>(path))
assertEquals(1, storage.getReferenceCount<BitmapFont>(path))
assertEquals(listOf(storage.getIdentifier<Texture>(dependency)), storage.getDependencies<BitmapFont>(path))
// Font dependencies:
assertTrue(storage.isLoaded<Texture>(dependency))
assertEquals(1, storage.getReferenceCount<Texture>(dependency))
assertSame(asset.region.texture, storage.get<Texture>(dependency))
storage.dispose()
}
@Test
fun `should unload BitmapFont with dependencies`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "com/badlogic/gdx/utils/arial-15.fnt"
val dependency = "com/badlogic/gdx/utils/arial-15.png"
storage.testLoad<BitmapFont>(path)
// When:
runBlocking { storage.unload<BitmapFont>(path) }
// Then:
assertFalse(storage.isLoaded<BitmapFont>(path))
assertEquals(0, storage.getReferenceCount<BitmapFont>(path))
assertFalse(storage.isLoaded<Texture>(dependency))
assertEquals(0, storage.getReferenceCount<Texture>(path))
}
@Test
fun `should load Music assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/sound.ogg"
// When:
val asset = storage.testLoad<Music>(path)
// Then:
assertTrue(storage.isLoaded<Music>(path))
assertSame(asset, storage.get<Music>(path))
assertEquals(1, storage.getReferenceCount<Music>(path))
assertEquals(emptyList<String>(), storage.getDependencies<Music>(path))
storage.dispose()
}
@Test
fun `should unload Music assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/sound.ogg"
storage.testLoad<Music>(path)
// When:
runBlocking { storage.unload<Music>(path) }
// Then:
assertFalse(storage.isLoaded<Music>(path))
assertEquals(0, storage.getReferenceCount<Music>(path))
}
@Test
fun `should load Sound assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/sound.ogg"
// When:
val asset = storage.testLoad<Sound>(path)
// Then:
assertTrue(storage.isLoaded<Sound>(path))
assertSame(asset, storage.get<Sound>(path))
assertEquals(1, storage.getReferenceCount<Sound>(path))
assertEquals(emptyList<String>(), storage.getDependencies<Sound>(path))
storage.dispose()
}
@Test
fun `should unload Sound assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/sound.ogg"
storage.testLoad<Sound>(path)
// When:
runBlocking { storage.unload<Sound>(path) }
// Then:
assertFalse(storage.isLoaded<Sound>(path))
assertEquals(0, storage.getReferenceCount<Sound>(path))
}
@Test
fun `should load TextureAtlas assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/skin.atlas"
val dependency = "ktx/assets/async/texture.png"
// When:
val asset = storage.testLoad<TextureAtlas>(path)
// Then:
assertTrue(storage.isLoaded<TextureAtlas>(path))
assertSame(asset, storage.get<TextureAtlas>(path))
assertEquals(1, storage.getReferenceCount<TextureAtlas>(path))
assertEquals(listOf(storage.getIdentifier<Texture>(dependency)), storage.getDependencies<TextureAtlas>(path))
// Atlas dependencies:
assertTrue(storage.isLoaded<Texture>(dependency))
assertSame(asset.textures.first(), storage.get<Texture>(dependency))
assertEquals(1, storage.getReferenceCount<Texture>(dependency))
storage.dispose()
}
@Test
fun `should unload TextureAtlas assets with dependencies`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/skin.atlas"
val dependency = "ktx/assets/async/texture.png"
storage.testLoad<TextureAtlas>(path)
// When:
runBlocking { storage.unload<TextureAtlas>(path) }
// Then:
assertFalse(storage.isLoaded<TextureAtlas>(path))
assertEquals(0, storage.getReferenceCount<TextureAtlas>(path))
assertFalse(storage.isLoaded<Texture>(dependency))
assertEquals(0, storage.getReferenceCount<Texture>(dependency))
}
@Test
fun `should load Texture assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/texture.png"
// When:
val asset = storage.testLoad<Texture>(path)
// Then:
assertTrue(storage.isLoaded<Texture>(path))
assertSame(asset, storage.get<Texture>(path))
assertEquals(1, storage.getReferenceCount<Texture>(path))
assertEquals(emptyList<String>(), storage.getDependencies<Texture>(path))
storage.dispose()
}
@Test
fun `should unload Texture assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/texture.png"
storage.testLoad<Texture>(path)
// When:
runBlocking { storage.unload<Texture>(path) }
// Then:
assertFalse(storage.isLoaded<Texture>(path))
assertEquals(0, storage.getReferenceCount<Texture>(path))
}
@Test
fun `should load Pixmap assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/texture.png"
// When:
val asset = storage.testLoad<Pixmap>(path)
// Then:
assertTrue(storage.isLoaded<Pixmap>(path))
assertSame(asset, storage.get<Pixmap>(path))
assertEquals(1, storage.getReferenceCount<Pixmap>(path))
assertEquals(emptyList<String>(), storage.getDependencies<Pixmap>(path))
storage.dispose()
}
@Test
fun `should unload Pixmap assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/texture.png"
storage.testLoad<Pixmap>(path)
// When:
runBlocking { storage.unload<Pixmap>(path) }
// Then:
assertFalse(storage.isLoaded<Pixmap>(path))
assertEquals(0, storage.getReferenceCount<Pixmap>(path))
}
@Test
fun `should load Skin assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/skin.json"
val atlas = "ktx/assets/async/skin.atlas"
val texture = "ktx/assets/async/texture.png"
// When:
val asset = storage.testLoad<Skin>(path)
// Then:
assertTrue(storage.isLoaded<Skin>(path))
assertSame(asset, storage.get<Skin>(path))
assertNotNull(asset.get("default", Button.ButtonStyle::class.java))
assertEquals(1, storage.getReferenceCount<Skin>(path))
assertEquals(listOf(storage.getIdentifier<TextureAtlas>(atlas)), storage.getDependencies<Skin>(path))
// Skin dependencies:
assertTrue(storage.isLoaded<TextureAtlas>(atlas))
assertEquals(1, storage.getReferenceCount<TextureAtlas>(atlas))
assertSame(asset.atlas, storage.get<TextureAtlas>(atlas))
assertEquals(listOf(storage.getIdentifier<Texture>(texture)), storage.getDependencies<TextureAtlas>(atlas))
// Atlas dependencies:
assertTrue(storage.isLoaded<Texture>(texture))
assertSame(asset.atlas.textures.first(), storage.get<Texture>(texture))
assertEquals(1, storage.getReferenceCount<Texture>(texture))
storage.dispose()
}
@Test
fun `should unload Skin assets with dependencies`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/skin.json"
val atlas = "ktx/assets/async/skin.atlas"
val texture = "ktx/assets/async/texture.png"
storage.testLoad<Skin>(path)
// When:
runBlocking { storage.unload<Skin>(path) }
// Then:
assertFalse(storage.isLoaded<Skin>(path))
assertEquals(0, storage.getReferenceCount<Skin>(path))
assertFalse(storage.isLoaded<TextureAtlas>(atlas))
assertEquals(0, storage.getReferenceCount<TextureAtlas>(atlas))
assertFalse(storage.isLoaded<Texture>(texture))
assertEquals(0, storage.getReferenceCount<Texture>(texture))
}
@Test
fun `should load I18NBundle assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/i18n"
// When:
val asset = storage.testLoad<I18NBundle>(path)
// Then:
assertTrue(storage.isLoaded<I18NBundle>(path))
assertEquals("Value.", asset["key"])
assertSame(asset, storage.get<I18NBundle>(path))
assertEquals(1, storage.getReferenceCount<I18NBundle>(path))
assertEquals(emptyList<String>(), storage.getDependencies<I18NBundle>(path))
storage.dispose()
}
@Test
fun `should unload I18NBundle assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/i18n"
storage.testLoad<I18NBundle>(path)
// When:
runBlocking { storage.unload<I18NBundle>(path) }
// Then:
assertFalse(storage.isLoaded<I18NBundle>(path))
assertEquals(0, storage.getReferenceCount<I18NBundle>(path))
}
@Test
fun `should load ParticleEffect assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/particle.p2d"
// When:
val asset = storage.testLoad<ParticleEffect>(path)
// Then:
assertTrue(storage.isLoaded<ParticleEffect>(path))
assertSame(asset, storage.get<ParticleEffect>(path))
assertEquals(1, storage.getReferenceCount<ParticleEffect>(path))
assertEquals(emptyList<String>(), storage.getDependencies<ParticleEffect>(path))
storage.dispose()
}
@Test
fun `should unload ParticleEffect assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/particle.p2d"
storage.testLoad<ParticleEffect>(path)
// When:
runBlocking { storage.unload<ParticleEffect>(path) }
// Then:
assertFalse(storage.isLoaded<ParticleEffect>(path))
assertEquals(0, storage.getReferenceCount<ParticleEffect>(path))
}
@Test
fun `should load ParticleEffect3D assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/particle.p3d"
val dependency = "ktx/assets/async/texture.png"
// When:
val asset = storage.testLoad<ParticleEffect3D>(path)
// Then:
assertTrue(storage.isLoaded<ParticleEffect3D>(path))
assertSame(asset, storage.get<ParticleEffect3D>(path))
assertEquals(1, storage.getReferenceCount<ParticleEffect3D>(path))
assertEquals(listOf(storage.getIdentifier<Texture>(dependency)), storage.getDependencies<ParticleEffect3D>(path))
// Particle dependencies:
assertTrue(storage.isLoaded<Texture>(dependency))
assertNotNull(storage.get<Texture>(dependency))
assertEquals(1, storage.getReferenceCount<Texture>(dependency))
storage.dispose()
}
@Test
fun `should unload ParticleEffect3D assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/particle.p3d"
val dependency = "ktx/assets/async/texture.png"
storage.testLoad<ParticleEffect3D>(path)
// When:
runBlocking { storage.unload<ParticleEffect3D>(path) }
// Then:
assertFalse(storage.isLoaded<ParticleEffect3D>(path))
assertEquals(0, storage.getReferenceCount<ParticleEffect3D>(path))
assertFalse(storage.isLoaded<Texture>(dependency))
assertEquals(0, storage.getReferenceCount<Texture>(dependency))
}
@Test
fun `should load PolygonRegion assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/polygon.psh"
val dependency = "ktx/assets/async/polygon.png"
// When:
val asset = storage.testLoad<PolygonRegion>(path)
// Then:
assertTrue(storage.isLoaded<PolygonRegion>(path))
assertSame(asset, storage.get<PolygonRegion>(path))
assertEquals(1, storage.getReferenceCount<PolygonRegion>(path))
assertEquals(listOf(storage.getIdentifier<Texture>(dependency)), storage.getDependencies<PolygonRegion>(path))
// Polygon region dependencies:
assertTrue(storage.isLoaded<Texture>(dependency))
assertSame(asset.region.texture, storage.get<Texture>(dependency))
assertEquals(1, storage.getReferenceCount<Texture>(dependency))
storage.dispose()
}
@Test
fun `should unload PolygonRegion assets with dependencies`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/polygon.psh"
val dependency = "ktx/assets/async/polygon.png"
storage.testLoad<PolygonRegion>(path)
// When:
runBlocking { storage.unload<PolygonRegion>(path) }
// Then:
assertFalse(storage.isLoaded<PolygonRegion>(path))
assertEquals(0, storage.getReferenceCount<PolygonRegion>(path))
assertFalse(storage.isLoaded<Texture>(dependency))
assertEquals(0, storage.getReferenceCount<Texture>(dependency))
}
@Test
fun `should load OBJ Model assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/model.obj"
// When:
val asset = storage.testLoad<Model>(path)
// Then:
assertTrue(storage.isLoaded<Model>(path))
assertSame(asset, storage.get<Model>(path))
assertEquals(1, storage.getReferenceCount<Model>(path))
assertEquals(emptyList<String>(), storage.getDependencies<Model>(path))
storage.dispose()
}
@Test
fun `should unload OBJ Model assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/model.obj"
storage.testLoad<Model>(path)
// When:
runBlocking { storage.unload<Model>(path) }
// Then:
assertFalse(storage.isLoaded<Model>(path))
assertEquals(0, storage.getReferenceCount<Model>(path))
}
@Test
fun `should load G3DJ Model assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/model.g3dj"
// When:
val asset = storage.testLoad<Model>(path)
// Then:
assertTrue(storage.isLoaded<Model>(path))
assertSame(asset, storage.get<Model>(path))
assertEquals(1, storage.getReferenceCount<Model>(path))
assertEquals(emptyList<String>(), storage.getDependencies<Model>(path))
storage.dispose()
}
@Test
fun `should unload G3DJ Model assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/model.g3dj"
storage.testLoad<Model>(path)
// When:
runBlocking { storage.unload<Model>(path) }
// Then:
assertFalse(storage.isLoaded<Model>(path))
assertEquals(0, storage.getReferenceCount<Model>(path))
}
@Test
fun `should load G3DB Model assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/model.g3db"
// When:
val asset = storage.testLoad<Model>(path)
// Then:
assertTrue(storage.isLoaded<Model>(path))
assertSame(asset, storage.get<Model>(path))
assertEquals(1, storage.getReferenceCount<Model>(path))
assertEquals(emptyList<String>(), storage.getDependencies<Model>(path))
storage.dispose()
}
@Test
fun `should unload G3DB Model assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/model.g3db"
storage.testLoad<Model>(path)
// When:
runBlocking { storage.unload<Model>(path) }
// Then:
assertFalse(storage.isLoaded<Model>(path))
assertEquals(0, storage.getReferenceCount<Model>(path))
}
@Test
fun `should load ShaderProgram assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/shader.frag"
// Silencing logs - shader will fail to compile, as GL is mocked:
storage.logger.level = Logger.NONE
// When:
val asset = storage.testLoad<ShaderProgram>(path)
// Then:
assertTrue(storage.isLoaded<ShaderProgram>(path))
assertSame(asset, storage.get<ShaderProgram>(path))
assertEquals(1, storage.getReferenceCount<ShaderProgram>(path))
assertEquals(emptyList<String>(), storage.getDependencies<ShaderProgram>(path))
storage.dispose()
}
@Test
fun `should unload ShaderProgram assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/shader.frag"
// Silencing logs - shader will fail to compile, as GL is mocked:
storage.logger.level = Logger.NONE
storage.testLoad<ShaderProgram>(path)
// When:
runBlocking { storage.unload<ShaderProgram>(path) }
// Then:
assertFalse(storage.isLoaded<ShaderProgram>(path))
assertEquals(0, storage.getReferenceCount<ShaderProgram>(path))
}
@Test
fun `should load Cubemap assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/cubemap.zktx"
// When:
val asset = storage.testLoad<Cubemap>(path)
// Then:
assertTrue(storage.isLoaded<Cubemap>(path))
assertSame(asset, storage.get<Cubemap>(path))
assertEquals(1, storage.getReferenceCount<Cubemap>(path))
assertEquals(emptyList<String>(), storage.getDependencies<Cubemap>(path))
storage.dispose()
}
@Test
fun `should unload Cubemap assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/cubemap.zktx"
storage.testLoad<Cubemap>(path)
// When:
runBlocking { storage.unload<Cubemap>(path) }
// Then:
assertFalse(storage.isLoaded<Cubemap>(path))
assertEquals(0, storage.getReferenceCount<Cubemap>(path))
}
@Test
fun `should dispose of multiple assets of different types without errors`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
storage.logger.level = Logger.NONE
val assets = listOf(
storage.getIdentifier<String>("ktx/assets/async/string.txt"),
storage.getIdentifier<BitmapFont>("com/badlogic/gdx/utils/arial-15.fnt"),
storage.getIdentifier<Music>("ktx/assets/async/sound.ogg"),
storage.getIdentifier<TextureAtlas>("ktx/assets/async/skin.atlas"),
storage.getIdentifier<Texture>("ktx/assets/async/texture.png"),
storage.getIdentifier<Skin>("ktx/assets/async/skin.json"),
storage.getIdentifier<I18NBundle>("ktx/assets/async/i18n"),
storage.getIdentifier<ParticleEffect>("ktx/assets/async/particle.p2d"),
storage.getIdentifier<ParticleEffect3D>("ktx/assets/async/particle.p3d"),
storage.getIdentifier<PolygonRegion>("ktx/assets/async/polygon.psh"),
storage.getIdentifier<Model>("ktx/assets/async/model.obj"),
storage.getIdentifier<Model>("ktx/assets/async/model.g3dj"),
storage.getIdentifier<Model>("ktx/assets/async/model.g3db"),
storage.getIdentifier<ShaderProgram>("ktx/assets/async/shader.frag"),
storage.getIdentifier<Cubemap>("ktx/assets/async/cubemap.zktx")
)
assets.forEach {
storage.testLoad(it.path, it.type, parameters = null)
assertTrue(storage.isLoaded(it))
}
// When:
storage.dispose()
// Then:
assets.forEach {
assertFalse(it in storage)
assertFalse(storage.isLoaded(it))
assertEquals(0, storage.getReferenceCount(it))
assertEquals(emptyList<String>(), storage.getDependencies(it))
shouldThrow<MissingAssetException> {
storage[it]
}
}
}
// --- Behavior tests:
@Test
fun `should return same asset instance with subsequent load calls on loaded asset`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/texture.png"
val loaded = storage.testLoad<Texture>(path)
// When:
val assets = (1..10).map { storage.testLoad<Texture>(path) }
// Then:
assertEquals(11, storage.getReferenceCount<Texture>(path))
assets.forEach { asset ->
assertSame(loaded, asset)
}
checkProgress(storage, loaded = 1, warn = true)
storage.dispose()
}
@Test
fun `should obtain loaded asset with path`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
// When:
storage.testLoad<String>(path)
// Then:
assertTrue(storage.contains<String>(path))
assertTrue(storage.isLoaded<String>(path))
assertEquals("Content.", storage.get<String>(path))
assertEquals("Content.", storage.getOrNull<String>(path))
assertEquals("Content.", runBlocking { storage.getAsync<String>(path).await() })
assertEquals(emptyList<String>(), storage.getDependencies<String>(path))
checkProgress(storage, loaded = 1, warn = true)
}
@Test
fun `should obtain loaded asset with identifier`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val identifier = storage.getIdentifier<String>("ktx/assets/async/string.txt")
// When:
storage.testLoad<String>(identifier.path)
// Then:
assertTrue(identifier in storage)
assertTrue(storage.isLoaded(identifier))
assertEquals("Content.", storage[identifier])
assertEquals("Content.", storage.getOrNull(identifier))
assertEquals("Content.", runBlocking { storage.getAsync(identifier).await() })
assertEquals(emptyList<String>(), storage.getDependencies(identifier))
checkProgress(storage, loaded = 1, warn = true)
}
@Test
fun `should obtain loaded asset with descriptor`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val descriptor = storage.getAssetDescriptor<String>("ktx/assets/async/string.txt")
// When:
storage.testLoad<String>(descriptor.fileName)
// Then:
assertTrue(descriptor in storage)
assertTrue(storage.isLoaded(descriptor))
assertEquals("Content.", storage[descriptor])
assertEquals("Content.", storage.getOrNull(descriptor))
assertEquals("Content.", runBlocking { storage.getAsync(descriptor).await() })
assertEquals(emptyList<String>(), storage.getDependencies(descriptor))
checkProgress(storage, loaded = 1, warn = true)
}
@Test
fun `should unload assets with path`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
storage.testLoad<String>(path)
// When:
runBlocking { storage.unload<String>(path) }
// Then:
assertFalse(storage.isLoaded<String>(path))
assertEquals(0, storage.getReferenceCount<String>(path))
checkProgress(storage, total = 0, warn = true)
}
@Test
fun `should unload assets with descriptor`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
val descriptor = storage.getAssetDescriptor<String>(path)
storage.testLoad<String>(path)
// When:
runBlocking { storage.unload(descriptor) }
// Then:
assertFalse(storage.isLoaded(descriptor))
assertEquals(0, storage.getReferenceCount(descriptor))
checkProgress(storage, total = 0, warn = true)
}
@Test
fun `should unload assets with identifier`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
val identifier = storage.getIdentifier<String>(path)
storage.testLoad<String>(path)
// When:
runBlocking { storage.unload(identifier) }
// Then:
assertFalse(storage.isLoaded(identifier))
assertEquals(0, storage.getReferenceCount(identifier))
checkProgress(storage, total = 0, warn = true)
}
@Test
fun `should allow to load multiple assets with different type and same path`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/texture.png"
// When:
storage.testLoad<Texture>(path)
storage.testLoad<Pixmap>(path)
// Then:
assertTrue(storage.isLoaded<Texture>(path))
assertTrue(storage.isLoaded<Pixmap>(path))
assertEquals(1, storage.getReferenceCount<Texture>(path))
assertEquals(1, storage.getReferenceCount<Pixmap>(path))
assertNotSame(storage.get<Texture>(path), storage.get<Pixmap>(path))
checkProgress(storage, loaded = 2, warn = true)
storage.dispose()
}
@Test
fun `should increase references count and return the same asset when trying to load asset with same path`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
val elements = IdentityHashMap<String, Boolean>()
// When:
repeat(3) {
val asset = storage.testLoad<String>(path)
elements[asset] = true
}
// Then:
assertEquals(3, storage.getReferenceCount<String>(path))
assertEquals(1, elements.size)
}
@Test
fun `should fail to load asset with missing loader`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
// When:
shouldThrow<MissingLoaderException> {
storage.testLoad<Vector2>(path)
}
// Then:
assertFalse(storage.contains<Vector2>(path))
checkProgress(storage, total = 0)
}
@Test
fun `should increase references counts of dependencies when loading same asset`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/skin.json"
val dependencies = arrayOf(
storage.getIdentifier<TextureAtlas>("ktx/assets/async/skin.atlas"),
storage.getIdentifier<Texture>("ktx/assets/async/texture.png")
)
val loadedAssets = IdentityHashMap<Skin, Boolean>()
// When:
repeat(3) {
val asset = storage.testLoad<Skin>(path)
loadedAssets[asset] = true
}
// Then:
assertEquals(3, storage.getReferenceCount<Skin>(path))
dependencies.forEach {
assertEquals(3, storage.getReferenceCount(it))
}
assertEquals(1, loadedAssets.size)
checkProgress(storage, loaded = 3, warn = true)
}
@Test
fun `should handle loading exceptions`() {
// Given:
val loader = AssetStorageTest.FakeSyncLoader(
onLoad = { throw IllegalStateException("Expected.") }
)
val storage = AssetStorage(useDefaultLoaders = false)
storage.setLoader { loader }
val path = "fake path"
// When:
shouldThrow<AssetLoadingException> {
storage.testLoad<AssetStorageTest.FakeAsset>(path)
}
// Then: asset should still be in storage, but rethrowing original exception:
assertTrue(storage.contains<AssetStorageTest.FakeAsset>(path))
assertEquals(1, storage.getReferenceCount<AssetStorageTest.FakeAsset>(path))
shouldThrow<AssetLoadingException> {
storage.get<AssetStorageTest.FakeAsset>(path)
}
shouldThrow<AssetLoadingException> {
storage.getOrNull<AssetStorageTest.FakeAsset>(path)
}
val reference = storage.getAsync<AssetStorageTest.FakeAsset>(path)
shouldThrow<AssetLoadingException> {
runBlocking { reference.await() }
}
checkProgress(storage, failed = 1, warn = true)
}
@Test
fun `should handle asynchronous loading exceptions`() {
// Given:
val loader = AssetStorageTest.FakeAsyncLoader(
onAsync = { throw IllegalStateException("Expected.") },
onSync = {}
)
val storage = AssetStorage(useDefaultLoaders = false)
storage.setLoader { loader }
val path = "fake path"
// When:
shouldThrow<AssetLoadingException> {
storage.testLoad<AssetStorageTest.FakeAsset>(path)
}
// Then: asset should still be in storage, but rethrowing original exception:
assertTrue(storage.contains<AssetStorageTest.FakeAsset>(path))
assertEquals(1, storage.getReferenceCount<AssetStorageTest.FakeAsset>(path))
shouldThrow<AssetLoadingException> {
storage.get<AssetStorageTest.FakeAsset>(path)
}
shouldThrow<AssetLoadingException> {
storage.getOrNull<AssetStorageTest.FakeAsset>(path)
}
val reference = storage.getAsync<AssetStorageTest.FakeAsset>(path)
shouldThrow<AssetLoadingException> {
runBlocking { reference.await() }
}
checkProgress(storage, failed = 1, warn = true)
}
@Test
fun `should handle synchronous loading exceptions`() {
// Given:
val loader = AssetStorageTest.FakeAsyncLoader(
onAsync = { },
onSync = { throw IllegalStateException("Expected.") }
)
val storage = AssetStorage(useDefaultLoaders = false)
storage.setLoader { loader }
val path = "fake path"
// When:
shouldThrow<AssetLoadingException> {
storage.testLoad<AssetStorageTest.FakeAsset>(path)
}
// Then: asset should still be in storage, but rethrowing original exception:
assertTrue(storage.contains<AssetStorageTest.FakeAsset>(path))
assertEquals(1, storage.getReferenceCount<AssetStorageTest.FakeAsset>(path))
shouldThrow<AssetLoadingException> {
storage.get<AssetStorageTest.FakeAsset>(path)
}
shouldThrow<AssetLoadingException> {
storage.getOrNull<AssetStorageTest.FakeAsset>(path)
}
val reference = storage.getAsync<AssetStorageTest.FakeAsset>(path)
shouldThrow<AssetLoadingException> {
runBlocking { reference.await() }
}
checkProgress(storage, failed = 1, warn = true)
}
@Test
fun `should not fail to unload asset that was loaded exceptionally`() {
// Given:
val loader = AssetStorageTest.FakeSyncLoader(
onLoad = { throw IllegalStateException("Expected.") }
)
val storage = AssetStorage(useDefaultLoaders = false)
val path = "fake path"
storage.setLoader { loader }
storage.logger.level = Logger.NONE // Disposing exception will be logged.
try {
storage.testLoad<AssetStorageTest.FakeAsset>(path)
} catch (exception: AssetLoadingException) {
// Expected.
}
// When:
val unloaded = runBlocking {
storage.unload<AssetStorageTest.FakeAsset>(path)
}
// Then:
assertTrue(unloaded)
assertFalse(storage.contains<AssetStorageTest.FakeAsset>(path))
assertEquals(0, storage.getReferenceCount<AssetStorageTest.FakeAsset>(path))
}
/**
* Allows to validate state of [LoadingProgress] without failing the test case.
* Pass [warn] not to fail the test on progress mismatch.
*
* Progress is eventually consistent. It does not have to be up to date with the [AssetStorage] state.
* Usually it will be and all tests would pass just fine, but there are these rare situations where
* the asserts are evaluated before the progress is updated. That's why if such case is possible,
* only a warning will be printed instead of failing the test.
*
* If the warnings are common, it might point to a bug within the progress updating.
*/
private fun checkProgress(
storage: AssetStorage,
loaded: Int = 0,
failed: Int = 0,
total: Int = loaded + failed,
warn: Boolean = false
) {
if (warn) {
val progress = storage.progress
if (total != progress.total || loaded != progress.loaded || failed != progress.failed) {
System.err.println(
"""
Warning: mismatch in progress value in `${testName.methodName}`.
Value | Expected | Actual
total | ${"%8d".format(total)} | ${progress.total}
loaded | ${"%8d".format(loaded)} | ${progress.loaded}
failed | ${"%8d".format(failed)} | ${progress.failed}
If this warning is repeated consistently, there might be a related bug in progress reporting.
""".trimIndent()
)
}
} else {
assertEquals(total, storage.progress.total)
assertEquals(loaded, storage.progress.loaded)
assertEquals(failed, storage.progress.failed)
}
}
companion object {
@JvmStatic
@BeforeClass
fun `load libGDX statics`() {
// Necessary for libGDX asset loaders to work.
Lwjgl3NativesLoader.load()
Gdx.graphics = mock()
Gdx.gl20 = mock()
Gdx.gl = Gdx.gl20
}
@JvmStatic
@AfterClass
fun `dispose of libGDX statics`() {
Gdx.graphics = null
Gdx.audio = null
Gdx.gl20 = null
Gdx.gl = null
}
}
@Before
override fun `setup libGDX application`() {
super.`setup libGDX application`()
if (System.getenv("TEST_PROFILE") != "ci") {
Gdx.audio = OpenALLwjgl3Audio()
}
}
@After
override fun `exit libGDX application`() {
super.`exit libGDX application`()
(Gdx.audio as? OpenALLwjgl3Audio)?.dispose()
}
}
/**
* Performs asset loading tests with [AssetStorage.loadAsync] consuming [AssetDescriptor].
*/
class AssetStorageLoadingTestWithAssetDescriptorLoadAsync : AbstractAssetStorageLoadingTest() {
override fun <T> AssetStorage.testLoad(
path: String,
type: Class<T>,
parameters: AssetLoaderParameters<T>?
): T = runBlocking {
loadAsync(AssetDescriptor(path, type, parameters)).await()
}
}
/**
* Performs asset loading tests with [AssetStorage.loadAsync] consuming [Identifier].
*/
class AssetStorageLoadingTestWithIdentifierLoadAsync : AbstractAssetStorageLoadingTest() {
override fun <T> AssetStorage.testLoad(
path: String,
type: Class<T>,
parameters: AssetLoaderParameters<T>?
): T = runBlocking {
loadAsync(Identifier(path, type), parameters).await()
}
}
/**
* Performs asset loading tests with [AssetStorage.load] consuming [AssetDescriptor].
*/
class AssetStorageLoadingTestWithAssetDescriptorLoad : AbstractAssetStorageLoadingTest() {
override fun <T> AssetStorage.testLoad(
path: String,
type: Class<T>,
parameters: AssetLoaderParameters<T>?
): T = runBlocking {
load(AssetDescriptor(path, type, parameters))
}
}
/**
* Performs asset loading tests with [AssetStorage.load] consuming [Identifier].
*/
class AssetStorageLoadingTestWithIdentifierLoad : AbstractAssetStorageLoadingTest() {
override fun <T> AssetStorage.testLoad(
path: String,
type: Class<T>,
parameters: AssetLoaderParameters<T>?
): T = runBlocking {
load(Identifier(path, type), parameters)
}
}
/**
* Performs asset loading tests with [AssetStorage.loadSync] consuming [AssetDescriptor].
*/
class AssetStorageLoadingTestWithAssetDescriptorLoadSync : AbstractAssetStorageLoadingTest() {
override fun <T> AssetStorage.testLoad(
path: String,
type: Class<T>,
parameters: AssetLoaderParameters<T>?
): T = loadSync(AssetDescriptor(path, type, parameters))
}
/**
* Performs asset loading tests with [AssetStorage.loadSync] consuming [Identifier].
*/
class AssetStorageLoadingTestWithIdentifierLoadSync : AbstractAssetStorageLoadingTest() {
override fun <T> AssetStorage.testLoad(
path: String,
type: Class<T>,
parameters: AssetLoaderParameters<T>?
): T = loadSync(Identifier(path, type), parameters)
}
| assets-async/src/test/kotlin/ktx/assets/async/assetStorageLoadingTest.kt | 10881882 |
package com.eden.orchid.strikt
import strikt.api.Assertion
import strikt.api.DescribeableBuilder
import strikt.api.expectThat
fun <T> Assertion.Builder<T>.assertBlock(
description: String,
block: Assertion.Builder<T>.(T) -> Any?
): Assertion.Builder<T> {
var message: Any? = null
return compose(description) {
message = block(it)
}.then {
when {
anyFailed -> fail()
message is AssertBlockFailure -> fail((message as AssertBlockFailure).errorMessage)
else -> pass()
}
}
}
fun <T> Assertion.Builder<T>.assertBlock(
description: String,
expected: Any?,
block: Assertion.Builder<T>.(T) -> Any?
): Assertion.Builder<T> {
var message: Any? = null
return compose(description, expected) {
message = block(it)
}.then {
when {
anyFailed -> fail()
message is AssertBlockFailure -> fail((message as AssertBlockFailure).errorMessage)
else -> pass()
}
}
}
data class AssertBlockFailure(val errorMessage: String)
fun <T> T.asExpected() : DescribeableBuilder<T> {
return expectThat(this)
}
fun <T> Assertion.Builder<T>.assertWhen(condition: Boolean, block: Assertion.Builder<T>.()-> Assertion.Builder<T>) : Assertion.Builder<T> {
if(condition) {
return block()
}
else {
return this
}
}
| OrchidTest/src/main/kotlin/com/eden/orchid/strikt/helpers.kt | 2088993950 |
/*
* Copyright (C) 2016, 2020 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.xpath.ast.xpath
import com.intellij.psi.PsiElement
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmSequenceType
/**
* An XPath 2.0 and XQuery 1.0 `SequenceType` node in the XQuery AST.
*/
interface XPathSequenceType : PsiElement, XdmSequenceType
| src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/ast/xpath/XPathSequenceType.kt | 2172126073 |
package assimp
import assimp.format.ProgressHandler
import glm_.plus
import glm_.shl
/**
* Created by elect on 13/11/2016.
*/
/** utility to do char4 to uint32 in a portable manner */
fun AI_MAKE_MAGIC(string: String) = (string[0] shl 24) + (string[1] shl 16) + (string[2] shl 8) + string[3]
abstract class BaseImporter {
/** The error description of the last error that occurred. An empty string if there was no error. */
var errorText = ""
private set
/** Currently set progress handler. */
var progress: ProgressHandler? = null
/** Returns whether the class can handle the format of the given file.
*.
* The implementation should be as quick as possible. A check for the file extension is enough. If no suitable
* loader is found with this strategy, canRead() is called again, the 'checkSig' parameter set to true this time.
* Now the implementation is expected to perform a full check of the file structure, possibly searching the first
* bytes of the file for magic identifiers or keywords.
*
* @param file Path and file name of the file to be examined.
* @param checkSig Set to true if this method is called a second time. This time, the implementation may take more
* time to examine the contents of the file to be loaded for magic bytes, keywords, etc to be able to load files
* with unknown/not existent file extensions.
* @return true if the class can read this file, false if not. */
abstract fun canRead(file: String, ioSystem: IOSystem, checkSig: Boolean): Boolean
/** Imports the given file and returns the imported data.
* If the import succeeds, ownership of the data is transferred to the caller. If the import fails, null is
* returned. The function takes care that any partially constructed data is destroyed beforehand.
*
* @param imp Importer object hosting this loader.
* @param file Path of the file to be imported.
* @return The imported data or null if failed. If it failed a human-readable error description can be retrieved
* by accessing errorText
*
* @note This function is not intended to be overridden. Implement internReadFile() to do the import. If an
* exception is thrown somewhere in internReadFile(), this function will catch it and transform it into a suitable
* response to the caller.
*/
fun readFile(imp: Importer, ioHandler: IOSystem = ASSIMP.defaultIOSystem, filePath: String): AiScene? {
progress = imp.progressHandler
assert(progress != null)
// Gather configuration properties for this run
setupProperties(imp)
// create a scene object to hold the data
val sc = AiScene()
// dispatch importing
try {
internReadFile(filePath, ioHandler, sc)
} catch (err: Exception) {
// extract error description
logger.error(err) {}
errorText = err.localizedMessage
return null
}
// return what we gathered from the import.
return sc
}
/** Called prior to ReadFile().
* The function is a request to the importer to update its configuration basing on the Importer's configuration
* property list.
* @param imp Importer instance
*/
open fun setupProperties(imp: Importer) = Unit
/** Called by Importer::GetImporterInfo to get a description of some loader features. Importers must provide this
* information. */
abstract val info: AiImporterDesc
/** Called by Importer::GetExtensionList for each loaded importer.
* Take the extension list contained in the structure returned by info and insert all file extensions into the
* given set.
* @param extension set to collect file extensions in*/
val extensionList get() = info.fileExtensions
/** Imports the given file into the given scene structure. The function is expected to throw an ImportErrorException
* if there is an error. If it terminates normally, the data in AiScene is expected to be correct. Override this
* function to implement the actual importing.
* <br>
* The output scene must meet the following requirements:<br>
* <ul>
* <li>At least a root node must be there, even if its only purpose is to reference one mesh.</li>
* <li>AiMesh.primitiveTypes may be 0. The types of primitives in the mesh are determined automatically in this
* case.</li>
* <li>the vertex data is stored in a pseudo-indexed "verbose" format.
* In fact this means that every vertex that is referenced by a face is unique. Or the other way round: a vertex
* index may not occur twice in a single AiMesh.</li>
* <li>AiAnimation.duration may be -1. Assimp determines the length of the animation automatically in this case as
* the length of the longest animation channel.</li>
* <li>AiMesh.bitangents may be null if tangents and normals are given. In this case bitangents are computed as the
* cross product between normal and tangent.</li>
* <li>There needn't be a material. If none is there a default material is generated. However, it is recommended
* practice for loaders to generate a default material for yourself that matches the default material setting for
* the file format better than Assimp's generic default material. Note that default materials *should* be named
* AI_DEFAULT_MATERIAL_NAME if they're just color-shaded or AI_DEFAULT_TEXTURED_MATERIAL_NAME if they define a
* (dummy) texture. </li>
* </ul>
* If the AI_SCENE_FLAGS_INCOMPLETE-Flag is <b>not</b> set:<ul>
* <li> at least one mesh must be there</li>
* <li> there may be no meshes with 0 vertices or faces</li>
* </ul>
* This won't be checked (except by the validation step): Assimp will crash if one of the conditions is not met!
*
* @param file Path of the file to be imported.
* @param scene The scene object to hold the imported data. Null is not a valid parameter.
* */
open fun internReadFile(file: String, ioSystem: IOSystem, scene: AiScene) = Unit
companion object {
/** Extract file extension from a string
* @param file Input file
* @return extension without trailing dot, all lowercase
*/
fun getExtension (file: String): String {
val pos = file.indexOfLast { it == '.' }
// no file extension at all
if( pos == -1) return ""
return file.substring(pos+1).toLowerCase() // thanks to Andy Maloney for the hint
}
}
} | src/main/kotlin/assimp/BaseImporter.kt | 1674490888 |
package org.livingdoc.engine.execution.examples.scenarios
import org.livingdoc.engine.execution.examples.scenarios.model.ScenarioResult
import org.livingdoc.repositories.model.scenario.Scenario
/**
* This class handles the execution of [Scenario] examples.
*/
class ScenarioExecutor {
fun execute(scenario: Scenario, fixtureClass: Class<*>, document: Any? = null): ScenarioResult {
return ScenarioExecution(fixtureClass, scenario, document).execute()
}
}
| livingdoc-engine/src/main/kotlin/org/livingdoc/engine/execution/examples/scenarios/ScenarioExecutor.kt | 126104457 |
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
interface Z{
private fun extension(): String {
return "OK"
}
}
object Z2 : Z {
}
fun box() : String {
val size = Class.forName("Z2").declaredMethods.size
if (size != 0) return "fail: $size"
return "OK"
} | backend.native/tests/external/codegen/box/traits/noPrivateDelegation.kt | 2546265275 |
package com.commit451.gitlab.api
/**
* Represents there was a null body from Retrofit
*/
class NullBodyException : Exception()
| app/src/main/java/com/commit451/gitlab/api/NullBodyException.kt | 2600112769 |
/*
* Copyright (c) 2015 Andrew O'Malley
*
* 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.github.andrewoma.kwery.core.dialect
import java.sql.*
open class HsqlDialect : Dialect {
override fun bind(value: Any, limit: Int): String = when (value) {
is String -> escapeSingleQuotedString(value.truncate(limit))
is Timestamp -> timestampFormat.get().format(value)
is Date -> "'$value'"
is Time -> "'$value'"
is java.sql.Array -> bindArray(value, limit, "array[", "]")
is Blob -> standardBlob(value, limit)
is ByteArray -> standardByteArray(value, limit)
is Clob -> escapeSingleQuotedString(standardClob(value, limit))
else -> value.toString()
}
override val supportsArrayBasedIn = true
override fun arrayBasedIn(name: String) = "in(unnest(:$name))"
override val supportsAllocateIds = true
override fun allocateIds(count: Int, sequence: String, columnName: String) =
"select next value for $sequence as $columnName from unnest(sequence_array(1, $count, 1))"
override val supportsFetchingGeneratedKeysByName = true
} | core/src/main/kotlin/com/github/andrewoma/kwery/core/dialect/HsqlDialect.kt | 2539514159 |
package com.ucsoftworks.leafdb
import com.ucsoftworks.leafdb.wrapper.ILeafDbCursor
import java.util.*
/**
* Created by Pasenchuk Victor on 19/08/2017
*/
internal fun appendEscapedSQLString(sb: StringBuilder, sqlString: String) {
sb.append('\'')
if (sqlString.indexOf('\'') != -1) {
val length = sqlString.length
for (i in 0..length - 1) {
val c = sqlString[i]
if (c == '\'') {
sb.append('\'')
}
sb.append(c)
}
} else
sb.append(sqlString)
sb.append('\'')
}
/**
* SQL-escape a string.
*/
internal fun sqlEscapeString(value: String): String {
val escaper = StringBuilder()
appendEscapedSQLString(escaper, value)
return escaper.toString()
}
internal val Any?.sqlValue: String
get() = when (this) {
null -> "NULL"
is Number -> this.toString()
is Date -> this.time.toString()
else -> sqlEscapeString(this.toString())
}
internal fun ILeafDbCursor?.collectIndexedStrings(position: Int = 1): List<Pair<Long, String>> {
val strings = mutableListOf<Pair<Long, String>>()
try {
if (this != null && !this.isClosed && !this.empty)
do {
strings.add(Pair(this.getLong(1), this.getString(position)))
} while (this.moveToNext())
} finally {
if (this != null && !this.isClosed) {
this.close()
}
}
return strings
} | leafdb-core/src/main/java/com/ucsoftworks/leafdb/DbUtils.kt | 1274418115 |
package com.czbix.klog.handler
import com.czbix.klog.database.dao.PostDao
import com.czbix.klog.http.core.DefaultHttpResponse
import com.czbix.klog.http.HttpContext
import com.czbix.klog.soy.Index2SoyInfo.IndexSoyTemplateInfo
import com.czbix.klog.template.SoyHelper
import com.czbix.klog.template.SoyHelper.setData
import io.netty.handler.codec.http.HttpRequest
import io.netty.handler.codec.http.HttpResponseStatus
import com.czbix.klog.soy.Index2SoyInfo as IndexSoyInfo
class IndexHandler : BaseHttpHandler() {
override fun getPattern() = "/"
override fun get(request: HttpRequest, context: HttpContext): DefaultHttpResponse {
val posts = PostDao.getAll().map {
mapOf(
"id" to it.id,
"title" to it.title,
"text" to it.text
)
}
val render = SoyHelper.newRenderer(IndexSoyInfo.INDEX, context).setData(IndexSoyTemplateInfo.POSTS, posts)
return newHtmlResponse(render.render())
}
}
| src/main/kotlin/com/czbix/klog/handler/IndexHandler.kt | 1264562737 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.typing
import com.intellij.pom.java.LanguageLevel
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiType
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrBuiltInTypeElement
import org.jetbrains.plugins.groovy.lang.psi.impl.GrAnonymousClassType
import org.jetbrains.plugins.groovy.lang.psi.impl.GrClassReferenceType
class DefaultNewExpressionTypeCalculator : GrTypeCalculator<GrNewExpression> {
override fun getType(expression: GrNewExpression): PsiType? {
return getAnonymousType(expression) ?:
getRegularType(expression)
}
private fun getAnonymousType(expression: GrNewExpression): PsiType? {
val anonymous = expression.anonymousClassDefinition ?: return null
return GrAnonymousClassType(
LanguageLevel.JDK_1_5,
anonymous.resolveScope,
JavaPsiFacade.getInstance(expression.project),
anonymous
)
}
private fun getRegularType(expression: GrNewExpression): PsiType? {
var type: PsiType = expression.referenceElement?.let { GrClassReferenceType(it) } ?:
(expression.typeElement as? GrBuiltInTypeElement)?.type ?:
return null
repeat(expression.arrayCount) {
type = type.createArrayType()
}
return type
}
} | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/DefaultNewExpressionTypeCalculator.kt | 3448442248 |
package info.nightscout.androidaps.utils.wizard
import android.content.Context
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.data.IobTotal
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensDataStore
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.interfaces.ResourceHelper
import org.junit.Assert
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.`when`
import org.mockito.invocation.InvocationOnMock
class BolusWizardTest : TestBase() {
private val pumpBolusStep = 0.1
@Mock lateinit var rh: ResourceHelper
@Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var constraintChecker: ConstraintChecker
@Mock lateinit var context: Context
@Mock lateinit var activePlugin: ActivePlugin
@Mock lateinit var commandQueue: CommandQueue
@Mock lateinit var loop: Loop
@Mock lateinit var iobCobCalculator: IobCobCalculator
@Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin
@Mock lateinit var dateUtil: DateUtil
@Mock lateinit var autosensDataStore: AutosensDataStore
val injector = HasAndroidInjector {
AndroidInjector {
if (it is BolusWizard) {
it.aapsLogger = aapsLogger
it.rh = rh
it.rxBus = RxBus(aapsSchedulers, aapsLogger)
it.profileFunction = profileFunction
it.constraintChecker = constraintChecker
it.activePlugin = activePlugin
it.commandQueue = commandQueue
it.loop = loop
it.dateUtil = dateUtil
it.iobCobCalculator = iobCobCalculator
it.glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator, dateUtil = dateUtil)
}
}
}
@Suppress("SameParameterValue")
private fun setupProfile(targetLow: Double, targetHigh: Double, insulinSensitivityFactor: Double, insulinToCarbRatio: Double): Profile {
val profile = Mockito.mock(Profile::class.java)
`when`(profile.getTargetLowMgdl()).thenReturn(targetLow)
`when`(profile.getTargetLowMgdl()).thenReturn(targetHigh)
`when`(profile.getIsfMgdl()).thenReturn(insulinSensitivityFactor)
`when`(profile.getIc()).thenReturn(insulinToCarbRatio)
`when`(profileFunction.getUnits()).thenReturn(GlucoseUnit.MGDL)
`when`(iobCobCalculator.calculateIobFromBolus()).thenReturn(IobTotal(System.currentTimeMillis()))
`when`(iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended()).thenReturn(IobTotal(System.currentTimeMillis()))
`when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
val pumpDescription = PumpDescription()
pumpDescription.bolusStep = pumpBolusStep
`when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription)
`when`(iobCobCalculator.ads).thenReturn(autosensDataStore)
Mockito.doAnswer { invocation: InvocationOnMock ->
invocation.getArgument<Constraint<Double>>(0)
}.`when`(constraintChecker).applyBolusConstraints(anyObject())
return profile
}
@Test
/** Should calculate the same bolus when different blood glucose but both in target range */
fun shouldCalculateTheSameBolusWhenBGsInRange() {
val profile = setupProfile(4.0, 8.0, 20.0, 12.0)
var bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 4.2, 0.0, 100, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false)
val bolusForBg42 = bw.calculatedTotalInsulin
bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 5.4, 0.0, 100, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false)
val bolusForBg54 = bw.calculatedTotalInsulin
Assert.assertEquals(bolusForBg42, bolusForBg54, 0.01)
}
@Test
fun shouldCalculateHigherBolusWhenHighBG() {
val profile = setupProfile(4.0, 8.0, 20.0, 12.0)
var bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 9.8, 0.0, 100, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false)
val bolusForHighBg = bw.calculatedTotalInsulin
bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 5.4, 0.0, 100, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false)
val bolusForBgInRange = bw.calculatedTotalInsulin
Assert.assertTrue(bolusForHighBg > bolusForBgInRange)
}
@Test
fun shouldCalculateLowerBolusWhenLowBG() {
val profile = setupProfile(4.0, 8.0, 20.0, 12.0)
var bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 3.6, 0.0, 100, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false)
val bolusForLowBg = bw.calculatedTotalInsulin
bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 5.4, 0.0, 100, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false)
val bolusForBgInRange = bw.calculatedTotalInsulin
Assert.assertTrue(bolusForLowBg < bolusForBgInRange)
}
} | app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt | 3571795753 |
package info.nightscout.androidaps.plugins.general.overview.notifications
class NotificationUserMessage (text :String): Notification() {
init {
var hash = text.hashCode()
if (hash < USER_MESSAGE) hash += USER_MESSAGE
id = hash
date = System.currentTimeMillis()
this.text = text
level = URGENT
}
} | core/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationUserMessage.kt | 1737157897 |
/*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.filesystem.compressed.extractcontents.helpers
import android.content.Context
import com.amaze.filemanager.asynchronous.management.ServiceWatcherUtil
import com.amaze.filemanager.file_operations.filesystem.compressed.ArchivePasswordCache
import com.amaze.filemanager.file_operations.utils.UpdatePosition
import com.amaze.filemanager.filesystem.FileUtil
import com.amaze.filemanager.filesystem.MakeDirectoryOperation
import com.amaze.filemanager.filesystem.compressed.CompressedHelper
import com.amaze.filemanager.filesystem.compressed.extractcontents.Extractor
import com.amaze.filemanager.filesystem.compressed.isPasswordProtectedCompat
import com.amaze.filemanager.filesystem.files.GenericCopyUtil
import com.github.junrar.Archive
import com.github.junrar.exception.CorruptHeaderException
import com.github.junrar.exception.RarException
import com.github.junrar.exception.UnsupportedRarV5Exception
import com.github.junrar.rarfile.FileHeader
import org.apache.commons.compress.PasswordRequiredException
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.IOException
import java.util.zip.CRC32
import java.util.zip.CheckedOutputStream
class RarExtractor(
context: Context,
filePath: String,
outputPath: String,
listener: OnUpdate,
updatePosition: UpdatePosition
) : Extractor(context, filePath, outputPath, listener, updatePosition) {
@Throws(IOException::class)
override fun extractWithFilter(filter: Filter) {
try {
var totalBytes: Long = 0
val rarFile: Archive = runCatching {
ArchivePasswordCache.getInstance()[filePath]?.let {
Archive(File(filePath), it).also { archive ->
archive.password = it
}
} ?: Archive(File(filePath))
}.onFailure {
if (UnsupportedRarV5Exception::class.java.isAssignableFrom(it::class.java)) {
throw it
} else {
throw PasswordRequiredException(filePath)
}
}.getOrNull()!!
if (rarFile.isPasswordProtectedCompat() || rarFile.isEncrypted) {
if (ArchivePasswordCache.getInstance().containsKey(filePath)) {
runCatching {
tryExtractSmallestFileInArchive(context, rarFile)
}.onFailure {
throw PasswordRequiredException(filePath)
}.onSuccess {
File(it).delete()
}
} else {
throw PasswordRequiredException(filePath)
}
}
val fileHeaders: List<FileHeader>
// iterating archive elements to find file names that are to be extracted
rarFile.fileHeaders.partition { header ->
CompressedHelper.isEntryPathValid(header.fileName)
}.apply {
fileHeaders = first
totalBytes = first.sumOf { it.fullUnpackSize }
invalidArchiveEntries = second.map { it.fileName }
}
if (fileHeaders.isNotEmpty()) {
listener.onStart(totalBytes, fileHeaders[0].fileName)
fileHeaders.forEach { entry ->
if (!listener.isCancelled) {
listener.onUpdate(entry.fileName)
extractEntry(context, rarFile, entry, outputPath)
}
}
listener.onFinish()
} else {
throw EmptyArchiveNotice()
}
} catch (e: RarException) {
throw IOException(e)
}
}
@Throws(IOException::class)
private fun extractEntry(
context: Context,
rarFile: Archive,
entry: FileHeader,
outputDir: String
) {
var _entry = entry
val entrySpawnsVolumes = entry.isSplitAfter
val name = fixEntryName(entry.fileName).replace(
"\\\\".toRegex(),
CompressedHelper.SEPARATOR
)
val outputFile = File(outputDir, name)
if (!outputFile.canonicalPath.startsWith(outputDir)) {
throw IOException("Incorrect RAR FileHeader path!")
}
if (entry.isDirectory) {
MakeDirectoryOperation.mkdir(outputFile, context)
outputFile.setLastModified(entry.mTime.time)
return
}
if (!outputFile.parentFile.exists()) {
MakeDirectoryOperation.mkdir(outputFile.parentFile, context)
outputFile.parentFile.setLastModified(entry.mTime.time)
}
/* junrar doesn't throw exceptions if wrong archive password is supplied, until extracted file
CRC is compared against the one stored in archive. So we can only rely on verifying CRC
during extracting
*/
val inputStream = BufferedInputStream(rarFile.getInputStream(entry))
val outputStream = CheckedOutputStream(
BufferedOutputStream(FileUtil.getOutputStream(outputFile, context)), CRC32()
)
try {
var len: Int
val buf = ByteArray(GenericCopyUtil.DEFAULT_BUFFER_SIZE)
while (inputStream.read(buf).also { len = it } != -1) {
if (!listener.isCancelled) {
outputStream.write(buf, 0, len)
ServiceWatcherUtil.position += len.toLong()
} else break
}
/* In multi-volume archives, FileHeader may have changed as the other parts of the
archive is processed. Need to lookup the FileHeader in the volume the archive
currently resides on again, as the correct CRC of the extract file will be there
instead.
*/
if (entrySpawnsVolumes) {
_entry = rarFile.fileHeaders.find { it.fileName.equals(entry.fileName) }!!
}
/* junrar does not provide convenient way to verify archive password is correct, we
can only rely on post-extract file checksum matching to see if the file is
extracted correctly = correct password.
RAR header stores checksum in signed 2's complement (as hex though). Some bitwise
ops needed to compare with CheckOutputStream used above, which always produces
checksum in unsigned long
*/
if (_entry.fileCRC.toLong() and 0xffffffffL != outputStream.checksum.value) {
throw IOException("Checksum verification failed for entry $name")
}
} finally {
outputStream.close()
inputStream.close()
outputFile.setLastModified(entry.mTime.time)
}
}
private fun tryExtractSmallestFileInArchive(context: Context, archive: Archive): String {
archive.fileHeaders ?: throw IOException(CorruptHeaderException())
with(
archive.fileHeaders.filter {
!it.isDirectory
}
) {
if (isEmpty()) {
throw IOException(CorruptHeaderException())
} else {
associateBy({ it.fileName }, { it.fullUnpackSize })
.minByOrNull {
it.value
}!!.run {
val header = archive.fileHeaders.find {
it.fileName.equals(this.key)
}!!
val filename = fixEntryName(header.fileName).replace(
"\\\\".toRegex(),
CompressedHelper.SEPARATOR
)
extractEntry(context, archive, header, context.externalCacheDir!!.absolutePath)
return "${context.externalCacheDir!!.absolutePath}/$filename"
}
}
}
}
}
| app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/RarExtractor.kt | 3472857889 |
package com.fsck.k9.ui.settings.account
import androidx.preference.PreferenceDataStore
import com.fsck.k9.Account
import com.fsck.k9.Account.SpecialFolderSelection
import com.fsck.k9.NotificationLight
import com.fsck.k9.NotificationVibration
import com.fsck.k9.Preferences
import com.fsck.k9.job.K9JobManager
import com.fsck.k9.notification.NotificationChannelManager
import com.fsck.k9.notification.NotificationController
import java.util.concurrent.ExecutorService
class AccountSettingsDataStore(
private val preferences: Preferences,
private val executorService: ExecutorService,
private val account: Account,
private val jobManager: K9JobManager,
private val notificationChannelManager: NotificationChannelManager,
private val notificationController: NotificationController
) : PreferenceDataStore() {
private var notificationSettingsChanged = false
override fun getBoolean(key: String, defValue: Boolean): Boolean {
return when (key) {
"mark_message_as_read_on_view" -> account.isMarkMessageAsReadOnView
"mark_message_as_read_on_delete" -> account.isMarkMessageAsReadOnDelete
"account_sync_remote_deletetions" -> account.isSyncRemoteDeletions
"always_show_cc_bcc" -> account.isAlwaysShowCcBcc
"message_read_receipt" -> account.isMessageReadReceipt
"default_quoted_text_shown" -> account.isDefaultQuotedTextShown
"reply_after_quote" -> account.isReplyAfterQuote
"strip_signature" -> account.isStripSignature
"account_notify" -> account.isNotifyNewMail
"account_notify_self" -> account.isNotifySelfNewMail
"account_notify_contacts_mail_only" -> account.isNotifyContactsMailOnly
"account_notify_sync" -> account.isNotifySync
"openpgp_hide_sign_only" -> account.isOpenPgpHideSignOnly
"openpgp_encrypt_subject" -> account.isOpenPgpEncryptSubject
"openpgp_encrypt_all_drafts" -> account.isOpenPgpEncryptAllDrafts
"autocrypt_prefer_encrypt" -> account.autocryptPreferEncryptMutual
"upload_sent_messages" -> account.isUploadSentMessages
"ignore_chat_messages" -> account.isIgnoreChatMessages
else -> defValue
}
}
override fun putBoolean(key: String, value: Boolean) {
when (key) {
"mark_message_as_read_on_view" -> account.isMarkMessageAsReadOnView = value
"mark_message_as_read_on_delete" -> account.isMarkMessageAsReadOnDelete = value
"account_sync_remote_deletetions" -> account.isSyncRemoteDeletions = value
"always_show_cc_bcc" -> account.isAlwaysShowCcBcc = value
"message_read_receipt" -> account.isMessageReadReceipt = value
"default_quoted_text_shown" -> account.isDefaultQuotedTextShown = value
"reply_after_quote" -> account.isReplyAfterQuote = value
"strip_signature" -> account.isStripSignature = value
"account_notify" -> account.isNotifyNewMail = value
"account_notify_self" -> account.isNotifySelfNewMail = value
"account_notify_contacts_mail_only" -> account.isNotifyContactsMailOnly = value
"account_notify_sync" -> account.isNotifySync = value
"openpgp_hide_sign_only" -> account.isOpenPgpHideSignOnly = value
"openpgp_encrypt_subject" -> account.isOpenPgpEncryptSubject = value
"openpgp_encrypt_all_drafts" -> account.isOpenPgpEncryptAllDrafts = value
"autocrypt_prefer_encrypt" -> account.autocryptPreferEncryptMutual = value
"upload_sent_messages" -> account.isUploadSentMessages = value
"ignore_chat_messages" -> account.isIgnoreChatMessages = value
else -> return
}
saveSettingsInBackground()
}
override fun getInt(key: String?, defValue: Int): Int {
return when (key) {
"chip_color" -> account.chipColor
else -> defValue
}
}
override fun putInt(key: String?, value: Int) {
when (key) {
"chip_color" -> setAccountColor(value)
else -> return
}
saveSettingsInBackground()
}
override fun getLong(key: String?, defValue: Long): Long {
return when (key) {
"openpgp_key" -> account.openPgpKey
else -> defValue
}
}
override fun putLong(key: String?, value: Long) {
when (key) {
"openpgp_key" -> account.openPgpKey = value
else -> return
}
saveSettingsInBackground()
}
override fun getString(key: String, defValue: String?): String? {
return when (key) {
"account_description" -> account.name
"show_pictures_enum" -> account.showPictures.name
"account_display_count" -> account.displayCount.toString()
"account_message_age" -> account.maximumPolledMessageAge.toString()
"account_autodownload_size" -> account.maximumAutoDownloadMessageSize.toString()
"account_check_frequency" -> account.automaticCheckIntervalMinutes.toString()
"folder_sync_mode" -> account.folderSyncMode.name
"folder_push_mode" -> account.folderPushMode.name
"delete_policy" -> account.deletePolicy.name
"expunge_policy" -> account.expungePolicy.name
"max_push_folders" -> account.maxPushFolders.toString()
"idle_refresh_period" -> account.idleRefreshMinutes.toString()
"message_format" -> account.messageFormat.name
"quote_style" -> account.quoteStyle.name
"account_quote_prefix" -> account.quotePrefix
"account_setup_auto_expand_folder" -> {
loadSpecialFolder(account.autoExpandFolderId, SpecialFolderSelection.MANUAL)
}
"folder_display_mode" -> account.folderDisplayMode.name
"folder_target_mode" -> account.folderTargetMode.name
"searchable_folders" -> account.searchableFolders.name
"archive_folder" -> loadSpecialFolder(account.archiveFolderId, account.archiveFolderSelection)
"drafts_folder" -> loadSpecialFolder(account.draftsFolderId, account.draftsFolderSelection)
"sent_folder" -> loadSpecialFolder(account.sentFolderId, account.sentFolderSelection)
"spam_folder" -> loadSpecialFolder(account.spamFolderId, account.spamFolderSelection)
"trash_folder" -> loadSpecialFolder(account.trashFolderId, account.trashFolderSelection)
"folder_notify_new_mail_mode" -> account.folderNotifyNewMailMode.name
"account_combined_vibration" -> getCombinedVibrationValue()
"account_remote_search_num_results" -> account.remoteSearchNumResults.toString()
"account_ringtone" -> account.notificationSettings.ringtone
"notification_light" -> account.notificationSettings.light.name
else -> defValue
}
}
override fun putString(key: String, value: String?) {
if (value == null) return
when (key) {
"account_description" -> account.name = value
"show_pictures_enum" -> account.showPictures = Account.ShowPictures.valueOf(value)
"account_display_count" -> account.displayCount = value.toInt()
"account_message_age" -> account.maximumPolledMessageAge = value.toInt()
"account_autodownload_size" -> account.maximumAutoDownloadMessageSize = value.toInt()
"account_check_frequency" -> {
if (account.updateAutomaticCheckIntervalMinutes(value.toInt())) {
reschedulePoll()
}
}
"folder_sync_mode" -> {
if (account.updateFolderSyncMode(Account.FolderMode.valueOf(value))) {
reschedulePoll()
}
}
"folder_push_mode" -> account.folderPushMode = Account.FolderMode.valueOf(value)
"delete_policy" -> account.deletePolicy = Account.DeletePolicy.valueOf(value)
"expunge_policy" -> account.expungePolicy = Account.Expunge.valueOf(value)
"max_push_folders" -> account.maxPushFolders = value.toInt()
"idle_refresh_period" -> account.idleRefreshMinutes = value.toInt()
"message_format" -> account.messageFormat = Account.MessageFormat.valueOf(value)
"quote_style" -> account.quoteStyle = Account.QuoteStyle.valueOf(value)
"account_quote_prefix" -> account.quotePrefix = value
"account_setup_auto_expand_folder" -> account.autoExpandFolderId = extractFolderId(value)
"folder_display_mode" -> account.folderDisplayMode = Account.FolderMode.valueOf(value)
"folder_target_mode" -> account.folderTargetMode = Account.FolderMode.valueOf(value)
"searchable_folders" -> account.searchableFolders = Account.Searchable.valueOf(value)
"archive_folder" -> saveSpecialFolderSelection(value, account::setArchiveFolderId)
"drafts_folder" -> saveSpecialFolderSelection(value, account::setDraftsFolderId)
"sent_folder" -> saveSpecialFolderSelection(value, account::setSentFolderId)
"spam_folder" -> saveSpecialFolderSelection(value, account::setSpamFolderId)
"trash_folder" -> saveSpecialFolderSelection(value, account::setTrashFolderId)
"folder_notify_new_mail_mode" -> account.folderNotifyNewMailMode = Account.FolderMode.valueOf(value)
"account_combined_vibration" -> setCombinedVibrationValue(value)
"account_remote_search_num_results" -> account.remoteSearchNumResults = value.toInt()
"account_ringtone" -> setNotificationSound(value)
"notification_light" -> setNotificationLight(value)
else -> return
}
saveSettingsInBackground()
}
private fun setAccountColor(color: Int) {
if (color != account.chipColor) {
account.chipColor = color
if (account.notificationSettings.light == NotificationLight.AccountColor) {
notificationSettingsChanged = true
}
}
}
private fun setNotificationSound(value: String) {
account.notificationSettings.let { notificationSettings ->
if (!notificationSettings.isRingEnabled || notificationSettings.ringtone != value) {
account.updateNotificationSettings { it.copy(isRingEnabled = true, ringtone = value) }
notificationSettingsChanged = true
}
}
}
private fun setNotificationLight(value: String) {
val light = NotificationLight.valueOf(value)
if (light != account.notificationSettings.light) {
account.updateNotificationSettings { it.copy(light = light) }
notificationSettingsChanged = true
}
}
fun saveSettingsInBackground() {
executorService.execute {
if (notificationSettingsChanged) {
notificationChannelManager.recreateMessagesNotificationChannel(account)
notificationController.restoreNewMailNotifications(listOf(account))
}
notificationSettingsChanged = false
saveSettings()
}
}
private fun saveSettings() {
preferences.saveAccount(account)
}
private fun reschedulePoll() {
jobManager.scheduleMailSync(account)
}
private fun extractFolderId(preferenceValue: String): Long? {
val folderValue = preferenceValue.substringAfter(FolderListPreference.FOLDER_VALUE_DELIMITER)
return if (folderValue == FolderListPreference.NO_FOLDER_VALUE) null else folderValue.toLongOrNull()
}
private fun saveSpecialFolderSelection(
preferenceValue: String,
specialFolderSetter: (Long?, SpecialFolderSelection) -> Unit
) {
val specialFolder = extractFolderId(preferenceValue)
val specialFolderSelection = if (preferenceValue.startsWith(FolderListPreference.AUTOMATIC_PREFIX)) {
SpecialFolderSelection.AUTOMATIC
} else {
SpecialFolderSelection.MANUAL
}
specialFolderSetter(specialFolder, specialFolderSelection)
}
private fun loadSpecialFolder(specialFolderId: Long?, specialFolderSelection: SpecialFolderSelection): String {
val prefix = when (specialFolderSelection) {
SpecialFolderSelection.AUTOMATIC -> FolderListPreference.AUTOMATIC_PREFIX
SpecialFolderSelection.MANUAL -> FolderListPreference.MANUAL_PREFIX
}
return prefix + (specialFolderId?.toString() ?: FolderListPreference.NO_FOLDER_VALUE)
}
private fun getCombinedVibrationValue(): String {
return with(account.notificationSettings.vibration) {
VibrationPreference.encode(
isVibrationEnabled = isEnabled,
vibratePattern = pattern,
vibrationTimes = repeatCount
)
}
}
private fun setCombinedVibrationValue(value: String) {
val (isVibrationEnabled, vibrationPattern, vibrationTimes) = VibrationPreference.decode(value)
account.updateNotificationSettings { notificationSettings ->
notificationSettings.copy(
vibration = NotificationVibration(
isEnabled = isVibrationEnabled,
pattern = vibrationPattern,
repeatCount = vibrationTimes,
)
)
}
notificationSettingsChanged = true
}
}
| app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/account/AccountSettingsDataStore.kt | 1679106711 |
package com.bajdcc.LALR1.syntax.automata.nga
/**
* 非确定性文法自动机边类型
*
* @author bajdcc
*/
enum class NGAEdgeType constructor(var desc: String?) {
EPSILON("Epsilon边"), TOKEN("终结符"), RULE("非终结符")
}
| src/main/kotlin/com/bajdcc/LALR1/syntax/automata/nga/NGAEdgeType.kt | 602268323 |
package bz.stewart.bracken.web.view
import bz.stewart.bracken.web.html.ViewRender
import bz.stewart.bracken.web.service.WebPageContext
import bz.stewart.bracken.web.view.bootstrap.BootstrapNavConfig
import bz.stewart.bracken.web.view.bootstrap.CommonHeader
import kotlinx.html.FlowContent
class SingleBillView : ViewRender {
override fun renderIn(parent: FlowContent, context: WebPageContext) {
//CommonHeader(BootstrapNavConfig()).renderIn(parent, context)
ContentRoot().renderIn(parent, context)
}
} | web/src/main/kotlin/bz/stewart/bracken/web/view/SingleBillView.kt | 3615718209 |
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.storage
import arcs.core.crdt.CrdtData
import arcs.core.crdt.CrdtOperation
import arcs.core.data.EntityType
import arcs.core.data.Schema
import arcs.core.data.SchemaFields
import arcs.core.data.SchemaName
import arcs.core.data.SingletonType
import arcs.core.storage.keys.RamDiskStorageKey
import arcs.core.storage.referencemode.ReferenceModeStorageKey
import arcs.core.storage.testutil.testStorageEndpointManager
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(JUnit4::class)
class LocalStorageEndpointManagerTest {
@Test
fun manager_get_createsNewStore() = runTest {
val endpointManager = testStorageEndpointManager(this)
val firstEndpoint = endpointManager.get(storageOptionsFrom(DUMMY_KEYNAME), DUMMY_CALLBACK)
val secondEndpoint = endpointManager.get(storageOptionsFrom("newKey"), DUMMY_CALLBACK)
assertThat(firstEndpoint.storeForTests()).isNotEqualTo(secondEndpoint.storeForTests())
}
@Test
fun manager_get_cachesStore() = runTest {
val endpointManager = testStorageEndpointManager(this)
val firstEndpoint = endpointManager.get(storageOptionsFrom(DUMMY_KEYNAME), DUMMY_CALLBACK)
val secondEndpoint = endpointManager.get(storageOptionsFrom(DUMMY_KEYNAME), DUMMY_CALLBACK)
assertThat(firstEndpoint.storeForTests()).isSameInstanceAs(secondEndpoint.storeForTests())
}
@Test
fun manager_reset_closesStores() = runTest {
val endpointManager = testStorageEndpointManager(this)
val endpoint = endpointManager.get(storageOptionsFrom(DUMMY_KEYNAME), DUMMY_CALLBACK)
endpointManager.reset()
assertThat((endpoint.storeForTests() as ReferenceModeStore).containerStore.closed).isTrue()
}
@Test
fun manager_reset_emptiesStoreCache() = runTest {
val endpointManager = testStorageEndpointManager(this)
val firstEndpoint = endpointManager.get(storageOptionsFrom(DUMMY_KEYNAME), DUMMY_CALLBACK)
endpointManager.reset()
val secondEndpoint = endpointManager.get(storageOptionsFrom(DUMMY_KEYNAME), DUMMY_CALLBACK)
assertThat(firstEndpoint.storeForTests()).isNotEqualTo(secondEndpoint.storeForTests())
}
private fun runTest(block: suspend CoroutineScope.() -> Unit): Unit = runBlockingTest {
block()
}
private fun StorageEndpoint<*, *, *>.storeForTests(): ActiveStore<*, *, *> =
(this as LocalStorageEndpoint<*, *, *>).storeForTests
private fun storageOptionsFrom(keyName: String): StoreOptions {
return StoreOptions(
storageKey = ReferenceModeStorageKey(
RamDiskStorageKey("backing"),
RamDiskStorageKey(keyName)
),
type = SingletonType(
EntityType(
Schema(
setOf(SchemaName("TestType")),
fields = SchemaFields(
emptyMap(), emptyMap()
),
hash = "abcdef"
)
)
)
)
}
companion object {
private val DUMMY_CALLBACK: ProxyCallback<CrdtData, CrdtOperation, Any> = {}
private val DUMMY_KEYNAME = "entity"
}
}
| javatests/arcs/core/storage/LocalStorageEndpointManagerTest.kt | 172178053 |
package failchat.exception
import failchat.Origin
class ChannelOfflineException(
val origin: Origin,
val channel: String
) : Exception("origin: $origin, channel: $channel")
| src/main/kotlin/failchat/exception/ChannelOfflineException.kt | 3690653494 |
import com.acornui.app
import com.acornui.component.Div
import com.acornui.component.input.button
import com.acornui.component.style.cssClass
import com.acornui.di.Context
import com.acornui.dom.add
import com.acornui.dom.addStyleToHead
import com.acornui.dom.head
import com.acornui.dom.linkElement
import com.acornui.input.clicked
import com.acornui.skins.DefaultStyles
import com.acornui.version
/**
* A barebones example with a Theme and a Button.
*/
class Main(owner: Context) : Div(owner) {
init {
DefaultStyles
println(version)
addClass(styleTag)
head.add(
linkElement(
"https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@200;400&display=swap",
rel = "stylesheet"
)
)
+button("Hello World") {
clicked.listen {
println("Hello World")
}
}
}
@Suppress("CssOverwrittenProperties")
companion object {
val styleTag by cssClass()
init {
addStyleToHead(
"""
$styleTag {
font-family: 'Roboto Mono', monospace;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
"""
)
}
}
}
/**
* `main` is our main entry point.
*/
fun main() = app("acornUiRoot") {
// Create and add our main component to the stage:
+Main(this)
} | templates/basic/app/src/main/kotlin/Main.kt | 3270501464 |
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.vimscript.model.expressions
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.ex.ExException
import com.maddyhome.idea.vim.vimscript.model.VimLContext
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDataType
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDictionary
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimList
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString
data class SublistExpression(val from: Expression?, val to: Expression?, val expression: Expression) : Expression() {
override fun evaluate(editor: VimEditor, context: ExecutionContext, vimContext: VimLContext): VimDataType {
val expressionValue = expression.evaluate(editor, context, vimContext)
val arraySize = when (expressionValue) {
is VimDictionary -> throw ExException("E719: Cannot slice a Dictionary")
is VimList -> expressionValue.values.size
else -> expressionValue.asString().length
}
var fromInt = Integer.parseInt(from?.evaluate(editor, context, vimContext)?.asString() ?: "0")
if (fromInt < 0) {
fromInt += arraySize
}
var toInt = Integer.parseInt(to?.evaluate(editor, context, vimContext)?.asString() ?: (arraySize - 1).toString())
if (toInt < 0) {
toInt += arraySize
}
return if (expressionValue is VimList) {
if (fromInt > arraySize) {
VimList(mutableListOf())
} else if (fromInt == toInt) {
expressionValue.values[fromInt]
} else if (fromInt <= toInt) {
VimList(expressionValue.values.subList(fromInt, toInt + 1))
} else {
VimList(mutableListOf())
}
} else {
if (fromInt > arraySize) {
VimString("")
} else if (fromInt <= toInt) {
if (toInt > expressionValue.asString().length - 1) {
VimString(expressionValue.asString().substring(fromInt))
} else {
VimString(expressionValue.asString().substring(fromInt, toInt + 1))
}
} else {
VimString("")
}
}
}
}
| vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/expressions/SublistExpression.kt | 3116238164 |
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.provider.plugins.precompiled.tasks
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.tasks.OutputDirectory
import org.gradle.work.DisableCachingByDefault
@DisableCachingByDefault(because = "Abstract super-class, not to be instantiated directly")
abstract class ClassPathSensitiveCodeGenerationTask : ClassPathSensitiveTask() {
@get:OutputDirectory
abstract val sourceCodeOutputDir: DirectoryProperty
}
| subprojects/kotlin-dsl-provider-plugins/src/main/kotlin/org/gradle/kotlin/dsl/provider/plugins/precompiled/tasks/ClassPathSensitiveCodeGenerationTask.kt | 3659466286 |
package ii_collections
fun example1(list: List<Int>) {
// If a lambda has exactly one parameter, that parameter can be accessed as 'it'
val positiveNumbers = list.filter { it > 0 }
val squares = list.map { it * it }
}
fun Shop.getCitiesCustomersAreFrom(): Set<City> {
// Return the set of cities the customers are from
// todoCollectionTask()
return customers.map { it.city }.toSet()
}
fun Shop.getCustomersFrom(city: City): List<Customer> {
return customers.filter { it.city==city }
// todoCollectionTask()
}
| src/ii_collections/_14_FilterMap.kt | 3017941231 |
package org.schabi.newpipe.local.subscription.item
import com.xwray.groupie.kotlinandroidextensions.GroupieViewHolder
import com.xwray.groupie.kotlinandroidextensions.Item
import kotlinx.android.synthetic.main.feed_group_card_item.icon
import kotlinx.android.synthetic.main.feed_group_card_item.title
import org.schabi.newpipe.R
import org.schabi.newpipe.database.feed.model.FeedGroupEntity
import org.schabi.newpipe.local.subscription.FeedGroupIcon
data class FeedGroupCardItem(
val groupId: Long = FeedGroupEntity.GROUP_ALL_ID,
val name: String,
val icon: FeedGroupIcon
) : Item() {
constructor (feedGroupEntity: FeedGroupEntity) : this(feedGroupEntity.uid, feedGroupEntity.name, feedGroupEntity.icon)
override fun getId(): Long {
return when (groupId) {
FeedGroupEntity.GROUP_ALL_ID -> super.getId()
else -> groupId
}
}
override fun getLayout(): Int = R.layout.feed_group_card_item
override fun bind(viewHolder: GroupieViewHolder, position: Int) {
viewHolder.title.text = name
viewHolder.icon.setImageResource(icon.getDrawableRes(viewHolder.containerView.context))
}
}
| app/src/main/java/org/schabi/newpipe/local/subscription/item/FeedGroupCardItem.kt | 1748873203 |
package org.wordpress.android.ui.mediapicker.loader
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.kotlin.any
import org.mockito.kotlin.isNull
import org.mockito.kotlin.whenever
import org.wordpress.android.BaseUnitTest
import org.wordpress.android.test
import org.wordpress.android.ui.mediapicker.MediaItem
import org.wordpress.android.ui.mediapicker.MediaItem.Identifier
import org.wordpress.android.ui.mediapicker.MediaType.IMAGE
import org.wordpress.android.ui.mediapicker.MediaType.VIDEO
import org.wordpress.android.ui.mediapicker.loader.MediaLoader.DomainModel
import org.wordpress.android.ui.mediapicker.loader.MediaLoader.LoadAction
import org.wordpress.android.ui.mediapicker.loader.MediaSource.MediaLoadingResult
import org.wordpress.android.ui.utils.UiString.UiStringText
class MediaLoaderTest : BaseUnitTest() {
@Mock lateinit var mediaSource: MediaSource
@Mock lateinit var identifier1: Identifier
@Mock lateinit var identifier2: Identifier
private lateinit var mediaLoader: MediaLoader
private lateinit var firstMediaItem: MediaItem
private lateinit var secondMediaItem: MediaItem
@Before
fun setUp() {
mediaLoader = MediaLoader(mediaSource)
firstMediaItem = MediaItem(identifier1, "url://first_item", "first item", IMAGE, "image/jpeg", 1)
secondMediaItem = MediaItem(identifier2, "url://second_item", "second item", VIDEO, "video/mpeg", 2)
}
@Test
fun `loads media items on start`() = withMediaLoader { resultModel, performAction ->
val mediaItems = listOf(firstMediaItem)
whenever(
mediaSource.load(
forced = false,
loadMore = false
)
).thenReturn(MediaLoadingResult.Success(mediaItems, hasMore = false))
performAction(LoadAction.Start(), true)
resultModel.assertModel(mediaItems)
}
@Test
fun `shows an error when loading fails`() = withMediaLoader { resultModel, performAction ->
val errorMessage = "error"
whenever(mediaSource.load(forced = false, loadMore = false)).thenReturn(
MediaLoadingResult.Failure(
UiStringText(errorMessage)
)
)
performAction(LoadAction.Start(), true)
resultModel.assertModel(errorMessage = errorMessage)
}
@Test
fun `loads next page`() = withMediaLoader { resultModel, performAction ->
val firstPage = MediaLoadingResult.Success(listOf(firstMediaItem), hasMore = true)
val secondPage = MediaLoadingResult.Success(listOf(firstMediaItem, secondMediaItem))
whenever(mediaSource.load(forced = false, loadMore = false)).thenReturn(firstPage)
whenever(mediaSource.load(forced = false, loadMore = true)).thenReturn(secondPage)
performAction(LoadAction.Start(), true)
resultModel.assertModel(listOf(firstMediaItem), hasMore = true)
performAction(LoadAction.NextPage, true)
resultModel.assertModel(listOf(firstMediaItem, secondMediaItem), hasMore = false)
}
@Test
fun `shows an error when loading next page fails`() = withMediaLoader { resultModel, performAction ->
val firstPage = MediaLoadingResult.Success(listOf(firstMediaItem), hasMore = true)
val message = "error"
val secondPage = MediaLoadingResult.Failure(UiStringText(message), data = listOf(firstMediaItem))
whenever(mediaSource.load(forced = false, loadMore = false)).thenReturn(firstPage)
whenever(mediaSource.load(forced = false, loadMore = true)).thenReturn(secondPage)
performAction(LoadAction.Start(), true)
resultModel.assertModel(listOf(firstMediaItem), hasMore = true)
performAction(LoadAction.NextPage, true)
resultModel.assertModel(listOf(firstMediaItem), errorMessage = message, hasMore = true)
}
@Test
fun `refresh overrides data`() = withMediaLoader { resultModel, performAction ->
val firstResult = MediaLoadingResult.Success(listOf(firstMediaItem))
val secondResult = MediaLoadingResult.Success(listOf(secondMediaItem))
whenever(mediaSource.load(any(), any(), isNull())).thenReturn(firstResult, secondResult)
performAction(LoadAction.Start(), true)
resultModel.assertModel(listOf(firstMediaItem))
performAction(LoadAction.Refresh(true), true)
resultModel.assertModel(listOf(secondMediaItem))
}
@Test
fun `filters out media item`() = withMediaLoader { resultModel, performAction ->
val mediaItems = listOf(firstMediaItem, secondMediaItem)
val filter = "second"
whenever(mediaSource.load(forced = false, loadMore = false)).thenReturn(MediaLoadingResult.Success(mediaItems))
whenever(
mediaSource.load(
forced = false,
loadMore = false,
filter = filter
)
).thenReturn(MediaLoadingResult.Success(listOf(secondMediaItem)))
performAction(LoadAction.Start(), true)
performAction(LoadAction.Filter(filter), true)
resultModel.assertModel(listOf(secondMediaItem))
performAction(LoadAction.ClearFilter, true)
resultModel.assertModel(mediaItems)
}
@Test
fun `clears filter`() = withMediaLoader { resultModel, performAction ->
val mediaItems = listOf(firstMediaItem, secondMediaItem)
val filter = "second"
whenever(
mediaSource.load(
forced = false,
loadMore = false,
filter = filter
)
).thenReturn(MediaLoadingResult.Success(listOf(secondMediaItem)))
whenever(
mediaSource.load(
forced = false,
loadMore = false
)
).thenReturn(MediaLoadingResult.Success(mediaItems))
performAction(LoadAction.Start(), true)
performAction(LoadAction.Filter(filter), true)
performAction(LoadAction.ClearFilter, true)
resultModel.assertModel(mediaItems)
}
private fun List<DomainModel>.assertModel(
mediaItems: List<MediaItem> = listOf(),
errorMessage: String? = null,
hasMore: Boolean = false
) {
this.last().apply {
assertThat(this.domainItems).isEqualTo(mediaItems)
if (errorMessage != null) {
assertThat(this.emptyState?.title).isEqualTo(UiStringText(errorMessage))
assertThat(this.emptyState?.isError).isTrue()
} else {
assertThat(this.emptyState?.title).isNull()
}
assertThat(this.hasMore).isEqualTo(hasMore)
}
}
private fun withMediaLoader(
assertFunction: suspend (
domainModels: List<DomainModel>,
performAction: suspend (
action: LoadAction,
awaitResult: Boolean
) -> Unit
) -> Unit
) =
test {
val loadActions: Channel<LoadAction> = Channel()
val domainModels: MutableList<DomainModel> = mutableListOf()
val job = launch {
mediaLoader.loadMedia(loadActions).collect {
domainModels.add(it)
}
}
assertFunction(domainModels) { action, awaitResult ->
val currentCount = domainModels.size
loadActions.send(action)
if (awaitResult) {
domainModels.awaitResult(currentCount + 1)
}
}
job.cancel()
}
private suspend fun List<DomainModel>.awaitResult(count: Int) {
val limit = 10
var counter = 0
while (counter < limit && this.size < count) {
counter++
delay(1)
}
}
}
| WordPress/src/test/java/org/wordpress/android/ui/mediapicker/loader/MediaLoaderTest.kt | 2243896305 |
package au.com.dius.pact.provider.junit5
import au.com.dius.pact.core.model.Interaction
import au.com.dius.pact.core.model.Pact
import au.com.dius.pact.provider.ProviderVerifier
import org.apache.http.HttpRequest
import org.junit.jupiter.api.extension.Extension
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.api.extension.ParameterContext
import org.junit.jupiter.api.extension.ParameterResolver
import org.junit.jupiter.api.extension.TestTemplateInvocationContext
object DummyTestTemplate : TestTemplateInvocationContext, ParameterResolver {
override fun getDisplayName(invocationIndex: Int) = "No pacts found to verify"
override fun getAdditionalExtensions(): MutableList<Extension> {
return mutableListOf(this)
}
override fun supportsParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Boolean {
return when (parameterContext.parameter.type) {
Pact::class.java -> true
Interaction::class.java -> true
HttpRequest::class.java -> true
PactVerificationContext::class.java -> true
ProviderVerifier::class.java -> true
else -> false
}
}
override fun resolveParameter(parameterContext: ParameterContext, extensionContext: ExtensionContext): Any? {
return null
}
}
| provider/junit5/src/main/kotlin/au/com/dius/pact/provider/junit5/DummyTestTemplate.kt | 3400938946 |
package org.wordpress.android.ui
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.View.MeasureSpec
import android.view.animation.AccelerateInterpolator
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.marginBottom
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar.SnackbarLayout
import org.wordpress.android.ui.WPTooltipView.TooltipPosition.ABOVE
/**
* This class will let WPTooltipViewBehavior anchor above FloatingActionButton with transition animation.
*/
class WPTooltipViewBehavior : CoordinatorLayout.Behavior<WPTooltipView> {
constructor() : super()
constructor(context: Context, attr: AttributeSet) : super(context, attr)
override fun layoutDependsOn(parent: CoordinatorLayout, child: WPTooltipView, dependency: View): Boolean {
return dependency is FloatingActionButton
}
override fun onDependentViewChanged(parent: CoordinatorLayout, child: WPTooltipView, dependency: View): Boolean {
if (child.position != ABOVE) {
// Remove this condition if you want to support different TooltipPosition
throw IllegalArgumentException("This behavior only supports TooltipPosition.ABOVE")
}
if (dependency.measuredWidth == 0 || child.measuredWidth == 0) {
dependency.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED)
}
child.x = dependency.x - child.measuredWidth + dependency.measuredWidth
child.y = dependency.y - child.measuredHeight
return true
}
override fun onDependentViewRemoved(parent: CoordinatorLayout, child: WPTooltipView, dependency: View) {
super.onDependentViewRemoved(parent, child, dependency)
child.visibility = View.GONE
}
}
/**
* This class will let FloatingActionButton anchor above SnackBar with transition animation.
*/
class FloatingActionButtonBehavior : CoordinatorLayout.Behavior<FloatingActionButton> {
constructor() : super()
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
override fun layoutDependsOn(parent: CoordinatorLayout, child: FloatingActionButton, dependency: View): Boolean {
return dependency is SnackbarLayout
}
override fun onDependentViewChanged(
parent: CoordinatorLayout,
child: FloatingActionButton,
dependency: View
): Boolean {
if (dependency.visibility == View.VISIBLE) {
moveChildUp(child, dependency.height + dependency.marginBottom)
return true
}
return false
}
override fun onDependentViewRemoved(parent: CoordinatorLayout, child: FloatingActionButton, dependency: View) {
moveChildToInitialPosition(child)
}
private fun moveChildUp(child: View, translation: Int) {
child.animate()
.translationY((-translation).toFloat())
.setInterpolator(AccelerateInterpolator())
.setDuration(child.resources.getInteger(android.R.integer.config_shortAnimTime).toLong())
.start()
}
private fun moveChildToInitialPosition(child: View) {
child.animate()
.translationY(0f)
.setInterpolator(AccelerateInterpolator())
.setDuration(child.resources.getInteger(android.R.integer.config_shortAnimTime).toLong())
.start()
}
}
| WordPress/src/main/java/org/wordpress/android/ui/LayoutBehaviors.kt | 3013342754 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.light
import com.intellij.ide.lightEdit.LightEdit
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.ide.lightEdit.LightEditService
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.wm.StatusBar
import com.intellij.openapi.wm.StatusBarWidget
import com.intellij.openapi.wm.StatusBarWidgetFactory
import com.intellij.util.Consumer
import git4idea.i18n.GitBundle
import java.awt.Component
import java.awt.event.MouseEvent
private const val ID = "light.edit.git"
private val LOG = Logger.getInstance("#git4idea.light.LightGitStatusBarWidget")
private class LightGitStatusBarWidget(private val lightGitTracker: LightGitTracker) : StatusBarWidget, StatusBarWidget.TextPresentation {
private var statusBar: StatusBar? = null
init {
lightGitTracker.addUpdateListener(object : LightGitTrackerListener {
override fun update() {
statusBar?.updateWidget(ID())
}
}, this)
}
override fun ID(): String = ID
override fun install(statusBar: StatusBar) {
this.statusBar = statusBar
}
override fun getPresentation(): StatusBarWidget.WidgetPresentation = this
override fun getText(): String {
return lightGitTracker.currentLocation?.let { GitBundle.message("git.light.status.bar.text", it) } ?: ""
}
override fun getTooltipText(): String {
val locationText = lightGitTracker.currentLocation?.let { GitBundle.message("git.light.status.bar.tooltip", it) } ?: ""
if (locationText.isBlank()) return locationText
val selectedFile = LightEditService.getInstance().selectedFile
if (selectedFile != null) {
val statusText = lightGitTracker.getFileStatus(selectedFile).getPresentation()
if (statusText.isNotBlank()) return HtmlBuilder().append(locationText).br().append(statusText).toString()
}
return locationText
}
override fun getAlignment(): Float = Component.LEFT_ALIGNMENT
override fun getClickConsumer(): Consumer<MouseEvent>? = null
override fun dispose() = Unit
}
class LightGitStatusBarWidgetFactory : StatusBarWidgetFactory, LightEditCompatible {
override fun getId(): String = ID
override fun getDisplayName(): String = GitBundle.message("git.light.status.bar.display.name")
override fun isAvailable(project: Project): Boolean = LightEdit.owns(project)
override fun createWidget(project: Project): StatusBarWidget {
LOG.assertTrue(LightEdit.owns(project))
return LightGitStatusBarWidget(LightGitTracker.getInstance())
}
override fun disposeWidget(widget: StatusBarWidget) = Disposer.dispose(widget)
override fun canBeEnabledOn(statusBar: StatusBar): Boolean = true
} | plugins/git4idea/src/git4idea/light/LightGitStatusBarWidget.kt | 446681883 |
package com.kelsos.mbrc.mappers
internal interface Mapper<From, To> {
fun map(from: From): To
}
| app/src/main/kotlin/com/kelsos/mbrc/mappers/Mapper.kt | 4016881323 |
// WITH_STDLIB
fun test() {
<caret>with ("") {
println("1")
println("2")
}
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantWith/simple.kt | 1662507999 |
package com.simplemobiletools.musicplayer.models
import androidx.room.ColumnInfo
import androidx.room.Entity
@Entity(tableName = "queue_items", primaryKeys = ["track_id"])
data class QueueItem(
@ColumnInfo(name = "track_id") var trackId: Long,
@ColumnInfo(name = "track_order") var trackOrder: Int,
@ColumnInfo(name = "is_current") var isCurrent: Boolean,
@ColumnInfo(name = "last_position") var lastPosition: Int
)
| app/src/main/kotlin/com/simplemobiletools/musicplayer/models/QueueItem.kt | 1152419240 |
/*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko.render
import org.jetbrains.android.anko.*
import org.jetbrains.android.anko.config.AnkoConfiguration
import org.jetbrains.android.anko.config.AnkoFile
import org.jetbrains.android.anko.config.ConfigurationOption
import org.jetbrains.android.anko.generator.GenerationState
import org.jetbrains.android.anko.generator.InterfaceWorkaroundsGenerator
import org.objectweb.asm.Type
class InterfaceWorkaroundsRenderer(config: AnkoConfiguration) : Renderer(config) {
override val renderIf: Array<ConfigurationOption> = arrayOf(AnkoFile.INTERFACE_WORKAROUNDS_JAVA)
override fun processElements(state: GenerationState) = StringBuilder {
val interfaces = state[javaClass<InterfaceWorkaroundsGenerator>()].toList()
append(render("interface_workarounds") {
"interfaces" % seq(interfaces) {
val (mainClass, ancestor, innerClass) = it
val probInterfaceName = innerClass.innerName
val conflict = interfaces.count { it.inner.innerName == probInterfaceName } > 1
val interfaceName = (if (conflict) innerClass.outerName.substringAfterLast("/") + "_" else "") + probInterfaceName
"name" % interfaceName
"ancestor" % ancestor.fqName
val acceptableFields = mainClass.fields.filter { it.isPublic && it.isStatic && it.isFinal }
"fields" % seq(acceptableFields) { field ->
"type" % Type.getType(field.desc).asJavaString()
"name" % field.name
}
}
})
}.toString()
} | dsl/src/org/jetbrains/android/anko/render/InterfaceWorkaroundsRenderer.kt | 2050054325 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.impl
import com.intellij.diagnostic.telemetry.createTask
import com.intellij.diagnostic.telemetry.useWithScope
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.NioFiles
import com.intellij.openapi.util.text.StringUtilRt
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.trace.Span
import org.jdom.Element
import org.jetbrains.intellij.build.*
import org.jetbrains.intellij.build.TraceManager.spanBuilder
import org.jetbrains.intellij.build.impl.productInfo.*
import org.jetbrains.intellij.build.impl.support.RepairUtilityBuilder
import org.jetbrains.intellij.build.io.copyFileToDir
import org.jetbrains.intellij.build.io.runProcess
import org.jetbrains.intellij.build.io.substituteTemplatePlaceholders
import org.jetbrains.intellij.build.io.transformFile
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.util.concurrent.ForkJoinTask
import java.util.function.BiPredicate
internal class WindowsDistributionBuilder(
override val context: BuildContext,
private val customizer: WindowsDistributionCustomizer,
private val ideaProperties: Path?,
private val patchedApplicationInfo: String,
) : OsSpecificDistributionBuilder {
private val icoFile: Path?
init {
val icoPath = (if (context.applicationInfo.isEAP) customizer.icoPathForEAP else null) ?: customizer.icoPath
icoFile = icoPath?.let { Path.of(icoPath) }
}
override val targetOs: OsFamily
get() = OsFamily.WINDOWS
override fun copyFilesForOsDistribution(targetPath: Path, arch: JvmArchitecture) {
val distBinDir = targetPath.resolve("bin")
Files.createDirectories(distBinDir)
val binWin = FileSet(context.paths.communityHomeDir.communityRoot.resolve("bin/win")).includeAll()
if (!context.includeBreakGenLibraries()) {
@Suppress("SpellCheckingInspection")
binWin.exclude("breakgen*")
}
binWin.copyToDir(distBinDir)
val pty4jNativeDir = unpackPty4jNative(context, targetPath, "win")
generateBuildTxt(context, targetPath)
copyDistFiles(context, targetPath)
Files.writeString(distBinDir.resolve(ideaProperties!!.fileName),
StringUtilRt.convertLineSeparators(Files.readString(ideaProperties), "\r\n"))
if (icoFile != null) {
Files.copy(icoFile, distBinDir.resolve("${context.productProperties.baseFileName}.ico"), StandardCopyOption.REPLACE_EXISTING)
}
if (customizer.includeBatchLaunchers) {
generateScripts(distBinDir)
}
generateVMOptions(distBinDir)
buildWinLauncher(targetPath)
customizer.copyAdditionalFiles(context, targetPath.toString())
context.executeStep(spanBuilder = spanBuilder("sign windows"), stepId = BuildOptions.WIN_SIGN_STEP) {
val nativeFiles = ArrayList<Path>()
for (nativeRoot in listOf(distBinDir, pty4jNativeDir)) {
Files.find(nativeRoot, Integer.MAX_VALUE, BiPredicate { file, attributes ->
if (attributes.isRegularFile) {
val path = file.toString()
path.endsWith(".exe") || path.endsWith(".dll")
}
else {
false
}
}).use { stream ->
stream.forEach(nativeFiles::add)
}
}
Span.current().setAttribute(AttributeKey.stringArrayKey("files"), nativeFiles.map(Path::toString))
customizer.getBinariesToSign(context).mapTo(nativeFiles) { targetPath.resolve(it) }
if (nativeFiles.isNotEmpty()) {
context.signFiles(nativeFiles, BuildOptions.WIN_SIGN_OPTIONS)
}
}
}
override fun buildArtifacts(osAndArchSpecificDistPath: Path, arch: JvmArchitecture) {
copyFilesForOsDistribution(osAndArchSpecificDistPath, arch)
val jreDir = context.bundledRuntime.extract(BundledRuntimeImpl.getProductPrefix(context), OsFamily.WINDOWS, arch)
@Suppress("SpellCheckingInspection")
val vcRtDll = jreDir.resolve("jbr/bin/msvcp140.dll")
check(Files.exists(vcRtDll)) {
"VS C++ Runtime DLL (${vcRtDll.fileName}) not found in ${vcRtDll.parent}.\n" +
"If JBR uses a newer version, please correct the path in this code and update Windows Launcher build configuration.\n" +
"If DLL was relocated to another place, please correct the path in this code."
}
copyFileToDir(vcRtDll, osAndArchSpecificDistPath.resolve("bin"))
val zipWithJbrPathTask = if (customizer.buildZipArchiveWithBundledJre) {
createBuildWinZipTask(listOf(jreDir), customizer.zipArchiveWithBundledJreSuffix, osAndArchSpecificDistPath, customizer, context).fork()
}
else {
null
}
val zipWithoutJbrPathTask = if (customizer.buildZipArchiveWithoutBundledJre) {
createBuildWinZipTask(emptyList(), customizer.zipArchiveWithoutBundledJreSuffix, osAndArchSpecificDistPath, customizer, context).fork()
}
else {
null
}
var exePath: Path? = null
context.executeStep("build Windows Exe Installer", BuildOptions.WINDOWS_EXE_INSTALLER_STEP) {
val productJsonDir = context.paths.tempDir.resolve("win.dist.product-info.json.exe")
validateProductJson(jsonText = generateProductJson(targetDir = productJsonDir, isJreIncluded = true, context = context),
relativePathToProductJson = "",
installationDirectories = listOf(context.paths.distAllDir, osAndArchSpecificDistPath, jreDir),
installationArchives = emptyList(),
context = context)
exePath = buildNsisInstaller(winDistPath = osAndArchSpecificDistPath,
additionalDirectoryToInclude = productJsonDir,
suffix = "",
customizer = customizer,
jreDir = jreDir,
context = context)
}
val zipWithJbrPath = zipWithJbrPathTask?.join()
zipWithoutJbrPathTask?.join()
val exePath1 = exePath
if (zipWithJbrPath != null && exePath1 != null) {
checkThatExeInstallerAndZipWithJbrAreTheSame(zipWithJbrPath, exePath1)
return
}
}
private fun checkThatExeInstallerAndZipWithJbrAreTheSame(zipPath: Path, exePath: Path) {
if (context.options.isInDevelopmentMode) {
Span.current().addEvent("comparing .zip and .exe skipped in development mode")
return
}
if (!SystemInfoRt.isLinux) {
Span.current().addEvent("comparing .zip and .exe is not supported on ${SystemInfoRt.OS_NAME}")
return
}
Span.current().addEvent("compare ${zipPath.fileName} vs. ${exePath.fileName}")
val tempZip = Files.createTempDirectory(context.paths.tempDir, "zip-")
val tempExe = Files.createTempDirectory(context.paths.tempDir, "exe-")
try {
runProcess(args = listOf("7z", "x", "-bd", exePath.toString()), workingDir = tempExe, logger = context.messages)
runProcess(args = listOf("unzip", "-q", zipPath.toString()), workingDir = tempZip, logger = context.messages)
@Suppress("SpellCheckingInspection")
NioFiles.deleteRecursively(tempExe.resolve("\$PLUGINSDIR"))
runProcess(listOf("diff", "-q", "-r", tempZip.toString(), tempExe.toString()), null, context.messages)
RepairUtilityBuilder.generateManifest(context, tempExe, exePath.fileName.toString())
}
finally {
NioFiles.deleteRecursively(tempZip)
NioFiles.deleteRecursively(tempExe)
}
}
private fun generateScripts(distBinDir: Path) {
val fullName = context.applicationInfo.productName
val baseName = context.productProperties.baseFileName
val scriptName = "${baseName}.bat"
val vmOptionsFileName = "${baseName}64.exe"
val classPathJars = context.bootClassPathJarNames
var classPath = "SET \"CLASS_PATH=%IDE_HOME%\\lib\\${classPathJars[0]}\""
for (i in 1 until classPathJars.size) {
classPath += "\nSET \"CLASS_PATH=%CLASS_PATH%;%IDE_HOME%\\lib\\${classPathJars[i]}\""
}
var additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.WINDOWS)
if (!context.xBootClassPathJarNames.isEmpty()) {
additionalJvmArguments = additionalJvmArguments.toMutableList()
val bootCp = context.xBootClassPathJarNames.joinToString(separator = ";") { "%IDE_HOME%\\lib\\${it}" }
additionalJvmArguments.add("\"-Xbootclasspath/a:$bootCp\"")
}
val winScripts = context.paths.communityHomeDir.communityRoot.resolve("platform/build-scripts/resources/win/scripts")
val actualScriptNames = Files.newDirectoryStream(winScripts).use { dirStream -> dirStream.map { it.fileName.toString() }.sorted() }
@Suppress("SpellCheckingInspection")
val expectedScriptNames = listOf("executable-template.bat", "format.bat", "inspect.bat", "ltedit.bat")
check(actualScriptNames == expectedScriptNames) {
"Expected script names '${expectedScriptNames.joinToString(separator = " ")}', " +
"but got '${actualScriptNames.joinToString(separator = " ")}' " +
"in $winScripts. Please review ${WindowsDistributionBuilder::class.java.name} and update accordingly"
}
substituteTemplatePlaceholders(
inputFile = winScripts.resolve("executable-template.bat"),
outputFile = distBinDir.resolve(scriptName),
placeholder = "@@",
values = listOf(
Pair("product_full", fullName),
Pair("product_uc", context.productProperties.getEnvironmentVariableBaseName(context.applicationInfo)),
Pair("product_vendor", context.applicationInfo.shortCompanyName),
Pair("vm_options", vmOptionsFileName),
Pair("system_selector", context.systemSelector),
Pair("ide_jvm_args", additionalJvmArguments.joinToString(separator = " ")),
Pair("class_path", classPath),
Pair("base_name", baseName),
Pair("main_class_name", context.productProperties.mainClassName),
)
)
val inspectScript = context.productProperties.inspectCommandName
@Suppress("SpellCheckingInspection")
for (fileName in listOf("format.bat", "inspect.bat", "ltedit.bat")) {
val sourceFile = winScripts.resolve(fileName)
val targetFile = distBinDir.resolve(fileName)
substituteTemplatePlaceholders(
inputFile = sourceFile,
outputFile = targetFile,
placeholder = "@@",
values = listOf(
Pair("product_full", fullName),
Pair("script_name", scriptName),
)
)
}
if (inspectScript != "inspect") {
val targetPath = distBinDir.resolve("${inspectScript}.bat")
Files.move(distBinDir.resolve("inspect.bat"), targetPath)
context.patchInspectScript(targetPath)
}
FileSet(distBinDir)
.include("*.bat")
.enumerate()
.forEach { file ->
transformFile(file) { target ->
@Suppress("BlockingMethodInNonBlockingContext")
Files.writeString(target, toDosLineEndings(Files.readString(file)))
}
}
}
private fun generateVMOptions(distBinDir: Path) {
val productProperties = context.productProperties
val fileName = "${productProperties.baseFileName}64.exe.vmoptions"
val vmOptions = VmOptionsGenerator.computeVmOptions(context.applicationInfo.isEAP, productProperties)
VmOptionsGenerator.writeVmOptions(distBinDir.resolve(fileName), vmOptions, "\r\n")
}
private fun buildWinLauncher(winDistPath: Path) {
spanBuilder("build Windows executable").useWithScope {
val executableBaseName = "${context.productProperties.baseFileName}64"
val launcherPropertiesPath = context.paths.tempDir.resolve("launcher.properties")
val upperCaseProductName = context.applicationInfo.upperCaseProductName
@Suppress("SpellCheckingInspection")
val vmOptions = context.getAdditionalJvmArguments(OsFamily.WINDOWS) + listOf("-Dide.native.launcher=true")
val productName = context.applicationInfo.shortProductName
val classPath = context.bootClassPathJarNames.joinToString(separator = ";")
val bootClassPath = context.xBootClassPathJarNames.joinToString(separator = ";")
val envVarBaseName = context.productProperties.getEnvironmentVariableBaseName(context.applicationInfo)
val icoFilesDirectory = context.paths.tempDir.resolve("win-launcher-ico")
val appInfoForLauncher = generateApplicationInfoForLauncher(patchedApplicationInfo, icoFilesDirectory)
@Suppress("SpellCheckingInspection")
Files.writeString(launcherPropertiesPath, """
IDS_JDK_ONLY=${context.productProperties.toolsJarRequired}
IDS_JDK_ENV_VAR=${envVarBaseName}_JDK
IDS_APP_TITLE=${productName} Launcher
IDS_VM_OPTIONS_PATH=%APPDATA%\\\\${context.applicationInfo.shortCompanyName}\\\\${context.systemSelector}
IDS_VM_OPTION_ERRORFILE=-XX:ErrorFile=%USERPROFILE%\\\\java_error_in_${executableBaseName}_%p.log
IDS_VM_OPTION_HEAPDUMPPATH=-XX:HeapDumpPath=%USERPROFILE%\\\\java_error_in_${executableBaseName}.hprof
IDC_WINLAUNCHER=${upperCaseProductName}_LAUNCHER
IDS_PROPS_ENV_VAR=${envVarBaseName}_PROPERTIES
IDS_VM_OPTIONS_ENV_VAR=${envVarBaseName}_VM_OPTIONS
IDS_ERROR_LAUNCHING_APP=Error launching $productName
IDS_VM_OPTIONS=${vmOptions.joinToString(separator = " ")}
IDS_CLASSPATH_LIBS=${classPath}
IDS_BOOTCLASSPATH_LIBS=${bootClassPath}
IDS_INSTANCE_ACTIVATION=${context.productProperties.fastInstanceActivation}
IDS_MAIN_CLASS=${context.productProperties.mainClassName.replace('.', '/')}
""".trimIndent().trim())
val communityHome = context.paths.communityHome
val inputPath = "${communityHome}/platform/build-scripts/resources/win/launcher/WinLauncher.exe"
val outputPath = winDistPath.resolve("bin/${executableBaseName}.exe")
val classpath = ArrayList<String>()
val generatorClasspath = context.getModuleRuntimeClasspath(module = context.findRequiredModule("intellij.tools.launcherGenerator"),
forTests = false)
classpath.addAll(generatorClasspath)
sequenceOf(context.findApplicationInfoModule(), context.findRequiredModule("intellij.platform.icons"))
.flatMap { it.sourceRoots }
.forEach { root ->
classpath.add(root.file.absolutePath)
}
for (p in context.productProperties.brandingResourcePaths) {
classpath.add(p.toString())
}
classpath.add(icoFilesDirectory.toString())
runJava(
context = context,
mainClass = "com.pme.launcher.LauncherGeneratorMain",
args = listOf(
inputPath,
appInfoForLauncher.toString(),
"$communityHome/native/WinLauncher/resource.h",
launcherPropertiesPath.toString(),
outputPath.toString(),
),
jvmArgs = listOf("-Djava.awt.headless=true"),
classPath = classpath
)
}
}
/**
* Generates ApplicationInfo.xml file for launcher generator which contains link to proper *.ico file.
* todo pass path to ico file to LauncherGeneratorMain directly (probably after IDEA-196705 is fixed).
*/
private fun generateApplicationInfoForLauncher(appInfo: String, icoFilesDirectory: Path): Path {
val patchedFile = context.paths.tempDir.resolve("win-launcher-application-info.xml")
if (icoFile == null) {
Files.writeString(patchedFile, appInfo)
return patchedFile
}
Files.createDirectories(icoFilesDirectory)
Files.copy(icoFile, icoFilesDirectory.resolve(icoFile.fileName), StandardCopyOption.REPLACE_EXISTING)
val root = JDOMUtil.load(appInfo)
// do not use getChild - maybe null due to namespace
val iconElement = root.content.firstOrNull { it is Element && it.name == "icon" }
?: throw RuntimeException("`icon` element not found in $appInfo:\n${appInfo}")
(iconElement as Element).setAttribute("ico", icoFile.fileName.toString())
JDOMUtil.write(root, patchedFile)
return patchedFile
}
}
private fun createBuildWinZipTask(jreDirectoryPaths: List<Path>,
@Suppress("SameParameterValue") zipNameSuffix: String,
winDistPath: Path,
customizer: WindowsDistributionCustomizer,
context: BuildContext): ForkJoinTask<Path> {
val baseName = context.productProperties.getBaseArtifactName(context.applicationInfo, context.buildNumber)
val targetFile = context.paths.artifactDir.resolve("${baseName}${zipNameSuffix}.zip")
return createTask(spanBuilder("build Windows ${zipNameSuffix}.zip distribution")
.setAttribute("targetFile", targetFile.toString())) {
val productJsonDir = context.paths.tempDir.resolve("win.dist.product-info.json.zip$zipNameSuffix")
generateProductJson(productJsonDir, !jreDirectoryPaths.isEmpty(), context)
val zipPrefix = customizer.getRootDirectoryName(context.applicationInfo, context.buildNumber)
val dirs = listOf(context.paths.distAllDir, winDistPath, productJsonDir) + jreDirectoryPaths
zipWithPrefixes(context = context,
targetFile = targetFile,
map = dirs.associateWithTo(LinkedHashMap(dirs.size)) { zipPrefix },
compress = true)
checkInArchive(archiveFile = targetFile, pathInArchive = zipPrefix, context = context)
context.notifyArtifactWasBuilt(targetFile)
targetFile
}
}
private fun generateProductJson(targetDir: Path, isJreIncluded: Boolean, context: BuildContext): String {
val launcherPath = "bin/${context.productProperties.baseFileName}64.exe"
val vmOptionsPath = "bin/${context.productProperties.baseFileName}64.exe.vmoptions"
val javaExecutablePath = if (isJreIncluded) "jbr/bin/java.exe" else null
val file = targetDir.resolve(PRODUCT_INFO_FILE_NAME)
Files.createDirectories(targetDir)
val json = generateMultiPlatformProductJson(
"bin",
context.builtinModule,
listOf(
ProductInfoLaunchData(
os = OsFamily.WINDOWS.osName,
launcherPath = launcherPath,
javaExecutablePath = javaExecutablePath,
vmOptionsFilePath = vmOptionsPath,
startupWmClass = null,
)
), context)
Files.writeString(file, json)
return json
}
private fun toDosLineEndings(x: String): String {
return x.replace("\r", "").replace("\n", "\r\n")
}
| platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/WindowsDistributionBuilder.kt | 3521900989 |
/*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko
import org.jetbrains.android.anko.config.DefaultAnkoConfiguration
import org.jetbrains.android.anko.utils.AndroidVersionDirectoryFilter
import org.jetbrains.android.anko.utils.JarFileFilter
import java.io.File
fun main(args: Array<String>) {
if (args.isNotEmpty()) {
args.forEach { taskName ->
println(":: $taskName")
when (taskName) {
"gen", "generate" -> gen()
"clean" -> clean()
"versions" -> versions()
else -> {
println("Invalid task $taskName")
return
}
}
}
println("Done.")
} else gen()
}
private fun clean() {
deleteDirectory(File("workdir/gen/"))
}
private fun versions() {
for (version in getVersions()) {
val jars = getJars(version)
println("${version.getName()}")
jars?.forEach { println(" ${it.name}") }
}
}
private fun deleteDirectory(f: File) {
if (!f.exists()) return
if (f.isDirectory()) {
f.listFiles()?.forEach { deleteDirectory(it) }
}
if (!f.delete()) {
throw RuntimeException("Failed to delete ${f.getAbsolutePath()}")
}
}
private fun getVersions(): Array<File> {
val original = File("workdir/original/")
if (!original.exists() || !original.isDirectory()) {
throw RuntimeException("\"workdir/original\" directory does not exist.")
}
return original.listFiles(AndroidVersionDirectoryFilter()) ?: arrayOf<File>()
}
private fun getJars(version: File) = version.listFiles(JarFileFilter())
private fun gen() {
for (version in getVersions()) {
val jars = getJars(version)?.map { it.getAbsolutePath() } ?: listOf<String>()
val intVersion = parseVersion(version.getName())
if (intVersion != null && jars.isNotEmpty()) {
println("Processing version ${version.getName()}, jars: ${jars.joinToString()}")
val outputDirectory = "workdir/gen/${version.getName()}/"
val fileOutputDirectory = File("$outputDirectory/src/main/kotlin/")
if (!fileOutputDirectory.exists()) {
fileOutputDirectory.mkdirs()
}
DSLGenerator(intVersion, version.getName(), jars, DefaultAnkoConfiguration(outputDirectory)).run()
}
}
}
private fun parseVersion(name: String): Int? {
val prob = name.filter { it.isDigit() }
return if (prob.isNotEmpty()) prob.toInt() else null
} | dsl/src/org/jetbrains/android/anko/Main.kt | 350332740 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.intention.FileModifier
import com.intellij.codeInspection.*
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel
import com.intellij.codeInspection.util.InspectionMessage
import com.intellij.codeInspection.util.IntentionFamilyName
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiFile
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.formatter.TrailingCommaVisitor
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaContext
import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaHelper
import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaState
import org.jetbrains.kotlin.idea.formatter.trailingComma.addTrailingCommaIsAllowedFor
import org.jetbrains.kotlin.idea.formatter.trailingCommaAllowedInModule
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.idea.util.isComma
import org.jetbrains.kotlin.idea.util.isLineBreak
import org.jetbrains.kotlin.idea.util.leafIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import javax.swing.JComponent
import kotlin.properties.Delegates
class TrailingCommaInspection(
@JvmField
var addCommaWarning: Boolean = false
) : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : TrailingCommaVisitor() {
override val recursively: Boolean = false
private var useTrailingComma by Delegates.notNull<Boolean>()
override fun process(trailingCommaContext: TrailingCommaContext) {
val element = trailingCommaContext.ktElement
val kotlinCustomSettings = element.containingKtFile.kotlinCustomSettings
useTrailingComma = kotlinCustomSettings.addTrailingCommaIsAllowedFor(element)
when (trailingCommaContext.state) {
TrailingCommaState.MISSING, TrailingCommaState.EXISTS -> {
checkCommaPosition(element)
checkLineBreaks(element)
}
else -> Unit
}
checkTrailingComma(trailingCommaContext)
}
private fun checkLineBreaks(commaOwner: KtElement) {
val first = TrailingCommaHelper.elementBeforeFirstElement(commaOwner)
if (first?.nextLeaf(true)?.isLineBreak() == false) {
first.nextSibling?.let {
registerProblemForLineBreak(commaOwner, it, ProblemHighlightType.INFORMATION)
}
}
val last = TrailingCommaHelper.elementAfterLastElement(commaOwner)
if (last?.prevLeaf(true)?.isLineBreak() == false) {
registerProblemForLineBreak(
commaOwner,
last,
if (addCommaWarning) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION,
)
}
}
private fun checkCommaPosition(commaOwner: KtElement) {
for (invalidComma in TrailingCommaHelper.findInvalidCommas(commaOwner)) {
reportProblem(
invalidComma,
KotlinBundle.message("inspection.trailing.comma.comma.loses.the.advantages.in.this.position"),
KotlinBundle.message("inspection.trailing.comma.fix.comma.position")
)
}
}
private fun checkTrailingComma(trailingCommaContext: TrailingCommaContext) {
val commaOwner = trailingCommaContext.ktElement
val trailingCommaOrLastElement = TrailingCommaHelper.trailingCommaOrLastElement(commaOwner) ?: return
when (trailingCommaContext.state) {
TrailingCommaState.MISSING -> {
if (!trailingCommaAllowedInModule(commaOwner)) return
reportProblem(
trailingCommaOrLastElement,
KotlinBundle.message("inspection.trailing.comma.missing.trailing.comma"),
KotlinBundle.message("inspection.trailing.comma.add.trailing.comma"),
if (addCommaWarning) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION,
)
}
TrailingCommaState.REDUNDANT -> {
reportProblem(
trailingCommaOrLastElement,
KotlinBundle.message("inspection.trailing.comma.useless.trailing.comma"),
KotlinBundle.message("inspection.trailing.comma.remove.trailing.comma"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
checkTrailingCommaSettings = false,
)
}
else -> Unit
}
}
private fun reportProblem(
commaOrElement: PsiElement,
@InspectionMessage message: String,
@IntentionFamilyName fixMessage: String,
highlightType: ProblemHighlightType = ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
checkTrailingCommaSettings: Boolean = true,
) {
val commaOwner = commaOrElement.parent as KtElement
// case for KtFunctionLiteral, where PsiWhiteSpace after KtTypeParameterList isn't included in this list
val problemOwner = commonParent(commaOwner, commaOrElement)
val highlightTypeWithAppliedCondition = highlightType.applyCondition(!checkTrailingCommaSettings || useTrailingComma)
// INFORMATION shouldn't be reported in batch mode
if (isOnTheFly || highlightTypeWithAppliedCondition != ProblemHighlightType.INFORMATION) {
holder.registerProblem(
problemOwner,
message,
highlightTypeWithAppliedCondition,
commaOrElement.textRangeOfCommaOrSymbolAfter.shiftLeft(problemOwner.startOffset),
createQuickFix(fixMessage, commaOwner),
)
}
}
private fun registerProblemForLineBreak(
commaOwner: KtElement,
elementForTextRange: PsiElement,
highlightType: ProblemHighlightType,
) {
val problemElement = commonParent(commaOwner, elementForTextRange)
val highlightTypeWithAppliedCondition = highlightType.applyCondition(useTrailingComma)
// INFORMATION shouldn't be reported in batch mode
if (isOnTheFly || highlightTypeWithAppliedCondition != ProblemHighlightType.INFORMATION) {
holder.registerProblem(
problemElement,
KotlinBundle.message("inspection.trailing.comma.missing.line.break"),
highlightTypeWithAppliedCondition,
TextRange.from(elementForTextRange.startOffset, 1).shiftLeft(problemElement.startOffset),
createQuickFix(KotlinBundle.message("inspection.trailing.comma.add.line.break"), commaOwner),
)
}
}
private fun commonParent(commaOwner: PsiElement, elementForTextRange: PsiElement): PsiElement =
PsiTreeUtil.findCommonParent(commaOwner, elementForTextRange)
?: throw KotlinExceptionWithAttachments("Common parent not found")
.withPsiAttachment("commaOwner", commaOwner)
.withAttachment("commaOwnerRange", commaOwner.textRange)
.withPsiAttachment("elementForTextRange", elementForTextRange)
.withAttachment("elementForTextRangeRange", elementForTextRange.textRange)
.withPsiAttachment("parent", commaOwner.parent)
.withAttachment("parentRange", commaOwner.parent.textRange)
private fun ProblemHighlightType.applyCondition(condition: Boolean): ProblemHighlightType = when {
isUnitTestMode() -> ProblemHighlightType.GENERIC_ERROR_OR_WARNING
condition -> this
else -> ProblemHighlightType.INFORMATION
}
private fun createQuickFix(
@IntentionFamilyName fixMessage: String,
commaOwner: KtElement,
): LocalQuickFix = ReformatTrailingCommaFix(commaOwner, fixMessage)
private val PsiElement.textRangeOfCommaOrSymbolAfter: TextRange
get() {
val textRange = textRange
if (isComma) return textRange
return nextLeaf()?.leafIgnoringWhitespaceAndComments(false)?.endOffset?.takeIf { it > 0 }?.let {
TextRange.create(it - 1, it).intersection(textRange)
} ?: TextRange.create(textRange.endOffset - 1, textRange.endOffset)
}
}
override fun createOptionsPanel(): JComponent = SingleCheckboxOptionsPanel(
KotlinBundle.message("inspection.trailing.comma.report.also.a.missing.comma"),
this,
"addCommaWarning",
)
class ReformatTrailingCommaFix(commaOwner: KtElement, @IntentionFamilyName private val fixMessage: String) : LocalQuickFix {
val commaOwnerPointer = commaOwner.createSmartPointer()
override fun getFamilyName(): String = fixMessage
override fun applyFix(project: Project, problemDescriptor: ProblemDescriptor) {
val element = commaOwnerPointer.element ?: return
val range = createFormatterTextRange(element)
val settings = CodeStyleSettingsManager.getInstance(project).cloneSettings(CodeStyle.getSettings(element.containingKtFile))
settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA = true
settings.kotlinCustomSettings.ALLOW_TRAILING_COMMA_ON_CALL_SITE = true
CodeStyle.doWithTemporarySettings(project, settings, Runnable {
CodeStyleManager.getInstance(project).reformatRange(element, range.startOffset, range.endOffset)
})
}
private fun createFormatterTextRange(commaOwner: KtElement): TextRange {
val startElement = TrailingCommaHelper.elementBeforeFirstElement(commaOwner) ?: commaOwner
val endElement = TrailingCommaHelper.elementAfterLastElement(commaOwner) ?: commaOwner
return TextRange.create(startElement.startOffset, endElement.endOffset)
}
override fun getFileModifierForPreview(target: PsiFile): FileModifier? {
val element = commaOwnerPointer.element ?: return null
return ReformatTrailingCommaFix(PsiTreeUtil.findSameElementInCopy(element, target), fixMessage)
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/TrailingCommaInspection.kt | 576785812 |
package org.thoughtcrime.securesms.components.settings.app.privacy.expire
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.NavHostFragment
import androidx.recyclerview.widget.RecyclerView
import com.dd.CircularProgressButton
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.settings.DSLConfiguration
import org.thoughtcrime.securesms.components.settings.DSLSettingsAdapter
import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment
import org.thoughtcrime.securesms.components.settings.DSLSettingsText
import org.thoughtcrime.securesms.components.settings.configure
import org.thoughtcrime.securesms.groups.ui.GroupChangeFailureReason
import org.thoughtcrime.securesms.groups.ui.GroupErrors
import org.thoughtcrime.securesms.util.ExpirationUtil
import org.thoughtcrime.securesms.util.ViewUtil
import org.thoughtcrime.securesms.util.livedata.ProcessState
import org.thoughtcrime.securesms.util.livedata.distinctUntilChanged
/**
* Depending on the arguments, can be used to set the universal expire timer, set expire timer
* for a individual or group recipient, or select a value and return it via result.
*/
class ExpireTimerSettingsFragment : DSLSettingsFragment(
titleId = R.string.PrivacySettingsFragment__disappearing_messages,
layoutId = R.layout.expire_timer_settings_fragment
) {
private lateinit var save: CircularProgressButton
private lateinit var viewModel: ExpireTimerSettingsViewModel
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
save = view.findViewById(R.id.timer_select_fragment_save)
save.setOnClickListener { viewModel.save() }
adjustListPaddingForSaveButton(view)
}
private fun adjustListPaddingForSaveButton(view: View) {
val recycler: RecyclerView = view.findViewById(R.id.recycler)
recycler.setPadding(recycler.paddingLeft, recycler.paddingTop, recycler.paddingRight, ViewUtil.dpToPx(80))
recycler.clipToPadding = false
}
override fun bindAdapter(adapter: DSLSettingsAdapter) {
val provider = ViewModelProvider(
NavHostFragment.findNavController(this).getViewModelStoreOwner(R.id.app_settings_expire_timer),
ExpireTimerSettingsViewModel.Factory(requireContext(), arguments.toConfig())
)
viewModel = provider.get(ExpireTimerSettingsViewModel::class.java)
viewModel.state.observe(viewLifecycleOwner) { state ->
adapter.submitList(getConfiguration(state).toMappingModelList())
}
viewModel.state.distinctUntilChanged(ExpireTimerSettingsState::saveState).observe(viewLifecycleOwner) { state ->
when (val saveState: ProcessState<Int> = state.saveState) {
is ProcessState.Working -> {
save.isClickable = false
save.isIndeterminateProgressMode = true
save.progress = 50
}
is ProcessState.Success -> {
if (state.isGroupCreate) {
requireActivity().setResult(Activity.RESULT_OK, Intent().putExtra(FOR_RESULT_VALUE, saveState.result))
}
save.isClickable = false
requireActivity().onNavigateUp()
}
is ProcessState.Failure -> {
val groupChangeFailureReason: GroupChangeFailureReason = saveState.throwable?.let(GroupChangeFailureReason::fromException) ?: GroupChangeFailureReason.OTHER
Toast.makeText(context, GroupErrors.getUserDisplayMessage(groupChangeFailureReason), Toast.LENGTH_LONG).show()
viewModel.resetError()
}
else -> {
save.isClickable = true
save.isIndeterminateProgressMode = false
save.progress = 0
}
}
}
}
private fun getConfiguration(state: ExpireTimerSettingsState): DSLConfiguration {
return configure {
textPref(
summary = DSLSettingsText.from(
if (state.isForRecipient) {
R.string.ExpireTimerSettingsFragment__when_enabled_new_messages_sent_and_received_in_this_chat_will_disappear_after_they_have_been_seen
} else {
R.string.ExpireTimerSettingsFragment__when_enabled_new_messages_sent_and_received_in_new_chats_started_by_you_will_disappear_after_they_have_been_seen
}
)
)
val labels: Array<String> = resources.getStringArray(R.array.ExpireTimerSettingsFragment__labels)
val values: Array<Int> = resources.getIntArray(R.array.ExpireTimerSettingsFragment__values).toTypedArray()
var hasCustomValue = true
labels.zip(values).forEach { (label, value) ->
radioPref(
title = DSLSettingsText.from(label),
isChecked = state.currentTimer == value,
onClick = { viewModel.select(value) }
)
hasCustomValue = hasCustomValue && state.currentTimer != value
}
radioPref(
title = DSLSettingsText.from(R.string.ExpireTimerSettingsFragment__custom_time),
summary = if (hasCustomValue) DSLSettingsText.from(ExpirationUtil.getExpirationDisplayValue(requireContext(), state.currentTimer)) else null,
isChecked = hasCustomValue,
onClick = { NavHostFragment.findNavController(this@ExpireTimerSettingsFragment).navigate(R.id.action_expireTimerSettingsFragment_to_customExpireTimerSelectDialog) }
)
}
}
companion object {
const val FOR_RESULT_VALUE = "for_result_value"
}
}
private fun Bundle?.toConfig(): ExpireTimerSettingsViewModel.Config {
if (this == null) {
return ExpireTimerSettingsViewModel.Config()
}
val safeArguments: ExpireTimerSettingsFragmentArgs = ExpireTimerSettingsFragmentArgs.fromBundle(this)
return ExpireTimerSettingsViewModel.Config(
recipientId = safeArguments.recipientId,
forResultMode = safeArguments.forResultMode,
initialValue = safeArguments.initialValue
)
}
| app/src/main/java/org/thoughtcrime/securesms/components/settings/app/privacy/expire/ExpireTimerSettingsFragment.kt | 2444599083 |
package com.gmail.htaihm.playdatabinding
import android.content.Context
import android.content.Intent
import android.databinding.DataBindingUtil
import android.databinding.ObservableInt
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.gmail.htaihm.playdatabinding.databinding.ActivityHeroBinding
class HeroActivity : AppCompatActivity() {
companion object {
const val ARG_HERO_ID = "hero_id"
fun createIntent(context: Context, heroId: String) : Intent {
// HeroActivity.javaClass is actually a static method, which gets the class of "this" object, which is
// HeroActivity.companion in this class, which is wrong.
val intent = Intent(context, HeroActivity::class.java)
intent.putExtra(ARG_HERO_ID, heroId)
return intent
}
}
private lateinit var heroVO: HeroVO
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: ActivityHeroBinding = DataBindingUtil.setContentView(this, R.layout.activity_hero)
val bundle = requireNotNull(intent.extras)
val heroId = bundle.getString(ARG_HERO_ID, "")
val repository = HeroesRepository.getInstance(applicationContext)
repository.getHero(heroId)?.let {
hero ->
heroVO = HeroVO(hero.id, hero.name, ObservableInt(hero.matches), hero.abilities)
binding.heroVO = heroVO
binding.increaseMatches.setOnClickListener {
heroVO.matches.set(heroVO.matches.get() + 1)
}
}
}
}
| android/jetpack/PlayDataBinding/app/src/main/java/com/gmail/htaihm/playdatabinding/HeroActivity.kt | 4205919449 |
object SimpleSingleton
interface SomeInterface {
fun doSomething(foo: String) {}
}
val someInterface = object : SomeInterface {
override fun doSomething(foo: String) {
super.doSomething(foo)
}
}
class SomeClass private constructor() {
private val id = "id"
companion object Factory : SomeInterface {
const val someVal = "val"
fun foo() {}
fun createSomeClass() = SomeClass()
override fun doSomething(foo: String) {
super.doSomething(foo)
}
}
}
fun main(args: Array<String>) {
SomeClass.foo()
val transient = object {
val prop = "foo"
}
println(transient.prop)
} | kotlin/Mastering-Kotlin-master/Chapter04/src/Object.kt | 3030995084 |
package com.fruitscale.ananas.store
import android.content.Context
import com.fruitscale.ananas.exception.config.InvalidCredentialsJsonException
import com.fruitscale.ananas.util.toList
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.debug
import org.json.JSONArray
import org.json.JSONObject
import org.matrix.androidsdk.HomeserverConnectionConfig
/**
* Use this class to retrieve and remove credentials from the preferences
*/
class LoginStorage(val context: Context): AnkoLogger {
companion object {
val PREFERENCES_LOGIN = "Ananas.LoginStorage"
val PREFERENCES_KEY_CONNECTION_CONFIGS = "PREFERENCES_KEY_CONNECTION_CONFIGS"
}
private fun getPreferences() = context.getSharedPreferences(PREFERENCES_LOGIN, Context.MODE_PRIVATE)
/**
* Get all the credentials from the preferences
*
* @return A list containing all the credentials
*/
fun getCredentials(): List<HomeserverConnectionConfig> {
val jsonString = getPreferences().getString(PREFERENCES_KEY_CONNECTION_CONFIGS, null)
?: return arrayListOf()
debug { "Received login json" }
val jsonArray = JSONArray(jsonString)
return jsonArray.toList().map {
if(it is JSONObject) {
HomeserverConnectionConfig.fromJson(it)
} else {
throw InvalidCredentialsJsonException()
}
}
}
/**
* Save [credentials] to the preferences
*
* @param credentials The credentials
*/
private fun putCredentials(credentials: List<HomeserverConnectionConfig>) {
val serialized = JSONArray(credentials.map { it.toJson() }).toString()
val editor = getPreferences().edit()
editor.putString(PREFERENCES_KEY_CONNECTION_CONFIGS, serialized)
editor.apply()
}
/**
* Add credentials to the preferences
*
* @param config The credentials
*/
fun addCredentials(config: HomeserverConnectionConfig) {
if(config.credentials == null) {
return
}
val credentials = getCredentials().map { it }.plus(config)
putCredentials(credentials)
}
/**
* remove credentials to the preferences
*
* @param config The credentials
*/
fun removeCredentials(config: HomeserverConnectionConfig) {
if(config.credentials == null) {
return
}
val credentials = getCredentials().filter { it.credentials.userId != config.credentials.userId }
putCredentials(credentials)
}
/**
* Replace credentials in the preferences
*
* @param config The credentials
*/
fun replaceCredentials(config: HomeserverConnectionConfig) {
if(config.credentials == null) {
return
}
val credentials = getCredentials().filter { it.credentials.userId != config.credentials.userId }.plus(config)
putCredentials(credentials)
}
/**
* Remove all the credentials from the preferences
*/
fun removeAllCredentials() {
val editor = getPreferences().edit()
editor.remove(PREFERENCES_KEY_CONNECTION_CONFIGS)
editor.apply()
}
} | app/src/main/java/com/fruitscale/ananas/store/LoginStorage.kt | 2355673359 |
/*
* Copyright 2019 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.subscriptions.ui
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ProgressBar
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.leanback.app.BackgroundManager
import androidx.leanback.app.DetailsSupportFragment
import androidx.leanback.widget.Action
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.ClassPresenterSelector
import androidx.leanback.widget.DetailsOverviewRow
import androidx.leanback.widget.FullWidthDetailsOverviewRowPresenter
import androidx.leanback.widget.SparseArrayObjectAdapter
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.example.subscriptions.R
import com.example.subscriptions.billing.isAccountHold
import com.example.subscriptions.billing.isBasicContent
import com.example.subscriptions.billing.isGracePeriod
import com.example.subscriptions.billing.isPremiumContent
import com.example.subscriptions.billing.isSubscriptionRestore
import com.example.subscriptions.billing.isTransferRequired
import com.example.subscriptions.data.SubscriptionContent
import com.example.subscriptions.data.SubscriptionStatus
import com.example.subscriptions.presenter.SubscriptionDetailsPresenter
import com.example.subscriptions.utils.basicTextForSubscription
import com.example.subscriptions.utils.premiumTextForSubscription
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
/**
* TvMainFragment implements DetailsSupportFragment to provide an Android TV optimized experience to the user.
* The class creates a Presenter and adds a DetailsOverviewRow Leanback widget used to display metadata from
* a SubscriptionContent object.
*
*
* This Activity subscribes to StateFlow updates observed by its parent Activity in order to update the content
* available.
*/
class TvMainFragment : DetailsSupportFragment() {
companion object {
private const val ACTION_SUBSCRIBE_BASIC = 1
private const val ACTION_SUBSCRIBE_PREMIUM = 2
private const val ACTION_MANAGE_SUBSCRIPTIONS = 3
private const val ACTION_SIGN_IN_OUT = 4
private const val TAG = "TvMainFragment"
}
private lateinit var metrics: DisplayMetrics
private lateinit var presenterSelector: ClassPresenterSelector
private lateinit var objectAdapter: ArrayObjectAdapter
private lateinit var subscriptionContent: SubscriptionContent
private lateinit var backgroundManager: BackgroundManager
private lateinit var detailsOverviewRow: DetailsOverviewRow
private lateinit var authenticationViewModel: FirebaseUserViewModel
private lateinit var subscriptionsStatusViewModel: SubscriptionStatusViewModel
private lateinit var billingViewModel: BillingViewModel
private var basicSubscription: SubscriptionStatus? = null
private var premiumSubscription: SubscriptionStatus? = null
private lateinit var spinnerFragment: SpinnerFragment
/**
* Lifecycle call onCreate()
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
prepareBackgroundManager()
}
/**
* Lifecycle call onActivityCreated()
*/
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
// Creates default SubscriptionContent object
createSubscriptionContent()
authenticationViewModel =
ViewModelProviders.of(requireActivity()).get(FirebaseUserViewModel::class.java)
subscriptionsStatusViewModel =
ViewModelProviders.of(requireActivity()).get(SubscriptionStatusViewModel::class.java)
billingViewModel =
ViewModelProviders.of(requireActivity()).get(BillingViewModel::class.java)
spinnerFragment = SpinnerFragment()
// Update the UI whenever a user signs in / out
authenticationViewModel.firebaseUser.observe(requireActivity(), {
Log.d(TAG, "firebaseUser onChange()")
refreshUI()
})
// Show or hide a Spinner based on loading state
lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
subscriptionsStatusViewModel.loading.collect { isLoading ->
if (isLoading) {
parentFragmentManager.beginTransaction()
.replace(R.id.main_frame, spinnerFragment)
.commit()
Log.i(TAG, "loading spinner shown")
} else {
parentFragmentManager.beginTransaction()
.remove(spinnerFragment)
.commit()
Log.i(TAG, "loading spinner hidden")
}
}
}
}
// Updates subscription image for Basic plan
lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
subscriptionsStatusViewModel.basicContent.collect { content ->
Log.d(TAG, "basicContent onChange()")
content?.url?.let {
// If a premium subscription exists, don't update image with basic plan
if (premiumSubscription == null) {
updateSubscriptionImage(it)
}
}
}
}
}
// Updates subscription image for Premium plan
lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
subscriptionsStatusViewModel.premiumContent.collect { content ->
content?.url?.let {
updateSubscriptionImage(it)
}
}
}
}
// Updates subscription details based on list of available subscriptions
lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
subscriptionsStatusViewModel.subscriptions.collect {
Log.d(TAG, "subscriptions onChange()")
updateSubscriptionDetails(it)
}
}
}
}
/**
* Lifecycle call onResume()
*/
override fun onResume() {
super.onResume()
updateBackground()
}
/**
* Lifecycle call onPause()
*/
override fun onPause() {
backgroundManager.release()
super.onPause()
}
/**
* Creates a SubscriptionContent object used for populating information about a Subscription.
*/
private fun createSubscriptionContent() {
subscriptionContent = SubscriptionContent.Builder()
.title(getString(R.string.app_name))
.subtitle(getString(R.string.paywall_message))
.build()
}
/**
* Prepares BackgroundManager class used for updating the backdrop image.
*/
private fun prepareBackgroundManager() {
backgroundManager = BackgroundManager.getInstance(requireActivity())
backgroundManager.attach(requireActivity().window)
metrics = DisplayMetrics()
requireActivity().windowManager.defaultDisplay.getMetrics(metrics)
}
/**
* Updates the background image used as backdrop.
*/
private fun updateBackground() {
val options = RequestOptions()
.fitCenter()
.dontAnimate()
Glide.with(this)
.asBitmap()
.load(R.drawable.tv_background_img)
.apply(options)
.into(object : SimpleTarget<Bitmap>(metrics.widthPixels, metrics.heightPixels) {
/**
* The method that will be called when the resource load has finished.
*
* @param resource the loaded resource.
*/
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
backgroundManager.setBitmap(resource)
}
})
}
/**
* Updates Subscription details based on the provided list of subscriptions retrieved from the server
*/
private fun updateSubscriptionDetails(subscriptionStatuses: List<SubscriptionStatus>?) {
// Clear out any previously cached subscriptions
basicSubscription = null
premiumSubscription = null
// Create new SubscriptionContent builder and populate with metadata from SubscriptionStatus list
val subscriptionContentBuilder = SubscriptionContent.Builder()
subscriptionContentBuilder.title(getString(R.string.app_name))
if (subscriptionStatuses != null && subscriptionStatuses.isNotEmpty()) {
Log.d(TAG, "We have subscriptions!")
// Iterate through the list of subscriptions to build our SubscriptionContent object
for (subscription in subscriptionStatuses) {
// Basic Plan
if (subscription.isBasicContent) {
Log.d(TAG, "basic subscription found")
// Update our builder object
subscriptionContentBuilder.subtitle(getString(R.string.basic_auto_message))
subscriptionContentBuilder.description(getString(R.string.basic_content_text))
// Cache the subscription in a global member variable
basicSubscription = subscription
}
// Premium Plan
if (isPremiumContent(subscription)) {
Log.d(TAG, "premium subscription found")
// Update our builder object
subscriptionContentBuilder.subtitle(getString(R.string.premium_auto_message))
subscriptionContentBuilder.description(getString(R.string.premium_content_text))
// Cache the subscription in a global member variable
premiumSubscription = subscription
}
// Subscription restore
if (isSubscriptionRestore(subscription)) {
Log.d(TAG, "subscription restore")
val expiryDate = getHumanReadableDate(subscription.activeUntilMillisec)
val subtitleText = getString(R.string.restore_message_with_date, expiryDate)
subscriptionContentBuilder.subtitle(subtitleText)
subscriptionContentBuilder.description(null)
}
// Account in grace period
if (isGracePeriod(subscription)) {
Log.d(TAG, "account in grace period")
subscriptionContentBuilder.subtitle(getString(R.string.grace_period_message))
subscriptionContentBuilder.description(null)
}
// Account transfer
if (isTransferRequired(subscription)) {
Log.d(TAG, "account transfer required")
subscriptionContentBuilder.subtitle(getString(R.string.transfer_message))
subscriptionContentBuilder.description(null)
}
// Account on hold
if (isAccountHold(subscription)) {
Log.d(TAG, "account on hold")
subscriptionContentBuilder.subtitle(getString(R.string.account_hold_message))
subscriptionContentBuilder.description(null)
}
}
} else {
// Default message to display when there are no subscriptions available
subscriptionContentBuilder.subtitle(getString(R.string.paywall_message))
}
// Refresh the UI
refreshUI()
detailsOverviewRow.item = subscriptionContentBuilder.build()
}
/**
* Updates DetailOverviewRow's image using the provided URL.
*/
private fun updateSubscriptionImage(url: String) {
val options = RequestOptions()
.fitCenter()
.dontAnimate()
Glide.with(requireActivity())
.asBitmap()
.load(url)
.apply(options)
.into(object : SimpleTarget<Bitmap>() {
/**
* The method that will be called when the resource load has finished.
*
* @param resource the loaded resource.
*/
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
detailsOverviewRow.setImageBitmap(requireActivity(), resource)
}
})
}
/**
* Creates a ClassPresenterSelector, adds a styled FullWidthDetailsOverviewRowPresenter with
* an OnActionClickedListener to handle click events for the available Actions.
*/
private fun setupAdapter() {
// Set detail background and style.
val detailsPresenter = FullWidthDetailsOverviewRowPresenter(SubscriptionDetailsPresenter())
detailsPresenter.backgroundColor =
ContextCompat.getColor(requireActivity(), R.color.primaryColor)
detailsPresenter.initialState = FullWidthDetailsOverviewRowPresenter.STATE_SMALL
detailsPresenter.alignmentMode = FullWidthDetailsOverviewRowPresenter.ALIGN_MODE_MIDDLE
// Set OnActionClickListener to handle Action click events
detailsPresenter.setOnActionClickedListener { action ->
if (action.id == ACTION_SUBSCRIBE_BASIC.toLong()) {
// TODO(232165789): update with new method calls
// Subscribe to basic plan
// billingViewModel.buyBasic()
} else if (action.id == ACTION_SUBSCRIBE_PREMIUM.toLong()) {
// If a basic subscription exists, handle as an upgrade to premium
// else, handle as a new subscription to premium
// if (basicSubscription != null) {
// billingViewModel.buyUpgrade()
// } else {
// billingViewModel.buyPremium()
// }
} else if (action.id == ACTION_MANAGE_SUBSCRIPTIONS.toLong()) {
// Launch Activity to manage subscriptions
startActivity(Intent(requireActivity(), TvManageSubscriptionsActivity::class.java))
} else if (action.id == ACTION_SIGN_IN_OUT.toLong()) {
// Handle sign-in / sign-out event based on current state
if (authenticationViewModel.isSignedIn()) {
(requireActivity() as TvMainActivity).triggerSignOut()
} else {
(requireActivity() as TvMainActivity).triggerSignIn()
}
}
}
// Create ClassPresenter, add the DetailsPresenter and bind to its adapter
presenterSelector = ClassPresenterSelector()
presenterSelector.addClassPresenter(DetailsOverviewRow::class.java, detailsPresenter)
objectAdapter = ArrayObjectAdapter(presenterSelector)
adapter = objectAdapter
}
/**
* Creates a DetailsOverviewRow and adds Action buttons to the layout
*/
private fun setupDetailsOverviewRow() {
// Create DetailsOverviewRow widget
detailsOverviewRow = DetailsOverviewRow(subscriptionContent)
// Create Action Adapter
val actionAdapter = SparseArrayObjectAdapter()
// Add Basic Plan Action button
actionAdapter.set(
ACTION_SUBSCRIBE_BASIC, Action(
ACTION_SUBSCRIBE_BASIC.toLong(),
if (basicSubscription != null)
basicTextForSubscription(resources, basicSubscription!!)
else
resources.getString(R.string.subscription_option_basic_message)
)
)
// Add Premium Plan Action button
actionAdapter.set(
ACTION_SUBSCRIBE_PREMIUM, Action(
ACTION_SUBSCRIBE_PREMIUM.toLong(),
if (premiumSubscription != null)
premiumTextForSubscription(resources, premiumSubscription!!)
else
resources.getString(R.string.subscription_option_premium_message)
)
)
// Add Manage Subscriptions Action button
actionAdapter.set(
ACTION_MANAGE_SUBSCRIPTIONS, Action(
ACTION_MANAGE_SUBSCRIPTIONS.toLong(),
resources.getString(R.string.manage_subscription_label)
)
)
// Add Sign in / out Action button
actionAdapter.set(
ACTION_SIGN_IN_OUT, Action(
ACTION_SIGN_IN_OUT.toLong(),
if (authenticationViewModel.isSignedIn())
getString(R.string.sign_out)
else
getString(R.string.sign_in)
)
)
// Set Action Adapter and add DetailsOverviewRow to Presenter class
detailsOverviewRow.actionsAdapter = actionAdapter
objectAdapter.add(detailsOverviewRow)
}
/**
* Refreshes the UI
*/
private fun refreshUI() {
setupAdapter()
setupDetailsOverviewRow()
}
/**
* Custom Fragment used for displaying a Spinner during long running tasks (e.g. network requests)
*/
class SpinnerFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val progressBar = ProgressBar(container?.context)
if (container is FrameLayout) {
val res = resources
val width = res.getDimensionPixelSize(R.dimen.spinner_width)
val height = res.getDimensionPixelSize(R.dimen.spinner_height)
val layoutParams = FrameLayout.LayoutParams(width, height, Gravity.CENTER)
progressBar.layoutParams = layoutParams
}
return progressBar
}
}
}
| ClassyTaxiAppKotlin/app/src/main/java/com/example/subscriptions/ui/TvMainFragment.kt | 1182218743 |
package net.squanchy.tweets
import androidx.appcompat.app.AppCompatActivity
import dagger.Component
import net.squanchy.injection.BaseActivityComponentBuilder
import net.squanchy.injection.ActivityLifecycle
import net.squanchy.injection.ApplicationComponent
import net.squanchy.injection.applicationComponent
import net.squanchy.navigation.NavigationModule
import net.squanchy.navigation.Navigator
import net.squanchy.tweets.service.TwitterService
internal fun twitterComponent(activity: AppCompatActivity): TwitterComponent =
DaggerTwitterComponent.builder()
.applicationComponent(activity.applicationComponent)
.activity(activity)
.build()
@ActivityLifecycle
@Component(
modules = [(TwitterModule::class), (NavigationModule::class)],
dependencies = [(ApplicationComponent::class)]
)
internal interface TwitterComponent {
fun service(): TwitterService
fun navigator(): Navigator
@Component.Builder
interface Builder : BaseActivityComponentBuilder<TwitterComponent>
}
| app/src/main/java/net/squanchy/tweets/TwitterComponent.kt | 490554639 |
/*
* Copyright (c) 2017
*
* 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.acra.config
/**
* A [Configuration] builder
*
* @author F43nd1r
* @since 01.06.2017
*/
interface ConfigurationBuilder {
/**
* Builds the configuration
*
* @return the fully configured and immutable configuration
* @throws ACRAConfigurationException if the configuration is invalid
*/
@Throws(ACRAConfigurationException::class)
fun build(): Configuration
} | acra-core/src/main/java/org/acra/config/ConfigurationBuilder.kt | 4025123036 |
package io.ipoli.android.planday.scenes
import android.content.res.ColorStateList
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.support.annotation.ColorRes
import android.support.v4.widget.TextViewCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.text.SpannableString
import android.text.style.StrikethroughSpan
import android.view.*
import android.widget.TextView
import com.mikepenz.google_material_typeface_library.GoogleMaterial
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.IIcon
import com.mikepenz.ionicons_typeface_library.Ionicons
import io.ipoli.android.Constants
import io.ipoli.android.R
import io.ipoli.android.common.ViewUtils
import io.ipoli.android.common.redux.android.BaseViewController
import io.ipoli.android.common.text.QuestStartTimeFormatter
import io.ipoli.android.common.view.*
import io.ipoli.android.common.view.recyclerview.BaseRecyclerViewAdapter
import io.ipoli.android.common.view.recyclerview.RecyclerViewViewModel
import io.ipoli.android.common.view.recyclerview.SimpleSwipeCallback
import io.ipoli.android.common.view.recyclerview.SimpleViewHolder
import io.ipoli.android.pet.AndroidPetAvatar
import io.ipoli.android.pet.PetState
import io.ipoli.android.planday.PlanDayAction
import io.ipoli.android.planday.PlanDayReducer
import io.ipoli.android.planday.PlanDayViewState
import io.ipoli.android.planday.PlanDayViewState.StateType.*
import io.ipoli.android.quest.schedule.addquest.AddQuestAnimationHelper
import kotlinx.android.synthetic.main.controller_plan_day_today.view.*
import kotlinx.android.synthetic.main.item_plan_today_quest.view.*
import kotlinx.android.synthetic.main.item_plan_today_suggestion.view.*
import kotlinx.android.synthetic.main.view_empty_list.view.*
import kotlinx.android.synthetic.main.view_loader.view.*
import org.threeten.bp.LocalDate
class PlanDayTodayViewController(args: Bundle? = null) :
BaseViewController<PlanDayAction, PlanDayViewState>(args) {
override val stateKey = PlanDayReducer.stateKey
private lateinit var addQuestAnimationHelper: AddQuestAnimationHelper
override var helpConfig: HelpConfig? =
HelpConfig(
R.string.help_dialog_plan_day_today_title,
R.string.help_dialog_plan_day_today_message
)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup,
savedViewState: Bundle?
): View {
setHasOptionsMenu(true)
val view = container.inflate(R.layout.controller_plan_day_today)
setToolbar(view.toolbar)
val collapsingToolbar = view.collapsingToolbarContainer
collapsingToolbar.isTitleEnabled = false
view.toolbar.title = stringRes(R.string.plan_my_day)
view.todayQuests.layoutManager =
LinearLayoutManager(
container.context,
LinearLayoutManager.VERTICAL,
false
)
view.todayQuests.adapter = QuestAdapter()
view.suggestionQuests.layoutManager =
LinearLayoutManager(
container.context,
LinearLayoutManager.VERTICAL,
false
)
view.suggestionQuests.adapter = SuggestionAdapter()
initSwipe(view)
initAddQuest(view)
initEmptyView(view)
view.descriptionIcon.setImageDrawable(
IconicsDrawable(activity!!)
.icon(GoogleMaterial.Icon.gmd_info_outline)
.color(attrData(R.attr.colorAccent))
.sizeDp(24)
)
view.importFromBucketList.onDebounceClick {
navigate().toBucketListPicker { qs ->
dispatch(PlanDayAction.MoveBucketListQuestsToToday(qs))
}
}
return view
}
private fun initSwipe(view: View) {
val swipeHandler = object : SimpleSwipeCallback(
R.drawable.ic_event_white_24dp,
R.color.md_blue_500,
R.drawable.ic_delete_white_24dp,
R.color.md_red_500
) {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val questId = questId(viewHolder)
if (direction == ItemTouchHelper.END) {
navigate()
.toReschedule(
includeToday = false,
listener = { date, time, duration ->
dispatch(
PlanDayAction.RescheduleQuest(
questId,
date,
time,
duration
)
)
},
cancelListener = {
view.todayQuests.adapter.notifyItemChanged(viewHolder.adapterPosition)
}
)
} else {
dispatch(PlanDayAction.RemoveQuest(questId))
PetMessagePopup(
stringRes(R.string.remove_quest_undo_message),
{ dispatch(PlanDayAction.UndoRemoveQuest(questId)) },
stringRes(R.string.undo)
).show(view.context)
}
}
private fun questId(holder: RecyclerView.ViewHolder): String {
val adapter = view.todayQuests.adapter as QuestAdapter
val item = adapter.getItemAt(holder.adapterPosition)
return item.id
}
override fun getSwipeDirs(
recyclerView: RecyclerView?,
viewHolder: RecyclerView.ViewHolder?
) = ItemTouchHelper.START or ItemTouchHelper.END
}
val itemTouchHelper = ItemTouchHelper(swipeHandler)
itemTouchHelper.attachToRecyclerView(view.todayQuests)
}
private fun initAddQuest(view: View) {
addQuestAnimationHelper = AddQuestAnimationHelper(
controller = this,
addContainer = view.addContainer,
fab = view.addQuest,
background = view.addContainerBackground
)
view.addContainerBackground.onDebounceClick {
addContainerRouter(view).popCurrentController()
ViewUtils.hideKeyboard(view)
addQuestAnimationHelper.closeAddContainer()
}
view.addQuest.onDebounceClick {
addQuestAnimationHelper.openAddContainer(LocalDate.now())
}
}
private fun addContainerRouter(view: View) =
getChildRouter(view.addContainer, "add-quest")
private fun initEmptyView(view: View) {
view.emptyAnimation.gone()
view.emptyTitle.setText(R.string.empty_plan_today_list_title)
view.emptyText.setText(R.string.empty_plan_today_list_text)
}
override fun onAttach(view: View) {
super.onAttach(view)
exitFullScreen()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.plan_day_today_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
dispatch(PlanDayAction.Back)
return true
}
if (item.itemId == R.id.actionDone) {
dispatch(PlanDayAction.StartDay)
return true
}
return super.onOptionsItemSelected(item)
}
override fun onCreateLoadAction() = PlanDayAction.LoadToday
override fun render(state: PlanDayViewState, view: View) {
when (state.type) {
TODAY_DATA_LOADED -> {
view.loader.gone()
(view.todayQuests.adapter as QuestAdapter).updateAll(state.todayViewModels)
if (state.todayQuests!!.isEmpty()) {
view.dailyQuestsTitle.gone()
view.timelineIndicator.gone()
view.emptyContainer.visible()
view.emptyAnimation.playAnimation()
} else {
view.dailyQuestsTitle.visible()
view.timelineIndicator.visible()
view.emptyContainer.gone()
view.emptyAnimation.pauseAnimation()
}
(view.suggestionQuests.adapter as SuggestionAdapter).updateAll(state.suggestionViewModels)
if (state.suggestedQuests!!.isEmpty()) {
view.suggestionQuestsContainer.gone()
} else {
view.suggestionQuestsContainer.visible()
}
renderPet(view, state)
}
DAILY_CHALLENGE_QUESTS_CHANGED -> {
(view.todayQuests.adapter as QuestAdapter).updateAll(state.todayViewModels)
renderPet(view, state)
}
MAX_DAILY_CHALLENGE_QUESTS_REACHED ->
showShortToast(
stringRes(
R.string.max_daily_challenge_selected_message,
Constants.DAILY_CHALLENGE_QUEST_COUNT
)
)
DAY_STARTED -> {
dispatch(PlanDayAction.Done)
navigateFromRoot().setHome()
}
NOT_ENOUGH_DAILY_CHALLENGE_QUESTS ->
showShortToast(
stringRes(
R.string.not_enough_daily_challenge_quests_message,
Constants.DAILY_CHALLENGE_QUEST_COUNT - state.dailyChallengeQuestIds!!.size
)
)
else -> {
}
}
}
private fun renderTag(tagNameView: TextView, tag: TagViewModel) {
tagNameView.visible()
tagNameView.text = tag.name
TextViewCompat.setTextAppearance(
tagNameView,
R.style.TextAppearance_AppCompat_Caption
)
val indicator = tagNameView.compoundDrawablesRelative[0] as GradientDrawable
indicator.mutate()
val size = ViewUtils.dpToPx(8f, tagNameView.context).toInt()
indicator.setSize(size, size)
indicator.setColor(colorRes(tag.color))
tagNameView.setCompoundDrawablesRelativeWithIntrinsicBounds(
indicator,
null,
null,
null
)
}
private fun renderPet(view: View, state: PlanDayViewState) {
view.dailyChallengePet.setImageResource(state.petAvatarImage)
view.dailyChallengePetState.setImageResource(state.petAvatarStateImage)
view.dailyChallengePet.visible()
view.dailyChallengePetState.visible()
view.selectedQuestsCount.text = state.selectedCount
}
data class TagViewModel(val name: String, @ColorRes val color: Int)
data class QuestItem(
override val id: String,
val name: String,
val startTime: String,
@ColorRes val color: Int,
val tags: List<TagViewModel>,
val icon: IIcon,
val isRepeating: Boolean,
val isFromChallenge: Boolean,
val isForDailyChallenge: Boolean,
val isSelectableForDailyChallenge: Boolean,
val isCompleted: Boolean
) : RecyclerViewViewModel
data class SuggestionItem(
override val id: String,
val name: String,
val startTime: String,
val startTimeIcon: IIcon,
@ColorRes val color: Int,
val tags: List<TagViewModel>,
val icon: IIcon,
val isRepeating: Boolean,
val isFromChallenge: Boolean
) : RecyclerViewViewModel
inner class QuestAdapter :
BaseRecyclerViewAdapter<QuestItem>(R.layout.item_plan_today_quest) {
override fun onBindViewModel(vm: QuestItem, view: View, holder: SimpleViewHolder) {
if (vm.isCompleted) {
val span = SpannableString(vm.name)
span.setSpan(StrikethroughSpan(), 0, vm.name.length, 0)
view.questName.text = span
} else {
view.questName.text = vm.name
}
view.questIcon.backgroundTintList =
ColorStateList.valueOf(colorRes(vm.color))
view.questIcon.setImageDrawable(smallListItemIcon(vm.icon))
view.questStartTime.text = vm.startTime
view.questStartTime.setCompoundDrawablesRelativeWithIntrinsicBounds(
IconicsDrawable(view.context)
.icon(GoogleMaterial.Icon.gmd_timer)
.sizeDp(16)
.colorRes(colorTextSecondaryResource)
.respectFontBounds(true),
null, null, null
)
if (vm.tags.isNotEmpty()) {
renderTag(view.questTagName, vm.tags.first())
} else {
view.questTagName.gone()
}
view.questRepeatIndicator.visibility =
if (vm.isRepeating) View.VISIBLE else View.GONE
view.questChallengeIndicator.visibility =
if (vm.isFromChallenge) View.VISIBLE else View.GONE
if (vm.isForDailyChallenge && !vm.isSelectableForDailyChallenge) {
view.questStar.visible()
view.questStar.setImageResource(R.drawable.ic_star_grey_24dp)
view.questStar.setOnClickListener(null)
} else if (vm.isForDailyChallenge) {
view.questStar.visible()
view.questStar.setImageResource(R.drawable.ic_star_accent_24dp)
view.questStar.onDebounceClick {
dispatch(PlanDayAction.RemoveDailyChallengeQuest(vm.id))
}
} else if (vm.isSelectableForDailyChallenge) {
view.questStar.visible()
view.questStar.setImageResource(R.drawable.ic_star_border_text_secondary_24dp)
view.questStar.onDebounceClick {
dispatch(PlanDayAction.AddDailyChallengeQuest(vm.id))
}
} else {
view.questStar.gone()
}
}
}
inner class SuggestionAdapter :
BaseRecyclerViewAdapter<SuggestionItem>(R.layout.item_plan_today_suggestion) {
override fun onBindViewModel(vm: SuggestionItem, view: View, holder: SimpleViewHolder) {
view.suggestionName.text = vm.name
view.suggestionIcon.backgroundTintList =
ColorStateList.valueOf(colorRes(vm.color))
view.suggestionIcon.setImageDrawable(smallListItemIcon(vm.icon))
view.suggestionStartTime.text = vm.startTime
view.suggestionStartTime.setCompoundDrawablesRelativeWithIntrinsicBounds(
IconicsDrawable(view.context)
.icon(vm.startTimeIcon)
.sizeDp(16)
.colorRes(colorTextSecondaryResource)
.respectFontBounds(true),
null, null, null
)
if (vm.tags.isNotEmpty()) {
renderTag(view.suggestionTagName, vm.tags.first())
} else {
view.suggestionTagName.gone()
}
view.suggestionRepeatIndicator.visibility =
if (vm.isRepeating) View.VISIBLE else View.GONE
view.suggestionChallengeIndicator.visibility =
if (vm.isFromChallenge) View.VISIBLE else View.GONE
view.suggestionAccept.onDebounceClick {
dispatch(PlanDayAction.AcceptSuggestion(vm.id))
showShortToast(R.string.suggestion_accepted)
}
}
}
private val PlanDayViewState.suggestionViewModels: List<SuggestionItem>
get() =
suggestedQuests!!.map {
SuggestionItem(
id = it.id,
name = it.name,
tags = it.tags.map { t ->
TagViewModel(
t.name,
t.color.androidColor.color500
)
},
startTime = QuestStartTimeFormatter.formatWithDuration(
it,
activity!!,
shouldUse24HourFormat
),
startTimeIcon =
if (it.isScheduled)
GoogleMaterial.Icon.gmd_access_time
else
GoogleMaterial.Icon.gmd_timer,
color = it.color.androidColor.color500,
icon = it.icon?.androidIcon?.icon
?: Ionicons.Icon.ion_checkmark,
isRepeating = it.isFromRepeatingQuest,
isFromChallenge = it.isFromChallenge
)
}
private val PlanDayViewState.todayViewModels: List<QuestItem>
get() =
todayQuests!!.map {
QuestItem(
id = it.id,
name = it.name,
tags = it.tags.map { t ->
TagViewModel(
t.name,
t.color.androidColor.color500
)
},
startTime = QuestStartTimeFormatter.formatWithDuration(
it,
activity!!,
shouldUse24HourFormat
),
color = it.color.androidColor.color500,
icon = it.icon?.androidIcon?.icon
?: Ionicons.Icon.ion_checkmark,
isRepeating = it.isFromRepeatingQuest,
isFromChallenge = it.isFromChallenge,
isForDailyChallenge = dailyChallengeQuestIds!!.contains(it.id),
isSelectableForDailyChallenge = !isDailyChallengeCompleted,
isCompleted = it.isCompleted
)
}
private val PlanDayViewState.petAvatarImage: Int
get() = AndroidPetAvatar.valueOf(petAvatar!!.name).image
private val PlanDayViewState.petAvatarStateImage: Int
get() {
val stateImage = AndroidPetAvatar.valueOf(petAvatar!!.name).stateImage
return when (dailyChallengeQuestIds!!.size) {
3 -> stateImage[PetState.AWESOME]!!
2 -> stateImage[PetState.HAPPY]!!
1 -> stateImage[PetState.GOOD]!!
0 -> stateImage[PetState.SAD]!!
else -> throw IllegalStateException("Unexpected daily challenge quests count ${dailyChallengeQuestIds.size}")
}
}
private val PlanDayViewState.selectedCount: String
get() {
val count = dailyChallengeQuestIds!!.size
return if (count == Constants.DAILY_CHALLENGE_QUEST_COUNT) {
stringRes(R.string.daily_challenge_active)
} else {
stringRes(
R.string.selected_daily_challenge_count,
count,
Constants.DAILY_CHALLENGE_QUEST_COUNT
)
}
}
} | app/src/main/java/io/ipoli/android/planday/scenes/PlanDayTodayViewController.kt | 3421350110 |
/*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q
import com.fasterxml.jackson.module.kotlin.convertValue
import com.netflix.spinnaker.orca.api.pipeline.SyntheticStageOwner.STAGE_AFTER
import com.netflix.spinnaker.orca.api.pipeline.SyntheticStageOwner.STAGE_BEFORE
import com.netflix.spinnaker.orca.jackson.OrcaObjectMapper
import com.netflix.spinnaker.q.Message
import java.util.UUID
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
internal object MessageCompatibilityTest : Spek({
describe("deserializing ContinueParentStage") {
val mapper = OrcaObjectMapper.newInstance().apply {
registerSubtypes(ContinueParentStage::class.java)
}
val json = mapOf(
"kind" to "continueParentStage",
"executionType" to "PIPELINE",
"executionId" to UUID.randomUUID().toString(),
"application" to "covfefe",
"stageId" to UUID.randomUUID().toString()
)
given("an older message with no syntheticStageOwner") {
on("deserializing the JSON") {
val message = mapper.convertValue<Message>(json)
it("doesn't blow up") {
assertThat(message).isInstanceOf(ContinueParentStage::class.java)
}
it("defaults the missing field") {
assertThat((message as ContinueParentStage).phase).isEqualTo(STAGE_BEFORE)
}
}
}
given("a newer message with a syntheticStageOwner") {
val newJson = json + mapOf("phase" to "STAGE_AFTER")
on("deserializing the JSON") {
val message = mapper.convertValue<Message>(newJson)
it("doesn't blow up") {
assertThat(message).isInstanceOf(ContinueParentStage::class.java)
}
it("deserializes the new field") {
assertThat((message as ContinueParentStage).phase).isEqualTo(STAGE_AFTER)
}
}
}
}
})
| orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/MessageCompatibilityTest.kt | 1459517749 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.kotlin
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.UExpression
@ApiStatus.Internal
interface KotlinEvaluatableUElement : UExpression {
val baseResolveProviderService: BaseKotlinUastResolveProviderService
override fun evaluate(): Any? {
return baseResolveProviderService.evaluate(this)
}
}
| plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinEvaluatableUElement.kt | 613490771 |
package streams.sequence.filter
fun main(args: Array<String>) {
//Breakpoint!
booleanArrayOf(true, false, false).asSequence().filterNot { it }.lastIndexOf(true)
} | plugins/kotlin/jvm-debugger/test/testData/sequence/streams/sequence/filter/FilterNot.kt | 1683903099 |
// FIR_COMPARISON
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtClass
// OPTIONS: derivedClasses
open class <caret>A {
}
| plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinClassDerivedObjects.0.kt | 2002517893 |
package com.uramonk.androidtemplateapp.di.module
import android.util.Log
import com.ihsanbal.logging.Level
import com.ihsanbal.logging.LoggingInterceptor
import com.uramonk.androidtemplateapp.BuildConfig
import com.uramonk.androidtemplateapp.data.error.RxJava2ErrorHandlingCallAdapterFactory
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
/**
* Created by uramonk on 2016/06/29.
*/
@Module
class NetworkModule(private val baseUrl: String) {
@Provides
@Singleton
fun provideOkHttpClient(): OkHttpClient {
val builder = OkHttpClient.Builder()
if (BuildConfig.DEBUG) {
builder.addInterceptor(LoggingInterceptor.Builder()
.loggable(BuildConfig.DEBUG)
.setLevel(Level.BASIC)
.log(Log.INFO)
.request("Request")
.response("Response")
.addHeader("version", BuildConfig.VERSION_NAME)
.build())
}
return builder
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build()
}
@Provides
@Singleton
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2ErrorHandlingCallAdapterFactory.create())
.build()
}
}
| app/src/main/java/com/uramonk/androidtemplateapp/di/module/NetworkModule.kt | 4130030321 |
// Copyright 2000-2017 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.debugger.streams.exec
import com.intellij.debugger.streams.test.TraceExecutionTestCase
import com.intellij.execution.configurations.JavaParameters
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PluginPathManager
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import com.intellij.testFramework.PsiTestUtil
import java.io.File
import java.nio.file.Paths
/**
* @author Vitaliy.Bibaev
*/
abstract class LibraryTraceExecutionTestCase(jarName: String) : TraceExecutionTestCase() {
private val libraryDirectory = File(PluginPathManager.getPluginHomePath("stream-debugger") + "/lib").absolutePath
private val jarPath = Paths.get(libraryDirectory, jarName).toAbsolutePath().toString()
private companion object {
fun String.replaceLibraryPath(libraryPath: String): String {
val caseSensitive = SystemInfo.isFileSystemCaseSensitive
val result = StringUtil.replace(this, FileUtil.toSystemDependentName(libraryPath), "!LIBRARY_JAR!", !caseSensitive)
return StringUtil.replace(result, FileUtil.toSystemIndependentName(libraryPath), "!LIBRARY_JAR!", !caseSensitive)
}
}
override fun setUpModule() {
super.setUpModule()
ApplicationManager.getApplication().runWriteAction {
VfsRootAccess.allowRootAccess(libraryDirectory)
PsiTestUtil.addLibrary(myModule, jarPath)
}
}
override fun replaceAdditionalInOutput(str: String): String {
return super.replaceAdditionalInOutput(str).replaceLibraryPath(jarPath)
}
override fun createJavaParameters(mainClass: String?): JavaParameters {
val parameters = super.createJavaParameters(mainClass)
parameters.classPath.add(jarPath)
return parameters
}
final override fun getTestAppPath(): String {
return File(PluginPathManager.getPluginHomePath("stream-debugger") + "/testData/${getTestAppRelativePath()}").absolutePath
}
abstract fun getTestAppRelativePath(): String
} | plugins/stream-debugger/test/com/intellij/debugger/streams/exec/LibraryTraceExecutionTestCase.kt | 3816053436 |
package lt.markmerkk.widgets.tickets
import lt.markmerkk.SchedulerProvider
import lt.markmerkk.TicketStorage
import lt.markmerkk.TimeProvider
import lt.markmerkk.UserSettings
import lt.markmerkk.entities.TicketStatus
import lt.markmerkk.tickets.TicketApi
import lt.markmerkk.tickets.TicketStatusesLoader
import org.slf4j.LoggerFactory
import rx.Subscription
class TicketFilterSettingsPresenter(
private val view: TicketFilterSettingsContract.View,
private val ticketApi: TicketApi,
private val timeProvider: TimeProvider,
private val ticketStorage: TicketStorage,
private val userSettings: UserSettings,
private val schedulerProvider: SchedulerProvider
) : TicketFilterSettingsContract.Presenter {
private var subsUpdate: Subscription? = null
private lateinit var ticketStatusesLoader: TicketStatusesLoader
override fun onAttach() {
ticketStatusesLoader = TicketStatusesLoader(
listener = view,
ticketApi = ticketApi,
timeProvider = timeProvider,
ioScheduler = schedulerProvider.io(),
uiScheduler = schedulerProvider.ui()
)
ticketStatusesLoader.onAttach()
}
override fun onDetach() {
ticketStatusesLoader.onDetach()
}
override fun loadTicketStatuses() {
ticketStatusesLoader.fetchTicketStatuses()
}
override fun saveTicketStatuses(
ticketStatusViewModels: List<TicketStatusViewModel>,
useOnlyCurrentUser: Boolean,
filterIncludeAssignee: Boolean,
filterIncludeReporter: Boolean,
filterIncludeIsWatching: Boolean
) {
val newTicketStatuses = ticketStatusViewModels
.map { TicketStatus(it.nameProperty.get(), it.enableProperty.get()) }
val enabledTicketStatusNames = newTicketStatuses
.filter { it.enabled }
.map { it.name }
subsUpdate = ticketStorage
.updateTicketStatuses(newTicketStatuses)
.subscribeOn(schedulerProvider.io())
.doOnSuccess {
userSettings.issueJql = TicketJQLGenerator
.generateJQL(enabledStatuses = enabledTicketStatusNames, onlyCurrentUser = useOnlyCurrentUser)
userSettings.onlyCurrentUserIssues = useOnlyCurrentUser
userSettings.ticketFilterIncludeAssignee = filterIncludeAssignee
userSettings.ticketFilterIncludeReporter = filterIncludeReporter
userSettings.ticketFilterIncludeIsWatching = filterIncludeIsWatching
}
.observeOn(schedulerProvider.ui())
.doOnSubscribe { view.showProgress() }
.doAfterTerminate { view.hideProgress() }
.subscribe({
view.cleanUpAndExit()
}, {
view.cleanUpAndExit()
logger.warn("Error saving ticket filter settings", it)
})
}
companion object {
private val logger = LoggerFactory.getLogger(TicketFilterSettingsPresenter::class.java)!!
}
} | app/src/main/java/lt/markmerkk/widgets/tickets/TicketFilterSettingsPresenter.kt | 781969685 |
/*
* Copyright 2019 LinkedIn Corporation
* All Rights Reserved.
*
* Licensed under the BSD 2-Clause License (the "License"). See License in the project root for
* license information.
*/
// header implementation by Kevin Mark is taken from https://gist.github.com/kmark/d8b1b01fb0d2febf5770 and modified
package com.linkedin.android.litr.io
import android.media.MediaCodec
import android.media.MediaFormat
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream
import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.IllegalStateException
private const val BYTES_PER_SAMPLE = 2
private const val MAX_SIZE = 4294967295
/**
* Implementation of [MediaTarget] that writes a single audio track to WAV file.
* Accepts only one track in "audio-raw" format that has channel count and sample rate data.
* Track rata must be in 16 bit little endian PCM format, e.g. coming from a direct ByteBuffer.
*/
class WavMediaTarget(
private val targetPath: String
) : MediaTarget {
private val tracks = mutableListOf<MediaFormat>()
private val outputStream: OutputStream
private var size: Long = 0
init {
outputStream = FileOutputStream(File(targetPath))
}
override fun addTrack(mediaFormat: MediaFormat, targetTrack: Int): Int {
return if (tracks.size == 0 &&
mediaFormat.containsKey(MediaFormat.KEY_MIME) &&
mediaFormat.getString(MediaFormat.KEY_MIME) == "audio/raw" &&
mediaFormat.containsKey(MediaFormat.KEY_CHANNEL_COUNT) &&
mediaFormat.containsKey(MediaFormat.KEY_SAMPLE_RATE)) {
tracks.add(mediaFormat)
writeWavHeader(
mediaFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT),
mediaFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE),
BYTES_PER_SAMPLE
)
0
} else {
-1
}
}
override fun writeSampleData(targetTrack: Int, buffer: ByteBuffer, info: MediaCodec.BufferInfo) {
size += info.size
if (size >= MAX_SIZE) {
release()
throw IllegalStateException("WAV file size cannot exceed $MAX_SIZE bytes")
}
outputStream.write(buffer.array(), info.offset, info.size)
}
override fun release() {
outputStream.close()
updateWavHeader()
}
override fun getOutputFilePath(): String {
return targetPath
}
// modified version of https://gist.github.com/kmark/d8b1b01fb0d2febf5770#file-audiorecordactivity-java-L288
/**
* Writes the proper 44-byte RIFF/WAVE header to/for the given stream
* Two size fields are left empty/null since we do not yet know the final stream size
*
* @param channelCount number of channels
* @param sampleRate sample rate in hertz
* @param bytesPerSample number of bytes per audio channel sample
*/
private fun writeWavHeader(channelCount: Int, sampleRate: Int, bytesPerSample: Int) {
// Convert the multi-byte integers to raw bytes in little endian format as required by the spec
val littleBytes = ByteBuffer
.allocate(14)
.order(ByteOrder.LITTLE_ENDIAN)
.putShort(channelCount.toShort())
.putInt(sampleRate)
.putInt(sampleRate * channelCount * bytesPerSample)
.putShort((channelCount * bytesPerSample).toShort())
.putShort((bytesPerSample * 8).toShort())
.array()
// Not necessarily the best, but it's very easy to visualize this way
outputStream.write(byteArrayOf( // RIFF header
'R'.toByte(), 'I'.toByte(), 'F'.toByte(), 'F'.toByte(), // ChunkID
0, 0, 0, 0, // ChunkSize (must be updated later)
'W'.toByte(), 'A'.toByte(), 'V'.toByte(), 'E'.toByte(), // Format
// fmt subchunk
'f'.toByte(), 'm'.toByte(), 't'.toByte(), ' '.toByte(), // Subchunk1ID
16, 0, 0, 0, // Subchunk1 Size
1, 0, // AudioFormat
littleBytes[0], littleBytes[1], // NumChannels
littleBytes[2], littleBytes[3], littleBytes[4], littleBytes[5], // SampleRate
littleBytes[6], littleBytes[7], littleBytes[8], littleBytes[9], // ByteRate
littleBytes[10], littleBytes[11], // BlockAlign
littleBytes[12], littleBytes[13], // BitsPerSample
// data subchunk
'd'.toByte(), 'a'.toByte(), 't'.toByte(), 'a'.toByte(), // Subchunk2 ID
0, 0, 0, 0))
}
// modified version of https://gist.github.com/kmark/d8b1b01fb0d2febf5770#file-audiorecordactivity-java-L331
/**
* Updates the given wav file's header to include the final chunk sizes
*/
private fun updateWavHeader() {
val targetFile = File(targetPath)
val sizes = ByteBuffer
.allocate(8)
.order(ByteOrder.LITTLE_ENDIAN)
.putInt((targetFile.length() - 8).toInt()) // ChunkSize
.putInt((targetFile.length() - 44).toInt()) // Subchunk2Size
.array()
var accessWave: RandomAccessFile? = null
try {
accessWave = RandomAccessFile(targetFile, "rw")
// ChunkSize
accessWave.seek(4)
accessWave.write(sizes, 0, 4)
// Subchunk2Size
accessWave.seek(40)
accessWave.write(sizes, 4, 4)
} catch (ex: IOException) {
throw ex
} finally {
if (accessWave != null) {
try {
accessWave.close()
} catch (ex: IOException) {
// fail silently
}
}
}
}
}
| litr/src/main/java/com/linkedin/android/litr/io/WavMediaTarget.kt | 2868330923 |
/*
* Copyright (C) 2019 Contentful GmbH
*
* 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.contentful.java.cma.e2e
import com.contentful.java.cma.CMAClient
import com.contentful.java.cma.model.CMASpaceMembership
import org.junit.BeforeClass
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
open class SpaceMembershipsE2E : Base() {
companion object {
@BeforeClass
@JvmStatic
fun setUpSpaceMembershipSuite() {
client = CMAClient.Builder().apply {
if (!(PROXY.isNullOrEmpty())) {
setCoreEndpoint(PROXY)
setUploadEndpoint(PROXY)
}
setAccessToken(ACCESS_TOKEN)
setSpaceId(SPACE_ID)
setCoreCallFactory(createCallFactory())
setUploadCallFactory(createCallFactory())
}.build()
client
.spaceMemberships()
.fetchAll()
.items
.forEach {
if (it.id != "2tb1QWsh8J49B1enRpfVYe"
&& it.id != "5DJ1zhqoIGiTmIUxkb8ITU") {
assertEquals(204, client.spaceMemberships().delete(it))
}
}
}
}
@Test
fun testCreateSpaceMembership() {
var spaceMembership = CMASpaceMembership().apply {
email = "[email protected]"
isAdmin = true
}
spaceMembership = client.spaceMemberships().create(spaceMembership)
assertTrue(spaceMembership.isAdmin)
assertNull(spaceMembership.email) // security: Do not show email
spaceMembership = client.spaceMemberships().fetchOne(spaceMembership.id)
assertTrue(spaceMembership.isAdmin)
assertNull(spaceMembership.email) // security: Do not show email
assertEquals(204, client.spaceMemberships().delete(spaceMembership))
}
} | src/test/kotlin/com/contentful/java/cma/e2e/SpaceMembershipsE2E.kt | 453456691 |
package org.dvbviewer.controller.data.api.io.exception
import java.io.IOException
class UnsuccessfulHttpException(statusCode: Int) : IOException("HTTP Code: $statusCode")
| dvbViewerController/src/main/java/org/dvbviewer/controller/data/api/io/exception/UnsuccessfulHttpException.kt | 3075810903 |
package org.dvbviewer.controller.activitiy.base
import android.database.Cursor
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import androidx.loader.app.LoaderManager
import androidx.loader.content.CursorLoader
import androidx.loader.content.Loader
import org.dvbviewer.controller.activitiy.DrawerActivity
import org.dvbviewer.controller.data.ProviderConsts
import org.dvbviewer.controller.data.entities.ChannelGroup
import org.dvbviewer.controller.data.entities.DVBViewerPreferences
import org.dvbviewer.controller.ui.fragments.ChannelEpg
import org.dvbviewer.controller.ui.fragments.ChannelPager
import org.dvbviewer.controller.ui.fragments.EpgPager
import java.util.*
abstract class GroupDrawerActivity : DrawerActivity(), OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor>, ChannelEpg.EpgDateInfo, ChannelPager.OnGroupChangedListener {
protected lateinit var prefs: DVBViewerPreferences
protected var mEpgPager: EpgPager? = null
protected var groupIndex = 0
protected var showFavs: Boolean = false
override var epgDate: Long = 0
/*
* (non-Javadoc)
*
* @see
* org.dvbviewer.controller.ui.base.BaseSinglePaneActivity#onCreate(android
* .os.Bundle)
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setDisplayHomeAsUpEnabled(true)
prefs = DVBViewerPreferences(this)
showFavs = prefs.prefs.getBoolean(DVBViewerPreferences.KEY_CHANNELS_USE_FAVS, false)
epgDate = if (savedInstanceState != null && savedInstanceState.containsKey(ChannelEpg.KEY_EPG_DAY)) savedInstanceState.getLong(ChannelEpg.KEY_EPG_DAY) else Date().time
if (savedInstanceState != null) {
groupIndex = savedInstanceState.getInt(ChannelPager.KEY_GROUP_INDEX, 0)
} else {
groupIndex = intent.getIntExtra(ChannelPager.KEY_GROUP_INDEX, 0)
}
supportLoaderManager.initLoader(0, savedInstanceState, this)
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> {
showFavs = prefs.getBoolean(DVBViewerPreferences.KEY_CHANNELS_USE_FAVS, false)
val selection = if (showFavs) ProviderConsts.GroupTbl.TYPE + " = " + ChannelGroup.TYPE_FAV else ProviderConsts.GroupTbl.TYPE + " = " + ChannelGroup.TYPE_CHAN
val orderBy = ProviderConsts.GroupTbl._ID
return CursorLoader(this, ProviderConsts.GroupTbl.CONTENT_URI, null, selection, null, orderBy)
}
override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor) {
mDrawerAdapter.changeCursor(data)
mDrawerList.setItemChecked(groupIndex, true)
}
override fun onLoaderReset(loader: Loader<Cursor>) {
}
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
groupIndex = position
mDrawerLayout.closeDrawers()
}
/* (non-Javadoc)
* @see com.actionbarsherlock.app.SherlockFragmentActivity#onSaveInstanceState(android.os.Bundle)
*/
override fun onSaveInstanceState(outState: Bundle) {
outState.putLong(ChannelEpg.KEY_EPG_DAY, epgDate)
outState.putInt(ChannelPager.KEY_GROUP_INDEX, groupIndex)
super.onSaveInstanceState(outState)
}
override fun groupChanged(groupId: Long, groupIndex: Int, channelIndex: Int) {
this.groupIndex = groupIndex
for (i in 0 until mDrawerList.adapter.count) {
mDrawerList.setItemChecked(i, false)
}
mDrawerList.setItemChecked(groupIndex, true)
if (mEpgPager != null) {
mEpgPager!!.refresh(groupId, channelIndex)
}
}
companion object {
val CHANNEL_PAGER_TAG = ChannelPager::class.java.simpleName
val EPG_PAGER_TAG = EpgPager::class.java.simpleName
}
}
| dvbViewerController/src/main/java/org/dvbviewer/controller/activitiy/base/GroupDrawerActivity.kt | 207267827 |
package com.example.santaev.domain.repository
import com.example.santaev.domain.dto.LanguageDto
import io.reactivex.Flowable
import io.reactivex.Observable
interface ILanguageRepository {
fun getLanguages(): Flowable<List<LanguageDto>>
fun requestLanguages(): Observable<LanguagesState>
enum class LanguagesState {
LOADING,
SUCCESS,
ERROR
}
} | domain/src/main/java/com/example/santaev/domain/repository/ILanguageRepository.kt | 1233531606 |
package eu.kanade.tachiyomi.data.updater
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.os.PowerManager
import androidx.core.content.ContextCompat
import eu.kanade.tachiyomi.BuildConfig
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.notification.Notifications
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.NetworkHelper
import eu.kanade.tachiyomi.network.ProgressListener
import eu.kanade.tachiyomi.network.await
import eu.kanade.tachiyomi.network.newCallWithProgress
import eu.kanade.tachiyomi.util.lang.launchIO
import eu.kanade.tachiyomi.util.storage.getUriCompat
import eu.kanade.tachiyomi.util.storage.saveTo
import eu.kanade.tachiyomi.util.system.acquireWakeLock
import eu.kanade.tachiyomi.util.system.isServiceRunning
import eu.kanade.tachiyomi.util.system.logcat
import logcat.LogPriority
import uy.kohesive.injekt.injectLazy
import java.io.File
class AppUpdateService : Service() {
private val network: NetworkHelper by injectLazy()
/**
* Wake lock that will be held until the service is destroyed.
*/
private lateinit var wakeLock: PowerManager.WakeLock
private lateinit var notifier: AppUpdateNotifier
override fun onCreate() {
super.onCreate()
notifier = AppUpdateNotifier(this)
wakeLock = acquireWakeLock(javaClass.name)
startForeground(Notifications.ID_APP_UPDATER, notifier.onDownloadStarted().build())
}
/**
* This method needs to be implemented, but it's not used/needed.
*/
override fun onBind(intent: Intent): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent == null) return START_NOT_STICKY
val url = intent.getStringExtra(EXTRA_DOWNLOAD_URL) ?: return START_NOT_STICKY
val title = intent.getStringExtra(EXTRA_DOWNLOAD_TITLE) ?: getString(R.string.app_name)
launchIO {
downloadApk(title, url)
}
stopSelf(startId)
return START_NOT_STICKY
}
override fun stopService(name: Intent?): Boolean {
destroyJob()
return super.stopService(name)
}
override fun onDestroy() {
destroyJob()
super.onDestroy()
}
private fun destroyJob() {
if (wakeLock.isHeld) {
wakeLock.release()
}
}
/**
* Called to start downloading apk of new update
*
* @param url url location of file
*/
private suspend fun downloadApk(title: String, url: String) {
// Show notification download starting.
notifier.onDownloadStarted(title)
val progressListener = object : ProgressListener {
// Progress of the download
var savedProgress = 0
// Keep track of the last notification sent to avoid posting too many.
var lastTick = 0L
override fun update(bytesRead: Long, contentLength: Long, done: Boolean) {
val progress = (100 * (bytesRead.toFloat() / contentLength)).toInt()
val currentTime = System.currentTimeMillis()
if (progress > savedProgress && currentTime - 200 > lastTick) {
savedProgress = progress
lastTick = currentTime
notifier.onProgressChange(progress)
}
}
}
try {
// Download the new update.
val response = network.client.newCallWithProgress(GET(url), progressListener).await()
// File where the apk will be saved.
val apkFile = File(externalCacheDir, "update.apk")
if (response.isSuccessful) {
response.body!!.source().saveTo(apkFile)
} else {
response.close()
throw Exception("Unsuccessful response")
}
notifier.onDownloadFinished(apkFile.getUriCompat(this))
} catch (error: Exception) {
logcat(LogPriority.ERROR, error)
notifier.onDownloadError(url)
}
}
companion object {
internal const val EXTRA_DOWNLOAD_URL = "${BuildConfig.APPLICATION_ID}.UpdaterService.DOWNLOAD_URL"
internal const val EXTRA_DOWNLOAD_TITLE = "${BuildConfig.APPLICATION_ID}.UpdaterService.DOWNLOAD_TITLE"
/**
* Returns the status of the service.
*
* @param context the application context.
* @return true if the service is running, false otherwise.
*/
private fun isRunning(context: Context): Boolean =
context.isServiceRunning(AppUpdateService::class.java)
/**
* Downloads a new update and let the user install the new version from a notification.
*
* @param context the application context.
* @param url the url to the new update.
*/
fun start(context: Context, url: String, title: String = context.getString(R.string.app_name)) {
if (!isRunning(context)) {
val intent = Intent(context, AppUpdateService::class.java).apply {
putExtra(EXTRA_DOWNLOAD_TITLE, title)
putExtra(EXTRA_DOWNLOAD_URL, url)
}
ContextCompat.startForegroundService(context, intent)
}
}
/**
* Returns [PendingIntent] that starts a service which downloads the apk specified in url.
*
* @param url the url to the new update.
* @return [PendingIntent]
*/
internal fun downloadApkPendingService(context: Context, url: String): PendingIntent {
val intent = Intent(context, AppUpdateService::class.java).apply {
putExtra(EXTRA_DOWNLOAD_URL, url)
}
return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
}
}
| app/src/main/java/eu/kanade/tachiyomi/data/updater/AppUpdateService.kt | 4065811149 |
package imgui.impl.glfw
import glm_.b
import glm_.c
import glm_.f
import glm_.vec2.Vec2
import glm_.vec2.Vec2d
import glm_.vec2.Vec2i
import imgui.*
import imgui.ImGui.io
import imgui.ImGui.mouseCursor
import imgui.Key
import imgui.api.g
import imgui.impl.*
import imgui.windowsIme.imeListener
import kool.cap
import kool.lim
import org.lwjgl.glfw.GLFW.*
import org.lwjgl.system.MemoryUtil.NULL
import org.lwjgl.system.Platform
import uno.glfw.*
import uno.glfw.GlfwWindow.CursorMode
import java.nio.ByteBuffer
import java.nio.FloatBuffer
import kotlin.collections.set
// GLFW callbacks
// - When calling Init with 'install_callbacks=true': GLFW callbacks will be installed for you. They will call user's previously installed callbacks, if any.
// - When calling Init with 'install_callbacks=false': GLFW callbacks won't be installed. You will need to call those function yourself from your own GLFW callbacks.
class ImplGlfw @JvmOverloads constructor(
/** Main window */
val window: GlfwWindow, installCallbacks: Boolean = true,
/** for vr environment */
val vrTexSize: Vec2i? = null,
clientApi: GlfwClientApi = GlfwClientApi.OpenGL) {
/** for passing inputs in vr */
var vrCursorPos: Vec2? = null
init {
with(io) {
// Setup backend capabilities flags
backendFlags = backendFlags or BackendFlag.HasMouseCursors // We can honor GetMouseCursor() values (optional)
backendFlags = backendFlags or BackendFlag.HasSetMousePos // We can honor io.WantSetMousePos requests (optional, rarely used)
backendPlatformName = "imgui_impl_glfw"
// Keyboard mapping. Dear ImGui will use those indices to peek into the io.KeysDown[] array.
keyMap[Key.Tab] = GLFW_KEY_TAB
keyMap[Key.LeftArrow] = GLFW_KEY_LEFT
keyMap[Key.RightArrow] = GLFW_KEY_RIGHT
keyMap[Key.UpArrow] = GLFW_KEY_UP
keyMap[Key.DownArrow] = GLFW_KEY_DOWN
keyMap[Key.PageUp] = GLFW_KEY_PAGE_UP
keyMap[Key.PageDown] = GLFW_KEY_PAGE_DOWN
keyMap[Key.Home] = GLFW_KEY_HOME
keyMap[Key.End] = GLFW_KEY_END
keyMap[Key.Insert] = GLFW_KEY_INSERT
keyMap[Key.Delete] = GLFW_KEY_DELETE
keyMap[Key.Backspace] = GLFW_KEY_BACKSPACE
keyMap[Key.Space] = GLFW_KEY_SPACE
keyMap[Key.Enter] = GLFW_KEY_ENTER
keyMap[Key.Escape] = GLFW_KEY_ESCAPE
keyMap[Key.KeyPadEnter] = GLFW_KEY_KP_ENTER
keyMap[Key.A] = GLFW_KEY_A
keyMap[Key.C] = GLFW_KEY_C
keyMap[Key.V] = GLFW_KEY_V
keyMap[Key.X] = GLFW_KEY_X
keyMap[Key.Y] = GLFW_KEY_Y
keyMap[Key.Z] = GLFW_KEY_Z
backendRendererName = null
backendPlatformName = null
backendLanguageUserData = null
backendRendererUserData = null
backendPlatformUserData = null
setClipboardTextFn = { _, text -> glfwSetClipboardString(clipboardUserData as Long, text) }
getClipboardTextFn = { glfwGetClipboardString(clipboardUserData as Long) }
clipboardUserData = window.handle.value
if (Platform.get() == Platform.WINDOWS)
imeWindowHandle = window.hwnd
}
// Create mouse cursors
// (By design, on X11 cursors are user configurable and some cursors may be missing. When a cursor doesn't exist,
// GLFW will emit an error which will often be printed by the app, so we temporarily disable error reporting.
// Missing cursors will return NULL and our _UpdateMouseCursor() function will use the Arrow cursor instead.)
val prevErrorCallback = glfwSetErrorCallback(null)
mouseCursors[MouseCursor.Arrow.i] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR)
mouseCursors[MouseCursor.TextInput.i] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR)
mouseCursors[MouseCursor.ResizeAll.i] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR) // FIXME: GLFW doesn't have this. [JVM] TODO
// mouseCursors[MouseCursor.ResizeAll.i] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR)
mouseCursors[MouseCursor.ResizeNS.i] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR)
mouseCursors[MouseCursor.ResizeEW.i] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR)
mouseCursors[MouseCursor.ResizeNESW.i] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR) // FIXME: GLFW doesn't have this.
mouseCursors[MouseCursor.ResizeNWSE.i] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR) // FIXME: GLFW doesn't have this.
// mouseCursors[MouseCursor.ResizeNESW.i] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR)
// mouseCursors[MouseCursor.ResizeNWSE.i] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR)
mouseCursors[MouseCursor.Hand.i] = glfwCreateStandardCursor(GLFW_HAND_CURSOR)
mouseCursors[MouseCursor.NotAllowed.i] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR)
// mouseCursors[MouseCursor.NotAllowed.i] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR)
glfwSetErrorCallback(prevErrorCallback)
// [JVM] Chain GLFW callbacks: our callbacks will be installed in parallel with any other already existing
if (installCallbacks) {
// native callbacks will be added at the GlfwWindow creation via default parameter
window.mouseButtonCBs["imgui"] = mouseButtonCallback
window.scrollCBs["imgui"] = scrollCallback
window.keyCBs["imgui"] = keyCallback
window.charCBs["imgui"] = charCallback
imeListener.install(window)
}
imgui.impl.clientApi = clientApi
}
fun shutdown() {
mouseCursors.forEach(::glfwDestroyCursor)
mouseCursors.fill(NULL)
clientApi = GlfwClientApi.Unknown
}
private fun updateMousePosAndButtons() {
// Update buttons
repeat(io.mouseDown.size) {
/* If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release
events that are shorter than 1 frame. */
io.mouseDown[it] = mouseJustPressed[it] || glfwGetMouseButton(window.handle.value, it) != 0
mouseJustPressed[it] = false
}
// Update mouse position
val mousePosBackup = Vec2d(io.mousePos)
io.mousePos put -Float.MAX_VALUE
if (window.isFocused)
if (io.wantSetMousePos)
window.cursorPos = mousePosBackup
else
io.mousePos put (vrCursorPos ?: window.cursorPos)
else
vrCursorPos?.let(io.mousePos::put) // window is usually unfocused in vr
}
private fun updateMouseCursor() {
if (io.configFlags has ConfigFlag.NoMouseCursorChange || window.cursorMode == CursorMode.disabled)
return
val imguiCursor = mouseCursor
if (imguiCursor == MouseCursor.None || io.mouseDrawCursor)
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
window.cursorMode = CursorMode.hidden
else {
// Show OS mouse cursor
// FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here.
window.cursor = GlfwCursor(mouseCursors[imguiCursor.i].takeIf { it != NULL }
?: mouseCursors[MouseCursor.Arrow.i])
window.cursorMode = CursorMode.normal
}
}
fun updateGamepads() {
io.navInputs.fill(0f)
if (io.configFlags has ConfigFlag.NavEnableGamepad) {
// Update gamepad inputs
val buttons = Joystick._1.buttons ?: ByteBuffer.allocate(0)
val buttonsCount = buttons.lim
val axes = Joystick._1.axes ?: FloatBuffer.allocate(0)
val axesCount = axes.lim
fun mapButton(nav: NavInput, button: Int) {
if (buttonsCount > button && buttons[button] == GLFW_PRESS.b)
io.navInputs[nav] = 1f
}
fun mapAnalog(nav: NavInput, axis: Int, v0: Float, v1: Float) {
var v = if (axesCount > axis) axes[axis] else v0
v = (v - v0) / (v1 - v0)
if (v > 1f) v = 1f
if (io.navInputs[nav] < v)
io.navInputs[nav] = v
}
mapButton(NavInput.Activate, 0) // Cross / A
mapButton(NavInput.Cancel, 1) // Circle / B
mapButton(NavInput.Menu, 2) // Square / X
mapButton(NavInput.Input, 3) // Triangle / Y
mapButton(NavInput.DpadLeft, 13) // D-Pad Left
mapButton(NavInput.DpadRight, 11) // D-Pad Right
mapButton(NavInput.DpadUp, 10) // D-Pad Up
mapButton(NavInput.DpadDown, 12) // D-Pad Down
mapButton(NavInput.FocusPrev, 4) // L1 / LB
mapButton(NavInput.FocusNext, 5) // R1 / RB
mapButton(NavInput.TweakSlow, 4) // L1 / LB
mapButton(NavInput.TweakFast, 5) // R1 / RB
mapAnalog(NavInput.LStickLeft, 0, -0.3f, -0.9f)
mapAnalog(NavInput.LStickRight, 0, +0.3f, +0.9f)
mapAnalog(NavInput.LStickUp, 1, +0.3f, +0.9f)
mapAnalog(NavInput.LStickDown, 1, -0.3f, -0.9f)
io.backendFlags = when {
axesCount > 0 && buttonsCount > 0 -> io.backendFlags or BackendFlag.HasGamepad
else -> io.backendFlags wo BackendFlag.HasGamepad
}
}
}
fun newFrame() {
assert(io.fonts.isBuilt) { "Font atlas not built! It is generally built by the renderer backend. Missing call to renderer _NewFrame() function? e.g. ImGui_ImplOpenGL3_NewFrame()." }
// Setup display size (every frame to accommodate for window resizing)
val size = window.size
val displaySize = window.framebufferSize
io.displaySize put (vrTexSize ?: window.size)
if (size allGreaterThan 0)
io.displayFramebufferScale put (displaySize / size)
// Setup time step
val currentTime = glfw.time
io.deltaTime = if (time > 0) (currentTime - time).f else 1f / 60f
time = currentTime
updateMousePosAndButtons()
updateMouseCursor()
// Update game controllers (if enabled and available)
updateGamepads()
}
companion object {
lateinit var instance: ImplGlfw
fun init(window: GlfwWindow, installCallbacks: Boolean = true, vrTexSize: Vec2i? = null) {
instance = ImplGlfw(window, installCallbacks, vrTexSize)
}
fun newFrame() = instance.newFrame()
fun shutdown() = instance.shutdown()
val mouseButtonCallback: MouseButtonCB = { button: Int, action: Int, _: Int ->
if (action == GLFW_PRESS && button in 0..2)
mouseJustPressed[button] = true
}
val scrollCallback: ScrollCB = { offset: Vec2d ->
io.mouseWheelH += offset.x.f
io.mouseWheel += offset.y.f
}
val keyCallback: KeyCB = { key: Int, _: Int, action: Int, _: Int ->
with(io) {
if (key in keysDown.indices)
if (action == GLFW_PRESS)
keysDown[key] = true
else if (action == GLFW_RELEASE)
keysDown[key] = false
// Modifiers are not reliable across systems
keyCtrl = keysDown[GLFW_KEY_LEFT_CONTROL] || keysDown[GLFW_KEY_RIGHT_CONTROL]
keyShift = keysDown[GLFW_KEY_LEFT_SHIFT] || keysDown[GLFW_KEY_RIGHT_SHIFT]
keyAlt = keysDown[GLFW_KEY_LEFT_ALT] || keysDown[GLFW_KEY_RIGHT_ALT]
keySuper = when(Platform.get()) {
Platform.WINDOWS -> false
else -> keysDown[GLFW_KEY_LEFT_SUPER] || keysDown[GLFW_KEY_RIGHT_SUPER]
}
}
}
val charCallback: CharCB = { c: Int -> if (!imeInProgress) io.addInputCharacter(c.c) }
fun initForOpengl(window: GlfwWindow, installCallbacks: Boolean = true, vrTexSize: Vec2i? = null): ImplGlfw =
ImplGlfw(window, installCallbacks, vrTexSize, GlfwClientApi.OpenGL)
fun initForVulkan(window: GlfwWindow, installCallbacks: Boolean = true, vrTexSize: Vec2i? = null): ImplGlfw =
ImplGlfw(window, installCallbacks, vrTexSize, GlfwClientApi.Vulkan)
}
} | glfw/src/main/kotlin/imgui/impl/glfw/ImplGlfw.kt | 3872048189 |
/*
* SPDX-FileCopyrightText: 2021 Maxim Leshchenko <[email protected]>
*
* SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
package org.kde.kdeconnect.Plugins.RunCommandPlugin
import android.app.PendingIntent
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.drawable.Icon
import android.service.controls.Control
import android.service.controls.ControlsProviderService
import android.service.controls.actions.CommandAction
import android.service.controls.actions.ControlAction
import android.service.controls.templates.StatelessTemplate
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.preference.PreferenceManager
import io.reactivex.Flowable
import io.reactivex.processors.ReplayProcessor
import org.json.JSONArray
import org.json.JSONException
import org.kde.kdeconnect.BackgroundService
import org.kde.kdeconnect.Device
import org.kde.kdeconnect.UserInterface.MainActivity
import org.kde.kdeconnect_tp.R
import org.reactivestreams.FlowAdapters
import java.util.*
import java.util.concurrent.Flow
import java.util.function.Consumer
private class CommandEntryWithDevice(name: String, cmd: String, key: String, val device: Device) : CommandEntry(name, cmd, key)
@RequiresApi(30)
class RunCommandControlsProviderService : ControlsProviderService() {
private lateinit var updatePublisher: ReplayProcessor<Control>
private lateinit var sharedPreferences: SharedPreferences
override fun createPublisherForAllAvailable(): Flow.Publisher<Control> {
return FlowAdapters.toFlowPublisher(Flowable.fromIterable(getAllCommandsList().map { commandEntry ->
Control.StatelessBuilder(commandEntry.device.deviceId + "-" + commandEntry.key, getIntent(commandEntry.device))
.setTitle(commandEntry.name)
.setSubtitle(commandEntry.command)
.setStructure(commandEntry.device.name)
.setCustomIcon(Icon.createWithResource(this, R.drawable.run_command_plugin_icon_24dp))
.build()
}))
}
override fun createPublisherFor(controlIds: MutableList<String>): Flow.Publisher<Control> {
updatePublisher = ReplayProcessor.create()
for (controlId in controlIds) {
val commandEntry = getCommandByControlId(controlId)
if (commandEntry != null && commandEntry.device.isReachable) {
updatePublisher.onNext(Control.StatefulBuilder(controlId, getIntent(commandEntry.device))
.setTitle(commandEntry.name)
.setSubtitle(commandEntry.command)
.setStructure(commandEntry.device.name)
.setStatus(Control.STATUS_OK)
.setStatusText(getString(R.string.tap_to_execute))
.setControlTemplate(StatelessTemplate(commandEntry.key))
.setCustomIcon(Icon.createWithResource(this, R.drawable.run_command_plugin_icon_24dp))
.build())
} else if (commandEntry != null && commandEntry.device.isPaired && !commandEntry.device.isReachable) {
updatePublisher.onNext(Control.StatefulBuilder(controlId, getIntent(commandEntry.device))
.setTitle(commandEntry.name)
.setSubtitle(commandEntry.command)
.setStructure(commandEntry.device.name)
.setStatus(Control.STATUS_DISABLED)
.setControlTemplate(StatelessTemplate(commandEntry.key))
.setCustomIcon(Icon.createWithResource(this, R.drawable.run_command_plugin_icon_24dp))
.build())
} else {
updatePublisher.onNext(Control.StatefulBuilder(controlId, getIntent(commandEntry?.device))
.setStatus(Control.STATUS_NOT_FOUND)
.build())
}
}
return FlowAdapters.toFlowPublisher(updatePublisher)
}
override fun performControlAction(controlId: String, action: ControlAction, consumer: Consumer<Int>) {
if (!this::updatePublisher.isInitialized) {
updatePublisher = ReplayProcessor.create()
}
if (action is CommandAction) {
val commandEntry = getCommandByControlId(controlId)
if (commandEntry != null) {
val plugin = BackgroundService.getInstance().getDevice(controlId.split("-")[0]).getPlugin(RunCommandPlugin::class.java)
if (plugin != null) {
BackgroundService.RunCommand(this) {
plugin.runCommand(commandEntry.key)
}
consumer.accept(ControlAction.RESPONSE_OK)
} else {
consumer.accept(ControlAction.RESPONSE_FAIL)
}
updatePublisher.onNext(Control.StatefulBuilder(controlId, getIntent(commandEntry.device))
.setTitle(commandEntry.name)
.setSubtitle(commandEntry.command)
.setStructure(commandEntry.device.name)
.setStatus(Control.STATUS_OK)
.setStatusText(getString(R.string.tap_to_execute))
.setControlTemplate(StatelessTemplate(commandEntry.key))
.setCustomIcon(Icon.createWithResource(this, R.drawable.run_command_plugin_icon_24dp))
.build())
}
}
}
private fun getSavedCommandsList(device: Device): List<CommandEntryWithDevice> {
if (!this::sharedPreferences.isInitialized) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
}
val commandList = mutableListOf<CommandEntryWithDevice>()
return try {
val jsonArray = JSONArray(sharedPreferences.getString(RunCommandPlugin.KEY_COMMANDS_PREFERENCE + device.deviceId, "[]"))
for (index in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(index)
commandList.add(CommandEntryWithDevice(jsonObject.getString("name"), jsonObject.getString("command"), jsonObject.getString("key"), device))
}
commandList
} catch (error: JSONException) {
Log.e("RunCommand", "Error parsing JSON", error)
listOf()
}
}
private fun getAllCommandsList(): List<CommandEntryWithDevice> {
val commandList = mutableListOf<CommandEntryWithDevice>()
val service = BackgroundService.getInstance() ?: return commandList
for (device in service.devices.values) {
if (!device.isReachable) {
commandList.addAll(getSavedCommandsList(device))
continue
} else if (!device.isPaired) {
continue
}
val plugin = device.getPlugin(RunCommandPlugin::class.java)
if (plugin != null) {
for (jsonObject in plugin.commandList) {
try {
commandList.add(CommandEntryWithDevice(jsonObject.getString("name"), jsonObject.getString("command"), jsonObject.getString("key"), device))
} catch (error: JSONException) {
Log.e("RunCommand", "Error parsing JSON", error)
}
}
}
}
return commandList
}
private fun getCommandByControlId(controlId: String): CommandEntryWithDevice? {
val controlIdParts = controlId.split("-")
val service = BackgroundService.getInstance();
if (service == null) return null
val device = service.getDevice(controlIdParts[0])
if (device == null || !device.isPaired) return null
val commandList = if (device.isReachable) {
device.getPlugin(RunCommandPlugin::class.java)?.commandList?.map { jsonObject ->
CommandEntryWithDevice(jsonObject.getString("name"), jsonObject.getString("command"), jsonObject.getString("key"), device)
}
} else {
getSavedCommandsList(device)
}
return commandList?.find { command ->
try {
command.key == controlIdParts[1]
} catch (error: JSONException) {
Log.e("RunCommand", "Error parsing JSON", error)
false
}
}
}
private fun getIntent(device: Device?): PendingIntent {
val intent = Intent(Intent.ACTION_MAIN).setClass(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.putExtra(MainActivity.EXTRA_DEVICE_ID, device?.deviceId)
return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}
} | src/org/kde/kdeconnect/Plugins/RunCommandPlugin/RunCommandControlsProviderService.kt | 805126868 |
package rynkbit.tk.coffeelist.ui.admin.invoice
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.manage_invoices_fragment.*
import rynkbit.tk.coffeelist.R
import rynkbit.tk.coffeelist.contract.entity.Invoice
import rynkbit.tk.coffeelist.db.facade.InvoiceFacade
class ManageInvoicesFragment : Fragment() {
private lateinit var viewModel: ManageInvoicesViewModel
private lateinit var invoiceAdapter: ManageInvoicesAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.manage_invoices_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(this).get(ManageInvoicesViewModel::class.java)
invoiceAdapter = ManageInvoicesAdapter()
invoiceAdapter.onInvoiceStateChange = updateInvoice()
listInvoices.adapter = invoiceAdapter
listInvoices.layoutManager = LinearLayoutManager(context,
LinearLayoutManager.VERTICAL, false)
updateInvoices()
}
private fun updateInvoice(): ((Invoice) -> Unit) = {invoice ->
InvoiceFacade()
.changeState(invoice)
.observe(this) {
}
}
private fun updateInvoices() {
val liveData = InvoiceFacade()
.findAll()
liveData
.observe(this, Observer {
liveData.removeObservers(this)
invoiceAdapter.updateInvoices(it)
})
}
}
| app/src/main/java/rynkbit/tk/coffeelist/ui/admin/invoice/ManageInvoicesFragment.kt | 3689976344 |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.rx
/**
* Singleton value used for use as value in Rx streams where presence of value indicates some event,
* but there's no meaningful value to emit (e.g., button clicks).
*/
enum class Nil {
NIL
}
| ground/src/main/java/com/google/android/ground/rx/Nil.kt | 1885459823 |
package com.ashish.movieguide.ui.common.adapter
import android.support.v7.widget.RecyclerView
import android.util.SparseArray
import android.view.ViewGroup
import com.ashish.movieguide.ui.base.recyclerview.BaseContentHolder
import com.ashish.movieguide.ui.common.adapter.ViewType.Companion.CONTENT_VIEW
import com.ashish.movieguide.ui.common.adapter.ViewType.Companion.LOADING_VIEW
import com.bumptech.glide.Glide
import java.util.ArrayList
/**
* Created by Ashish on Dec 30.
*/
class RecyclerViewAdapter<in I : ViewType>(
layoutId: Int,
adapterType: Int,
onItemClickListener: OnItemClickListener?
) : RecyclerView.Adapter<RecyclerView.ViewHolder>(), RemoveListener {
private val loadingItem = object : ViewType {
override fun getViewType() = LOADING_VIEW
}
private var itemList: ArrayList<ViewType> = ArrayList()
private var delegateAdapters = SparseArray<ViewTypeDelegateAdapter>()
private val contentAdapter = AdapterFactory.getAdapter(layoutId, adapterType, onItemClickListener)
init {
delegateAdapters.put(LOADING_VIEW, LoadingDelegateAdapter())
delegateAdapters.put(CONTENT_VIEW, contentAdapter)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int)
= delegateAdapters.get(viewType).onCreateViewHolder(parent)
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
delegateAdapters.get(getItemViewType(position)).onBindViewHolder(holder, itemList[position])
}
override fun getItemViewType(position: Int) = itemList[position].getViewType()
override fun onViewRecycled(holder: RecyclerView.ViewHolder?) {
super.onViewRecycled(holder)
if (holder is BaseContentHolder<*>) Glide.clear(holder.posterImage)
}
override fun getItemCount() = itemList.size
@Suppress("UNCHECKED_CAST")
fun <I> getItem(position: Int) = itemList[position] as I
fun showItemList(newItemList: List<I>?) {
newItemList?.let {
val oldPosition = itemCount
itemList = ArrayList(it)
notifyItemRangeInserted(oldPosition, it.size)
}
}
fun addLoadingItem() {
itemList.add(loadingItem)
notifyItemInserted(itemCount - 1)
}
fun addNewItemList(newItemList: List<I>?) {
val loadingItemPosition = removeLoadingItem()
newItemList?.let {
itemList.addAll(it)
notifyItemRangeChanged(loadingItemPosition, itemCount)
}
}
fun removeLoadingItem(): Int {
val loadingItemPosition = itemCount - 1
itemList.removeAt(loadingItemPosition)
notifyItemRemoved(loadingItemPosition)
notifyItemRangeChanged(loadingItemPosition, itemCount)
return loadingItemPosition
}
fun replaceItem(position: Int, item: I) {
itemList[position] = item
notifyItemChanged(position)
}
fun removeItem(position: Int) {
itemList.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, itemCount)
}
fun clearAll() {
val oldSize = itemCount
if (oldSize > 0) {
itemList.clear()
notifyItemRangeRemoved(0, oldSize)
}
}
override fun removeListener() = (contentAdapter as RemoveListener).removeListener()
} | app/src/main/kotlin/com/ashish/movieguide/ui/common/adapter/RecyclerViewAdapter.kt | 984954441 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.indexing.diagnostic
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.ObjectEventData
import com.intellij.internal.statistic.eventLog.events.ObjectListEventField
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.internal.statistic.utils.StatisticsUtil
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.project.Project
import com.intellij.util.indexing.diagnostic.dto.toMillis
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.collections.HashMap
import kotlin.math.roundToLong
class ProjectIndexingHistoryFusReporterListener : ProjectIndexingHistoryListener {
override fun onStartedIndexing(projectIndexingHistory: ProjectIndexingHistory) {
ProjectIndexingHistoryFusReporter.reportIndexingStarted(
projectIndexingHistory.project,
projectIndexingHistory.indexingSessionId
)
}
override fun onFinishedIndexing(projectIndexingHistory: ProjectIndexingHistory) {
val scanningTime = projectIndexingHistory.times.scanFilesDuration.toMillis()
val numberOfFileProviders = projectIndexingHistory.scanningStatistics.size
val numberOfScannedFiles = projectIndexingHistory.scanningStatistics.sumOf { it.numberOfScannedFiles }
val numberOfFilesIndexedByExtensionsDuringScan =
projectIndexingHistory.scanningStatistics.sumOf { it.numberOfFilesFullyIndexedByInfrastructureExtensions }
val numberOfFilesIndexedByExtensionsWithLoadingContent =
projectIndexingHistory.providerStatistics.sumOf { it.totalNumberOfFilesFullyIndexedByExtensions }
val numberOfFilesIndexedWithLoadingContent = projectIndexingHistory.providerStatistics.sumOf { it.totalNumberOfIndexedFiles }
val totalContentLoadingTime = projectIndexingHistory.totalStatsPerFileType.values.sumOf { it.totalContentLoadingTimeInAllThreads }
val totalContentData = projectIndexingHistory.totalStatsPerFileType.values.sumOf { it.totalBytes }
val averageContentLoadingSpeed = calculateReadSpeed(totalContentData, totalContentLoadingTime)
val contentLoadingSpeedByFileType = HashMap<FileType, Long>()
projectIndexingHistory.totalStatsPerFileType.forEach { (fileType, stats) ->
if (stats.totalContentLoadingTimeInAllThreads != 0L && stats.totalBytes != 0L) {
contentLoadingSpeedByFileType[FileTypeManager.getInstance().getStdFileType(fileType)] =
calculateReadSpeed(stats.totalBytes, stats.totalContentLoadingTimeInAllThreads)
}
}
ProjectIndexingHistoryFusReporter.reportIndexingFinished(
projectIndexingHistory.project,
projectIndexingHistory.indexingSessionId,
projectIndexingHistory.times.scanningType,
projectIndexingHistory.times.totalUpdatingTime.toMillis(),
projectIndexingHistory.times.indexingDuration.toMillis(),
scanningTime,
numberOfFileProviders,
numberOfScannedFiles,
numberOfFilesIndexedByExtensionsDuringScan,
numberOfFilesIndexedByExtensionsWithLoadingContent,
numberOfFilesIndexedWithLoadingContent,
averageContentLoadingSpeed,
contentLoadingSpeedByFileType
)
}
/**
* @return speed as bytes per second
* */
private fun calculateReadSpeed(bytes: BytesNumber, loadingTime: TimeNano): Long {
if (bytes == 0L || loadingTime == 0L) return 0L
val nanoSecondInOneSecond = TimeUnit.SECONDS.toNanos(1)
return if (bytes * nanoSecondInOneSecond > 0) // avoid hitting overflow; possible if loaded more then 9 223 372 037 bytes
// as `loadingTime` in nanoseconds tend to be much bigger value then `bytes` prefer to divide as second step
(bytes * nanoSecondInOneSecond) / loadingTime
else // do not use by default to avoid unnecessary conversions
((bytes.toDouble() / loadingTime) * nanoSecondInOneSecond).roundToLong()
}
}
object ProjectIndexingHistoryFusReporter : CounterUsagesCollector() {
private val GROUP = EventLogGroup("indexing.statistics", 6)
override fun getGroup() = GROUP
private val indexingSessionId = EventFields.Long("indexing_session_id")
private val isFullRescanning = EventFields.Boolean("is_full")
private val scanningType = EventFields.Enum<ScanningType>("type") { type -> type.name.lowercase(Locale.ENGLISH) }
private val totalTime = EventFields.Long("total_time")
private val indexingTime = EventFields.Long("indexing_time")
private val scanningTime = EventFields.Long("scanning_time")
private val numberOfFileProviders = EventFields.Int("number_of_file_providers")
private val numberOfScannedFiles = EventFields.Int("number_of_scanned_files")
private val numberOfFilesIndexedByExtensionsDuringScan =
EventFields.Int("number_of_files_indexed_by_extensions_during_scan")
private val numberOfFilesIndexedByExtensionsWithLoadingContent =
EventFields.Int("number_of_files_indexed_by_extensions_with_loading_content")
private val numberOfFilesIndexedWithLoadingContent =
EventFields.Int("number_of_files_indexed_with_loading_content")
private val averageContentLoadingSpeed = EventFields.Long("average_content_loading_speed_bps")
private val contentLoadingSpeedForFileType = EventFields.Long("average_content_loading_speed_for_file_type_bps")
private val contentLoadingSpeedByFileType =
ObjectListEventField("average_content_loading_speeds_by_file_type", EventFields.FileType, contentLoadingSpeedForFileType)
private val indexingStarted = GROUP.registerVarargEvent(
"started",
indexingSessionId
)
private val indexingFinished = GROUP.registerVarargEvent(
"finished",
indexingSessionId,
isFullRescanning,
scanningType,
totalTime,
indexingTime,
scanningTime,
numberOfFileProviders,
numberOfScannedFiles,
numberOfFilesIndexedByExtensionsDuringScan,
numberOfFilesIndexedByExtensionsWithLoadingContent,
numberOfFilesIndexedWithLoadingContent,
averageContentLoadingSpeed,
contentLoadingSpeedByFileType
)
fun reportIndexingStarted(project: Project, indexingSessionId: Long) {
indexingStarted.log(
project,
this.indexingSessionId.with(indexingSessionId)
)
}
fun reportIndexingFinished(
project: Project,
indexingSessionId: Long,
scanningType: ScanningType,
totalTime: Long,
indexingTime: Long,
scanningTime: Long,
numberOfFileProviders: Int,
numberOfScannedFiles: Int,
numberOfFilesIndexedByExtensionsDuringScan: Int,
numberOfFilesIndexedByExtensionsWithLoadingContent: Int,
numberOfFilesIndexedWithLoadingContent: Int,
averageContentLoadingSpeed: Long,
contentLoadingSpeedByFileType: Map<FileType, Long>
) {
indexingFinished.log(
project,
this.indexingSessionId.with(indexingSessionId),
this.isFullRescanning.with(scanningType.isFull),
this.scanningType.with(scanningType),
this.totalTime.with(totalTime),
this.indexingTime.with(indexingTime),
this.scanningTime.with(scanningTime),
this.numberOfFileProviders.with(numberOfFileProviders),
this.numberOfScannedFiles.with(StatisticsUtil.roundToHighestDigit(numberOfScannedFiles)),
this.numberOfFilesIndexedByExtensionsDuringScan.with(StatisticsUtil.roundToHighestDigit(numberOfFilesIndexedByExtensionsDuringScan)),
this.numberOfFilesIndexedByExtensionsWithLoadingContent.with(
StatisticsUtil.roundToHighestDigit(numberOfFilesIndexedByExtensionsWithLoadingContent)),
this.numberOfFilesIndexedWithLoadingContent.with(StatisticsUtil.roundToHighestDigit(numberOfFilesIndexedWithLoadingContent)),
this.averageContentLoadingSpeed.with(averageContentLoadingSpeed),
this.contentLoadingSpeedByFileType.with(contentLoadingSpeedByFileType.map { entry ->
ObjectEventData(EventFields.FileType.with(entry.key), contentLoadingSpeedForFileType.with(entry.value))
})
)
}
} | platform/lang-impl/src/com/intellij/util/indexing/diagnostic/ProjectIndexingHistoryFusReporterListener.kt | 394542757 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast
import com.intellij.psi.PsiAnonymousClass
import com.intellij.psi.PsiClass
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.internal.convertOrReport
import org.jetbrains.uast.internal.log
import org.jetbrains.uast.visitor.UastTypedVisitor
import org.jetbrains.uast.visitor.UastVisitor
/**
* A class wrapper to be used in [UastVisitor].
*/
interface UClass : UDeclaration, PsiClass {
@get:ApiStatus.ScheduledForRemoval
@get:Deprecated("see the base property description")
@Deprecated("see the base property description", ReplaceWith("javaPsi"))
override val psi: PsiClass
override val javaPsi: PsiClass
override fun getQualifiedName(): String?
override fun isInterface(): Boolean
override fun isAnnotationType(): Boolean
/**
* Returns a [UClass] wrapper of the superclass of this class, or null if this class is [java.lang.Object].
*/
@Deprecated("will return null if existing superclass is not convertable to Uast, use `javaPsi.superClass` instead",
ReplaceWith("javaPsi.superClass"))
override fun getSuperClass(): UClass? {
val superClass = javaPsi.superClass ?: return null
return UastFacade.convertWithParent(superClass)
}
val uastSuperTypes: List<UTypeReferenceExpression>
/**
* Returns [UDeclaration] wrappers for the class declarations.
*/
val uastDeclarations: List<UDeclaration>
override fun getFields(): Array<UField> =
javaPsi.fields.mapNotNull { convertOrReport<UField>(it, this) }.toTypedArray()
override fun getInitializers(): Array<UClassInitializer> =
javaPsi.initializers.mapNotNull { convertOrReport<UClassInitializer>(it, this) }.toTypedArray()
override fun getMethods(): Array<UMethod> =
javaPsi.methods.mapNotNull { convertOrReport<UMethod>(it, this) }.toTypedArray()
override fun getInnerClasses(): Array<UClass> =
javaPsi.innerClasses.mapNotNull { convertOrReport<UClass>(it, this) }.toTypedArray()
override fun asLogString(): String = log("name = $name")
override fun accept(visitor: UastVisitor) {
if (visitor.visitClass(this)) return
uAnnotations.acceptList(visitor)
uastDeclarations.acceptList(visitor)
visitor.afterVisitClass(this)
}
override fun asRenderString(): String = buildString {
append(javaPsi.renderModifiers())
val kind = when {
javaPsi.isAnnotationType -> "annotation"
javaPsi.isInterface -> "interface"
javaPsi.isEnum -> "enum"
else -> "class"
}
append(kind).append(' ').append(javaPsi.name)
val superTypes = uastSuperTypes
if (superTypes.isNotEmpty()) {
append(" : ")
append(superTypes.joinToString { it.asRenderString() })
}
appendln(" {")
uastDeclarations.forEachIndexed { _, declaration ->
appendln(declaration.asRenderString().withMargin)
}
append("}")
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R =
visitor.visitClass(this, data)
}
interface UAnonymousClass : UClass, PsiAnonymousClass {
@get:ApiStatus.ScheduledForRemoval
@get:Deprecated("see the base property description")
@Deprecated("see the base property description", ReplaceWith("javaPsi"))
override val psi: PsiAnonymousClass
}
| uast/uast-common/src/org/jetbrains/uast/declarations/UClass.kt | 703490552 |
// INSPECTION_CLASS: com.android.tools.idea.lint.AndroidLintDrawAllocationInspection
// INSPECTION_CLASS2: com.android.tools.idea.lint.AndroidLintUseSparseArraysInspection
// INSPECTION_CLASS3: com.android.tools.idea.lint.AndroidLintUseValueOfInspection
import android.annotation.SuppressLint
import java.util.HashMap
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.SparseArray
import android.widget.Button
@SuppressWarnings("unused")
@Suppress("UsePropertyAccessSyntax", "UNUSED_VARIABLE", "unused", "UNUSED_PARAMETER", "DEPRECATION", "UNNECESSARY_NOT_NULL_ASSERTION", "NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
class JavaPerformanceTest(context: Context, attrs: AttributeSet, defStyle: Int) : Button(context, attrs, defStyle) {
private var cachedRect: Rect? = null
private var shader: LinearGradient? = null
private var lastHeight: Int = 0
private var lastWidth: Int = 0
override fun onDraw(canvas: android.graphics.Canvas) {
super.onDraw(canvas)
// Various allocations:
<warning descr="Avoid object allocations during draw/layout operations (preallocate and reuse instead)">java.lang.String("foo")</warning>
val s = <warning descr="Avoid object allocations during draw/layout operations (preallocate and reuse instead)">java.lang.String("bar")</warning>
// This one should not be reported:
@SuppressLint("DrawAllocation")
val i = 5
// Cached object initialized lazily: should not complain about these
if (cachedRect == null) {
cachedRect = Rect(0, 0, 100, 100)
}
if (cachedRect == null || cachedRect!!.width() != 50) {
cachedRect = Rect(0, 0, 50, 100)
}
val b = java.lang.Boolean.valueOf(true)!! // auto-boxing
dummy(1, 2)
// Non-allocations
super.animate()
dummy2(1, 2)
// This will involve allocations, but we don't track
// inter-procedural stuff here
someOtherMethod()
}
internal fun dummy(foo: Int?, bar: Int) {
dummy2(foo!!, bar)
}
internal fun dummy2(foo: Int, bar: Int) {
}
internal fun someOtherMethod() {
// Allocations are okay here
java.lang.String("foo")
val s = java.lang.String("bar")
val b = java.lang.Boolean.valueOf(true)!! // auto-boxing
// Sparse array candidates
val myMap = <warning descr="Use `new SparseArray<String>(...)` instead for better performance">HashMap<Int, String>()</warning>
// Should use SparseBooleanArray
val myBoolMap = <warning descr="Use `new SparseBooleanArray(...)` instead for better performance">HashMap<Int, Boolean>()</warning>
// Should use SparseIntArray
val myIntMap = <warning descr="Use new `SparseIntArray(...)` instead for better performance">java.util.HashMap<Int, Int>()</warning>
// This one should not be reported:
@SuppressLint("UseSparseArrays")
val myOtherMap = HashMap<Int, Any>()
}
protected fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int,
x: Boolean) {
// wrong signature
java.lang.String("not an error")
}
protected fun onMeasure(widthMeasureSpec: Int) {
// wrong signature
java.lang.String("not an error")
}
protected fun onLayout(changed: Boolean, left: Int, top: Int, right: Int,
bottom: Int, wrong: Int) {
// wrong signature
java.lang.String("not an error")
}
protected fun onLayout(changed: Boolean, left: Int, top: Int, right: Int) {
// wrong signature
java.lang.String("not an error")
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int,
bottom: Int) {
<warning descr="Avoid object allocations during draw/layout operations (preallocate and reuse instead)">java.lang.String("flag me")</warning>
}
@SuppressWarnings("null") // not real code
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
<warning descr="Avoid object allocations during draw/layout operations (preallocate and reuse instead)">java.lang.String("flag me")</warning>
// Forbidden factory methods:
<warning descr="Avoid object allocations during draw/layout operations (preallocate and reuse instead)">Bitmap.createBitmap(100, 100, null)</warning>
<warning descr="Avoid object allocations during draw/layout operations (preallocate and reuse instead)">android.graphics.Bitmap.createScaledBitmap(null, 100, 100, false)</warning>
<warning descr="Avoid object allocations during draw/layout operations (preallocate and reuse instead)">BitmapFactory.decodeFile(null)</warning>
val canvas: Canvas? = null
<warning descr="Avoid object allocations during draw operations: Use `Canvas.getClipBounds(Rect)` instead of `Canvas.getClipBounds()` which allocates a temporary `Rect`">canvas!!.getClipBounds()</warning> // allocates on your behalf
canvas.clipBounds // allocates on your behalf
canvas.getClipBounds(null) // NOT an error
val layoutWidth = width
val layoutHeight = height
if (mAllowCrop && (mOverlay == null || mOverlay!!.width != layoutWidth ||
mOverlay!!.height != layoutHeight)) {
mOverlay = Bitmap.createBitmap(layoutWidth, layoutHeight, Bitmap.Config.ARGB_8888)
mOverlayCanvas = Canvas(mOverlay!!)
}
if (widthMeasureSpec == 42) {
throw IllegalStateException("Test") // NOT an allocation
}
// More lazy init tests
var initialized = false
if (!initialized) {
java.lang.String("foo")
initialized = true
}
// NOT lazy initialization
if (!initialized || mOverlay == null) {
<warning descr="Avoid object allocations during draw/layout operations (preallocate and reuse instead)">java.lang.String("foo")</warning>
}
}
internal fun factories() {
val i1 = 42
val l1 = 42L
val b1 = true
val c1 = 'c'
val f1 = 1.0f
val d1 = 1.0
// The following should not generate errors:
val i3 = Integer.valueOf(42)
}
private val mAllowCrop: Boolean = false
private var mOverlayCanvas: Canvas? = null
private var mOverlay: Bitmap? = null
override fun layout(l: Int, t: Int, r: Int, b: Int) {
// Using "this." to reference fields
if (this.shader == null)
this.shader = LinearGradient(0f, 0f, width.toFloat(), 0f, intArrayOf(0), null,
Shader.TileMode.REPEAT)
val width = width
val height = height
if (shader == null || lastWidth != width || lastHeight != height) {
lastWidth = width
lastHeight = height
shader = LinearGradient(0f, 0f, width.toFloat(), 0f, intArrayOf(0), null, Shader.TileMode.REPEAT)
}
}
fun inefficientSparseArray() {
<warning descr="Use `new SparseIntArray(...)` instead for better performance">SparseArray<Int>()</warning> // Use SparseIntArray instead
SparseArray<Long>() // Use SparseLongArray instead
<warning descr="Use `new SparseBooleanArray(...)` instead for better performance">SparseArray<Boolean>()</warning> // Use SparseBooleanArray instead
SparseArray<Any>() // OK
}
fun longSparseArray() {
// but only minSdkVersion >= 17 or if has v4 support lib
val myStringMap = HashMap<Long, String>()
}
fun byteSparseArray() {
// bytes easily apply to ints
val myByteMap = <warning descr="Use `new SparseArray<String>(...)` instead for better performance">HashMap<Byte, String>()</warning>
}
}
| plugins/kotlin/idea/tests/testData/android/lint/javaPerformance.kt | 3085491291 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.