content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package de.maibornwolff.codecharta.model import org.hamcrest.BaseMatcher import org.hamcrest.Description import org.hamcrest.Matcher object NodeMatcher { fun matchesNode(expectedNode: Node): Matcher<Node> { return object : BaseMatcher<Node>() { override fun describeTo(description: Description) { description.appendText("should be ").appendValue(expectedNode) } override fun matches(item: Any): Boolean { return match(item as Node, expectedNode) } } } fun match(n1: Node, n2: Node): Boolean { return n1.name == n2.name && n1.type == n2.type && linksMatch(n1, n2) && n1.attributes == n2.attributes && n1.children.size == n2.children.size && n1.children.indices .map { match(n1.children.toMutableList()[it], n2.children.toMutableList()[it]) } .fold(true) { x, y -> x && y } } private fun linksMatch(n1: Node, n2: Node) = n1.link == n2.link || (n1.link.isNullOrEmpty() && n2.link.isNullOrEmpty()) fun hasNodeAtPath(node: Node, path: Path): Matcher<Node> { return object : BaseMatcher<Node>() { private var nodeAtPath: Node? = null override fun describeTo(description: Description) { description.appendText("paths should contain ").appendValue(node).appendText(" at ").appendValue(path) } override fun matches(item: Any?): Boolean { nodeAtPath = (item as Node).getNodeBy(path) as Node return if (nodeAtPath == null) false else match(nodeAtPath!!, node) } override fun describeMismatch(item: Any, description: Description) { description.appendText("but was ").appendValue(nodeAtPath) description.appendText(", where paths to leaves were ").appendValue((item as MutableNode).pathsToLeaves) } } } }
analysis/model/src/test/kotlin/de/maibornwolff/codecharta/model/NodeMatcher.kt
3804565645
package talent.bearers.slimefusion.common.block import com.teamwizardry.librarianlib.common.base.block.BlockMod import net.minecraft.block.SoundType import net.minecraft.block.material.Material import net.minecraft.block.properties.PropertyEnum import net.minecraft.block.state.BlockStateContainer import net.minecraft.block.state.IBlockState import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.util.EnumFacing import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.util.math.RayTraceResult import net.minecraft.world.IBlockAccess import net.minecraft.world.World import talent.bearers.slimefusion.common.core.EnumOreType import talent.bearers.slimefusion.common.items.ModItems import talent.bearers.slimefusion.common.lib.LibNames import java.util.* /** * @author WireSegal * Created at 5:13 PM on 12/29/16. */ class BlockMoonshard : BlockMod(LibNames.MOONSHARD, Material.IRON, *EnumOreType.getNamesFor(LibNames.MOONSHARD)) { companion object { val TYPE: PropertyEnum<EnumOreType> = PropertyEnum.create("ore", EnumOreType::class.java) val SIDE: PropertyEnum<EnumFacing> = PropertyEnum.create("side", EnumFacing::class.java, EnumFacing.UP, EnumFacing.DOWN) val AABB_DOWN = AxisAlignedBB(5.5 / 16, 0.0, 5.5 / 16, 10.5 / 16, 1.0 / 16, 10.5 / 16) val AABB_UP = AxisAlignedBB(5.5 / 16, 0.0, 5.5 / 16, 10.5 / 16, 1.0 / 16, 10.5 / 16) val RAND = Random() } init { setHardness(5.0F) setResistance(10.0F) soundType = SoundType.METAL } override fun canSilkHarvest(world: World?, pos: BlockPos?, state: IBlockState?, player: EntityPlayer?) = true override fun createStackedBlock(state: IBlockState) = ItemStack(this, 1, state.getValue(TYPE).ordinal) override fun isOpaqueCube(state: IBlockState) = false override fun isFullCube(state: IBlockState) = false override fun getPickBlock(state: IBlockState, target: RayTraceResult, world: World?, pos: BlockPos?, player: EntityPlayer?) = createStackedBlock(state) override fun getDrops(world: IBlockAccess, pos: BlockPos, state: IBlockState, fortune: Int): MutableList<ItemStack> { val type = state.getValue(TYPE) val totalDrops = Math.max(RAND.nextInt(fortune + 3) + 1, 1) val secondaryDrops = if (type.rareDrop != null) (RAND.nextDouble() * totalDrops * 0.5).toInt() else 0 val ret = mutableListOf<ItemStack>() for (i in 0 until (totalDrops - secondaryDrops)) ret.add(ItemStack(ModItems.CRYSTAL, 1, type.mainDrop.ordinal)) for (i in 0 until secondaryDrops) ret.add(ItemStack(ModItems.CRYSTAL, 1, type.rareDrop?.ordinal ?: 0)) return ret } override fun createBlockState() = BlockStateContainer(this, TYPE, SIDE) override fun getMetaFromState(state: IBlockState) = state.getValue(TYPE).ordinal or (state.getValue(SIDE).index shl 3) override fun getStateFromMeta(meta: Int) = defaultState .withProperty(TYPE, EnumOreType[meta and 7]) .withProperty(SIDE, EnumFacing.VALUES[(meta and 8) shr 3]) override fun getBoundingBox(state: IBlockState, source: IBlockAccess, pos: BlockPos) = if (state.getValue(SIDE) == EnumFacing.UP) AABB_UP else AABB_DOWN }
src/main/java/talent/bearers/slimefusion/common/block/BlockMoonshard.kt
2694846697
package appnexus.com.appnexussdktestapp.adapter import android.annotation.SuppressLint import android.content.Context import android.graphics.Bitmap import android.net.Uri import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.recyclerview.widget.RecyclerView import com.appnexus.opensdk.AdView import com.appnexus.opensdk.BannerAdView import com.appnexus.opensdk.InterstitialAdView import com.appnexus.opensdk.NativeAdResponse import com.appnexus.opensdk.instreamvideo.Quartile import com.appnexus.opensdk.instreamvideo.VideoAd import com.appnexus.opensdk.instreamvideo.VideoAdPlaybackListener import com.appnexus.opensdk.utils.Clog import com.appnexus.opensdk.utils.ViewUtil import com.xandr.lazyloaddemo.R import kotlinx.android.synthetic.main.layout_ad_view.view.* import java.util.* class AdViewRecyclerAdapter(val items: ArrayList<Any?>, val context: Context) : RecyclerView.Adapter<AdViewRecyclerAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( LayoutInflater.from(context).inflate( R.layout.layout_ad_view, parent, false ) ) } override fun getItemCount(): Int { return items.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val currentAd = items.get(position) if (currentAd is NativeAdResponse) { handleNativeResponse(currentAd, holder.layoutMain) } else if (currentAd is AdView) { if (currentAd is InterstitialAdView) { holder.layoutMain.setOnClickListener({ currentAd.show() }) } else { if (currentAd is BannerAdView) { if (currentAd.isLazyLoadEnabled && currentAd.getTag( R.string.button_tag ) == null ) { val btn = Button(context) btn.setText("Activate") btn.setOnClickListener { Clog.e("LAZYLOAD", "Webview Activated") currentAd.loadLazyAd() currentAd.setTag(R.string.button_tag, btn) } currentAd.setTag(R.string.button_tag, true) holder.layoutMain.addView(btn) } else { if (currentAd.getTag(R.string.button_tag) is Button && currentAd.isLazyLoadEnabled) { ViewUtil.removeChildFromParent(currentAd.getTag(R.string.button_tag) as Button) ViewUtil.removeChildFromParent(currentAd) holder.layoutMain.addView(currentAd) Clog.e("LAZYLOAD", "Banner Added to the parent view") currentAd.post({ Clog.e("WIDTH", "${currentAd.width}") Clog.e("HEIGHT", "${currentAd.height}") currentAd.invalidate() currentAd.visibility = View.VISIBLE }) } else { ViewUtil.removeChildFromParent(currentAd) holder.layoutMain.addView(currentAd) Clog.e("LAZYLOAD", "Banner Added to the parent view") currentAd.post({ Clog.e("WIDTH", "${currentAd.width}") Clog.e("HEIGHT", "${currentAd.height}") currentAd.invalidate() currentAd.visibility = View.VISIBLE }) } } } } } else if (currentAd is VideoAd) { handleVideoAd(currentAd, holder.layoutMain) } } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { // Holds the TextView that will add each animal to val layoutMain = view.layoutMain } private fun handleVideoAd(videoAd: VideoAd, layoutVideo: LinearLayout) { // Load and display a Video // Video Ad elements val instreamVideoLayout = LayoutInflater.from(context).inflate(R.layout.fragment_preview_instream, null) val playButon = instreamVideoLayout.findViewById(R.id.play_button) as ImageButton playButon.visibility = View.VISIBLE val videoPlayer = instreamVideoLayout.findViewById(R.id.video_player) as VideoView val baseContainer = instreamVideoLayout.findViewById(R.id.instream_container_Layout) as RelativeLayout layoutVideo.removeAllViews() layoutVideo.addView(baseContainer) baseContainer.layoutParams.height = 1000 baseContainer.layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT videoPlayer.setVideoURI(Uri.parse("https://acdn.adnxs.com/mobile/video_test/content/Scenario.mp4")) val controller = MediaController(context) videoPlayer.setMediaController(controller) playButon.setOnClickListener { if (videoAd.isReady) { videoAd.playAd(baseContainer) } else { videoPlayer.start() } playButon.visibility = View.INVISIBLE } // Set PlayBack Listener. videoAd.videoPlaybackListener = object : VideoAdPlaybackListener { override fun onAdPlaying(videoAd: VideoAd) { Clog.d("VideoAd", "onAdPlaying::") } override fun onQuartile(view: VideoAd, quartile: Quartile) { Clog.d("VideoAd", "onQuartile::$quartile") } override fun onAdCompleted( view: VideoAd, playbackState: VideoAdPlaybackListener.PlaybackCompletionState ) { if (playbackState == VideoAdPlaybackListener.PlaybackCompletionState.COMPLETED) { Clog.d("VideoAd", "adCompleted::playbackState") } else if (playbackState == VideoAdPlaybackListener.PlaybackCompletionState.SKIPPED) { Clog.d("VideoAd", "adSkipped::") } videoPlayer.start() } override fun onAdMuted(view: VideoAd, isMute: Boolean) { Clog.d("VideoAd", "isAudioMute::$isMute") } override fun onAdClicked(adView: VideoAd) { Clog.d("VideoAd", "onAdClicked") } override fun onAdClicked(videoAd: VideoAd, clickUrl: String) { Clog.d("VideoAd", "onAdClicked::clickUrl$clickUrl") } } } private fun handleNativeResponse(response: NativeAdResponse, layoutNative: LinearLayout) { val builder = NativeAdBuilder(context) if (response.icon != null) builder.setIconView(response.icon) if (response.image != null) builder.setImageView(response.image) builder.setTitle(response.title) builder.setDescription(response.description) builder.setCallToAction(response.callToAction) builder.setSponsoredBy(response.sponsoredBy) if (response.adStarRating != null) { builder.setAdStartValue(response.adStarRating.value.toString() + "/" + response.adStarRating.scale.toString()) } // register all the views if (builder.container != null && builder.container!!.parent != null) (builder.container!!.parent as ViewGroup).removeAllViews() val nativeContainer = builder.container Handler().post { layoutNative.removeAllViews() layoutNative.addView(nativeContainer) } } internal inner class NativeAdBuilder @SuppressLint("NewApi") constructor(context: Context) { var container: RelativeLayout? = null var iconAndTitle: LinearLayout var customViewLayout: LinearLayout var imageView: ImageView var iconView: ImageView var title: TextView var description: TextView var callToAction: TextView var adStarRating: TextView var socialContext: TextView var sponsoredBy: TextView var customView = null // Any Mediated network requiring to render there own view for impression tracking would go in here. var views: LinkedList<View>? = null val allViews: LinkedList<View> get() { if (views == null) { views = LinkedList() views!!.add(imageView) views!!.add(iconView) views!!.add(title) views!!.add(description) views!!.add(callToAction) views!!.add(adStarRating) views!!.add(socialContext) views!!.add(sponsoredBy) } return views as LinkedList<View> } init { container = RelativeLayout(context) iconAndTitle = LinearLayout(context) iconAndTitle.id = View.generateViewId() iconAndTitle.orientation = LinearLayout.HORIZONTAL iconView = ImageView(context) iconAndTitle.addView(iconView) title = TextView(context) iconAndTitle.addView(title) container!!.addView(iconAndTitle) imageView = ImageView(context) imageView.id = View.generateViewId() val imageView_params = RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) imageView_params.addRule(RelativeLayout.BELOW, iconAndTitle.id) description = TextView(context) description.id = View.generateViewId() val description_params = RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) description_params.addRule(RelativeLayout.BELOW, imageView.id) callToAction = TextView(context) callToAction.id = View.generateViewId() val callToAction_params = RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) callToAction_params.addRule(RelativeLayout.BELOW, description.id) adStarRating = TextView(context) adStarRating.id = View.generateViewId() val adStarRating_params = RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) adStarRating_params.addRule(RelativeLayout.BELOW, callToAction.id) socialContext = TextView(context) socialContext.id = View.generateViewId() val socialContext_params = RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) socialContext_params.addRule(RelativeLayout.BELOW, adStarRating.id) sponsoredBy = TextView(context) sponsoredBy.id = View.generateViewId() val sponsoredBy_params = RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) sponsoredBy_params.addRule(RelativeLayout.BELOW, socialContext.id) customViewLayout = LinearLayout(context) customViewLayout.id = View.generateViewId() customViewLayout.orientation = LinearLayout.HORIZONTAL val customViewLayout_params = RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) customViewLayout_params.addRule(RelativeLayout.BELOW, sponsoredBy.id) container!!.addView(description, description_params) container!!.addView(imageView, imageView_params) container!!.addView(callToAction, callToAction_params) container!!.addView(adStarRating, adStarRating_params) container!!.addView(socialContext, socialContext_params) container!!.addView(sponsoredBy, sponsoredBy_params) container!!.addView(customViewLayout, customViewLayout_params) } fun setImageView(bitmap: Bitmap) { imageView.setImageBitmap(bitmap) } fun setIconView(bitmap: Bitmap) { iconView.setImageBitmap(bitmap) } fun setCustomView(customView: View) { this.customViewLayout.addView(customView) } fun setTitle(title: String) { this.title.text = title } fun setDescription(description: String) { this.description.text = description } fun setCallToAction(callToAction: String) { this.callToAction.text = callToAction } fun setSocialContext(socialContext: String) { this.socialContext.text = socialContext } fun setSponsoredBy(sponsoredBy: String) { this.sponsoredBy.text = sponsoredBy } fun setAdStartValue(value: String) { this.adStarRating.text = value } } }
examples/kotlin/LazyLoadDemo/app/src/main/java/com/xandr/lazyloaddemo/adapter/AdViewRecyclerAdapter.kt
821407337
package at.cpickl.gadsu.client.view import at.cpickl.gadsu.client.Client import at.cpickl.gadsu.view.ViewConstants import at.cpickl.gadsu.view.components.panels.GridPanel import at.cpickl.gadsu.view.swing.Pad import at.cpickl.gadsu.view.swing.opaque import java.awt.Component import java.awt.GridBagConstraints import javax.swing.JLabel import javax.swing.JList import javax.swing.ListCellRenderer //class ClientRenderer : DefaultListCellRenderer() { // // override fun getListCellRendererComponent(list: JList<*>?, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { // val comp = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus) // (comp as JLabel).text = (value as Client?)?.fullName ?: "null" // return comp // } // //} class ClientRenderer : ListCellRenderer<Client> { override fun getListCellRendererComponent(list: JList<out Client>?, value: Client?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { val panel = GridPanel() panel.opaque() ViewConstants.Table.changeBackground(panel, cellHasFocus) with(panel.c) { fill = GridBagConstraints.VERTICAL anchor = GridBagConstraints.WEST weightx = 0.0 panel.add(JLabel(value?.picture?.toViewLilRepresentation())) gridx++ insets = Pad.LEFT fill = GridBagConstraints.BOTH weightx = 1.0 panel.add(JLabel(value?.preferredName ?: "null")) } return panel } }
src/main/kotlin/at/cpickl/gadsu/client/view/renderer.kt
4117509309
package ee.design.gen.ts import ee.common.ext.logger import ee.lang.* import ee.design.* import ee.lang.gen.ts.* import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.* import org.slf4j.Logger object SimpleComp: Comp({ artifact("ee-lang-test").namespace("ee.lang.test") }) { object SimpleModule: Module() { // Simple object with basic elements object SimpleBasic : Basic() { val firstSimpleProperty = propS() val anotherSimpleProperty = propS() val lastSimpleProperty = propS() } object SimpleEntity : Entity() { val simpleBasicProperties = prop(SimpleBasic) val name = propS() val birthday = propDT() val bool = propB() val count = propI() val float = propF() } object SimpleEnum : EnumType() { val variable1 = lit() val variable2 = lit() val variable3 = lit() } // Object for Testing with Generic object GenericEntity : Entity() { val elementWithGenericType = prop(n.List.GT(SimpleEntity)) val elementWithoutGenericType = propS() } // Object for Testing with Operation object EntityWithOperations : Entity() { val name = propS() val birthday = propDT() val contact = prop(OperationComponent) val findByFirstName = findBy(contact.sub { firstname }) val findByLastName = findBy(contact.sub { lastname }) } object OperationComponent : Basic() { val firstname = propS() val lastname = propS() } // Object for Testing with Nullables object EntityWithNullables : Entity() { val nameNotNullable = propS { nullable(false) } val nameNullable = propS { nullable(true) } } // Object for Testing with Empty Constructor object EntityWithEmptyConstructor : Entity() { val superunit = defineSuperUnitsAsAnonymousProps() val constructor = constructorOwnPropsOnly() } } } // Object for Testing with Constructor object CompWithConstructor: Comp({ artifact("ee-lang-test").namespace("ee.lang.test") }) { object ModuleWithConstructor: Module() { object EntityWithConstructor : Entity() { val superunit = prop { type(superUnit().name("superUnitTest")) } val voidItem = prop { type() } } } } object ComponentWithoutInterface: Comp({ artifact("ee-lang-test").namespace("ee.lang.test") }) { object ModuleWithoutInherit: Module() { object BasicWithoutInherit : Basic() { val firstSimpleProperty = propS() val anotherSimpleProperty = propS() val lastSimpleProperty = propS() } } } object ComponentWithInterface: Comp({ artifact("ee-lang-test").namespace("ee.lang.test") }) { object ModuleWithInherit: Module() { object BasicWithInherit : Basic() { val firstSimpleProperty = prop(BasicWithoutInherit) val anotherSimpleProperty = propS() val lastSimpleProperty = propS() } object BasicWithoutInherit : Basic() { val firstSimpleProperty = propS() val anotherSimpleProperty = propS() val lastSimpleProperty = propS() } } } @TestMethodOrder(MethodOrderer.OrderAnnotation::class) class TypeScriptPojosTest { val log = logger() @BeforeEach fun beforeTypeScriptPojosTest() { SimpleComp.prepareForTsGeneration() } @Test @Order(1) @DisplayName("Empty Test without Derived") fun emptyTypeScriptTestWithoutDerived() { val out = SimpleComp.toTypeScriptEMPTY(context(), "") log.infoBeforeAfter(out) assertThat(out, `is`("SimpleComp.EMPTY")) } @Test @Order(2) @DisplayName("Empty Test with Derived") fun emptyTypeScriptTestWithDerived() { val out = SimpleComp.toTypeScriptEMPTY(context(), "WithDerived") log.infoBeforeAfter(out) assertThat(out, `is`("SimpleCompWithDerived.EMPTY")) } @Test @Order(3) @DisplayName("Typescript Test Basic Elements") fun simpleBasicTest() { val out = SimpleComp.SimpleModule.SimpleBasic.toTypeScriptImpl(context(), "", "") log.infoBeforeAfter(out) assertThat(out, `is`(""" export class SimpleBasic { firstSimpleProperty: string anotherSimpleProperty: string lastSimpleProperty: string constructor() { } } """.trimIndent())) } @Test @Order(4) @DisplayName("Typescript Test Entity Elements") fun simpleEntityTest() { val out = SimpleComp.SimpleModule.SimpleEntity.toTypeScriptImpl(context(), "", "") log.infoBeforeAfter(out) assertThat(out, `is`(""" export class SimpleEntity { simpleBasicProperties: SimpleBasic name: string birthday: Date bool: boolean count: number float: number constructor() { } } """.trimIndent())) } @Test @Order(5) @DisplayName("Typescript Test Entity Elements with Extend") fun simpleEntityTestWithExtends() { val out = SimpleComp.SimpleModule.SimpleEntity.toTypeScriptImpl(context(), "") log.infoBeforeAfter(out) assertThat(out, `is`(""" export class SimpleEntity extends SimpleEntity { simpleBasicProperties: SimpleBasic name: string birthday: Date bool: boolean count: number float: number constructor() { } } """.trimIndent())) } @Test @Order(6) @DisplayName("Typescript Test Entity Elements with Generics") fun simpleEntityTestWithGeneric() { val out = SimpleComp.SimpleModule.GenericEntity.toTypeScriptImpl(context(), "", "") log.infoBeforeAfter(out) assertThat(out, `is`(""" export class GenericEntity { elementWithGenericType: Array<SimpleEntity> elementWithoutGenericType: string constructor() { } } """.trimIndent())) } @Test @Order(7) @DisplayName("Typescript Test Entity Elements with Operations") fun simpleEntityTestWithOperations() { val out = SimpleComp.SimpleModule.EntityWithOperations.toTypeScriptImpl(context(), "", "") log.infoBeforeAfter(out) assertThat(out, `is`(""" export class EntityWithOperations { name: string birthday: Date contact: OperationComponent constructor() { } findByFirstName(firstname: string = ''): EntityWithOperations { throw new ReferenceError('Not implemented yet.'); } findByLastName(lastname: string = ''): EntityWithOperations { throw new ReferenceError('Not implemented yet.'); } } """.trimIndent())) } @Test @Order(8) @DisplayName("Typescript Test Entity Elements with Nullables") fun simpleEntityTestWithNullables() { val out = SimpleComp.SimpleModule.EntityWithNullables.toTypeScriptImpl(context(), "", "") log.infoBeforeAfter(out) assertThat(out, `is`(""" export class EntityWithNullables { nameNotNullable: string nameNullable: string? constructor() { } } """.trimIndent())) } @Test @Order(9) @DisplayName("Typescript Test Enum Elements") fun simpleEnumTest() { val out = SimpleComp.SimpleModule.SimpleEnum.toTypeScriptEnum(context(), "") log.infoBeforeAfter(out) assertThat(out, `is`(""" export enum SimpleEnum { VARIABLE1, VARIABLE2, VARIABLE3 } """.trimIndent())) } @Test @Order(10) @DisplayName("Typescript Test Enum Parse Method") fun simpleEnumParseMethodTest() { val out = SimpleComp.SimpleModule.SimpleEnum.toTypeScriptEnumParseMethod(context(), "") log.infoBeforeAfter(out) assertThat(out, `is`(""" fun String?.toSimpleEnum(): SimpleEnum { return if (this != null) SimpleEnum.valueOf(this) else SimpleEnum.VARIABLE1; } """.trimIndent())) } @Test @Order(11) @DisplayName("Typescript Test Entity Elements Default") fun toTypeScriptDefaultTest() { val out = SimpleComp.SimpleModule.SimpleEntity.toTypeScriptDefault(context(), "", Attribute.EMPTY) log.infoBeforeAfter(out) assertThat(out, `is`("new SimpleEntity()".trimIndent())) } @Test @Order(12) @DisplayName("Typescript Test with Empty Constructor") fun simpleEmptyConstructor() { val out = SimpleComp.SimpleModule.EntityWithEmptyConstructor.toTypeScriptImpl(context(), "", "") log.infoBeforeAfter(out) assertThat(out, `is`(""" export class EntityWithEmptyConstructor { @@EMPTY@@: @@EMPTY@@ constructor(@@EMPTY@@: @@EMPTY@@ = @@EMPTY@@.EMPTY) { { this.@@EMPTY@@ = @@EMPTY@@ } } """.trimIndent())) } /*@Test @Order(13) @DisplayName("Typescript Test with Constructor") fun entityWithConstructor() { CompWithConstructor.prepareForTsGeneration() val out = CompWithConstructor.ModuleWithConstructor.EntityWithConstructor.toTypeScriptImpl(contextConst(), "", "") log.infoBeforeAfter(out) assertThat(out, `is`(""" export class EntityWithConstructor extends superUnitTest { superunit: superUnitTest voidItem: void superUnitTest: superUnitTest constructor(superUnitTest: superUnitTest = superUnitTest.EMPTY) { this.superUnitTest = superUnitTest } } """.trimIndent())) }*/ } private fun context() = LangTsContextFactory().buildForImplOnly().builder.invoke(SimpleComp) private fun contextConst() = LangTsContextFactory().buildForImplOnly().builder.invoke(CompWithConstructor) private fun contextCompWithInterface() = LangTsContextFactory().buildForImplOnly().builder.invoke(ComponentWithInterface) private fun contextCompWithoutInterface() = LangTsContextFactory().buildForImplOnly().builder.invoke(ComponentWithoutInterface) fun Logger.infoBeforeAfter(out: String) { info("before") info(out) info("after") }
ee-design/src/test/kotlin/ee/design/gen/ts/TypeScriptPojosTest.kt
2062078365
package com.sksamuel.kotest.specs.describe import io.kotest.assertions.fail import io.kotest.core.spec.style.DescribeSpec import kotlin.time.ExperimentalTime import kotlin.time.milliseconds @UseExperimental(ExperimentalTime::class) class DescribeSpecExample : DescribeSpec() { init { describe("some thing") { it("test name") { // test here } xit("disabled test") { fail("should not be invoked") } describe("a nested describe!") { it("test name") { // test here } xit("disabled test") { fail("should not be invoked") } } context("with some context") { it("test name") { // test here } it("test name 2").config(enabled = false) { // test here } context("with some context") { it("test name") { // test here } it("test name 2").config(timeout = 1512.milliseconds) { // test here } } } xdescribe("disabled describe") { fail("should not be invoked") } } describe("some other thing") { context("with some context") { it("test name") { // test here } it("test name 2").config(enabled = true) { // test here } context("with some context") { it("test name") { // test here } it("test name 2").config(timeout = 1512.milliseconds) { // test here } } } } xdescribe("disabled top level describe") { fail("should not be invoked") } } }
kotest-tests/kotest-tests-core/src/jvmTest/kotlin/com/sksamuel/kotest/specs/describe/DescribeSpecExample.kt
1365021500
package io.kotest.core.factory import io.kotest.core.SourceRef import io.kotest.core.Tag import io.kotest.core.extensions.Extension import io.kotest.core.listeners.TestListener import io.kotest.core.spec.Spec import io.kotest.core.test.* /** * A [TestFactory] is a generator of tests along with optional configuration and * callbacks related to those tests. A test factory can be added to a [Spec] and the * tests generated by the factory will be included in that spec. */ data class TestFactory( val factoryId: TestFactoryId, val tests: List<DynamicTest>, val tags: Set<Tag>, val assertionMode: AssertionMode?, val listeners: List<TestListener>, val extensions: List<Extension>, val factories: List<TestFactory> ) /** * A [DynamicTest] is an intermediate test state held by a factory. Once the factory is added to a * [Spec] and the spec is created, the factories dynamic tests will be added to the spec * as fully fledged [TestCase]s. */ data class DynamicTest( val name: String, val test: suspend TestContext.() -> Unit, val config: TestCaseConfig, val type: TestType, val source: SourceRef )
kotest-core/src/commonMain/kotlin/io/kotest/core/factory/factory.kt
2212306808
package com.lasthopesoftware.bluewater.client.stored.library.items.files.download.GivenARequestForAStoredFile.ThatSucceeds import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFileUriQueryParamsProvider import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId import com.lasthopesoftware.bluewater.client.connection.FakeConnectionProvider import com.lasthopesoftware.bluewater.client.connection.FakeConnectionResponseTuple import com.lasthopesoftware.bluewater.client.connection.libraries.ProvideLibraryConnections import com.lasthopesoftware.bluewater.client.stored.library.items.files.download.StoredFileDownloader import com.lasthopesoftware.bluewater.client.stored.library.items.files.repository.StoredFile import com.lasthopesoftware.bluewater.shared.promises.extensions.FuturePromise import com.lasthopesoftware.bluewater.shared.promises.extensions.ProgressingPromise import org.apache.commons.io.IOUtils import org.assertj.core.api.Assertions import org.junit.BeforeClass import org.junit.Test import org.mockito.Mockito import java.io.ByteArrayOutputStream import java.io.IOException import java.io.InputStream import java.util.* class WhenDownloading { companion object { private val responseBytes by lazy { val bytes = ByteArray(400) Random().nextBytes(bytes) bytes } private var inputStream: InputStream? = null @BeforeClass @JvmStatic fun before() { val fakeConnectionProvider = FakeConnectionProvider() fakeConnectionProvider.mapResponse({ FakeConnectionResponseTuple( 200, responseBytes ) }) val libraryConnections = Mockito.mock( ProvideLibraryConnections::class.java ) Mockito.`when`(libraryConnections.promiseLibraryConnection(LibraryId(4))) .thenReturn(ProgressingPromise(fakeConnectionProvider)) val downloader = StoredFileDownloader(ServiceFileUriQueryParamsProvider(), libraryConnections) inputStream = FuturePromise( downloader.promiseDownload( LibraryId(4), StoredFile().setServiceId(4) ) ).get() } } @Test @Throws(IOException::class) fun thenTheInputStreamIsReturned() { val outputStream = ByteArrayOutputStream() IOUtils.copy(inputStream, outputStream) Assertions.assertThat(outputStream.toByteArray()).containsExactly(*responseBytes) } }
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/stored/library/items/files/download/GivenARequestForAStoredFile/ThatSucceeds/WhenDownloading.kt
3546544794
package com.example.one fun main() { resizePane(newSize = 10, forceResize = true, noAnimation = false) // Swap the order of last two named arguments resizePane(newSize = 11, noAnimation = false, forceResize = true) // Named arguments can be passed in any order resizePane(forceResize = true, newSize = 12, noAnimation = false) // Mixing Named and Positional Arguments // Kotlin 1.3 would allow us to name only the arguments after the positional ones resizePane(20, true, noAnimation = false) // Using a positional argument in the middle of named arguments (supported from Kotlin 1.4.0) // resizePane(newSize = 20, true, noAnimation = false) // Only the last argument as a positional argument (supported from Kotlin 1.4.0) // resizePane(newSize = 30, forceResize = true, false) // Use a named argument in the middle of positional arguments (supported from Kotlin 1.4.0) // resizePane(40, forceResize = true, false) } fun resizePane(newSize: Int, forceResize: Boolean, noAnimation: Boolean) { println("The parameters are newSize = $newSize, forceResize = $forceResize, noAnimation = $noAnimation") }
pitest-maven-verification/src/test/resources/pit-kotlin-multi-module/sub-module-1/src/main/kotlin/NamedArguments.kt
574838422
import com.devcharly.kotlin.ant.* import java.io.File fun main(args: Array<String>) { // make basedirs used below File("_files_").mkdirs() File("_fileset_").mkdirs() File("_zip_").mkdirs() demoEcho() demoProperty() demoFiles() demoFileset() demoZip() demoTar() demoJar() demoJava() } fun demoEcho() { Ant { echo("Hello World") echo { +"aa" +"bb" +"cc" } echo(level = EchoLevel.ERROR) { +""" 111 22 3 """ } } } fun demoProperty() { Ant { property("place", "World") echo("Hello ${p("place")}") } } fun demoFiles() { Ant(basedir = "_files_") { touch("file.txt") echo("content2\n", file = "file2.txt", append = true) copy("file.txt", todir = "dir", overwrite = true) copy("file2.txt", tofile = "dir/file2.txt") delete("file.txt") } } fun demoFileset() { Ant(basedir = "_fileset_", logLevel = LogLevel.VERBOSE) { mkdir("dir1") mkdir("dir2") touch("dir1/file1.java") touch("dir2/file2.java") touch("dir2/fileTest.java") copy(todir = "dir") { fileset("dir1") fileset("dir2") { include(name = "**/*.java") exclude(name = "**/*Test*") } } } } fun demoZip() { Ant(basedir = "_zip_") { echo("content1", file = "dir/file1.txt") echo("content2", file = "dir/file2.txt") zip("out1.zip", basedir = "dir") zip("out2.zip", basedir = "dir", includes = "file1.txt") zip("out3.zip") { fileset(dir = "dir", includes = "file2.txt") } zip("out4.zip") { zipfileset(dir = "dir", prefix = "pre-dir") } } } fun demoTar() { Ant(basedir = "_zip_", logLevel = LogLevel.VERBOSE) { tar("out1.tar") { tarfileset(dir = "dir", username = "user1", uid = 123, filemode = "600") } bzip2(src = "out1.tar", destfile = "out1.tar.bz2") gzip(src = "out1.tar", destfile = "out1.tar.gz") bunzip2(src = "out1.tar.bz2", dest = "out1b.tar") gunzip(src = "out1.tar.gz", dest = "out1g.tar") } } fun demoJar() { Ant(basedir = "_zip_") { jar(destfile = "out1.jar", basedir = "dir") { manifest { attribute("Main-Class", "com.myapp.Main") attribute("Class-Path", "common.jar") } service("javax.script.ScriptEngineFactory") { provider("org.acme.PinkyLanguage") provider("org.acme.BrainLanguage") } } } } fun demoJava() { Ant { java(classname="test.Main") { arg("-h") classpath { pathelement(location = "dist/test.jar") pathelement(path = p("java.class.path")) } } } }
examples/src/demo.kt
2048539092
package com.ruuvi.station.tag.domain import android.content.Context import com.ruuvi.station.app.preferences.Preferences import com.ruuvi.station.database.tables.RuuviTagEntity import com.ruuvi.station.units.domain.UnitsConverter class TagConverter( private val context: Context, private val preferences: Preferences, private val unitsConverter: UnitsConverter ) { fun fromDatabase(entity: RuuviTagEntity): RuuviTag = RuuviTag( id = entity.id.orEmpty(), name = entity.name.orEmpty(), displayName = entity.name ?: entity.id.toString(), rssi = entity.rssi, temperature = entity.temperature, humidity = entity.humidity, pressure = entity.pressure, updatedAt = entity.updateAt, temperatureString = unitsConverter.getTemperatureString(entity.temperature), humidityString = unitsConverter.getHumidityString(entity.humidity, entity.temperature), pressureString = unitsConverter.getPressureString(entity.pressure), defaultBackground = entity.defaultBackground, userBackground = entity.userBackground, dataFormat = entity.dataFormat, connectable = entity.connectable, lastSync = entity.lastSync ) }
app/src/main/java/com/ruuvi/station/tag/domain/TagConverter.kt
672124895
package com.baulsupp.okurl.services.transferwise import com.baulsupp.okurl.authenticator.oauth2.Oauth2ServiceDefinition import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token import com.baulsupp.okurl.credentials.ServiceDefinition open class TransferwiseAuthInterceptor : BaseTransferwiseAuthInterceptor() { override val serviceDefinition: ServiceDefinition<Oauth2Token> = Oauth2ServiceDefinition( "api.transferwise.com", "Transferwise API", "transferwise", "https://api-docs.transferwise.com/docs/versions/v1/overview", "https://api-docs.transferwise.com/api-explorer/transferwise-api/versions/v1/" ) }
src/main/kotlin/com/baulsupp/okurl/services/transferwise/TransferwiseAuthInterceptor.kt
2807665278
package com.curiosityio.androidboilerplate.util import android.telephony.PhoneNumberUtils import android.util.Patterns open class ValidCheckUtil { companion object { fun isValidEmail(email: String?): Boolean { if (email == null) return false else return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches() } fun isValidPhoneNumber(number: String?): Boolean { if (number == null) return false else return PhoneNumberUtils.isGlobalPhoneNumber(number) } fun isValidURL(url: String?): Boolean { if (url == null) return false else return Patterns.WEB_URL.matcher(url).matches() } fun isValidFirstAndLastName(fullname: String): Boolean { // regex accepts any [1 or more none whitespace character(s)], [one space], [1 or more none whitespace character(s)] // (allows hyphens in names for example why allowing any non-whitespace char.) val splitFullName = fullname.trim { it <= ' ' }.split("\\S+[ ]\\S+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() return splitFullName.size == 2 } fun getSplitFullName(fullname: String): Array<String>? { if (isValidFirstAndLastName(fullname)) { return fullname.trim { it <= ' ' }.split("\\S+[ ]\\S+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() } return null } } }
androidboilerplate/src/main/java/com/curiosityio/androidboilerplate/util/ValidCheckUtil.kt
1365105763
package io.particle.mesh.setup.flow.setupsteps import io.particle.mesh.setup.flow.MeshSetupStep import io.particle.mesh.setup.flow.Scopes import io.particle.mesh.setup.flow.context.SetupContexts import io.particle.mesh.setup.flow.FlowUiDelegate class StepShowCellularConnectingToDeviceCloudUi( private val flowUi: FlowUiDelegate ) : MeshSetupStep() { override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) { if (ctxs.cellular.connectingToCloudUiShown) { return } ctxs.cellular.connectingToCloudUiShown = true flowUi.showConnectingToDeviceCloudCellularUi() } }
mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepShowCellularConnectingToDeviceCloudUi.kt
706362323
package reactivecircus.flowbinding.material import android.view.View import androidx.test.filters.LargeTest import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.common.truth.Truth.assertThat import org.junit.Test import reactivecircus.flowbinding.material.fixtures.MaterialFragment1 import reactivecircus.flowbinding.material.test.R import reactivecircus.flowbinding.testing.FlowRecorder import reactivecircus.flowbinding.testing.launchTest import reactivecircus.flowbinding.testing.recordWith @LargeTest class BottomSheetBehaviorStateChangedFlowTest { @Test fun bottomSheetStateChanges() { launchTest<MaterialFragment1> { val recorder = FlowRecorder<Int>(testScope) val bottomSheet = getViewById<View>(R.id.bottomSheetLayout) val behavior = BottomSheetBehavior.from(bottomSheet) bottomSheet.bottomSheetStateChanges().recordWith(recorder) recorder.assertNoMoreValues() behavior.state = BottomSheetBehavior.STATE_EXPANDED // STATE_DRAGGING state is not emitted for programmatic state change assertThat(recorder.takeValue()) .isEqualTo(BottomSheetBehavior.STATE_SETTLING) assertThat(recorder.takeValue()) .isEqualTo(BottomSheetBehavior.STATE_EXPANDED) behavior.state = BottomSheetBehavior.STATE_COLLAPSED // STATE_DRAGGING state is not emitted for programmatic state change assertThat(recorder.takeValue()) .isEqualTo(BottomSheetBehavior.STATE_SETTLING) assertThat(recorder.takeValue()) .isEqualTo(BottomSheetBehavior.STATE_COLLAPSED) behavior.state = BottomSheetBehavior.STATE_HIDDEN // STATE_DRAGGING state is not emitted for programmatic state change assertThat(recorder.takeValue()) .isEqualTo(BottomSheetBehavior.STATE_SETTLING) assertThat(recorder.takeValue()) .isEqualTo(BottomSheetBehavior.STATE_HIDDEN) cancelTestScope() recorder.clearValues() behavior.state = BottomSheetBehavior.STATE_EXPANDED recorder.assertNoMoreValues() } } }
flowbinding-material/src/androidTest/java/reactivecircus/flowbinding/material/BottomSheetBehaviorStateChangedFlowTest.kt
2409481109
/* * Copyright 2020-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.lettuce.core.sentinel.api.coroutines import io.lettuce.core.ExperimentalLettuceCoroutinesApi import io.lettuce.core.KillArgs import io.lettuce.core.output.CommandOutput import io.lettuce.core.protocol.CommandArgs import io.lettuce.core.protocol.ProtocolKeyword import io.lettuce.core.sentinel.api.reactive.RedisSentinelReactiveCommands import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.toList import kotlinx.coroutines.reactive.asFlow import kotlinx.coroutines.reactive.awaitFirstOrNull import kotlinx.coroutines.reactive.awaitLast import java.net.SocketAddress /** * Coroutine executed commands (based on reactive commands) for Redis Sentinel. * * @param <K> Key type. * @param <V> Value type. * @author Mikhael Sokolov * @since 6.0 */ @ExperimentalLettuceCoroutinesApi internal class RedisSentinelCoroutinesCommandsImpl<K : Any, V : Any>(private val ops: RedisSentinelReactiveCommands<K, V>) : RedisSentinelCoroutinesCommands<K, V> { override suspend fun getMasterAddrByName(key: K): SocketAddress = ops.getMasterAddrByName(key).awaitLast() override suspend fun masters(): List<Map<K, V>> = ops.masters().asFlow().toList() override suspend fun master(key: K): Map<K, V> = ops.master(key).awaitLast() override suspend fun slaves(key: K): List<Map<K, V>> = ops.slaves(key).asFlow().toList() override suspend fun reset(key: K): Long = ops.reset(key).awaitLast() override suspend fun failover(key: K): String = ops.failover(key).awaitLast() override suspend fun monitor(key: K, ip: String, port: Int, quorum: Int): String = ops.monitor(key, ip, port, quorum).awaitLast() override suspend fun set(key: K, option: String, value: V): String = ops.set(key, option, value).awaitLast() override suspend fun remove(key: K): String = ops.remove(key).awaitLast() override suspend fun clientGetname(): K? = ops.clientGetname().awaitFirstOrNull() override suspend fun clientSetname(name: K): String = ops.clientSetname(name).awaitLast() override suspend fun clientKill(addr: String): String = ops.clientKill(addr).awaitLast() override suspend fun clientKill(killArgs: KillArgs): Long = ops.clientKill(killArgs).awaitLast() override suspend fun clientPause(timeout: Long): String = ops.clientPause(timeout).awaitLast() override suspend fun clientList(): String = ops.clientList().awaitLast() override suspend fun info(): String = ops.info().awaitLast() override suspend fun info(section: String): String = ops.info(section).awaitLast() override suspend fun ping(): String = ops.ping().awaitLast() override fun <T : Any> dispatch(type: ProtocolKeyword, output: CommandOutput<K, V, T>): Flow<T> = ops.dispatch<T>(type, output).asFlow() override fun <T : Any> dispatch(type: ProtocolKeyword, output: CommandOutput<K, V, T>, args: CommandArgs<K, V>): Flow<T> = ops.dispatch<T>(type, output, args).asFlow() override fun isOpen(): Boolean = ops.isOpen }
src/main/kotlin/io/lettuce/core/sentinel/api/coroutines/RedisSentinelCoroutinesCommandsImpl.kt
3532166173
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.provider import org.gradle.internal.concurrent.Stoppable open class ClassPathModeExceptionCollector : Stoppable { private val collection = mutableListOf<Exception>() val exceptions: List<Exception> get() = collection fun collect(error: Exception) { collection.add(error) } override fun stop() { collection.clear() } } inline fun <T> ClassPathModeExceptionCollector.ignoringErrors(f: () -> T): T? = try { f() } catch (e: Exception) { collect(e) null }
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/provider/ClassPathModeExceptionCollector.kt
87931634
package elite.gils.country /** * Continent: (Name) * Country: (Name) */ enum class BR private constructor( //Leave the code below alone (unless optimizing) private val name: String) { //List of State/Province names (Use 2 Letter/Number Combination codes) /** * Name: */ AA("Example"), /** * Name: */ AB("Example"), /** * Name: */ AC("Example"); fun getName(state: BR): String { return state.name } }
ObjectAvoidance/kotlin/src/elite/gils/country/BR.kt
718619511
package com.github.kittinunf.fuel.android.util import android.os.Handler import android.os.Looper import com.github.kittinunf.fuel.core.Environment import java.util.concurrent.Executor internal class AndroidEnvironment : Environment { val handler = Handler(Looper.getMainLooper()) override var callbackExecutor: Executor = Executor { command -> handler.post(command) } }
fuel-android/src/main/kotlin/com/github/kittinunf/fuel/android/util/AndroidEnvironment.kt
723622238
package com.waz.zclient.storage.db.history import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "EditHistory") data class EditHistoryEntity( @PrimaryKey @ColumnInfo(name = "original_id") val originalId: String, @ColumnInfo(name = "updated_id", defaultValue = "") val updatedId: String, @ColumnInfo(name = "timestamp", defaultValue = "0") val timestamp: Int )
storage/src/main/kotlin/com/waz/zclient/storage/db/history/EditHistoryEntity.kt
41380237
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.main import androidx.fragment.app.DialogFragment import androidx.fragment.app.FragmentManager import jp.toastkid.yobidashi.tab.tab_list.TabListDialogFragment /** * @author toastkidjp */ class TabListUseCase( private val fragmentManager: FragmentManager, private val thumbnailRefresher: () -> Unit ) { /** * Tab list dialog fragment. */ private var tabListDialogFragment: DialogFragment = TabListDialogFragment() fun switch() { if (tabListDialogFragment.isVisible) { dismiss() } else { showTabList() } } fun dismiss() { tabListDialogFragment.dismiss() } /** * Show tab list. */ private fun showTabList() { thumbnailRefresher() tabListDialogFragment.show(fragmentManager, TabListDialogFragment::class.java.canonicalName) } fun onBackPressed(): Boolean { if (tabListDialogFragment.isVisible) { tabListDialogFragment.dismiss() return true } return false } }
app/src/main/java/jp/toastkid/yobidashi/main/TabListUseCase.kt
3054760940
package screenswitchersample.core.components import screenswitchersample.core.activity.ActivityComponentFactory interface ApplicationComponent : PassthroughComponent { val activityComponentFactory: ActivityComponentFactory }
sample-core/src/main/java/screenswitchersample/core/components/ApplicationComponent.kt
2482462464
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.resolve.ref import org.rust.lang.core.psi.ext.RsElement import org.rust.lang.core.types.BoundElement interface RsPathReference : RsReference { fun advancedResolve(): BoundElement<RsElement>? fun advancedMultiResolve(): List<BoundElement<RsElement>> }
src/main/kotlin/org/rust/lang/core/resolve/ref/RsPathReference.kt
2479898088
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho.codelab.events import com.facebook.litho.Component import com.facebook.litho.ComponentContext import com.facebook.litho.Row import com.facebook.litho.annotations.LayoutSpec import com.facebook.litho.annotations.OnCreateLayout import com.facebook.litho.annotations.Prop import com.facebook.litho.widget.Text import com.facebook.yoga.YogaAlign @Suppress("MagicNumber") @LayoutSpec object ButtonSpec { @OnCreateLayout fun onCreateLayout(c: ComponentContext, @Prop text: String): Component { return Row.create(c, 0, R.style.Widget_AppCompat_Button_Small) .clickable(true) .child(Text.create(c).alignSelf(YogaAlign.CENTER).textSizeSp(20f).text(text)) .build() } }
codelabs/events/app/src/main/java/com/facebook/litho/codelab/events/ButtonSpec.kt
2527887064
package net.yslibrary.monotweety.changelog import dagger.Module import dagger.Provides import net.yslibrary.monotweety.base.EventBus import net.yslibrary.monotweety.base.di.ControllerScope import net.yslibrary.monotweety.base.di.Names import javax.inject.Named @Module class ChangelogViewModule(private val activityBus: EventBus) { @ControllerScope @Provides @Named(Names.FOR_ACTIVITY) fun provideActivityBus(): EventBus = activityBus interface DependencyProvider { @Named(Names.FOR_ACTIVITY) fun activityBus(): EventBus } }
app/src/main/java/net/yslibrary/monotweety/changelog/ChangelogViewModule.kt
618403310
// 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.vcs.log.data.index import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.LocalFilePath import com.intellij.util.containers.BiDirectionalEnumerator import com.intellij.util.containers.ContainerUtil.canonicalStrategy import com.intellij.vcs.log.data.index.VcsLogPathsIndex.ChangeData import com.intellij.vcs.log.data.index.VcsLogPathsIndex.ChangeKind.* import junit.framework.TestCase class FileNamesDataTest : TestCase() { fun `test linear file history`() { val data = TestFileNamesData() val file = LocalFilePath("file.txt", false) data.add(0, file, mutableListOf(modification()), listOf()) data.add(1, file, mutableListOf(modification()), listOf(0)) data.add(2, file, mutableListOf(modification()), listOf(1)) assertEquals(mapOf(Pair(0, file), Pair(1, file), Pair(2, file)), data.buildPathsMap()) } fun `test history with rename`() { val data = TestFileNamesData() val file = LocalFilePath("file.txt", false) val oldFile = LocalFilePath("oldfile.txt", false) val renameFrom = ChangeData(RENAMED_FROM, data.getPathId(file)) val renameTo = ChangeData(RENAMED_TO, data.getPathId(oldFile)) data.add(0, oldFile, mutableListOf(modification()), listOf()) data.add(1, file, mutableListOf(renameTo), listOf(0)) data.add(1, oldFile, mutableListOf(renameFrom), listOf(0)) data.add(2, file, mutableListOf(modification()), listOf(1)) assertEquals(file, data.getPathInChildRevision(1, 0, oldFile)) assertEquals(oldFile, data.getPathInParentRevision(1, 0, file)) assertEquals(mapOf(Pair(0, oldFile), Pair(1, file), Pair(2, file)), data.buildPathsMap()) } fun `test history with simple merge`() { val data = TestFileNamesData() val file = LocalFilePath("file.txt", false) data.add(0, file, mutableListOf(modification()), listOf()) data.add(1, file, mutableListOf(modification()), listOf(0)) // 3 is merge commit of 1 and 2 // where 1 had a change, 2 did not data.add(3, file, mutableListOf(null, modification()), listOf(1, 2)) assertEquals(file, data.getPathInParentRevision(3, 1, file)) assertEquals(file, data.getPathInParentRevision(3, 2, file)) assertEquals(mapOf(Pair(0, file), Pair(1, file), Pair(3, file)), data.buildPathsMap()) } fun `test history with merge rename`() { val data = TestFileNamesData() val file = LocalFilePath("file.txt", false) val oldFile = LocalFilePath("oldfile.txt", false) val renameFrom = ChangeData(RENAMED_FROM, data.getPathId(file)) val renameTo = ChangeData(RENAMED_TO, data.getPathId(oldFile)) data.add(0, oldFile, mutableListOf(modification()), listOf()) // commit 1 renames file data.add(1, file, mutableListOf(renameTo), listOf(0)) data.add(1, oldFile, mutableListOf(renameFrom), listOf(0)) // commit 3 is a merge of 1 and 2 // since file was renamed in 1, then file is renamed the same way from 2 to 3 data.add(3, file, mutableListOf(null, renameTo), listOf(1, 2)) data.add(3, oldFile, mutableListOf(null, renameFrom), listOf(1, 2)) assertEquals(file, data.getPathInParentRevision(3, 1, file)) assertEquals(oldFile, data.getPathInParentRevision(3, 2, file)) assertEquals(file, data.getPathInChildRevision(3, 1, file)) assertEquals(file, data.getPathInChildRevision(3, 2, oldFile)) assertEquals(mapOf(Pair(0, oldFile), Pair(1, file), Pair(3, file)), data.buildPathsMap()) } private fun modification() = ChangeData(MODIFIED, -1) } private class TestFileNamesData : IndexDataGetter.FileNamesData() { private val pathEnumerator = BiDirectionalEnumerator<String>(1, canonicalStrategy<String>()) override fun getPathById(pathId: Int): FilePath = LocalFilePath(pathEnumerator.getValue(pathId), false) fun getPathId(path: FilePath) = pathEnumerator.enumerate(path.path) }
platform/vcs-log/impl/test/com/intellij/vcs/log/data/index/FileNamesDataTest.kt
1105301028
package de.constantinuous.angus.parsing.impl import de.constantinuous.angus.parsing.DatabaseParser import java.sql.Connection import java.sql.DriverManager import java.sql.SQLException /** * Created by RichardG on 09.10.2016. */ class JdbcDatabaseParser : DatabaseParser { override fun extractFoo(connectionString: String, user: String, password: String){ val conn = DriverManager.getConnection(connectionString, user, password) conn.catalog = "IOL_Dubai_P" val md = conn.metaData val numericFunctions = md.numericFunctions.split(",") val procedures = md.getProcedures(null, null, "%") val tables = md.getTables(null, null, "%", null) println("---- Procedures ----") while (procedures.next()) { println("Procedure: "+procedures.getString(3)) } println("---- Functions ----") for (function in numericFunctions) { println("Numeric Function: "+function) } println("---- Tables ----") while (tables.next()) { println("Table: "+tables.getString(3)) } } private fun getProcedureCode(connection: Connection, myViewName : String){ val query = "exec sp_helptext ?" val stmt = connection.prepareStatement(query) stmt.setString(1, myViewName) val rs = stmt.executeQuery() val b = StringBuilder() while (rs.next()) { b.append(rs.getString("Text")) } rs.close() stmt.close() println(b.toString()) } }
infrastructure/src/main/kotlin/de/constantinuous/angus/parsing/impl/JdbcDatabaseParser.kt
3107642958
package rxjoin.internal.codegen import rxjoin.annotation.Joined import javax.annotation.processing.Messager import javax.lang.model.type.MirroredTypeException import javax.lang.model.type.TypeMirror import javax.tools.Diagnostic.Kind.ERROR fun Joined.getValue(): TypeMirror { try { return value as TypeMirror } catch (e: MirroredTypeException) { return e.typeMirror } } fun Messager.error(message: String) { this.printMessage(ERROR, message) }
compiler/src/main/kotlin/rxjoin/internal/codegen/Util.kt
3833059698
package com.bachhuberdesign.deckbuildergwent.features.cardviewer import android.graphics.Color import android.os.Bundle import android.support.v4.view.MenuItemCompat import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.SearchView import android.util.Log import android.view.* import com.afollestad.materialdialogs.MaterialDialog import com.bachhuberdesign.deckbuildergwent.MainActivity import com.bachhuberdesign.deckbuildergwent.R import com.bachhuberdesign.deckbuildergwent.features.deckbuild.Deck import com.bachhuberdesign.deckbuildergwent.features.deckbuild.DeckbuildController import com.bachhuberdesign.deckbuildergwent.features.shared.model.Card import com.bachhuberdesign.deckbuildergwent.features.shared.model.Lane import com.bachhuberdesign.deckbuildergwent.inject.module.ActivityModule import com.bachhuberdesign.deckbuildergwent.util.changehandler.SharedElementDelayingChangeHandler import com.bachhuberdesign.deckbuildergwent.util.getStringResourceByName import com.bachhuberdesign.deckbuildergwent.util.inflate import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.FadeChangeHandler import com.bluelinelabs.conductor.changehandler.TransitionChangeHandlerCompat import com.google.gson.Gson import com.mikepenz.fastadapter.FastAdapter import com.mikepenz.fastadapter.commons.adapters.FastItemAdapter import com.mikepenz.fastadapter.helpers.ClickListenerHelper import com.mikepenz.fastadapter.listeners.ClickEventHook import com.mikepenz.fontawesome_typeface_library.FontAwesome import com.mikepenz.iconics.IconicsDrawable import kotlinx.android.synthetic.main.controller_cardviewer.view.* import javax.inject.Inject /** * @author Eric Bachhuber * @version 1.0.0 * @since 1.0.0 */ class CardViewerController : Controller, CardViewerMvpContract { constructor(filters: CardFilters) : super() { this.filters = filters } constructor(filters: CardFilters, deckId: Int) { this.filters = filters this.deckId = deckId } constructor(args: Bundle) : super() companion object { @JvmStatic val TAG: String = CardViewerController::class.java.name } @Inject lateinit var presenter: CardViewerPresenter @Inject lateinit var gson: Gson lateinit var recyclerView: RecyclerView lateinit var adapter: FastItemAdapter<CardItem> var currentSortMethod: Int = 0 var isSortAscending = true var isAddCardButtonClickable = true var filters: CardFilters? = null var deckId: Int = 0 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View { val view = container.inflate(R.layout.controller_cardviewer) (activity as MainActivity).persistedComponent .activitySubcomponent(ActivityModule(activity!!)) .inject(this) if (filters == null) { filters = gson.fromJson(args.getString("filters"), CardFilters::class.java) } if (deckId == 0) { deckId = args.getInt("deckId", 0) } if (deckId > 0) { (activity as MainActivity).displayHomeAsUp(true) } else { activity?.title = "Card Database" } setHasOptionsMenu(true) initRecyclerView(view) return view } override fun onAttach(view: View) { Log.d(TAG, "onAttach()") super.onAttach(view) presenter.attach(this) // TODO: Take getCards() call off UI thread presenter.getCards(filters!!, deckId) } override fun onDetach(view: View) { Log.d(TAG, "onDetach()") super.onDetach(view) presenter.detach() } override fun onDestroyView(view: View) { (activity as MainActivity).displayHomeAsUp(false) super.onDestroyView(view) } override fun onSaveInstanceState(outState: Bundle) { outState.putString("filters", gson.toJson(filters)) outState.putInt("deckId", deckId) super.onSaveInstanceState(outState) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_card_viewer, menu) menu.findItem(R.id.menu_filter_cards).icon = IconicsDrawable(activity!!) .icon(FontAwesome.Icon.faw_sort_amount_desc) .color(Color.WHITE) .sizeDp(18) menu.findItem(R.id.menu_search_cards).icon = IconicsDrawable(activity!!) .icon(FontAwesome.Icon.faw_search) .color(Color.WHITE) .sizeDp(18) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_search_cards -> showSearchActionView(item) R.id.menu_filter_cards -> showSortingDialog() } return super.onOptionsItemSelected(item) } private fun showSortingDialog() { val items = arrayListOf(activity!!.getString(R.string.sort_name), activity!!.getString(R.string.sort_type), activity!!.getString(R.string.sort_scrap_cost), activity!!.getString(R.string.sort_faction), activity!!.getString(R.string.sort_lane)) MaterialDialog.Builder(activity!!) .title(R.string.sort_title) .items(items) .itemsCallbackSingleChoice(currentSortMethod, { dialog, view, which, text -> isSortAscending = dialog.isPromptCheckBoxChecked currentSortMethod = which when (which) { 0 -> adapter.itemAdapter.withComparator(CardItem.CardNameComparator(isSortAscending)) 1 -> adapter.itemAdapter.withComparator(CardItem.CardTypeComparator(isSortAscending)) 2 -> adapter.itemAdapter.withComparator(CardItem.CardScrapCostComparator(isSortAscending)) 3 -> adapter.itemAdapter.withComparator(CardItem.CardFactionComparator(isSortAscending)) 4 -> adapter.itemAdapter.withComparator(CardItem.CardLaneComparator(isSortAscending)) } true }) .positiveText(R.string.confirm) .negativeText(android.R.string.cancel) .checkBoxPromptRes(R.string.checkbox_sort_ascending, isSortAscending, null) .show() } private fun showSearchActionView(searchItem: MenuItem) { val searchView = searchItem.actionView as SearchView MenuItemCompat.expandActionView(searchItem) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(queryText: String): Boolean { Log.d(TAG, "onQueryTextChange(): $queryText") adapter.filter(queryText) return true } override fun onQueryTextSubmit(p0: String?): Boolean { // Adapter filtering already handled by onQueryTextChange() -- ignore return true } }) } private fun initRecyclerView(v: View) { adapter = FastItemAdapter() adapter.withOnClickListener({ view, adapter, item, position -> val imageTransitionName = "imageTransition${item.card.cardId}" val nameTransitionName = "nameTransition${item.card.cardId}" val transitionNames = java.util.ArrayList<String>() transitionNames.add(imageTransitionName) transitionNames.add(nameTransitionName) router.pushController(RouterTransaction.with(CardDetailController(item.card.cardId)) .tag(DeckbuildController.TAG) .pushChangeHandler(TransitionChangeHandlerCompat(SharedElementDelayingChangeHandler(transitionNames), FadeChangeHandler())) .popChangeHandler(TransitionChangeHandlerCompat(SharedElementDelayingChangeHandler(transitionNames), FadeChangeHandler()))) true }) adapter.withItemEvent(object : ClickEventHook<CardItem>() { override fun onBindMany(viewHolder: RecyclerView.ViewHolder): MutableList<View>? { if (viewHolder is CardItem.ViewHolder) { return ClickListenerHelper.toList(viewHolder.removeCardButton, viewHolder.addCardButton) } else { return super.onBindMany(viewHolder) } } override fun onClick(v: View, position: Int, adapter: FastAdapter<CardItem>, item: CardItem) { if (v.tag == "add") { // Check if clickable to prevent duplicate presenter calls if (isAddCardButtonClickable) { isAddCardButtonClickable = false presenter.checkCardAddable(item.card, deckId) } } else if (v.tag == "remove") { if (item.count > 0) { presenter.removeCardFromDeck(deckId, item.card) } } } }) adapter.withFilterPredicate({ item, constraint -> val cardNameCondensed: String = item.card.name.replace("[\\W]".toRegex(), "") val constraintCondensed: String = constraint.replace("[\\W]".toRegex(), "") val descriptionCondensed: String = item.card.description.replace("[\\W]".toRegex(), "") // Filter out any item that doesn't match card name or description constraints !(cardNameCondensed.contains(constraintCondensed, ignoreCase = true) || descriptionCondensed.contains(constraintCondensed, ignoreCase = true)) }) val layoutManager = LinearLayoutManager(activity) recyclerView = v.recycler_view recyclerView.setHasFixedSize(false) recyclerView.layoutManager = layoutManager recyclerView.adapter = adapter } private fun refreshFilters(filters: CardFilters) { presenter.getCards(filters, deckId) } override fun onDeckbuildModeCardsLoaded(cards: List<Card>, deck: Deck) { cards.forEach { card -> val cardItem = CardItem(card, true) cardItem.count = deck.cards.filter { it.cardId == card.cardId }.size adapter.add(cardItem) } } override fun handleBack(): Boolean { return super.handleBack() } override fun onCardChecked(card: Card, isCardAddable: Boolean) { if (isCardAddable) { presenter.addCardToDeck(deckId, card) } isAddCardButtonClickable = true } override fun updateCount(card: Card, itemRemoved: Boolean) { Log.d(TAG, "updateCount()") val item = adapter.adapterItems.find { it.card.cardId == card.cardId } val position = adapter.adapterItems.indexOf(item) if (itemRemoved) { adapter.adapterItems.find { it.card.cardId == card.cardId }!!.count -= 1 } else { adapter.adapterItems.find { it.card.cardId == card.cardId }!!.count += 1 } adapter.notifyAdapterItemChanged(position) } override fun showLaneSelection(lanesToDisplay: List<Int>, card: Card) { val laneNames: MutableList<String> = ArrayList() lanesToDisplay.forEach { laneInt -> laneNames.add(activity!!.getStringResourceByName(Lane.ID_TO_KEY.apply(laneInt))) } MaterialDialog.Builder(activity!!) .title("Choose A Lane To Display This Card.") .items(laneNames) .itemsCallbackSingleChoice(0, { dialog, view, which, text -> when (text) { activity!!.getStringResourceByName(Lane.ID_TO_KEY.apply(Lane.EVENT)) -> card.selectedLane = Lane.EVENT activity!!.getStringResourceByName(Lane.ID_TO_KEY.apply(Lane.MELEE)) -> card.selectedLane = Lane.MELEE activity!!.getStringResourceByName(Lane.ID_TO_KEY.apply(Lane.RANGED)) -> card.selectedLane = Lane.RANGED activity!!.getStringResourceByName(Lane.ID_TO_KEY.apply(Lane.SIEGE)) -> card.selectedLane = Lane.SIEGE else -> { throw UnsupportedOperationException("Selected lane does not match Event/Melee/Ranged/Siege. Lane text: $text") } } presenter.addCardToDeck(deckId, card) isAddCardButtonClickable = true true }) .cancelListener { dialog -> isAddCardButtonClickable = true } .positiveText(android.R.string.ok) .show() } override fun onViewModeCardsLoaded(cards: List<Card>) { cards.forEach { card -> val cardItem = CardItem(card, false) adapter.add(cardItem) } } override fun onListFiltered(filteredCards: List<Card>) { Log.d(TAG, "onListFiltered()") } }
app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/cardviewer/CardViewerController.kt
507268567
/* * Copyright 2020 Andrey Tolpeev * * 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.vase4kin.teamcityapp.navigation.tracker import com.github.vase4kin.teamcityapp.base.tracker.BaseFirebaseTracker import com.google.firebase.analytics.FirebaseAnalytics /** * Navigation tracking class firebase impl */ class NavigationTrackerImpl(firebaseAnalytics: FirebaseAnalytics) : BaseFirebaseTracker(firebaseAnalytics), NavigationTracker { /** * {@inheritDoc} */ override fun trackView() { firebaseAnalytics.logEvent(NavigationTracker.SCREEN_NAME, null) } /** * {@inheritDoc} */ override fun trackUserClickedOnRateCancel() { firebaseAnalytics.logEvent(NavigationTracker.EVENT_RATE_LATER, null) } /** * {@inheritDoc} */ override fun trackUserClickedOnRateNow() { firebaseAnalytics.logEvent(NavigationTracker.EVENT_RATE_NOW, null) } /** * {@inheritDoc} */ override fun trackUserSawRateTheApp() { firebaseAnalytics.logEvent(NavigationTracker.EVENT_RATE_SHOW, null) } }
app/src/main/java/com/github/vase4kin/teamcityapp/navigation/tracker/NavigationTrackerImpl.kt
3968622132
package us.mikeandwan.photos.authorization import kotlinx.coroutines.runBlocking import net.openid.appauth.AuthorizationException import net.openid.appauth.AuthorizationService import okhttp3.Authenticator import okhttp3.Request import okhttp3.Response import okhttp3.Route import timber.log.Timber import java.io.IOException import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine @Suppress("UNUSED_ANONYMOUS_PARAMETER") class AuthAuthenticator( private val _authService: AuthorizationService, private val _authStateManager: AuthStateManager ) : Authenticator { @Synchronized @Throws(IOException::class) override fun authenticate(route: Route?, response: Response): Request? { val authState = _authStateManager.current var request: Request? = null Timber.d("Starting Authenticator.authenticate") runBlocking { suspendCoroutine<Unit> { continuation -> authState.performActionWithFreshTokens(_authService) { accessToken: String?, idToken: String?, ex: AuthorizationException? -> when { ex != null -> { Timber.e("Failed to authorize = %s", ex.message) request = null continuation.resume(Unit) } accessToken == null -> { Timber.e("Failed to authorize, received null access token") request = null // Give up, we've already failed to authenticate. continuation.resume(Unit) } else -> { Timber.i("authenticate: obtained access token") request = response.request.newBuilder() .header("Authorization", String.format("Bearer %s", accessToken)) .build() continuation.resume(Unit) } } } } } return request } }
MaWPhotos/src/main/java/us/mikeandwan/photos/authorization/AuthAuthenticator.kt
225255076
package us.mikeandwan.photos.ui.screens.upload import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import us.mikeandwan.photos.domain.FileStorageRepository import javax.inject.Inject @HiltViewModel class UploadViewModel @Inject constructor ( fileStorageRepository: FileStorageRepository ): ViewModel() { val filesToUpload = fileStorageRepository.pendingUploads init { viewModelScope.launch { fileStorageRepository.refreshPendingUploads() } } }
MaWPhotos/src/main/java/us/mikeandwan/photos/ui/screens/upload/UploadViewModel.kt
48402004
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.ksp.symbol /** * A value argument to function / constructor calls. * * Currently, only appears in annotation arguments. */ interface KSValueArgument : KSAnnotated { /** * The name for the named argument, or null otherwise. * * For example, in `ignore(name=123456)`, the name value is "name" */ val name: KSName? /** * True if it is a spread argument (i.e., has a "*" in front of the argument). */ val isSpread: Boolean /** * The value of the argument. */ val value: Any? }
api/src/main/kotlin/com/google/devtools/ksp/symbol/KSValueArgument.kt
105159415
package com.garymcgowan.moviepedia import com.garymcgowan.moviepedia.dagger.DaggerAppComponent import dagger.android.AndroidInjector import dagger.android.support.DaggerApplication import timber.log.Timber class App : DaggerApplication() { override fun applicationInjector(): AndroidInjector<out DaggerApplication> = DaggerAppComponent.builder().application(this).build() companion object { const val mBaseUrl = "http://www.omdbapi.com" } override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } } }
app/src/main/java/com/garymcgowan/moviepedia/App.kt
4231067625
package com.itsronald.twenty2020.backup import android.app.backup.BackupAgentHelper import android.app.backup.SharedPreferencesBackupHelper import android.os.Build import android.preference.PreferenceManager /** * A custom agent to handle Android backup of the app's SharedPreferences. * * See https://developer.android.com/training/backup/backupapi.html */ class Twenty2020BackupAgent : BackupAgentHelper() { /** Backup key for SharedPreferences. */ private val DEFAULT_SHARED_PREFS_BACKUP_KEY: String get() = "${applicationContext.packageName}.backup.preferences" /** Name of the default SharedPreferences file. */ private val defaultSharedPreferencesName: String get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { PreferenceManager.getDefaultSharedPreferencesName(applicationContext) } else { // While the `getDefaultSharedPreferencesName` API is not exposed pre API-24, this // is the return value used internally. "${applicationContext.packageName}_preferences" } //region lifecycle override fun onCreate() { super.onCreate() // Backup default SharedPreferences. val sharedPrefsBackupHelper = SharedPreferencesBackupHelper(this, defaultSharedPreferencesName) addHelper(DEFAULT_SHARED_PREFS_BACKUP_KEY, sharedPrefsBackupHelper) } //endregion }
app/src/main/java/com/itsronald/twenty2020/backup/Twenty2020BackupAgent.kt
3658916704
package ca.six.tomato.view import android.app.Service import android.os.Vibrator import android.support.v4.view.GestureDetectorCompat import android.support.v7.widget.RecyclerView import android.view.GestureDetector import android.view.MotionEvent /** * Created by songzhw on 2016-06-09. */ abstract class OnRvItemClickListener(private val rv: RecyclerView) : RecyclerView.OnItemTouchListener { private val gestureDetector: GestureDetectorCompat private val vibrator: Vibrator init { gestureDetector = GestureDetectorCompat(rv.context, RvGestureListener()) vibrator = rv.context.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator } private inner class RvGestureListener : GestureDetector.SimpleOnGestureListener() { override fun onLongPress(e: MotionEvent) { // vibrate vibrator.vibrate(70) val child = rv.findChildViewUnder(e.x, e.y) if (child != null) { val vh = rv.getChildViewHolder(child) onLongClick(vh) } } override fun onSingleTapUp(e: MotionEvent): Boolean { val child = rv.findChildViewUnder(e.x, e.y) if (child != null) { val vh = rv.getChildViewHolder(child) onItemClick(vh) } return true //@return true if the event is consumed, else false } } // ========================= OnItemTouchListener ================================= override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean { gestureDetector.onTouchEvent(e) return false } override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) { gestureDetector.onTouchEvent(e) } override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) { } // ========================= abstract methods ================================= abstract fun onLongClick(vh: RecyclerView.ViewHolder) abstract fun onItemClick(vh: RecyclerView.ViewHolder) }
app/src/main/java/ca/six/tomato/view/OnRvItemClickListener.kt
2779193449
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.measurement.sampleapp.view.base import dagger.android.support.DaggerAppCompatActivity import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import javax.inject.Inject /* * BaseActivity * This is the Base Activity that provides common elements. * */ open class BaseActivity : DaggerAppCompatActivity() { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory /* * provideViewModel * This is a helper method to provide view models * */ inline fun <reified VM : ViewModel> provideViewModel() = ViewModelProvider(this, viewModelFactory)[VM::class.java] }
AttributionReporting/MeasurementSampleApp/app/src/main/java/com/example/measurement/sampleapp/view/base/BaseActivity.kt
1874615808
package com.neva.javarel.gradle.instance import com.neva.javarel.gradle.DefaultTask import org.gradle.api.tasks.TaskAction open class DestroyTask : DefaultTask() { companion object { val NAME = "instanceDestroy" } @TaskAction fun destroy() { logger.info("Destroying local instance(s) (${config.localInstances.size})") config.localInstances.onEach { LocalHandler(project, it).destroy() } } }
tooling/gradle-plugin/src/main/kotlin/com/neva/javarel/gradle/instance/DestroyTask.kt
2756844014
package com.openlattice.graph.processing.processors import com.openlattice.analysis.requests.ValueFilter import com.openlattice.postgres.DataTables import org.apache.olingo.commons.api.edm.FullQualifiedName import java.time.temporal.ChronoUnit abstract class BaseDurationProcessor: SelfProcessor { protected abstract fun getHandledEntityType(): String protected abstract fun getPropertyTypeForStart(): String protected abstract fun getPropertyTypeForEnd(): String protected abstract fun getPropertyTypeForDuration(): String protected abstract fun getDisplayTimeUnit(): ChronoUnit protected abstract fun getCalculationTimeUnit(): ChronoUnit override fun getFilters(): Map<FullQualifiedName, Map<FullQualifiedName, ValueFilter<*>>> { return mapOf() } protected fun firstStart():String { return "(SELECT unnest(${DataTables.quote(getPropertyTypeForStart())}) ORDER BY 1 LIMIT 1)" } protected fun lastEnd(): String { return "(SELECT unnest(${DataTables.quote(getPropertyTypeForEnd())}) ORDER BY 1 DESC LIMIT 1)" } protected fun numberOfDays():String { return "SUM(EXTRACT(epoch FROM (${lastEnd()} - ${firstStart()}))/3600/24)" } protected fun numberOfHours():String { return "SUM(EXTRACT(epoch FROM (${lastEnd()} - ${firstStart()}))/3600)" } protected fun numberOfMinutes():String { return "SUM(EXTRACT(epoch FROM (${lastEnd()} - ${firstStart()}))/60)" } protected fun addDurationToFirstStart(): String { val firstStart = firstStart() return "$firstStart + ${DataTables.quote(getPropertyTypeForDuration())}[1] " } } abstract class DurationProcessor:BaseDurationProcessor() { override fun getInputs(): Map<FullQualifiedName, Set<FullQualifiedName>> { return mapOf(FullQualifiedName(getHandledEntityType()) to setOf(FullQualifiedName(getPropertyTypeForStart()), FullQualifiedName(getPropertyTypeForEnd()))) } override fun getOutput(): Pair<FullQualifiedName, FullQualifiedName> { return Pair(FullQualifiedName(getHandledEntityType()), FullQualifiedName(getPropertyTypeForDuration())) } }
src/main/kotlin/com/openlattice/graph/processing/processors/BaseDurationProcessor.kt
699723125
package org.http4k.hamkrest import com.natpryce.hamkrest.containsSubstring import com.natpryce.hamkrest.equalTo import org.http4k.core.with import org.http4k.lens.FormField import org.http4k.lens.WebForm import org.junit.jupiter.api.Test class FormMatchersTest { @Test fun formField() = FormField.required("name").let { assertMatchAndNonMatch(WebForm().with(it of "bob"), hasFormField(it, containsSubstring("bob")), hasFormField(it, equalTo("bill"))) } }
http4k-testing/hamkrest/src/test/kotlin/org/http4k/hamkrest/FormMatchersTest.kt
4191934298
package com.binarymonks.jj.core.specs.physics import com.badlogic.gdx.graphics.Color import com.binarymonks.jj.core.properties.PropOverride abstract class LightSpec { var name: String? = null var rays: Int = 100 var color: PropOverride<Color> = PropOverride(Color(0.3f, 0.3f, 0.3f, 1f)) var reach: Float = 2f var collisionGroup :CollisionGroupSpec = CollisionGroupSpecExplicit() } class PointLightSpec:LightSpec() { var offsetX: Float = 0f var offsetY: Float = 0f }
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/specs/physics/LightSpec.kt
3571475932
package com.beyondtechnicallycorrect.visitordetector.persistence data class Devices(val visitorDevices: List<SavedDevice>, val homeDevices: List<SavedDevice>)
app/src/main/kotlin/com/beyondtechnicallycorrect/visitordetector/persistence/Devices.kt
4208457
/* * PackList is an open-source packing-list for Android * * Copyright (c) 2017 Nicolas Bossard and other contributors. * * 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.nbossard.packlist.gui /* @startuml interface com.nbossard.packlist.gui.IMainActivity { + openTripDetailFragment(...) + openNewTripFragment(...) + showFABIfAccurate(boolean) + updateTitleBar(String) } @enduml */ import com.nbossard.packlist.model.TripItem import java.util.UUID /** * The what fragments expects from main hosting activity. * @author Created by nbossard on 01/01/16. */ internal interface IMainActivity { /** * Ask Main activity to open new trip fragment to display Trip of provided UUID. * * @param parTripId a trip unique identifier (UUID) if editing, null otherwise. */ fun openNewTripFragment(parTripId: UUID?) /** * Display provided TripItem to allow editing of details. * @param parItem item to be edited */ fun openItemDetailFragment(parItem: TripItem) /** * Hide or show FAB, depending on fragment. * @param parShow true to show, false to hide */ fun showFABIfAccurate(parShow: Boolean) /** * Ask activity to update title bar with provided new title. * This will also display homeAsUp. * * @param parNewTitleInTitleBar new title to be displayed in title bar */ fun updateTitleBar(parNewTitleInTitleBar: String) }
app/src/main/java/com/nbossard/packlist/gui/IMainActivity.kt
4027559355
package cm.aptoide.pt.wallet import android.content.pm.PackageManager import cm.aptoide.pt.aab.DynamicSplitsManager import cm.aptoide.pt.aab.DynamicSplitsModel import cm.aptoide.pt.ads.MoPubAdsManager import cm.aptoide.pt.ads.WalletAdsOfferManager import cm.aptoide.pt.app.DownloadModel import cm.aptoide.pt.app.DownloadStateParser import cm.aptoide.pt.database.room.RoomDownload import cm.aptoide.pt.download.DownloadFactory import cm.aptoide.pt.install.AppInstallerStatusReceiver import cm.aptoide.pt.install.InstallManager import cm.aptoide.pt.install.InstalledRepository import cm.aptoide.pt.packageinstaller.InstallStatus import cm.aptoide.pt.promotions.WalletApp import cm.aptoide.pt.utils.AptoideUtils import hu.akarnokd.rxjava.interop.RxJavaInterop import rx.Completable import rx.Observable class WalletInstallManager(val packageManager: PackageManager, val installManager: InstallManager, val downloadFactory: DownloadFactory, val downloadStateParser: DownloadStateParser, val moPubAdsManager: MoPubAdsManager, val walletInstallAnalytics: WalletInstallAnalytics, val installedRepository: InstalledRepository, val walletAppProvider: WalletAppProvider, val appInstallerStatusReceiver: AppInstallerStatusReceiver, val dynamicSplitsManager: DynamicSplitsManager) { fun getAppIcon(packageName: String?): Observable<String> { return Observable.fromCallable { AptoideUtils.SystemU.getApkIconPath( packageManager.getPackageInfo(packageName, 0)) }.onErrorReturn { null } } fun shouldShowRootInstallWarningPopup(): Boolean { return installManager.showWarning() } fun allowRootInstall(answer: Boolean) { installManager.rootInstallAllowed(answer) } fun downloadApp(walletApp: WalletApp): Completable { return RxJavaInterop.toV1Single<DynamicSplitsModel>( dynamicSplitsManager.getAppSplitsByMd5(walletApp.md5sum!!)).flatMapObservable { Observable.just( downloadFactory.create( downloadStateParser.parseDownloadAction(DownloadModel.Action.INSTALL), walletApp.appName, walletApp.packageName, walletApp.md5sum, walletApp.icon, walletApp.versionName, walletApp.versionCode, walletApp.path, walletApp.pathAlt, walletApp.obb, false, walletApp.size, walletApp.splits, walletApp.requiredSplits, walletApp.trustedBadge, walletApp.storeName, it.dynamicSplitsList)) } .flatMapSingle { download -> moPubAdsManager.adsVisibilityStatus.doOnSuccess { responseStatus -> setupDownloadEvents(download, DownloadModel.Action.INSTALL, walletApp.id, responseStatus, walletApp.packageName, walletApp.developer) }.map { download } } .flatMapCompletable { download -> installManager.splitInstall(download) } .toCompletable() } private fun setupDownloadEvents(download: RoomDownload, downloadAction: DownloadModel.Action?, appId: Long, offerResponseStatus: WalletAdsOfferManager.OfferResponseStatus, packageName: String, developer: String) { walletInstallAnalytics.setupDownloadEvents(download, downloadAction, appId, offerResponseStatus) walletInstallAnalytics.sendClickOnInstallButtonEvent(packageName, developer, download.hasSplits()) } fun onWalletInstalled(): Observable<Boolean> { return installedRepository.isInstalled("com.appcoins.wallet").filter { isInstalled -> isInstalled } } fun getWallet(): Observable<WalletApp> { return walletAppProvider.getWalletApp() } fun removeDownload(app: WalletApp): Completable? { return installManager.cancelInstall(app.md5sum, app.packageName, app.versionCode) } fun cancelDownload(app: WalletApp): Completable { return Completable.fromAction { removeDownload(app) } } fun loadDownloadModel(walletApp: WalletApp): Observable<DownloadModel> { return installManager.getInstall(walletApp.md5sum, walletApp.packageName, walletApp.versionCode) .map { install -> DownloadModel(downloadStateParser.parseDownloadType(install.type, false), install.progress, downloadStateParser.parseDownloadState(install.state, install.isIndeterminate), install.appSize) } } fun pauseDownload(app: WalletApp): Completable { return installManager.pauseInstall(app.md5sum) } fun resumeDownload(app: WalletApp): Completable { return installManager.getDownload(app.md5sum) .flatMap { download -> moPubAdsManager.adsVisibilityStatus .doOnSuccess { responseStatus -> setupDownloadEvents(download, DownloadModel.Action.INSTALL, app.id, responseStatus, app.packageName, app.developer) }.map { download } } .flatMapCompletable { download -> installManager.splitInstall(download) } } fun onWalletInstallationCanceled(): Observable<Boolean> { return appInstallerStatusReceiver.installerInstallStatus .map { installStatus -> InstallStatus.Status.CANCELED.equals(installStatus.status) }.filter { isCanceled -> isCanceled } } fun setupAnalyticsHistoryTracker() { walletInstallAnalytics.setupHistoryTracker() } }
app/src/main/java/cm/aptoide/pt/wallet/WalletInstallManager.kt
2093970209
/* * Copyright 2018 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.example.androidthings.endtoend.shared.domain import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import com.example.androidthings.endtoend.shared.util.DefaultScheduler import com.example.androidthings.endtoend.shared.util.Scheduler /** * Utility class for executing background work and publishing results in an observable LiveData. * Clients should call [observe] once to watch for results and call [execute] every time an action * should be performed. For continuous use cases, this is sufficient. * * For one-shot use cases (e.g. an http call for a result), you should additionally supply something * in the parameters and result that can be used to distinguish between different executions so that * clients can map the result back later. */ abstract class UseCase<in P, R> { /** Scheduler provided for convenience if this UseCase needs to move to another thread. */ protected val scheduler: Scheduler = DefaultScheduler protected val result = MediatorLiveData<R>() fun observe(): LiveData<R> = result abstract fun execute(parameters: P) } /** Allows calls like useCase.execute() for UseCases with no parameters. */ fun <R> UseCase<Unit, R>.execute() = execute(Unit)
shared/src/main/java/com/example/androidthings/endtoend/shared/domain/UseCase.kt
3043565171
package mixit.util.validator import com.samskivert.mustache.Mustache import org.owasp.html.HtmlPolicyBuilder import org.owasp.html.Sanitizers /** * @author Dev-Mind <[email protected]> * @since 16/01/18. */ class StringEscapers { val htmlPolicy = Sanitizers.FORMATTING .and(Sanitizers.LINKS) .and(Sanitizers.TABLES) .and(Sanitizers.BLOCKS) .and( HtmlPolicyBuilder() .allowUrlProtocols("http", "https") .allowElements("img", "picture", "source") .allowAttributes("alt", "src", "srcset", "type", "class") .onElements("img", "picture", "source") .toFactory() ) .and(HtmlPolicyBuilder().allowAttributes("class").globally().toFactory()) val markdownPolicy = Sanitizers.FORMATTING val HTML: Mustache.Escaper = Mustache.Escaper { text -> htmlPolicy.sanitize(text) } val MARKDOWN: Mustache.Escaper = Mustache.Escaper { text -> markdownPolicy.sanitize(text) } }
src/main/kotlin/mixit/util/validator/StringEscapers.kt
14643859
package im.fdx.v2ex.utils import android.text.format.DateUtils import com.elvishew.xlog.XLog import im.fdx.v2ex.MyApp import im.fdx.v2ex.R import im.fdx.v2ex.utils.extensions.getNum import java.text.ParseException import java.text.SimpleDateFormat import java.util.* /** * Created by a708 on 15-9-9. * 获取相对时间 */ object TimeUtil { /** * @param created 若等-1 (目前设定),则为没有回复。 * * * @return */ fun getRelativeTime(created: Long): String { if (created <= 0) { return "" } val c = created * 1000 val now = System.currentTimeMillis() val difference = now - c val text = if (difference >= 0 && difference <= DateUtils.MINUTE_IN_MILLIS) MyApp.get().getString(R.string.just_now) else DateUtils.getRelativeTimeSpanString( c, now, DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE) return text.toString() } fun getAbsoluteTime(created: String): String { val createdNum = created.toLongOrNull() ?: return "" val obj = 1000 * createdNum val format1 = SimpleDateFormat("yyyy/MM/dd", Locale.US) format1.timeZone = TimeZone.getTimeZone("GMT+8:00") return format1.format(obj) } /** * 遗憾的是只能通过这样得到一个不准确的时间。 * 坑爹的char,让我卡了好久 * 算出绝对时间是为了保存如缓存,不然可以直接用得到的时间展示。 * @param timeStr 两个点中间的字符串,包括空格 * * * @return long value */ fun toUtcTime(timeStr: String): Long { var theTime = timeStr theTime = theTime.trim() // String theTime = time.replace("&nbsp", ""); // 44 分钟前用 iPhone 发布 // · 1 小时 34 分钟前 · 775 次点击 // · 100 天前 · 775 次点击 // 1992.02.03 12:22:22 +0800 // 2017-09-26 22:27:57 PM // 刚刚 //其中可能出现一些奇怪的字符,你可能以为是空格。 var created = System.currentTimeMillis() / 1000 // ms -> second val second = theTime.indexOf("秒") val hour = theTime.indexOf("小时") val minute = theTime.indexOf("分钟") val day = theTime.indexOf("天") val now = theTime.indexOf("刚刚") try { when { // theTime.isEmpty() -> return System.currentTimeMillis()/1000 second != -1 -> return created hour != -1 -> created -= theTime.substring(0, hour).getNum().toLong() * 60 * 60 + theTime.substring(hour + 2, minute).getNum().toLong() * 60 day != -1 -> created -= theTime.substring(0, day).getNum().toLong() * 60 * 60 * 24 minute != -1 -> created -= theTime.substring(0, minute).getNum().toLong() * 60 now != -1 -> return created else -> { val sdf = SimpleDateFormat("yyyy-MM-dd hh:mm:ss +08:00", Locale.getDefault()) val date = sdf.parse(theTime.trim()) created = date?.time?.div(1000) ?: 0 } } } catch (e1: NumberFormatException) { XLog.tag("TimeUtil").e("NumberFormatException error: $theTime, $timeStr") } catch (e2: StringIndexOutOfBoundsException) { XLog.tag("TimeUtil").e(" StringIndexOutOfBoundsException error: $theTime, $timeStr") } catch (e2: ParseException) { try { val ccc = SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.US) val date = ccc.parse(theTime.trim()) created = date?.time?.div(1000) ?: 0 } catch (ignore: ParseException) { try { val ccc = SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss", Locale.US) val date = ccc.parse(theTime.trim()) created = date?.time?.div(1000) ?: 0 } catch (ignre:ParseException){ XLog.tag("TimeUtil").e("time str parse error: $theTime") } } } return created } }
app/src/main/java/im/fdx/v2ex/utils/TimeUtil.kt
3005307073
package ru.a1024bits.bytheway.dagger import android.app.Application import android.content.Context import dagger.Module import dagger.Provides import ru.a1024bits.bytheway.App import javax.inject.Singleton /** * Created by andrey.gusenkov on 19/09/2017 */ @Module class AppModule(val application: App) { @Provides @Singleton fun providerApplicationContext(): Context = application.applicationContext @Provides @Singleton fun provideApplication(): Application = application }
app/src/main/java/ru/a1024bits/bytheway/dagger/AppModule.kt
1627043984
package io.gitlab.arturbosch.detekt.rules.naming import io.gitlab.arturbosch.detekt.test.TestConfig import io.gitlab.arturbosch.detekt.test.compileAndLint import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatExceptionOfType import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.util.regex.PatternSyntaxException class NamingConventionCustomPatternTest : Spek({ val configCustomRules = object : TestConfig() { override fun subConfig(key: String): TestConfig = this @Suppress("UNCHECKED_CAST") override fun <T : Any> valueOrDefault(key: String, default: T): T = when (key) { FunctionNaming.FUNCTION_PATTERN -> "^`.+`$" as T ClassNaming.CLASS_PATTERN -> "^aBbD$" as T VariableNaming.VARIABLE_PATTERN -> "^123var$" as T TopLevelPropertyNaming.CONSTANT_PATTERN -> "^lowerCaseConst$" as T EnumNaming.ENUM_PATTERN -> "^(enum1)|(enum2)$" as T PackageNaming.PACKAGE_PATTERN -> "^(package_1)$" as T FunctionMaxLength.MAXIMUM_FUNCTION_NAME_LENGTH -> 50 as T else -> default } } val testConfig = object : TestConfig() { override fun subConfig(key: String): TestConfig = when (key) { FunctionNaming::class.simpleName -> configCustomRules FunctionMaxLength::class.simpleName -> configCustomRules ClassNaming::class.simpleName -> configCustomRules VariableNaming::class.simpleName -> configCustomRules TopLevelPropertyNaming::class.simpleName -> configCustomRules EnumNaming::class.simpleName -> configCustomRules PackageNaming::class.simpleName -> configCustomRules else -> this } override fun <T : Any> valueOrDefault(key: String, default: T): T = default } val excludeClassPatternVariableRegexCode = """ class Bar { val MYVar = 3 } object Foo { val MYVar = 3 }""" val excludeClassPatternFunctionRegexCode = """ class Bar { fun MYFun() {} } object Foo { fun MYFun() {} }""" describe("NamingRules rule") { it("should use custom name for method and class") { val rule = NamingRules(testConfig) assertThat(rule.compileAndLint(""" class aBbD{ fun `name with back ticks`(){ val `123var` = "" } companion object { const val lowerCaseConst = "" } } """)).isEmpty() } it("should use custom name for constant") { val rule = NamingRules(testConfig) assertThat(rule.compileAndLint(""" class aBbD{ companion object { const val lowerCaseConst = "" } } """)).isEmpty() } it("should use custom name for enum") { val rule = NamingRules(testConfig) assertThat(rule.compileAndLint(""" class aBbD{ enum class aBbD { enum1, enum2 } } """)).isEmpty() } it("should use custom name for package") { val rule = NamingRules(testConfig) assertThat(rule.compileAndLint("package package_1")).isEmpty() } it("shouldExcludeClassesFromVariableNaming") { val code = """ class Bar { val MYVar = 3 } object Foo { val MYVar = 3 }""" val config = TestConfig(mapOf(VariableNaming.EXCLUDE_CLASS_PATTERN to "Foo|Bar")) assertThat(VariableNaming(config).compileAndLint(code)).isEmpty() } it("shouldNotFailWithInvalidRegexWhenDisabledVariableNaming") { val configValues = mapOf( "active" to "false", VariableNaming.EXCLUDE_CLASS_PATTERN to "*Foo" ) val config = TestConfig(configValues) assertThat(VariableNaming(config).compileAndLint(excludeClassPatternVariableRegexCode)).isEmpty() } it("shouldFailWithInvalidRegexVariableNaming") { val config = TestConfig(mapOf(VariableNaming.EXCLUDE_CLASS_PATTERN to "*Foo")) assertThatExceptionOfType(PatternSyntaxException::class.java).isThrownBy { VariableNaming(config).compileAndLint(excludeClassPatternVariableRegexCode) } } it("shouldExcludeClassesFromFunctionNaming") { val code = """ class Bar { fun MYFun() {} } object Foo { fun MYFun() {} }""" val config = TestConfig(mapOf(FunctionNaming.EXCLUDE_CLASS_PATTERN to "Foo|Bar")) assertThat(FunctionNaming(config).compileAndLint(code)).isEmpty() } it("shouldNotFailWithInvalidRegexWhenDisabledFunctionNaming") { val configRules = mapOf( "active" to "false", FunctionNaming.EXCLUDE_CLASS_PATTERN to "*Foo" ) val config = TestConfig(configRules) assertThat(FunctionNaming(config).compileAndLint(excludeClassPatternFunctionRegexCode)).isEmpty() } it("shouldFailWithInvalidRegexFunctionNaming") { val config = TestConfig(mapOf(FunctionNaming.EXCLUDE_CLASS_PATTERN to "*Foo")) assertThatExceptionOfType(PatternSyntaxException::class.java).isThrownBy { FunctionNaming(config).compileAndLint(excludeClassPatternFunctionRegexCode) } } } })
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/naming/NamingConventionCustomPatternTest.kt
1547418477
package de.christinecoenen.code.zapp.app.main import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.preference.PreferenceManager import de.christinecoenen.code.zapp.R class MainViewModel(application: Application) : AndroidViewModel(application) { val pageCount get() = PageType.values().size init { PreferenceManager.setDefaultValues(application, R.xml.preferences, false) } fun getPageTypeAt(position: Int) = PageType.values()[position] fun getPageTypeFromMenuResId(itemId: Int) = when (itemId) { R.id.menu_live -> PageType.PAGE_CHANNEL_LIST R.id.menu_mediathek -> PageType.PAGE_MEDIATHEK_LIST R.id.menu_downloads -> PageType.PAGE_DOWNLOADS else -> throw IllegalArgumentException("Unknown menu item $itemId.") } }
app/src/main/java/de/christinecoenen/code/zapp/app/main/MainViewModel.kt
539360967
package im.fdx.v2ex.network.cookie import okhttp3.Cookie /** * Created by fdx on 2017/3/16. */ interface CookiePersistor { fun removeAll(cookies: List<Cookie>) fun clear() fun persist(cookie: Cookie) fun persistAll(cookies: Collection<Cookie>) fun loadAll(): List<Cookie> }
app/src/main/java/im/fdx/v2ex/network/cookie/CookiePersistor.kt
826558078
package org.kikermo.thingsaudio.core.model enum class PlayState { STATE_READY, STATE_PLAYING, STATE_PAUSED }
core/src/main/java/org/kikermo/thingsaudio/core/model/PlayState.kt
3791159218
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.composequadrant.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
Unit 1/Pathway 3/ComposeQuadrant/app/src/main/java/com/example/composequadrant/ui/theme/Shape.kt
3021209687
/* * Copyright 2021 Alex Almeida Tavella * * 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 br.com.moov.bookmark.movie object UnbookmarkError
feature/bookmark-movie/public/src/main/java/br/com/moov/bookmark/movie/UnbookmarkError.kt
3904509152
package coursework.kiulian.com.freerealestate.view.custom import android.graphics.* import android.graphics.drawable.Drawable /** * Created by User on 10.11.2016. */ class RoundedDrawable(var bitmap: Bitmap, cornerRadius: Int, private val margin: Int, type: Type) : Drawable() { private val cornerRadius: Float = cornerRadius.toFloat() private var mRect = RectF() private val bitmapShader: BitmapShader private val paint: Paint private var mType = Type.fitXY enum class Type { center, fitXY, centerCrop } init { mType = type bitmapShader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) paint = Paint() paint.isAntiAlias = true paint.shader = bitmapShader } override fun onBoundsChange(bounds: Rect) { super.onBoundsChange(bounds) mRect.set(margin.toFloat(), margin.toFloat(), (bounds.width() - margin).toFloat(), (bounds.height() - margin).toFloat()) val shaderMatrix = Matrix() val width = bounds.width() val height = bounds.height() when (mType) { Type.centerCrop -> { var scale = width * 1.0f / bitmap.width if (scale * bitmap.height < height) { scale = height * 1.0f / bitmap.height } val outWidth = Math.round(scale * bitmap.width) val outHeight = Math.round(scale * bitmap.height) shaderMatrix.postScale(scale, scale) var left = 0 var top = 0 if (outWidth == width) { top = (outHeight - height) * -1 / 2 } else { left = (outWidth - width) * -1 / 2 } shaderMatrix.postTranslate(left.toFloat(), top.toFloat()) } Type.fitXY -> { val wScale = width * 1.0f / bitmap.width val hScale = height * 1.0f / bitmap.height shaderMatrix.postScale(wScale, hScale) } Type.center -> { val moveleft: Int val movetop: Int moveleft = (width - bitmap.width) / 2 movetop = (height - bitmap.height) / 2 shaderMatrix.postTranslate(moveleft.toFloat(), movetop.toFloat()) } } bitmapShader.setLocalMatrix(shaderMatrix) } override fun draw(canvas: Canvas) { canvas.drawRoundRect(mRect, cornerRadius, cornerRadius, paint) } override fun getOpacity(): Int { return PixelFormat.TRANSLUCENT } override fun setAlpha(alpha: Int) { paint.alpha = alpha } override fun setColorFilter(cf: ColorFilter?) { paint.colorFilter = cf } }
app/src/main/java/coursework/kiulian/com/freerealestate/view/custom/RoundedDrawable.kt
3600916798
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.diagram interface ThemeItem { /** * Get the number for this theme item. Multiple items should never return the same * number. Conciseness will help though. * @return The item ordinal. */ val itemNo: Int /** * Get the state that needs to be used for drawing the item at the given state. This allows * for optimization in caching. * @param The state needed. * @return The effective state. */ fun getEffectiveState(state: Int): Int fun <PEN_T : Pen<PEN_T>> createPen(strategy: DrawingStrategy<*, PEN_T, *>, state: Int): PEN_T }
PE-common/src/commonMain/kotlin/nl/adaptivity/diagram/ThemeItem.kt
4079346328
package app.youkai.ui.common.app import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.Toolbar import app.youkai.R import com.hannesdorfmann.mosby.mvp.MvpActivity import com.hannesdorfmann.mosby.mvp.MvpPresenter import com.hannesdorfmann.mosby.mvp.MvpView import kotlinx.android.synthetic.main.activity_fragment_container.* /** * A base Activity class that takes care of the dirty work of wrapper layout, fragment transaction, * and toolbar stuff... */ abstract class FragmentContainerActivity<V : MvpView, P : MvpPresenter<V>> : MvpActivity<V, P>() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_fragment_container) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportFragmentManager.beginTransaction() .replace(R.id.fragmentContainer, newFragment()) .commit() } override fun onSupportNavigateUp(): Boolean { finish() return true } protected fun getToolbar(): Toolbar = toolbar /** * Returns the fragment to be used in this Activity */ abstract fun newFragment(): Fragment }
app/src/main/kotlin/app/youkai/ui/common/app/FragmentContainerActivity.kt
4224716208
package io.github.binaryfoo.decoders import io.github.binaryfoo.DecodedData import io.github.binaryfoo.Decoder import io.github.binaryfoo.EmvTags import io.github.binaryfoo.decoders.apdu.APDUCommand import io.github.binaryfoo.tlv.Tag class ResponseFormat1Decoder : Decoder { override fun decode(input: String, startIndexInBytes: Int, session: DecodeSession): List<DecodedData> { if (session.currentCommand == APDUCommand.GetProcessingOptions) { val aip = input.substring(0, 4) val afl = input.substring(4) return listOf( decode(EmvTags.APPLICATION_INTERCHANGE_PROFILE, aip, startIndexInBytes, 2, session), decode(EmvTags.AFL, afl, startIndexInBytes + 2, (input.length - 4) / 2, session)) } if (session.currentCommand == APDUCommand.GenerateAC) { val cid = input.substring(0, 2) val atc = input.substring(2, 6) val applicationCryptogram = input.substring(6, 22) val issuerApplicationData = input.substring(22) return listOf( decode(EmvTags.CRYPTOGRAM_INFORMATION_DATA, cid, startIndexInBytes, 1, session), decode(EmvTags.APPLICATION_TRANSACTION_COUNTER, atc, startIndexInBytes + 1, 2, session), decode(EmvTags.APPLICATION_CRYPTOGRAM, applicationCryptogram, startIndexInBytes + 3, 8, session), decode(EmvTags.ISSUER_APPLICATION_DATA, issuerApplicationData, startIndexInBytes + 11, (input.length - 22) / 2, session)) } if (session.currentCommand == APDUCommand.InternalAuthenticate) { // 9F4B is only used for Format 2 responses to Internal authenticate session.signedDynamicAppData = input } return listOf() } private fun decode(tag: Tag, value: String, startIndexInBytes: Int, length: Int, decodeSession: DecodeSession): DecodedData { val tagMetaData = decodeSession.tagMetaData!! val children = tagMetaData.get(tag).decoder.decode(value, startIndexInBytes, decodeSession) return DecodedData.withTag(tag, tagMetaData, tagMetaData.get(tag).decodePrimitiveTlvValue(value), startIndexInBytes, startIndexInBytes + length, children) } override fun validate(input: String?): String? = null override fun getMaxLength(): Int = 0 }
src/main/java/io/github/binaryfoo/decoders/ResponseFormat1Decoder.kt
3157379030
package app.youkai import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import app.youkai.data.local.Credentials import app.youkai.data.models.ext.MediaType import app.youkai.ui.feature.login.LoginActivity import app.youkai.ui.feature.media.MediaActivity import app.youkai.ui.feature.settings.SettingsActivity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar as Toolbar) if (!Credentials.isAuthenticated) { startActivity(LoginActivity.getLaunchIntent(this)) finish() } // SNK Manga = 14916 // SNK Anime = 7442 // Bakemonogatari = 3919 // Hanamonogatari = 8032 // Development code. TODO: Remove go.setOnClickListener { val id = mediaId.text.toString() val type = MediaType.fromString(mediaType.text.toString()) startActivity(MediaActivity.getLaunchIntent(this, id, type)) } } companion object { fun getLaunchIntent(context: Context) = Intent(context, MainActivity::class.java) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.activity_main, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.settings -> { startActivity(SettingsActivity.getLaunchIntent(this)) true } else -> { super.onOptionsItemSelected(item) } } }
app/src/main/kotlin/app/youkai/MainActivity.kt
3876323396
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.data.value import org.lanternpowered.api.util.collections.containsAll import org.lanternpowered.api.util.uncheckedCast import org.spongepowered.api.data.Key import org.spongepowered.api.data.value.CollectionValue import org.spongepowered.api.data.value.Value import java.util.function.Function import java.util.function.Predicate abstract class LanternCollectionValue<E, C : MutableCollection<E>> protected constructor( key: Key<out Value<C>>, value: C ) : LanternValue<C>(key, value), CollectionValue<E, C> { override fun size() = this.value.size override fun isEmpty() = this.value.isEmpty() override fun contains(element: E) = element in this.value override fun containsAll(iterable: Iterable<E>) = this.value.containsAll(iterable) override fun getAll(): C = CopyHelper.copy(this.value) override fun iterator() = get().iterator() abstract class Mutable<E, C : MutableCollection<E>, M : CollectionValue.Mutable<E, C, M, I>, I : CollectionValue.Immutable<E, C, I, M>> protected constructor(key: Key<out Value<C>>, value: C) : LanternCollectionValue<E, C>(key, value), CollectionValue.Mutable<E, C, M, I> { private inline fun also(fn: () -> Unit) = apply { fn() }.uncheckedCast<M>() override fun add(element: E) = also { this.value.add(element) } override fun addAll(elements: Iterable<E>) = also { this.value.addAll(elements) } override fun remove(element: E) = also { this.value.remove(element) } override fun removeAll(elements: Iterable<E>) = also { this.value.removeAll(elements) } override fun removeAll(predicate: Predicate<E>) = also { this.value.removeIf(predicate) } override fun set(value: C) = also { this.value = value } override fun transform(function: Function<C, C>) = set(function.apply(get())) } abstract class Immutable<E, C : MutableCollection<E>, I : CollectionValue.Immutable<E, C, I, M>, M : CollectionValue.Mutable<E, C, M, I>> protected constructor(key: Key<out Value<C>>, value: C) : LanternCollectionValue<E, C>(key, value), CollectionValue.Immutable<E, C, I, M> { override fun get(): C = CopyHelper.copy(super.get()) override fun withElement(element: E): I { val collection = get() return if (collection.add(element)) withValue(collection) else uncheckedCast() } override fun withAll(elements: Iterable<E>): I { var change = false val collection = get() for (element in elements) { change = collection.add(element) || change } return if (change) withValue(collection) else uncheckedCast() } override fun without(element: E): I { if (element !in this) { return uncheckedCast() } val collection = get() collection.remove(element) return withValue(collection) } override fun withoutAll(elements: Iterable<E>): I { val collection = get() return if (collection.removeAll(elements)) withValue(collection) else uncheckedCast() } override fun withoutAll(predicate: Predicate<E>): I { val collection = get() return if (collection.removeIf(predicate)) withValue(collection) else uncheckedCast() } override fun with(value: C) = withValue(CopyHelper.copy(value)) /** * Constructs a new [LanternCollectionValue.Immutable] * without copying the actual value. * * @param value The value element * @return The new immutable value */ protected abstract fun withValue(value: C): I override fun transform(function: Function<C, C>) = with(function.apply(get())) } }
src/main/kotlin/org/lanternpowered/server/data/value/LanternCollectionValue.kt
2755075340
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.vanilla.packet.handler.play import org.lanternpowered.api.cause.causeOf import org.lanternpowered.api.event.EventManager import org.lanternpowered.server.event.LanternEventFactory import org.lanternpowered.server.data.key.LanternKeys import org.lanternpowered.server.network.NetworkContext import org.lanternpowered.server.network.packet.PacketHandler import org.lanternpowered.server.network.vanilla.packet.type.play.ClientSettingsPacket import org.lanternpowered.server.registry.type.data.SkinPartRegistry import org.lanternpowered.api.data.Keys object ClientSettingsHandler : PacketHandler<ClientSettingsPacket> { override fun handle(ctx: NetworkContext, packet: ClientSettingsPacket) { val player = ctx.session.player val cause = causeOf(player) val skinParts = SkinPartRegistry.fromBitPattern(packet.skinPartsBitPattern) val event = LanternEventFactory.createPlayerChangeClientSettingsEvent( cause, packet.chatVisibility, skinParts, packet.locale, player, packet.enableColors, packet.viewDistance) EventManager.post(event) player.locale = event.locale player.viewDistance = event.viewDistance player.chatVisibility = event.chatVisibility player.isChatColorsEnabled = packet.enableColors player.offer(LanternKeys.DISPLAYED_SKIN_PARTS, event.displayedSkinParts) player.offer(Keys.DOMINANT_HAND, packet.dominantHand) } }
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/handler/play/ClientSettingsHandler.kt
1390627650
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers import com.google.cloud.spanner.Value import org.wfanet.measurement.common.identity.InternalId import org.wfanet.measurement.gcloud.spanner.bufferUpdateMutation import org.wfanet.measurement.gcloud.spanner.set import org.wfanet.measurement.internal.kingdom.Requisition import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.RequisitionReader internal fun SpannerWriter.TransactionScope.updateRequisition( readResult: RequisitionReader.Result, state: Requisition.State, details: Requisition.Details, fulfillingDuchyId: InternalId? = null ) { transactionContext.bufferUpdateMutation("Requisitions") { set("MeasurementId" to readResult.measurementId.value) set("MeasurementConsumerId" to readResult.measurementConsumerId.value) set("RequisitionId" to readResult.requisitionId.value) set("UpdateTime" to Value.COMMIT_TIMESTAMP) set("State" to state) set("RequisitionDetails" to details) if (fulfillingDuchyId != null) { set("FulfillingDuchyId" to fulfillingDuchyId.value) } } }
src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/writers/UpdateRequisition.kt
115163730
package com.abplus.surroundcalc import android.app.Activity import android.app.ActionBar import com.abplus.surroundcalc.models.Drawing import com.abplus.surroundcalc.utls.Preferences import com.abplus.surroundcalc.models.Drawing.KeyColor import android.view.Menu import android.view.MenuItem import android.app.FragmentTransaction import android.os.Bundle import android.widget.PopupWindow import android.view.Gravity import android.view.ViewGroup import android.view.WindowManager import android.view.View import android.view.WindowManager.LayoutParams import com.abplus.surroundcalc.models.Region import com.abplus.surroundcalc.models.ValueLabel import android.widget.TextView import android.graphics.Rect import android.util.Log import android.widget.PopupMenu import android.graphics.Point import android.widget.RelativeLayout import android.graphics.PointF import com.google.ads.AdView import com.google.ads.AdSize import android.widget.FrameLayout import com.google.ads.AdRequest import com.google.ads.InterstitialAd import com.google.ads.AdListener import com.google.ads.Ad import android.os.Handler import com.abplus.surroundcalc.exporters.ActionSender import com.abplus.surroundcalc.utls.Purchases import com.abplus.surroundcalc.billing.BillingHelper import android.app.AlertDialog import android.content.DialogInterface import android.content.Intent import com.abplus.surroundcalc.billing.BillingHelper.Result import android.widget.Toast /** * Created by kazhida on 2014/01/02. */ class DoodleActivity : Activity() { var purchases: Purchases? = null var adView: AdView? = null var interstitial: InterstitialAd? = null val sku_basic: String get() = getString(R.string.sku_basic) protected override fun onCreate(savedInstanceState: Bundle?) : Unit { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) purchases = Purchases(this) adView = AdView(this, AdSize.BANNER, getString(R.string.banner_unit_id)) val params = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) adView!!.setLayoutParams(params) val frame = (findViewById(R.id.ad_frame) as FrameLayout?) frame?.addView(adView!!) interstitial = InterstitialAd(this, getString(R.string.interstitial_unit_id)) interstitial?.loadAd(AdRequest()); interstitial?.setAdListener(object: AdListener{ override fun onReceiveAd(p0: Ad?) { Log.d("surroundcalc", "Received") } override fun onFailedToReceiveAd(p0: Ad?, p1: AdRequest.ErrorCode?) { Log.d("surroundcalc", "Failed") } override fun onPresentScreen(p0: Ad?) { Log.d("surroundcalc", "PresentScreen") } override fun onDismissScreen(p0: Ad?) { Log.d("surroundcalc", "DismissScreen") interstitial?.loadAd(AdRequest()) } override fun onLeaveApplication(p0: Ad?) { Log.d("surroundcalc", "LeaveApplication") } }); val actionBar = getActionBar()!! addTab(actionBar, Drawing.KeyColor.BLUE, true) addTab(actionBar, Drawing.KeyColor.GREEN, false) addTab(actionBar, Drawing.KeyColor.RED, false) addTab(actionBar, Drawing.KeyColor.YELLOW, false) actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS) } protected override fun onActivityResult(requestCode : Int, resultCode : Int, data : Intent?) : Unit { if (! purchases!!.billingHelper.handleActivityResult(requestCode, resultCode, data)) { super.onActivityResult(requestCode, resultCode, data) } } protected override fun onResume() { super.onResume() adView?.loadAd(AdRequest()) val keyColor = Preferences(this).currentColor if (keyColor != null) { val actionBar = getActionBar()!! val tab = actionBar.getTabAt(keyColor.ordinal()); actionBar.selectTab(tab) } if (purchases!!.isPurchased(sku_basic)){ findViewById(R.id.ad_frame)?.setVisibility(View.GONE) } purchases!!.checkState(sku_basic, object : BillingHelper.QueryInventoryFinishedListener { override fun onQueryInventoryFinished(result: BillingHelper.Result?, inventory: BillingHelper.Inventory?) { if (result!!.isSuccess()) { if (inventory!!.hasPurchase(sku_basic)) { findViewById(R.id.ad_frame)?.setVisibility(View.GONE) } else { findViewById(R.id.ad_frame)?.setVisibility(View.VISIBLE) } } else { findViewById(R.id.ad_frame)?.setVisibility(View.VISIBLE) showErrorToast(R.string.err_inventory) } } }) } public override fun onPause() { super.onPause() adView?.stopLoading() } public override fun onDestroy() { adView?.destroy() purchases?.billingHelper?.dispose() super.onDestroy() } public override fun onCreateOptionsMenu(menu : Menu?) : Boolean { val inflater = getMenuInflater() inflater.inflate(R.menu.actions, menu) return super.onCreateOptionsMenu(menu) } public override fun onOptionsItemSelected(item : MenuItem?) : Boolean { return when (item?.getItemId()) { R.id.action_clear_drawing -> { doodleView.clear() true } R.id.action_content_undo -> { doodleView.undo() true } R.id.action_social_share -> { if (purchases!!.isPurchased(sku_basic)) { ActionSender().startActivity(this, doodleView.createBitmap()) } else { val builder = AlertDialog.Builder(this) builder.setTitle(R.string.upgrade_title) builder.setMessage(R.string.upgrade_message) builder.setPositiveButton(R.string.upgrade) {(dialog: DialogInterface, which: Int) -> purchases!!.purchase(this, getString(R.string.sku_basic), object : Runnable { override fun run() { findViewById(R.id.ad_frame)?.setVisibility(View.GONE) } }) } builder.setNegativeButton(R.string.close, null) builder.setCancelable(true) builder.create().show() } true } else -> super.onOptionsItemSelected(item) } } private val doodleView: DoodleView get() { val fragment = getFragmentManager().findFragmentById(R.id.fragment_container) as DoodleFragment return fragment.mainView } private fun showErrorToast(msgId: Int) { Toast.makeText(this, msgId, Toast.LENGTH_SHORT).show() } private fun addTab(actionBar : ActionBar, keyColor : Drawing.KeyColor, selected : Boolean) : Unit { val tab = actionBar.newTab() val resId = when (keyColor) { Drawing.KeyColor.BLUE -> { R.string.blue } Drawing.KeyColor.GREEN -> { R.string.green } Drawing.KeyColor.RED -> { R.string.red } Drawing.KeyColor.YELLOW -> { R.string.yellow } } tab.setText(resId) tab.setTabListener(TabListener(getString(resId), keyColor)) actionBar.addTab(tab, selected) } private fun setKeyColor(keyColor: Drawing.KeyColor) { Preferences(this).currentColor = keyColor } private inner class TabListener(val tag: String, val keyColor: Drawing.KeyColor): ActionBar.TabListener { var fragment: DoodleFragment? = null override fun onTabSelected(tab: ActionBar.Tab?, ft: FragmentTransaction?) { if (fragment == null) { fragment = DoodleFragment(keyColor) ft?.add(R.id.fragment_container, fragment!!, tag) } else { ft?.attach(fragment) } setKeyColor(keyColor) if (! purchases!!.isPurchased(sku_basic)) { interstitial?.show() } } override fun onTabUnselected(tab: ActionBar.Tab?, ft: FragmentTransaction?) { if (fragment != null) { ft?.detach(fragment) } } override fun onTabReselected(tab: ActionBar.Tab?, ft: FragmentTransaction?) {} } }
src/com/abplus/surroundcalc/DoodleActivity.kt
457371436
package sample import android.app.Application import com.esafirm.sample.BuildConfig import com.squareup.leakcanary.LeakCanary class SampleApplication : Application() { override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { if (LeakCanary.isInAnalyzerProcess(this)) { // This process is dedicated to LeakCanary for heap analysis. // You should not init your app in this process. return } LeakCanary.install(this) } } }
sample/src/debug/java/sample/SampleApplication.kt
668815833
package nl.hannahsten.texifyidea.inspections.latex.probablebugs.packages import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl import io.mockk.every import io.mockk.mockkStatic import nl.hannahsten.texifyidea.file.LatexFileType import nl.hannahsten.texifyidea.inspections.TexifyInspectionTestBase import nl.hannahsten.texifyidea.testutils.writeCommand import nl.hannahsten.texifyidea.util.runCommandWithExitCode class LatexMissingImportInspectionTest : TexifyInspectionTestBase(LatexMissingImportInspection()) { override fun getTestDataPath(): String { return "test/resources/inspections/latex/missingimport" } override fun setUp() { super.setUp() myFixture.copyDirectoryToProject("", "") (myFixture as CodeInsightTestFixtureImpl).canChangeDocumentDuringHighlighting(true) mockkStatic(::runCommandWithExitCode) every { runCommandWithExitCode(*anyVararg(), workingDirectory = any(), timeout = any(), returnExceptionMessage = any()) } returns Pair(null, 0) } fun testWarning() { myFixture.configureByText( LatexFileType, """ <error descr="Command requires color, or xcolor package">\color</error>{blue} """.trimIndent() ) myFixture.checkHighlighting() } fun testQuickfix() { myFixture.configureByText( LatexFileType, """ \documentclass{article} \usepackage{amsmath} \begin{document} \color{blue} \end{document} """.trimIndent() ) val quickFixes = myFixture.getAllQuickFixes() assertEquals(2, quickFixes.size) writeCommand(myFixture.project) { quickFixes.last().invoke(myFixture.project, myFixture.editor, myFixture.file) } myFixture.checkResult( """ \documentclass{article} \usepackage{amsmath} \usepackage{xcolor} \begin{document} \color{blue} \end{document} """.trimIndent() ) } fun `test package imported in subfile root`() { myFixture.configureByFiles("main.tex", "sub.tex") myFixture.checkHighlighting() } fun `test package not imported in subfile root`() { myFixture.configureByFiles("missingsub.tex", "missingmain.tex") myFixture.checkHighlighting() } }
test/nl/hannahsten/texifyidea/inspections/latex/probablebugs/packages/LatexMissingImportInspectionTest.kt
1181124490
package io.gitlab.arturbosch.detekt.rules.naming import io.gitlab.arturbosch.detekt.test.lint import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.subject.SubjectSpek class NamingRulesSpec : SubjectSpek<NamingRules>({ subject { NamingRules() } describe("properties in classes") { it("should detect all positive cases") { val code = """ class C(val CONST_PARAMETER: String, private val PRIVATE_CONST_PARAMETER: Int) { private val _FIELD = 5 val FIELD get() = _field val camel_Case_Property = 5 const val MY_CONST = 7 const val MYCONST = 7 fun doStuff(FUN_PARAMETER: String) {} } """ val findings = subject.lint(code) assertThat(findings).hasSize(8) } it("checks all negative cases") { val code = """ class C(val constParameter: String, private val privateConstParameter: Int) { private val _field = 5 val field get() = _field val camelCaseProperty = 5 const val myConst = 7 data class D(val i: Int, val j: Int) fun doStuff() { val (_, holyGrail) = D(5, 4) emptyMap<String, String>().forEach { _, v -> println(v) } } val doable: (Int) -> Unit = { _ -> Unit } fun doStuff(funParameter: String) {} } """ val findings = subject.lint(code) assertThat(findings).isEmpty() } } describe("naming like in constants is allowed for destructuring and lambdas") { it("should not detect any") { val code = """ data class D(val i: Int, val j: Int) fun doStuff() { val (_, HOLY_GRAIL) = D(5, 4) emptyMap<String, String>().forEach { _, V -> println(v) } } """ val findings = subject.lint(code) assertThat(findings).isEmpty() } } })
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/naming/NamingRulesSpec.kt
17531634
package com.jamieadkins.gwent.latest import com.jamieadkins.gwent.R import com.xwray.groupie.kotlinandroidextensions.Item import com.xwray.groupie.kotlinandroidextensions.ViewHolder class LatestDividerItem : Item() { override fun getLayout(): Int = R.layout.view_latest_divider override fun bind(viewHolder: ViewHolder, position: Int) { // Do nothing. } }
app/src/main/java/com/jamieadkins/gwent/latest/LatestDividerItem.kt
939052416
package com.pr0gramm.app.ui.views import android.content.Context import android.util.AttributeSet import com.pr0gramm.app.util.AndroidUtility /** */ class CustomSwipeRefreshLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : androidx.swiperefreshlayout.widget.SwipeRefreshLayout(context, attrs) { private var canScrollUpTest: (() -> Boolean)? = null fun setCanChildScrollUpTest(test: () -> Boolean) { canScrollUpTest = test } override fun canChildScrollUp(): Boolean { return (canScrollUpTest?.invoke() ?: false) || super.canChildScrollUp() } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { try { super.onLayout(changed, left, top, right, bottom) } catch (err: Exception) { // I found crashlytics reports during layout, // lets just catch everything inside this layout. AndroidUtility.logToCrashlytics(err) } } }
app/src/main/java/com/pr0gramm/app/ui/views/CustomSwipeRefreshLayout.kt
2617531584
package org.metplus.cruncher.web.controller import org.springframework.http.MediaType import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping(value = [ "/api/v1", "/api/v2", "/api/v99999" ]) class AuthenticationController { // tag::authenticate[] @RequestMapping(path = ["authenticate"], method = [RequestMethod.POST], produces = [MediaType.APPLICATION_JSON_VALUE]) fun authenticate() { /*return "This is just for in-code-documentation purposes and Rest API reference documentation." + "Servlet will never get to this point as Http requests are processed by AuthenticationFilter." + "Nonetheless to authenticate Domain User POST request with X-Auth-Username and X-Auth-Password headers " + "is mandatory to this URL. If username and password are correct valid token will be returned (just json string in response) " + "This token must be present in X-Auth-Token header in all requests for all other URLs, including logout." + "Authentication can be issued multiple times and each call results in new ticket.";*/ } // end::authenticate[] }
web/src/main/kotlin/org/metplus/cruncher/web/controller/AuthenticationController.kt
3252393949
/* * Copyright (C) 2014 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.internal.http2 import java.io.IOException import okhttp3.Protocol import okio.BufferedSource /** * [HTTP/2][Protocol.HTTP_2] only. Processes server-initiated HTTP requests on the client. * Implementations must quickly dispatch callbacks to avoid creating a bottleneck. * * While [onReset] may occur at any time, the following callbacks are expected in order, * correlated by stream ID. * * * [onRequest] * * [onHeaders] (unless canceled) * * [onData] (optional sequence of data frames) * * As a stream ID is scoped to a single HTTP/2 connection, implementations which target multiple * connections should expect repetition of stream IDs. * * Return true to request cancellation of a pushed stream. Note that this does not guarantee * future frames won't arrive on the stream ID. */ interface PushObserver { /** * Describes the request that the server intends to push a response for. * * @param streamId server-initiated stream ID: an even number. * @param requestHeaders minimally includes `:method`, `:scheme`, `:authority`, * and `:path`. */ fun onRequest(streamId: Int, requestHeaders: List<Header>): Boolean /** * The response headers corresponding to a pushed request. When [last] is true, there are * no data frames to follow. * * @param streamId server-initiated stream ID: an even number. * @param responseHeaders minimally includes `:status`. * @param last when true, there is no response data. */ fun onHeaders(streamId: Int, responseHeaders: List<Header>, last: Boolean): Boolean /** * A chunk of response data corresponding to a pushed request. This data must either be read or * skipped. * * @param streamId server-initiated stream ID: an even number. * @param source location of data corresponding with this stream ID. * @param byteCount number of bytes to read or skip from the source. * @param last when true, there are no data frames to follow. */ @Throws(IOException::class) fun onData(streamId: Int, source: BufferedSource, byteCount: Int, last: Boolean): Boolean /** Indicates the reason why this stream was canceled. */ fun onReset(streamId: Int, errorCode: ErrorCode) companion object { @JvmField val CANCEL: PushObserver = PushObserverCancel() private class PushObserverCancel : PushObserver { override fun onRequest(streamId: Int, requestHeaders: List<Header>): Boolean { return true } override fun onHeaders(streamId: Int, responseHeaders: List<Header>, last: Boolean): Boolean { return true } @Throws(IOException::class) override fun onData(streamId: Int, source: BufferedSource, byteCount: Int, last: Boolean): Boolean { source.skip(byteCount.toLong()) return true } override fun onReset(streamId: Int, errorCode: ErrorCode) { } } } }
okhttp/src/main/kotlin/okhttp3/internal/http2/PushObserver.kt
1885828552
package yotkaz.thimman.backend.controller import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import yotkaz.thimman.backend.model.Course import yotkaz.thimman.backend.service.impl.CourseService @RestController @RequestMapping("/courses") class CourseController : AbstractCRUDController<Course, Long, CourseService>()
thimman-backend/src/main/kotlin/yotkaz/thimman/backend/controller/CourseController.kt
1628799478
package de.thm.arsnova.service.authservice.exception import org.springframework.http.HttpStatus import org.springframework.web.server.ResponseStatusException class BadRequestException : ResponseStatusException { constructor() : super(HttpStatus.BAD_REQUEST) constructor(reason: String?) : super(HttpStatus.BAD_REQUEST, reason) constructor(reason: String?, cause: Throwable?) : super(HttpStatus.BAD_REQUEST, reason, cause) }
authz/src/main/kotlin/de/thm/arsnova/service/authservice/exception/BadRequestException.kt
274627066
package com.sys1yagi.mastodon4j import com.google.gson.JsonParser import com.sys1yagi.mastodon4j.api.exception.Mastodon4jRequestException import com.sys1yagi.mastodon4j.extension.toPageable import okhttp3.Response import java.lang.Exception open class MastodonRequest<T>( private val executor: () -> Response, private val mapper: (String) -> Any ) { interface Action1<T> { fun invoke(arg: T) } private var action: (String) -> Unit = {} private var isPageable: Boolean = false internal fun toPageable() = apply { isPageable = true } @JvmSynthetic fun doOnJson(action: (String) -> Unit) = apply { this.action = action } fun doOnJson(action: Action1<String>) = apply { this.action = { action.invoke(it) } } @Suppress("UNCHECKED_CAST") @Throws(Mastodon4jRequestException::class) fun execute(): T { val response = executor() if (response.isSuccessful) { try { val body = response.body().string() val element = JsonParser().parse(body) if (element.isJsonObject) { action(body) return mapper(body) as T } else { val list = arrayListOf<Any>() element.asJsonArray.forEach { val json = it.toString() action(json) list.add(mapper(json)) } if (isPageable) { return list.toPageable(response) as T } else { return list as T } } } catch (e: Exception) { throw Mastodon4jRequestException(e) } } else { throw Mastodon4jRequestException(response) } } }
mastodon4j/src/main/java/com/sys1yagi/mastodon4j/MastodonRequest.kt
2252233512
package cc.aoeiuv020.panovel.find.qidiantu.list import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import cc.aoeiuv020.base.jar.ioExecutorService import cc.aoeiuv020.panovel.R import cc.aoeiuv020.panovel.data.DataManager import cc.aoeiuv020.panovel.report.Reporter import cc.aoeiuv020.panovel.util.noCover import cc.aoeiuv020.regex.pick import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread class QidiantuListAdapter : RecyclerView.Adapter<QidiantuListAdapter.ViewHolder>() { private val data = mutableListOf<Item>() private var onItemClickListener: OnItemClickListener? = null @SuppressLint("NotifyDataSetChanged") fun setData(data: List<Item>) { this.data.clear() this.data.addAll(data) notifyDataSetChanged() } fun setOnItemClickListener(listener: OnItemClickListener) { this.onItemClickListener = listener } override fun getItemCount(): Int { return data.count() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( LayoutInflater.from(parent.context) .inflate(R.layout.item_qidiantu_list, parent, false) ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = data[position] holder.itemView.setOnClickListener { onItemClickListener?.onItemClick(item) } holder.bind(item) } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val ivImage: ImageView = itemView.findViewById(R.id.ivImage) private val tvName: TextView = itemView.findViewById(R.id.tvName) private val tvAuthor: TextView = itemView.findViewById(R.id.tvAuthor) private val tvDate: TextView = itemView.findViewById(R.id.tvDate) private val tvType: TextView = itemView.findViewById(R.id.tvType) private val tvWords: TextView = itemView.findViewById(R.id.tvWords) private val tvRatio: TextView = itemView.findViewById(R.id.tvRatio) @SuppressLint("SetTextI18n") fun bind(item: Item) { showImage(item) tvName.text = item.name tvAuthor.text = item.author + " • " + item.level tvDate.text = item.dateAdded tvType.text = item.type tvWords.text = item.words val ratio = if (item.collection.isBlank() && item.firstOrder.isBlank()) { item.ratio } else { "${item.collection}/${item.firstOrder}= ${item.ratio}" } tvRatio.text = ratio } private fun showImage(item: Item) { ivImage.setTag(R.id.tag_image_item, item) val ctx = ivImage.context if (!item.image.isNullOrBlank()) { Glide.with(ctx.applicationContext) .load(item.image) .apply(RequestOptions().apply { placeholder(R.mipmap.no_cover) error(R.mipmap.no_cover) }) .into(ivImage) return } val url = item.url val name = item.name ivImage.setImageResource(R.mipmap.no_cover) ivImage.context.doAsync({ e -> val message = "刷新小说《${name}》失败," Reporter.post(message, e) }, ioExecutorService) { val bookId = url.pick("http.*/info/(\\d*)").first() val site = "起点中文" val novelManager = DataManager.query(site, item.author, item.name, bookId) novelManager.requestDetail(false) val imageUrl = novelManager.novel.image item.image = imageUrl item.name = novelManager.novel.name uiThread { ctx -> val tag = ivImage.getTag(R.id.tag_image_item) if (tag != item) { return@uiThread } tvName.text = item.name if (imageUrl == noCover) { ivImage.setImageResource(R.mipmap.no_cover) } else { Glide.with(ctx.applicationContext) .load(novelManager.getImage(imageUrl)) .apply(RequestOptions().apply { placeholder(R.mipmap.no_cover) error(R.mipmap.no_cover) }) .into(ivImage) } } } ivImage.setImageResource(R.mipmap.no_cover) } } interface OnItemClickListener { fun onItemClick(item: Item) } }
app/src/main/java/cc/aoeiuv020/panovel/find/qidiantu/list/QidiantuListAdapter.kt
3372948572
@file:Suppress("UNUSED_PARAMETER", "unused", "PackageName", "MemberVisibilityCanBePrivate", "ClassName") package tested.developer_reference import com.nextfaze.devfun.reference.DeveloperReference import com.nextfaze.devfun.reference.MethodReference import kotlin.reflect.jvm.javaMethod import kotlin.test.expect annotation class ExecutableReferences class er_PublicClass { @DeveloperReference fun testPublicFunction(ref: MethodReference) { expect(ref.method, this::testPublicFunction::javaMethod) } @DeveloperReference private fun testPrivateFunction(ref: MethodReference) { expect(ref.method, this::testPrivateFunction::javaMethod) } } private class er_PrivateClass { @DeveloperReference fun testPublicFunction(ref: MethodReference) { expect(ref.method, this::testPublicFunction::javaMethod) } @DeveloperReference private fun testPrivateFunction(ref: MethodReference) { expect(ref.method, this::testPrivateFunction::javaMethod) } } object er_PublicObject { @DeveloperReference fun testPublicFunction(ref: MethodReference) { expect(ref.method, this::testPublicFunction::javaMethod) } @DeveloperReference private fun testPrivateFunction(ref: MethodReference) { expect(ref.method, this::testPrivateFunction::javaMethod) } } private object er_PrivateObject { @DeveloperReference fun testPublicFunction(ref: MethodReference) { expect(ref.method, this::testPublicFunction::javaMethod) } @DeveloperReference private fun testPrivateFunction(ref: MethodReference) { expect(ref.method, this::testPrivateFunction::javaMethod) } } class er_PublicClassCompanionObject { companion object { @DeveloperReference fun testPublicFunction(ref: MethodReference) { expect(ref.method, this::testPublicFunction::javaMethod) } @DeveloperReference private fun testPrivateFunction(ref: MethodReference) { expect(ref.method, this::testPrivateFunction::javaMethod) } } } private class er_PrivateClassCompanionObject { companion object SomeName { @DeveloperReference fun testPublicFunction(ref: MethodReference) { expect(ref.method, this::testPublicFunction::javaMethod) } @DeveloperReference private fun testPrivateFunction(ref: MethodReference) { expect(ref.method, this::testPrivateFunction::javaMethod) } } } private class er_PrivateClassPrivateCompanionObject { private companion object PrivateCompanion { @DeveloperReference fun testPublicFunction(ref: MethodReference) { expect(ref.method, this::testPublicFunction::javaMethod) } @DeveloperReference private fun testPrivateFunction(ref: MethodReference) { expect(ref.method, this::testPrivateFunction::javaMethod) } } } @DeveloperReference fun testPublicTopLevelFunction(ref: MethodReference) { expect(ref.method, ::testPublicTopLevelFunction::javaMethod) } @DeveloperReference private fun testPrivateTopLevelFunction(ref: MethodReference) { expect(ref.method, ::testPrivateTopLevelFunction::javaMethod) } @DeveloperReference fun String.testPublicTopLevelExtensionFunction(ref: MethodReference) { expect(ref.method, ::testPublicTopLevelExtensionFunction::javaMethod) } @DeveloperReference private fun String.testPrivateTopLevelExtensionFunction(ref: MethodReference) { expect(ref.method, ::testPrivateTopLevelExtensionFunction::javaMethod) } @DeveloperReference val String.testTopLevelExtensionFunctionProperty get() = "Hello World from public" @DeveloperReference private val String.testPrivateTopLevelExtensionFunctionProperty get() = "Hello World from private"
test/src/testData/kotlin/tested/developer_reference/ExecutableReferences.kt
3451666631
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.menu.context import android.app.Activity import android.app.Dialog import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.content.pm.ActivityInfo import android.content.pm.PackageManager import android.content.pm.ResolveInfo import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.net.Uri import android.os.Environment import android.preference.PreferenceManager import com.google.android.material.internal.NavigationMenuView import com.google.android.material.navigation.NavigationView import androidx.appcompat.app.AlertDialog import android.text.Html import android.view.LayoutInflater import android.view.View import android.widget.TextView import mozilla.components.browser.session.Session import org.mozilla.focus.R import org.mozilla.focus.activity.MainActivity import org.mozilla.focus.open.OpenWithFragment import org.mozilla.focus.ext.components import org.mozilla.focus.telemetry.TelemetryWrapper import org.mozilla.focus.telemetry.TelemetryWrapper.BrowserContextMenuValue import org.mozilla.focus.utils.Browsers import org.mozilla.focus.utils.Settings import org.mozilla.focus.utils.UrlUtils import org.mozilla.focus.utils.ViewUtils import org.mozilla.focus.utils.asFragmentActivity import org.mozilla.focus.web.Download import org.mozilla.focus.web.IWebView /** * The context menu shown when long pressing a URL or an image inside the WebView. */ object WebContextMenu { private fun createTitleView(context: Context, title: String): View { val titleView = LayoutInflater.from(context).inflate(R.layout.context_menu_title, null) as TextView titleView.text = title return titleView } @Suppress("ComplexMethod") fun show( context: Context, callback: IWebView.Callback, hitTarget: IWebView.HitTarget, session: Session ) { if (!(hitTarget.isLink || hitTarget.isImage)) { // We don't support any other classes yet: throw IllegalStateException("WebContextMenu can only handle long-press on images and/or links.") } TelemetryWrapper.openWebContextMenuEvent() val builder = AlertDialog.Builder(context) builder.setCustomTitle(when { hitTarget.isLink -> createTitleView(context, hitTarget.linkURL) hitTarget.isImage -> createTitleView(context, hitTarget.imageURL) else -> throw IllegalStateException("Unhandled long press target type") }) val view = LayoutInflater.from(context).inflate(R.layout.context_menu, null) builder.setView(view) builder.setOnCancelListener { // What type of element was long-pressed val value: BrowserContextMenuValue = if (hitTarget.isImage && hitTarget.isLink) { BrowserContextMenuValue.ImageWithLink } else if (hitTarget.isImage) { BrowserContextMenuValue.Image } else { BrowserContextMenuValue.Link } // This even is only sent when the back button is pressed, or when a user // taps outside of the dialog: TelemetryWrapper.cancelWebContextMenuEvent(value) } val dialog = builder.create() dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) val menu = view.findViewById<View>(R.id.context_menu) as NavigationView menu.elevation = 0f val navigationMenuView = menu.getChildAt(0) as? NavigationMenuView if (navigationMenuView != null) { navigationMenuView.isVerticalScrollBarEnabled = false } setupMenuForHitTarget(dialog, menu, callback, hitTarget, context, session) val warningView = view.findViewById<View>(R.id.warning) as TextView if (hitTarget.isImage) { menu.setBackgroundResource(R.drawable.no_corners_context_menu_navigation_view_background) @Suppress("DEPRECATION") warningView.text = Html.fromHtml( context.getString(R.string.contextmenu_image_warning, context.getString(R.string.app_name)) ) } else { warningView.visibility = View.GONE } dialog.show() } private fun getAppDataForLink(context: Context, url: String): Array<ActivityInfo>? { val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse(url) val browsers = Browsers(context, url) val resolveInfos: List<ResolveInfo> = context.packageManager .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) .filter { !browsers.installedBrowsers.contains(it.activityInfo) && it.activityInfo.packageName != context.packageName } return if (resolveInfos.isEmpty()) null else resolveInfos.map { it.activityInfo }.toTypedArray() } /** * Set up the correct menu contents. Note: this method can only be called once the Dialog * has already been created - we need the dialog in order to be able to dismiss it in the * menu callbacks. */ @Suppress("ComplexMethod", "LongParameterList") private fun setupMenuForHitTarget( dialog: Dialog, navigationView: NavigationView, callback: IWebView.Callback, hitTarget: IWebView.HitTarget, context: Context, session: Session ) = with(navigationView) { val appLinkData = if (hitTarget.linkURL != null) getAppDataForLink(context, hitTarget.linkURL) else null inflateMenu(R.menu.menu_browser_context) menu.findItem(R.id.menu_open_with_app).isVisible = appLinkData != null menu.findItem(R.id.menu_new_tab).isVisible = hitTarget.isLink && !session.isCustomTabSession() menu.findItem(R.id.menu_open_in_focus).title = resources.getString( R.string.menu_open_with_default_browser2, resources.getString(R.string.app_name) ) menu.findItem(R.id.menu_open_in_focus).isVisible = hitTarget.isLink && session.isCustomTabSession() menu.findItem(R.id.menu_link_share).isVisible = hitTarget.isLink menu.findItem(R.id.menu_link_copy).isVisible = hitTarget.isLink menu.findItem(R.id.menu_image_share).isVisible = hitTarget.isImage menu.findItem(R.id.menu_image_copy).isVisible = hitTarget.isImage menu.findItem(R.id.menu_image_save).isVisible = hitTarget.isImage && UrlUtils.isHttpOrHttps(hitTarget.imageURL) setNavigationItemSelectedListener { item -> dialog.dismiss() when (item.itemId) { R.id.menu_open_with_app -> { val fragment = OpenWithFragment.newInstance(appLinkData!!, hitTarget.linkURL, null) fragment.show( context.asFragmentActivity()!!.supportFragmentManager, OpenWithFragment.FRAGMENT_TAG ) true } R.id.menu_open_in_focus -> { // Open selected link in Focus and navigate there val newSession = Session(hitTarget.linkURL, source = Session.Source.MENU) context.components.sessionManager.add(newSession, selected = true) val intent = Intent(context, MainActivity::class.java) intent.action = Intent.ACTION_MAIN intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP context.startActivity(intent) TelemetryWrapper.openLinkInFullBrowserFromCustomTabEvent() true } R.id.menu_new_tab -> { val newSession = Session(hitTarget.linkURL, source = Session.Source.MENU) context.components.sessionManager.add( newSession, selected = Settings.getInstance(context).shouldOpenNewTabs() ) if (!Settings.getInstance(context).shouldOpenNewTabs()) { // Show Snackbar to allow users to switch to tab they just opened val snackbar = ViewUtils.getBrandedSnackbar( (context as Activity).findViewById(android.R.id.content), R.string.new_tab_opened_snackbar) snackbar.setAction(R.string.open_new_tab_snackbar) { context.components.sessionManager.select(newSession) } snackbar.show() } TelemetryWrapper.openLinkInNewTabEvent() PreferenceManager.getDefaultSharedPreferences(context).edit() .putBoolean( context.getString(R.string.has_opened_new_tab), true ).apply() true } R.id.menu_link_share -> { TelemetryWrapper.shareLinkEvent() val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.type = "text/plain" shareIntent.putExtra(Intent.EXTRA_TEXT, hitTarget.linkURL) dialog.context.startActivity( Intent.createChooser( shareIntent, dialog.context.getString(R.string.share_dialog_title) ) ) true } R.id.menu_image_share -> { TelemetryWrapper.shareImageEvent() val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.type = "text/plain" shareIntent.putExtra(Intent.EXTRA_TEXT, hitTarget.imageURL) dialog.context.startActivity( Intent.createChooser( shareIntent, dialog.context.getString(R.string.share_dialog_title) ) ) true } R.id.menu_image_save -> { val download = Download(hitTarget.imageURL, null, null, null, -1, Environment.DIRECTORY_PICTURES, null) callback.onDownloadStart(download) TelemetryWrapper.saveImageEvent() true } R.id.menu_link_copy, R.id.menu_image_copy -> { val clipboard = dialog.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val uri: Uri = when { item.itemId == R.id.menu_link_copy -> { TelemetryWrapper.copyLinkEvent() Uri.parse(hitTarget.linkURL) } item.itemId == R.id.menu_image_copy -> { TelemetryWrapper.copyImageEvent() Uri.parse(hitTarget.imageURL) } else -> throw IllegalStateException("Unknown hitTarget type - cannot copy to clipboard") } val clip = ClipData.newUri(dialog.context.contentResolver, "URI", uri) clipboard.primaryClip = clip true } else -> throw IllegalArgumentException("Unhandled menu item id=" + item.itemId) } } } }
app/src/main/java/org/mozilla/focus/menu/context/WebContextMenu.kt
220810721
package com.adrianfaciu.teamcity.flowdockPlugin.notifications /** * Notification object that will be serialized and sent to Flowdock */ class FlowdockNotification { var author: NotificationAuthor? = null var external_thread_id: String? = null var title: String? = null var event: String? = null var thread: NotificationThread? = null var thread_id: String? = null var body: String? = null var flow_token: String? = null override fun toString(): String { return "[author = $author, body = $body, external_thread_id = $external_thread_id, title = $title, event = $event, thread = $thread, thread_id = $thread_id, flow_token = $flow_token]" } }
flowdock-teamcity-plugin-server/src/main/kotlin/com/adrianfaciu/teamcity/flowdockPlugin/notifications/FlowdockNotification.kt
2110050860
package com.kinotir.api import io.reactivex.Single import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface ServerApi { @GET("/ajax/user.php?action=login&submit=true") fun login(@Query("email") email: String, @Query("password") password: String): Single<Response<String>> @GET("/") fun todayFilms(): Single<Response<String>> @GET("/skoro-v-kino") fun soonFilms(): Single<Response<String>> @GET("{path}") fun filmDetails(@Path("path") path: String): Single<Response<String>> @GET("/lc/") fun tickets(): Single<Response<String>> @GET("/novosti") fun newses(): Single<Response<String>> }
KinotirApi/src/main/java/com/kinotir/api/ServerApi.kt
3251752655
/* * Copyright (C) 2018 Andrzej Ressel ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.jereksel.libresubstratum.domain.usecases import android.os.Looper import com.google.common.util.concurrent.MoreExecutors import com.jereksel.libresubstratum.domain.IPackageManager import com.jereksel.libresubstratum.domain.InvalidOverlayService import com.jereksel.libresubstratum.domain.LoggedOverlayService import com.jereksel.libresubstratum.domain.OverlayService import com.jereksel.libresubstratum.extensions.getLogger import java.util.concurrent.Executors class CleanUnusedOverlays( val packageManager: IPackageManager, val overlayManager: OverlayService ): ICleanUnusedOverlays { val log = getLogger() val executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()) override fun clean() = executor.submit { if (overlayManager is InvalidOverlayService || (overlayManager as? LoggedOverlayService)?.overlayService is InvalidOverlayService) { return@submit } log.debug("Cleaning overlays") val overlays = packageManager.getInstalledOverlays() for (overlay in overlays) { val overlayId = overlay.overlayId val themeAppId = overlay.sourceThemeId val targetAppId = overlay.targetId if (!packageManager.isPackageInstalled(themeAppId) || !packageManager.isPackageInstalled(targetAppId)) { try { log.debug("Removing overlay: $overlayId") overlayManager.uninstallApk(overlayId).get() } catch (e: Exception) { log.error("Cannot remove $overlayId", e) } } } } }
app/src/main/kotlin/com/jereksel/libresubstratum/domain/usecases/CleanUnusedOverlays.kt
1994222360
package com.iyanuadelekan.kanary.app.framework.router import com.iyanuadelekan.kanary.app.RouteList import com.iyanuadelekan.kanary.app.RouterAction import com.iyanuadelekan.kanary.app.adapter.component.middleware.MiddlewareAdapter import com.iyanuadelekan.kanary.app.constant.RouteType import com.iyanuadelekan.kanary.app.router.RouteNode /** * @author Iyanu Adelekan on 18/11/2018. */ internal interface RouteManager { /** * Invoked to register a new route to the router. * * @param routeType - type of route to be added. See [RouteType]. * @param path - URL path. * @param action - router action. * * @return [RouteManager] - current [RouteManager] instance. */ fun addRoute( routeType: RouteType, path: String, action: RouterAction, middleware: List<MiddlewareAdapter>? = null ): RouteManager /** * Invoked to resolve a corresponding RouteNode to a given URL target - if any. * * @param path - URL path (target). * @return [RouteNode] - Returns corresponding instance of [RouteNode], if one exists. Else returns null. */ fun getRouteNode(path: String, method: RouteType): RouteNode? /** * Invoked to get a matching route node - within a given route list - for a given sub path. * * @param routeList - list of routes. * @param subPath - sub path to match. * @return [RouteNode] - returns a [RouteNode] is one exists and null otherwise. */ fun getMatchingNode(routeList: RouteList, subPath: String): RouteNode? }
src/main/com/iyanuadelekan/kanary/app/framework/router/RouteManager.kt
767692336
package net.nemerosa.ontrack.extension.notifications.webhooks import com.fasterxml.jackson.databind.JsonNode import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import net.nemerosa.ontrack.common.BaseException import net.nemerosa.ontrack.json.asJson import net.nemerosa.ontrack.json.format import net.nemerosa.ontrack.json.parseOrNull import net.nemerosa.ontrack.model.exceptions.NotFoundException import net.nemerosa.ontrack.model.security.SecurityService import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.web.bind.annotation.* import java.util.* import javax.annotation.PostConstruct /** * Internal endpoint for simulating a webhook. * * Should be used only for testing. */ @RestController @ConditionalOnProperty( prefix = "ontrack.config.extension.notifications.webhook.internal", name = ["enabled"], havingValue = "true", matchIfMissing = false, ) @RequestMapping("/extension/notifications/webhooks/internal") class WebhookInternalEndpointController( private val securityService: SecurityService, private val webhookAdminService: WebhookAdminService, private val webhookExecutionService: WebhookExecutionService, ) { private val logger: Logger = LoggerFactory.getLogger(WebhookInternalEndpointController::class.java) /** * Logging the usage */ @PostConstruct fun warning() { logger.warn("Using internal webhook - this must be disabled in production!") } /** * Storing the payloads in memory */ private val payloads = mutableListOf<JsonWebhookPayload>() /** * Testing a webhook using the test payload */ @PostMapping("test") fun test(@RequestBody wrapper: TestPayloadWrapper) { securityService.asAdmin { val webhook = webhookAdminService.findWebhookByName(wrapper.webhook) ?: throw WebhookNotFoundException( wrapper.webhook) webhookExecutionService.send( webhook = webhook, payload = WebhookPayload( type = "test", data = wrapper.payload, ) ) } } /** * The endpoint. */ @PostMapping("") fun post(@RequestBody payload: JsonWebhookPayload): String { payloads += payload return when (payload.type) { "test" -> test(payload) ?: "OK" "ping" -> ping(payload.data) else -> "OK" } } private fun ping(data: JsonNode): String = mapOf("ping" to data).asJson().format() private fun test(payload: JsonWebhookPayload): String? { val test = payload.data.parseOrNull<TestPayload>() ?: return null val value = when (test.mode) { TestPayloadMode.OK -> test.content TestPayloadMode.NOT_FOUND -> throw TestPayloadNotFoundException(test.content) TestPayloadMode.INTERNAL_ERROR -> throw TestPayloadInternalException(test.content) } if (test.delayMs != null) { runBlocking { delay(test.delayMs) } } return value } /** * Gets the list of payloads */ @GetMapping("payloads") fun payloads() = payloads.toList() /** * Json payload */ data class JsonWebhookPayload( val uuid: UUID, val type: String, val data: JsonNode, ) /** * Test payload wrapper */ data class TestPayloadWrapper( val webhook: String, val payload: TestPayload, ) /** * Test payload */ data class TestPayload( val mode: TestPayloadMode, val content: String, val delayMs: Long? = null, ) /** * Test payload mode. How the internal endpoint must act. */ enum class TestPayloadMode { /** * Returning an OK answer, with the given content in the request. */ OK, /** * Returning a not found error */ NOT_FOUND, /** * Returning an internal error */ INTERNAL_ERROR, } /** * Not found exception */ class TestPayloadNotFoundException(message: String) : NotFoundException(message) /** * Internal exception */ class TestPayloadInternalException(message: String) : BaseException(message) }
ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/webhooks/WebhookInternalEndpointController.kt
2303031969
package net.nemerosa.ontrack.model.structure import com.fasterxml.jackson.core.JsonProcessingException import com.fasterxml.jackson.databind.node.IntNode import net.nemerosa.ontrack.json.JsonUtils import net.nemerosa.ontrack.model.structure.ID.Companion.isDefined import net.nemerosa.ontrack.model.structure.ID.Companion.of import net.nemerosa.ontrack.test.TestUtils import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue class IDTest { @Test fun none() { val id = ID.NONE assertNotNull(id) assertFalse(id.isSet) assertEquals(0, id.value.toLong()) assertEquals("0", id.toString()) } @Test fun set() { val id = of(1) assertNotNull(id) assertTrue(id.isSet) assertEquals(1, id.value.toLong()) assertEquals("1", id.toString()) } @Test(expected = IllegalArgumentException::class) fun not_zero() { of(0) } @Test(expected = IllegalArgumentException::class) fun not_negative() { of(-1) } @Test @Throws(JsonProcessingException::class) fun set_to_json() { TestUtils.assertJsonWrite( JsonUtils.number(12), of(12) ) } @Test @Throws(JsonProcessingException::class) fun read_from_json() { TestUtils.assertJsonRead( of(9), IntNode(9), ID::class.java ) } @Test @Throws(JsonProcessingException::class) fun unset_to_json() { TestUtils.assertJsonWrite( JsonUtils.number(0), ID.NONE ) } @Test fun is_defined_null() { assertFalse(isDefined(null)) } @Test fun is_defined_none() { assertFalse(isDefined(ID.NONE)) } @Test fun is_defined_set() { assertTrue(isDefined(of(1))) } }
ontrack-model/src/test/java/net/nemerosa/ontrack/model/structure/IDTest.kt
1902423081
// Copyright (c) Akop Karapetyan // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package org.akop.ararat.formatter import org.akop.ararat.core.Crossword import org.akop.ararat.core.CrosswordReader import org.akop.ararat.core.CrosswordWriter import org.akop.ararat.io.PuzFormatter import org.junit.Test import org.junit.Assert import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream class TestReaderWriter: BaseTest() { @Test fun crossword_testReadWrite() { checkReadWrite(PuzFormatter().load("puzzle.puz")) } private fun checkReadWrite(crossword: Crossword) { println("Checking write..") val content = ByteArrayOutputStream().use { stream -> CrosswordWriter(stream).use { it.write(crossword) stream.flush() } stream.toByteArray() } println("Checking read...") val cw = ByteArrayInputStream(content).use { s -> CrosswordReader(s).use { it.read() } } Assert.assertEquals("Width mismatch!", crossword.width, cw.width) Assert.assertEquals("Height mismatch!", crossword.height, cw.height) Assert.assertEquals("SquareCount mismatch!", crossword.squareCount, cw.squareCount) Assert.assertEquals("Title mismatch!", crossword.title, cw.title) Assert.assertEquals("Description mismatch!", crossword.description, cw.description) Assert.assertEquals("Author mismatch!", crossword.author, cw.author) Assert.assertEquals("Copyright mismatch!", crossword.copyright, cw.copyright) Assert.assertEquals("Comment mismatch!", crossword.comment, cw.comment) Assert.assertEquals("Date mismatch!", crossword.date, cw.date) Assert.assertEquals("Hash mismatch!", crossword.hash, cw.hash) } }
library/src/test/java/org/akop/ararat/formatter/TestReaderWriter.kt
376490050
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs import com.intellij.ide.file.BatchFileChangeListener import com.intellij.openapi.application.AccessToken import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Document import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.BaseLineStatusTrackerTestCase.Companion.parseInput import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.changes.committed.MockAbstractVcs import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl import com.intellij.openapi.vcs.impl.projectlevelman.AllVcses import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.LightPlatformTestCase import com.intellij.testFramework.RunAll import com.intellij.util.ThrowableRunnable import com.intellij.util.ui.UIUtil import com.intellij.vcsUtil.VcsUtil import java.util.concurrent.Semaphore import java.util.concurrent.TimeUnit abstract class BaseChangeListsTest : LightPlatformTestCase() { companion object { val DEFAULT = LocalChangeList.DEFAULT_NAME } protected lateinit var vcs: MyMockVcs protected lateinit var changeProvider: MyMockChangeProvider protected lateinit var clm: ChangeListManagerImpl protected lateinit var dirtyScopeManager: VcsDirtyScopeManagerImpl protected lateinit var testRoot: VirtualFile protected lateinit var vcsManager: ProjectLevelVcsManagerImpl protected var arePartialChangelistsSupported: Boolean = true override fun setUp() { super.setUp() testRoot = runWriteAction { VfsUtil.markDirtyAndRefresh(false, false, true, ourProject.baseDir) VfsUtil.createDirectoryIfMissing(ourProject.baseDir, getTestName(true)) } vcs = MyMockVcs(ourProject) changeProvider = MyMockChangeProvider() vcs.changeProvider = changeProvider clm = ChangeListManagerImpl.getInstanceImpl(ourProject) dirtyScopeManager = VcsDirtyScopeManager.getInstance(ourProject) as VcsDirtyScopeManagerImpl vcsManager = ProjectLevelVcsManager.getInstance(ourProject) as ProjectLevelVcsManagerImpl vcsManager.registerVcs(vcs) vcsManager.directoryMappings = listOf(VcsDirectoryMapping(testRoot.path, vcs.name)) vcsManager.waitForInitialized() assertTrue(vcsManager.hasActiveVcss()) try { resetTestState() } catch (e: Throwable) { super.tearDown() throw e } } override fun tearDown() { RunAll() .append(ThrowableRunnable { resetSettings() }) .append(ThrowableRunnable { resetChanges() }) .append(ThrowableRunnable { resetChangelists() }) .append(ThrowableRunnable { vcsManager.directoryMappings = emptyList() }) .append(ThrowableRunnable { AllVcses.getInstance(ourProject).unregisterManually(vcs) }) .append(ThrowableRunnable { runWriteAction { testRoot.delete(this) } }) .append(ThrowableRunnable { super.tearDown() }) .run() } protected open fun resetSettings() { arePartialChangelistsSupported = false } protected open fun resetTestState() { resetSettings() resetChanges() resetChangelists() resetTestRootContent() } private fun resetTestRootContent() { VfsUtil.markDirtyAndRefresh(false, true, true, testRoot) runWriteAction { testRoot.children.forEach { child -> child.delete(this) } } } private fun resetChanges() { changeProvider.changes.clear() changeProvider.files.clear() clm.waitUntilRefreshed() } private fun resetChangelists() { clm.addChangeList(LocalChangeList.DEFAULT_NAME, null) clm.setDefaultChangeList(LocalChangeList.DEFAULT_NAME) for (changeListName in clm.changeLists.map { it.name }) { if (changeListName != LocalChangeList.DEFAULT_NAME) clm.removeChangeList(changeListName) } clm.waitUntilRefreshed() } protected fun addLocalFile(name: String, content: String): VirtualFile { val file = runWriteAction { val file = testRoot.createChildData(this, name) VfsUtil.saveText(file, parseInput(content)) file } assertFalse(changeProvider.files.contains(file)) changeProvider.files.add(file) return file } protected fun removeLocalFile(name: String) { val file = runWriteAction { val file = VfsUtil.findRelativeFile(testRoot, name) file!!.delete(this) file } assertTrue(changeProvider.files.contains(file)) changeProvider.files.remove(file) } protected fun setBaseVersion(name: String, baseContent: String?) { setBaseVersion(name, baseContent, name) } protected fun setBaseVersion(name: String, baseContent: String?, oldName: String) { val contentRevision: ContentRevision? = when (baseContent) { null -> null else -> SimpleContentRevision(parseInput(baseContent), oldName.toFilePath, baseContent) } changeProvider.changes[name.toFilePath] = contentRevision } protected fun removeBaseVersion(name: String) { changeProvider.changes.remove(name.toFilePath) } protected fun refreshCLM() { dirtyScopeManager.markEverythingDirty() clm.scheduleUpdate() clm.waitUntilRefreshed() UIUtil.dispatchAllInvocationEvents() // ensure `fileStatusesChanged` events are fired } protected val String.toFilePath: FilePath get() = VcsUtil.getFilePath(testRoot, this) protected fun Array<out String>.toFilePaths() = this.asList().toFilePaths() protected fun List<String>.toFilePaths() = this.map { it.toFilePath } protected val VirtualFile.change: Change? get() = clm.getChange(this) protected val VirtualFile.document: Document get() = FileDocumentManager.getInstance().getDocument(this)!! protected fun VirtualFile.assertAffectedChangeLists(vararg expectedNames: String) { assertSameElements(clm.getChangeLists(this).map { it.name }, *expectedNames) } protected fun FilePath.assertAffectedChangeLists(vararg expectedNames: String) { val change = clm.getChange(this)!! assertSameElements(clm.getChangeLists(change).map { it.name }, *expectedNames) } protected fun String.asListNameToList(): LocalChangeList = clm.changeLists.find { it.name == this }!! protected fun String.asListIdToList(): LocalChangeList = clm.changeLists.find { it.id == this }!! protected fun String.asListNameToId(): String = asListNameToList().id protected fun String.asListIdToName(): String = asListIdToList().name protected fun Iterable<String>.asListNamesToIds() = this.map { it.asListNameToId() } protected fun Iterable<String>.asListIdsToNames() = this.map { it.asListIdToName() } private fun changeListsNames() = clm.changeLists.map { it.name } fun runBatchFileChangeOperation(task: () -> Unit) { BackgroundTaskUtil.syncPublisher(BatchFileChangeListener.TOPIC).batchChangeStarted(ourProject, "Update") try { task() } finally { BackgroundTaskUtil.syncPublisher(BatchFileChangeListener.TOPIC).batchChangeCompleted(ourProject) } } protected fun createChangelist(listName: String) { assertDoesntContain(changeListsNames(), listName) clm.addChangeList(listName, null) } protected fun removeChangeList(listName: String) { assertContainsElements(changeListsNames(), listName) clm.removeChangeList(listName) } protected fun setDefaultChangeList(listName: String) { assertContainsElements(changeListsNames(), listName) clm.setDefaultChangeList(listName) } protected fun VirtualFile.moveChanges(fromListName: String, toListName: String) { assertContainsElements(changeListsNames(), fromListName) assertContainsElements(changeListsNames(), toListName) val listChange = fromListName.asListNameToList().changes.find { it == this.change!! }!! clm.moveChangesTo(toListName.asListNameToList(), listChange) } protected fun VirtualFile.moveAllChangesTo(toListName: String) { assertContainsElements(changeListsNames(), toListName) clm.moveChangesTo(toListName.asListNameToList(), this.change!!) } protected inner class MyMockChangeProvider : ChangeProvider { private val semaphore = Semaphore(1) private val markerSemaphore = Semaphore(0) val changes = mutableMapOf<FilePath, ContentRevision?>() val files = mutableSetOf<VirtualFile>() override fun getChanges(dirtyScope: VcsDirtyScope, builder: ChangelistBuilder, progress: ProgressIndicator, addGate: ChangeListManagerGate) { markerSemaphore.release() semaphore.acquireOrThrow() try { for ((filePath, beforeRevision) in changes) { val file = files.find { VcsUtil.getFilePath(it) == filePath } val afterContent: ContentRevision? = when (file) { null -> null else -> CurrentContentRevision(filePath) } val change = Change(beforeRevision, afterContent) builder.processChange(change, MockAbstractVcs.getKey()) } } finally { semaphore.release() markerSemaphore.acquireOrThrow() } } override fun isModifiedDocumentTrackingRequired(): Boolean { return false } override fun doCleanup(files: List<VirtualFile>) { } fun awaitAndBlockRefresh(): AccessToken { semaphore.acquireOrThrow() dirtyScopeManager.markEverythingDirty() clm.scheduleUpdate() markerSemaphore.acquireOrThrow() markerSemaphore.release() return object : AccessToken() { override fun finish() { semaphore.release() } } } private fun Semaphore.acquireOrThrow() { val success = this.tryAcquire(10000, TimeUnit.MILLISECONDS) if (!success) throw IllegalStateException() } } protected inner class MyMockVcs(project: Project) : MockAbstractVcs(project) { override fun arePartialChangelistsSupported(): Boolean = arePartialChangelistsSupported } }
platform/vcs-tests/testSrc/com/intellij/openapi/vcs/BaseChangeListsTest.kt
4034126070
/* * Copyright (c) 2016. LaunchKey, Inc. All rights reserved. */ package com.launchkey.android.authenticator.demo.ui.fragment.security import android.os.Handler import android.os.Looper import com.launchkey.android.authenticator.sdk.core.auth_method_management.* import com.launchkey.android.authenticator.sdk.core.auth_method_management.LocationsManager.GetStoredLocationsCallback import com.launchkey.android.authenticator.sdk.core.auth_method_management.WearablesManager.GetStoredWearablesCallback import com.launchkey.android.authenticator.sdk.core.authentication_management.AuthenticatorManager import java.util.* import java.util.concurrent.ConcurrentHashMap /** * Class that allows White Label * implementers to get current * information on the security * aspect of the White Label * SDK. */ class SecurityService private constructor() { private val statusListenerIntegerMap: MutableMap<SecurityStatusListener, Int> = ConcurrentHashMap() private fun getUpdatedStatus(listener: SecurityStatusListener) { val pinEnabled = AuthenticatorManager.instance.config.isMethodAllowed(AuthMethod.PIN_CODE) && AuthMethodManagerFactory.getPINCodeManager().isPINCodeSet val circleEnabled = AuthenticatorManager.instance.config.isMethodAllowed(AuthMethod.CIRCLE_CODE) && AuthMethodManagerFactory.getCircleCodeManager().isCircleCodeSet val fingerprintEnabled = AuthenticatorManager.instance.config.isMethodAllowed(AuthMethod.BIOMETRIC) && AuthMethodManagerFactory.getBiometricManager().isBiometricSet val list: MutableList<SecurityFactor> = ArrayList() if (pinEnabled) { list.add(SecurityFactorImpl(AuthMethod.PIN_CODE, AuthMethodType.KNOWLEDGE)) } if (circleEnabled) { list.add(SecurityFactorImpl(AuthMethod.CIRCLE_CODE, AuthMethodType.KNOWLEDGE)) } if (fingerprintEnabled) { list.add(SecurityFactorImpl(AuthMethod.BIOMETRIC, AuthMethodType.INHERENCE)) } statusListenerIntegerMap[listener] = 0 if (AuthenticatorManager.instance.config.isMethodAllowed(AuthMethod.LOCATIONS)) { AuthMethodManagerFactory.getLocationsManager().getStoredLocations(object : GetStoredLocationsCallback { override fun onGetSuccess(locations: List<LocationsManager.StoredLocation>) { val locationsEnabled = !locations.isEmpty() if (locationsEnabled) { var locationsActive = false for (location in locations) { if (location.isActive) { locationsActive = true break } } list.add(SecurityFactorImpl(AuthMethod.LOCATIONS, AuthMethodType.INHERENCE, locationsActive)) } val i = statusListenerIntegerMap[listener]!! statusListenerIntegerMap[listener] = i + 1 notifyListenerIfDone(listener, list) } override fun onGetFailure(e: Exception) { val i = statusListenerIntegerMap[listener]!! statusListenerIntegerMap[listener] = i + 1 notifyListenerIfDone(listener, list) } }) } else { notifyListenerIfDone(listener, list) } if (AuthenticatorManager.instance.config.isMethodAllowed(AuthMethod.LOCATIONS)) { AuthMethodManagerFactory.getWearablesManager().getStoredWearables(object : GetStoredWearablesCallback { override fun onGetSuccess(wearablesFactor: List<WearablesManager.Wearable>) { val wearablesEnabled = !wearablesFactor.isEmpty() if (wearablesEnabled) { var wearablesActive = false for (wearableFactor in wearablesFactor) { if (wearableFactor.isActive) { wearablesActive = true break } } list.add(SecurityFactorImpl(AuthMethod.WEARABLES, AuthMethodType.POSSESSION, wearablesActive)) } val i = statusListenerIntegerMap[listener]!! statusListenerIntegerMap[listener] = i + 1 notifyListenerIfDone(listener, list) } override fun onGetFailure(exception: Exception) { val i = statusListenerIntegerMap[listener]!! statusListenerIntegerMap[listener] = i + 1 notifyListenerIfDone(listener, list) } }) } else { notifyListenerIfDone(listener, list) } } fun getStatus(listener: SecurityStatusListener?) { if (listener == null || statusListenerIntegerMap.containsKey(listener)) { return } getStatusAsyncInternal(listener) } private fun getStatusAsyncInternal(l: SecurityStatusListener) { val r = Runnable { getUpdatedStatus(l) } val t = Thread(r) t.start() } private fun notifyListenerIfDone(securityStatusListener: SecurityStatusListener, securityFactors: List<SecurityFactor>) { if (statusListenerIntegerMap[securityStatusListener] == 2) { statusListenerIntegerMap.remove(securityStatusListener) val uiHandler = Handler(Looper.getMainLooper()) uiHandler.post { securityStatusListener.onSecurityStatusUpdate(securityFactors) } } } interface SecurityStatusListener { fun onSecurityStatusUpdate(list: List<SecurityFactor>) } companion object { /** * @return the single instance. */ val instance = SecurityService() } }
demo-app/app/src/kotlinApp/java/com/launchkey/android/authenticator/demo/ui/fragment/security/SecurityService.kt
929001176
/* * Copyright 2013 Maurício Linhares * * Maurício Linhares licenses this file to you 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.mauricio.async.db.column import java.math.BigInteger object BigIntegerEncoderDecoder : ColumnEncoderDecoder { override fun decode(value: String): Any = BigInteger(value) }
db-async-common/src/main/kotlin/com/github/mauricio/async/db/column/BigIntegerEncoderDecoder.kt
1073223002
/* * Copyright (c) 2016-present. Drakeet Xu * * 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.drakeet.multitype /** * @author Drakeet Xu */ internal class ClassLinkerBridge<T> private constructor( private val javaClassLinker: JavaClassLinker<T>, private val delegates: Array<ItemViewDelegate<T, *>> ) : Linker<T> { override fun index(position: Int, item: T): Int { val indexedClass = javaClassLinker.index(position, item) val index = delegates.indexOfFirst { it.javaClass == indexedClass } if (index != -1) return index throw IndexOutOfBoundsException( "The delegates'(${delegates.contentToString()}) you registered do not contain this ${indexedClass.name}." ) } companion object { fun <T> toLinker( javaClassLinker: JavaClassLinker<T>, delegates: Array<ItemViewDelegate<T, *>> ): Linker<T> { return ClassLinkerBridge(javaClassLinker, delegates) } } }
library/src/main/kotlin/com/drakeet/multitype/ClassLinkerBridge.kt
1838759738
package org.softpark.stateful4k.config.states import org.softpark.stateful4k.config.events.EventConfiguration import org.softpark.stateful4k.config.events.EventConfigurator import org.softpark.stateful4k.config.events.IEventConfiguration import org.softpark.stateful4k.config.events.IEventConfigurator internal class StateConfigurator<C, S, E, AS : S>( private val stateType: Class<AS>, private val configuration: IStateConfiguration<C, S, E>, private val addEvent: (IEventConfiguration<C, S, E>) -> Unit) : IStateConfigurator<C, S, E, AS> { private val textId: String = "State(${configuration.stateType.javaClass.name})" override fun alias(name: String): IStateConfigurator<C, S, E, AS> { if (configuration.alias != null) throw UnsupportedOperationException("$textId.alias(...) has been already defined") configuration.alias = name return this } override fun enter(action: IStateContext<C, AS>.() -> Unit): IStateConfigurator<C, S, E, AS> { if (configuration.onEnter != null) throw UnsupportedOperationException("$textId.enter(...) has been already defined") configuration.onEnter = { c, s -> StateContext(c, stateType.cast(s)).action() } return this } override fun exit(action: IStateContext<C, AS>.() -> Unit): IStateConfigurator<C, S, E, AS> { if (configuration.onExit != null) throw UnsupportedOperationException("$textId.exit(...) has been already defined") configuration.onExit = { c, s -> StateContext(c, stateType.cast(s)).action() } return this } override fun <AE : E> event(eventType: Class<AE>): IEventConfigurator<C, S, E, AS, AE> { val eventConfig = EventConfiguration<C, S, E, AS, AE>(stateType, eventType).apply(addEvent) return EventConfigurator(stateType, eventType, eventConfig) } override fun toString(): String = "EventConfigurator($configuration)" }
src/main/java/org/softpark/stateful4k/config/states/StateConfigurator.kt
4276825112
package pl.mareklangiewicz.myintent import android.app.SearchManager import android.content.Context import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.SearchView import kotlinx.android.synthetic.main.mi_log_fragment.mi_lf_et_command import kotlinx.android.synthetic.main.mi_log_fragment.mi_lf_iv_play_stop import kotlinx.android.synthetic.main.mi_log_fragment.mi_lf_pb_countdown import kotlinx.android.synthetic.main.mi_log_fragment.mi_lf_rv_log import pl.mareklangiewicz.myactivities.MyActivity import pl.mareklangiewicz.myfragments.MyFragment import pl.mareklangiewicz.myintent.PlayStopButton.State.HIDDEN import pl.mareklangiewicz.myintent.PlayStopButton.State.PLAY import pl.mareklangiewicz.myintent.PlayStopButton.State.STOP import pl.mareklangiewicz.myutils.* import pl.mareklangiewicz.upue.* class MIStartFragment : MyFragment(), PlayStopButton.Listener, Countdown.Listener { var mSearchItem: MenuItem? = null private val adapter = MyMDAndroLogAdapter(log.history) private val tocancel = Lst<Pushee<Cancel>>() lateinit var mPSButton: PlayStopButton lateinit var mCountdown: Countdown var onResumePlayCmd = "" private val updateButtonsRunnable = Runnable { updateFAB() updatePS() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) //just for logging setHasOptionsMenu(true) return inflater.inflate(R.layout.mi_log_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) manager?.name = BuildConfig.NAME_PREFIX + getString(R.string.mi_start) mCountdown = Countdown(mi_lf_pb_countdown) mCountdown.listener = this mPSButton = PlayStopButton(mi_lf_iv_play_stop) mPSButton.listener = this mi_lf_rv_log.adapter = adapter val ctl1 = log.history.changes { adapter.notifyDataSetChanged() } tocancel.add(ctl1) adapter.notifyDataSetChanged() // to make sure we are up to date //TODO SOMEDAY: some nice simple header with fragment title manager?.lnav?.menuId = R.menu.mi_log_local updateCheckedItem() manager?.fab?.setImageResource(R.drawable.mi_ic_mic_white_24dp) manager?.fab?.setOnClickListener { if(isViewAvailable) { mCountdown.cancel() mi_lf_et_command.setText("") (activity as MyActivity).execute("start custom action listen") } } mi_lf_et_command.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable) { updatePS() } }) arguments?.getString("play")?.let { onResumePlayCmd = it } val ctl2 = manager!!.lnav!!.items { when (it) { R.id.mi_ll_i_error -> log.history.level = MyLogLevel.ERROR R.id.mi_ll_i_warning -> log.history.level = MyLogLevel.WARN R.id.mi_ll_i_info -> log.history.level = MyLogLevel.INFO R.id.mi_ll_i_debug -> log.history.level = MyLogLevel.DEBUG R.id.mi_ll_i_verbose -> log.history.level = MyLogLevel.VERBOSE R.id.mi_clear_log_history -> log.history.clr() } } tocancel.add(ctl2) } override fun onResume() { super.onResume() if(onResumePlayCmd.isNotEmpty()) play(onResumePlayCmd) onResumePlayCmd = "" lazyUpdateButtons() } override fun onStop() { mCountdown.cancel() super.onStop() } override fun onDestroyView() { view?.removeCallbacks(updateButtonsRunnable) mSearchItem = null mPSButton.listener = null mPSButton.state = HIDDEN manager?.fab?.setOnClickListener(null) manager?.fab?.hide() manager?.lnav?.menuId = -1 mCountdown.cancel() mCountdown.listener = null tocancel.forEach { it(Cancel) } tocancel.clr() mi_lf_rv_log.adapter = null super.onDestroyView() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.mi_log_options, menu) mSearchItem = menu.findItem(R.id.action_search) val sview = mSearchItem?.actionView as SearchView val manager = activity!!.getSystemService(Context.SEARCH_SERVICE) as SearchManager sview.setSearchableInfo(manager.getSearchableInfo(activity!!.componentName)) sview.setIconifiedByDefault(true) } private fun updateCheckedItem() { val id = when (log.history.level) { MyLogLevel.ERROR, MyLogLevel.ASSERT -> R.id.mi_ll_i_error MyLogLevel.WARN -> R.id.mi_ll_i_warning MyLogLevel.INFO -> R.id.mi_ll_i_info MyLogLevel.DEBUG -> R.id.mi_ll_i_debug MyLogLevel.VERBOSE -> R.id.mi_ll_i_verbose } manager?.lnav?.setCheckedItem(id, false) } override fun onDrawerSlide(drawerView: View, slideOffset: Float) { if (slideOffset == 0f) { lazyUpdateButtons() } else { manager?.fab?.hide() mPSButton.state = HIDDEN } } override fun onDrawerClosed(drawerView: View) { lazyUpdateButtons() } private val isSomethingOnOurFragment: Boolean get() = view !== null && ( manager?.lnav?.overlaps(view) ?: false || manager?.gnav?.overlaps(view) ?: false ) private fun updateFAB() { if (isSomethingOnOurFragment) manager?.fab?.hide() else manager?.fab?.show() } private fun lazyUpdateButtons() { if (!isViewAvailable) { log.d("View is not available.") return } view?.removeCallbacks(updateButtonsRunnable) view?.postDelayed(updateButtonsRunnable, 300) } private fun updatePS() { if (!isViewAvailable) { log.v("UI not ready.") return } if (isSomethingOnOurFragment) mPSButton.state = HIDDEN else mPSButton.state = if (mCountdown.isRunning) STOP else PLAY if(mCountdown.isRunning) mi_lf_et_command.isFocusable = false // it also sets isFocusableInTouchMode property to false else mi_lf_et_command.isFocusableInTouchMode = true // it also sets isFocusable property to true } /** * Starts counting to start given command. * It will start the command if user doesn't press stop fast enough. * If no command is given it will try to get command from EditText */ fun play(cmd: String = "") { if(!isViewAvailable) { onResumePlayCmd = cmd // if it is empty - nothing is scheduled. return } if(!cmd.isEmpty()) mi_lf_et_command.setText(cmd) val acmd = if(!cmd.isEmpty()) cmd else mi_lf_et_command.text.toString() if (acmd.isEmpty()) { log.e("No command provided.") lazyUpdateButtons() return } mSearchItem?.collapseActionView() mCountdown.start(acmd) } override fun onPlayStopClicked(oldState: PlayStopButton.State, newState: PlayStopButton.State) { when (oldState) { PLAY -> play() STOP -> mCountdown.cancel() HIDDEN -> log.d("Clicked on hidden button. ignoring..") } } override fun onCountdownStarted(cmd: String?) { activity?.hideKeyboard() updatePS() } override fun onCountdownFinished(cmd: String?) { if (cmd == null) { log.d("onCountdownFinished(null)") return } log.w(cmd) try { (activity as MyActivity).execute(cmd) MIContract.CmdRecent.insert(activity!!, cmd) mi_lf_et_command.setText("") } catch (e: RuntimeException) { log.e(e.message, "ML", e) } updatePS() } override fun onCountdownCancelled(cmd: String?) = updatePS() }
myintent/src/main/java/pl/mareklangiewicz/myintent/MIStartFragment.kt
2657436332
package com.soywiz.korge.ext.spriter.com.brashmonkey.spriter import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Mainline.Key import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Mainline.Key.BoneRef import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Mainline.Key.ObjectRef import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Timeline.Key.Bone import com.soywiz.korge.ext.spriter.com.brashmonkey.spriter.Timeline.Key.Object /** * Represents an animation of a Spriter SCML file. * An animation holds [Timeline]s and a [Mainline] to animate objects. * Furthermore it holds an [.id], a [.length], a [.name] and whether it is [.looping] or not. * @author Trixt0r */ @Suppress("MemberVisibilityCanBePrivate") open class Animation( val mainline: Mainline, val id: Int, val name: String, val length: Int, val looping: Boolean, timelines: Int ) { companion object { val DUMMY = Animation(Mainline.DUMMY, 0, "", 0, false, 0) } private val timelines: Array<Timeline> = Array(timelines) { Timeline.DUMMY } private var timelinePointer = 0 private val nameToTimeline: HashMap<String, Timeline> = HashMap() open var currentKey: Key = Key.DUMMY var tweenedKeys: Array<Timeline.Key> = emptyArray() var unmappedTweenedKeys: Array<Timeline.Key> = emptyArray() private var prepared: Boolean = false /** * Returns a [Timeline] with the given index. * @param index the index of the timeline * * * @return the timeline with the given index * * * @throws IndexOutOfBoundsException if the index is out of range */ fun getTimeline(index: Int): Timeline { return this.timelines[index] } /** * Returns a [Timeline] with the given name. * @param name the name of the time line * * * @return the time line with the given name or null if no time line exists with the given name. */ fun getTimeline(name: String): Timeline? { return this.nameToTimeline[name] } fun addTimeline(timeline: Timeline) { this.timelines[timelinePointer++] = timeline this.nameToTimeline[timeline.name] = timeline } /** * Returns the number of time lines this animation holds. * @return the number of time lines */ fun timelines(): Int { return timelines.size } override fun toString(): String { var toReturn = "" + this::class + "|[id: " + id + ", " + name + ", duration: " + length + ", is looping: " + looping toReturn += "Mainline:\n" toReturn += mainline toReturn += "Timelines\n" for (timeline in this.timelines) toReturn += timeline toReturn += "]" return toReturn } /** * Updates the bone and object structure with the given time to the given root bone. * @param time The time which has to be between 0 and [.length] to work properly. * * * @param root The root bone which is not allowed to be null. The whole animation runs relative to the root bone. */ open fun update(time: Int, root: Bone?) { if (!this.prepared) throw SpriterException("This animation is not ready yet to animate itself. Please call prepare()!") if (root == null) throw SpriterException("The root can not be null! Set a root bone to apply this animation relative to the root bone.") this.currentKey = mainline.getKeyBeforeTime(time) for (timelineKey in this.unmappedTweenedKeys) timelineKey.active = false for (ref in currentKey.boneRefs) this.update(ref, root, time) for (ref in currentKey.objectRefs) this.update(ref, root, time) } protected open fun update(ref: BoneRef, root: Bone, time: Int) { val isObject = ref is ObjectRef //Get the timelines, the refs pointing to val timeline = getTimeline(ref.timeline) val key = timeline.getKey(ref.key) var nextKey: Timeline.Key = timeline.getKey((ref.key + 1) % timeline.keys.size) val currentTime = key.time var nextTime = nextKey.time if (nextTime < currentTime) { if (!looping) nextKey = key else nextTime = length } //Normalize the time var t = (time - currentTime).toFloat() / (nextTime - currentTime).toFloat() if (t.isNaN() || t.isInfinite()) t = 1f if (currentKey.time > currentTime) { var tMid = (currentKey.time - currentTime).toFloat() / (nextTime - currentTime).toFloat() if (tMid.isNaN() || tMid.isInfinite()) tMid = 0f t = (time - currentKey.time).toFloat() / (nextTime - currentKey.time).toFloat() if (t.isNaN() || t.isInfinite()) t = 1f t = currentKey.curve.tween(tMid, 1f, t) } else t = currentKey.curve.tween(0f, 1f, t) //Tween bone/object val bone1 = key.`object`() val bone2 = nextKey.`object`() val tweenTarget = this.tweenedKeys[ref.timeline].`object`() if (isObject) this.tweenObject(bone1, bone2, tweenTarget, t, key.curve, key.spin) else this.tweenBone(bone1 as Bone, bone2 as Bone, tweenTarget as Bone, t, key.curve, key.spin) this.unmappedTweenedKeys[ref.timeline].active = true this.unmapTimelineObject( ref.timeline, isObject, if (ref.parent != null) this.unmappedTweenedKeys[ref.parent.timeline].`object`() else root ) } fun unmapTimelineObject(timeline: Int, isObject: Boolean, root: Bone) { val tweenTarget = this.tweenedKeys[timeline].`object`() val mapTarget = this.unmappedTweenedKeys[timeline].`object`() if (isObject) mapTarget.set(tweenTarget) else (mapTarget as Bone).set(tweenTarget as Bone) mapTarget.unmap(root) } protected fun tweenBone(bone1: Bone, bone2: Bone, target: Bone, t: Float, curve: Curve, spin: Int) { target._angle = curve.tweenAngle(bone1._angle, bone2._angle, t, spin) curve.tweenPoint(bone1.position, bone2.position, t, target.position) curve.tweenPoint(bone1.scale, bone2.scale, t, target.scale) curve.tweenPoint(bone1.pivot, bone2.pivot, t, target.pivot) } protected fun tweenObject(object1: Object, object2: Object, target: Object, t: Float, curve: Curve, spin: Int) { this.tweenBone(object1, object2, target, t, curve, spin) target.alpha = curve.tweenAngle(object1.alpha, object2.alpha, t) target.ref.set(object1.ref) } fun getSimilarTimeline(t: Timeline): Timeline? { var found: Timeline? = getTimeline(t.name) if (found == null && t.id < this.timelines()) found = this.getTimeline(t.id) return found } /*Timeline getSimilarTimeline(BoneRef ref, Collection<Timeline> coveredTimelines){ if(ref.parent == null) return null; for(BoneRef boneRef: this.currentKey.objectRefs){ Timeline t = this.getTimeline(boneRef.timeline); if(boneRef.parent != null && boneRef.parent.id == ref.parent.id && !coveredTimelines.contains(t)) return t; } return null; } Timeline getSimilarTimeline(ObjectRef ref, Collection<Timeline> coveredTimelines){ if(ref.parent == null) return null; for(ObjectRef objRef: this.currentKey.objectRefs){ Timeline t = this.getTimeline(objRef.timeline); if(objRef.parent != null && objRef.parent.id == ref.parent.id && !coveredTimelines.contains(t)) return t; } return null; }*/ /** * Prepares this animation to set this animation in any time state. * This method has to be called before [.update]. */ fun prepare() { if (this.prepared) return this.tweenedKeys = Array(timelines.size) { Timeline.Key.DUMMY } this.unmappedTweenedKeys = Array(timelines.size) { Timeline.Key.DUMMY } for (i in this.tweenedKeys.indices) { this.tweenedKeys[i] = Timeline.Key(i) this.unmappedTweenedKeys[i] = Timeline.Key(i) this.tweenedKeys[i].setObject(Object(Point(0f, 0f))) this.unmappedTweenedKeys[i].setObject(Object(Point(0f, 0f))) } if (mainline.keys.isNotEmpty()) currentKey = mainline.getKey(0) this.prepared = true } }
@old/korge-spriter/src/commonMain/kotlin/com/soywiz/korge/ext/spriter/com/brashmonkey/spriter/Animation.kt
1069449112
package yuku.alkitab.base.util import android.graphics.Color import android.graphics.drawable.GradientDrawable import android.graphics.drawable.StateListDrawable import android.widget.TextView import androidx.core.graphics.ColorUtils import yuku.alkitab.model.Label object LabelColorUtil { @JvmStatic fun encodeBackground(colorRgb_background: Int): String { val sb = StringBuilder(10) sb.append('b') // 'b': background color val h = Integer.toHexString(colorRgb_background) for (x in h.length until 6) { sb.append('0') } sb.append(h) return sb.toString() } /** * @return colorRgb (without alpha) or -1 if can't decode */ @JvmStatic fun decodeBackground(backgroundColor: String?): Int { if (backgroundColor == null || backgroundColor.isEmpty()) return -1 return if (backgroundColor.length >= 7 && backgroundColor[0] == 'b') { // 'b': background color Integer.parseInt(backgroundColor.substring(1, 7), 16) } else { -1 } } @JvmStatic fun getForegroundBasedOnBackground(colorRgb: Int): Int { val hsl = floatArrayOf(0f, 0f, 0f) ColorUtils.RGBToHSL(Color.red(colorRgb), Color.green(colorRgb), Color.blue(colorRgb), hsl) if (hsl[2] > 0.5f) { hsl[2] -= 0.44f } else { hsl[2] += 0.44f } return ColorUtils.HSLToColor(hsl) and 0xffffff } @JvmStatic fun apply(label: Label, view: TextView): Int { var bgColorRgb = decodeBackground(label.backgroundColor) if (bgColorRgb == -1) { bgColorRgb = 0x212121 // default color Grey 900 } var grad: GradientDrawable? = null val bg = view.background if (bg is GradientDrawable) { grad = bg } else if (bg is StateListDrawable) { val current = bg.current if (current is GradientDrawable) { grad = current } } if (grad != null) { grad.setColor(0xff000000.toInt() or bgColorRgb) val labelColor = 0xff000000.toInt() or getForegroundBasedOnBackground(bgColorRgb) view.setTextColor(labelColor) return labelColor } return 0 } }
Alkitab/src/main/java/yuku/alkitab/base/util/LabelColorUtil.kt
2691556204
package ui.swing.components import vision.Camera import java.awt.Dimension import java.awt.Graphics import javax.swing.JComponent class CaptureComponent : JComponent() { var image = Camera.getBufferedImage() init { preferredSize = Dimension(640, 480) } override fun paintComponent(g: Graphics?) { g?.drawImage(image, 0, 0, null) } }
src/main/kotlin/ui/swing/components/CaptureComponent.kt
2985781160
/* * 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.libanki import androidx.test.ext.junit.runners.AndroidJUnit4 import com.ichi2.anki.RobolectricTest import org.hamcrest.MatcherAssert import org.hamcrest.Matchers import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) class StorageRustTest : RobolectricTest() { @Test @Config(qualifiers = "en") fun testModelCount() { val modelNames = col.models.all().map { x -> x.getString("name") } MatcherAssert.assertThat( modelNames, Matchers.containsInAnyOrder( "Basic", "Basic (and reversed card)", "Cloze", "Basic (type in the answer)", "Basic (optional reversed card)" ) ) } }
AnkiDroid/src/test/java/com/ichi2/libanki/StorageRustTest.kt
3991089832
package de.saschahlusiak.freebloks.game import android.graphics.Color import android.os.Bundle import android.view.View import android.view.WindowInsets import androidx.cardview.widget.CardView import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import de.saschahlusiak.freebloks.R import de.saschahlusiak.freebloks.databinding.PlayerDetailFragmentBinding import de.saschahlusiak.freebloks.model.Game import de.saschahlusiak.freebloks.model.colorOf import de.saschahlusiak.freebloks.utils.viewBinding /** * The current player sheet at the bottom of the screen. * * Observes [FreebloksActivityViewModel.playerToShowInSheet]. There are several cases: * * - Not connected * "Not connected" * * - Game in not started * "No player" * * - Game is running * If the board is not rotated, the current player. * If the board is rotated, the rotated player. * If the current player is a local player, show number of turns. * If current player is remote player, show spinner. * * - Game is finished * The board is rotating. At any time the status is showing the currently shown player and their left stones. * */ class PlayerDetailFragment : Fragment(R.layout.player_detail_fragment) { private val viewModel by lazy { ViewModelProvider(requireActivity()).get(FreebloksActivityViewModel::class.java) } private val binding by viewBinding(PlayerDetailFragmentBinding::bind) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val cardView = view as CardView view.setOnApplyWindowInsetsListener { _: View, insets: WindowInsets -> cardView.setContentPadding(insets.systemWindowInsetLeft, 0, insets.systemWindowInsetRight, insets.systemWindowInsetBottom) insets } viewModel.playerToShowInSheet.observe(viewLifecycleOwner) { updateViews(it) } viewModel.inProgress.observe(viewLifecycleOwner) { inProgressChanged(it) } } private fun inProgressChanged(inProgress: Boolean) { binding.movesLeft.isVisible = !inProgress binding.progressBar.isVisible = inProgress } private fun updateViews(data: SheetPlayer) = with(binding) { val client = viewModel.client val background = root currentPlayer.clearAnimation() // the intro trumps everything if (viewModel.intro != null) { background.setCardBackgroundColor(Color.rgb(64, 64, 80)) currentPlayer.setText(R.string.touch_to_skip) points.visibility = View.GONE movesLeft.text = "" return } // if not connected, show that if (client == null || !client.isConnected()) { background.setCardBackgroundColor(Color.rgb(64, 64, 80)) currentPlayer.setText(R.string.not_connected) points.visibility = View.GONE movesLeft.text = "" return } // no current player if (data.player < 0) { background.setCardBackgroundColor(Color.rgb(64, 64, 80)) currentPlayer.setText(R.string.no_player) points.visibility = View.GONE movesLeft.text = "" return } val game: Game = client.game val board = game.board // is it "your turn", like, in general? val isYourTurn = client.game.isLocalPlayer() val playerColor = game.gameMode.colorOf(data.player) val playerName = viewModel.getPlayerName(data.player) val p = board.getPlayer(data.player) background.setCardBackgroundColor(resources.getColor(playerColor.backgroundColorId)) points.visibility = View.VISIBLE points.text = resources.getQuantityString(R.plurals.number_of_points, p.totalPoints, p.totalPoints) if (client.game.isFinished) { currentPlayer.text = "[$playerName]" movesLeft.text = resources.getQuantityString(R.plurals.number_of_stones_left, p.stonesLeft, p.stonesLeft) return } movesLeft.text = resources.getQuantityString(R.plurals.player_status_moves, p.numberOfPossibleTurns, p.numberOfPossibleTurns) // we are showing "home" if (!data.isRotated) { if (isYourTurn) { currentPlayer.text = getString(R.string.your_turn, playerName) } else { currentPlayer.text = getString(R.string.waiting_for_color, playerName) } } else { if (p.numberOfPossibleTurns <= 0) currentPlayer.text = "[${getString(R.string.color_is_out_of_moves, playerName)}]" else { currentPlayer.text = playerName } } } private fun startAnimation() { // FIXME: animation of current player /* final Animation a = new TranslateAnimation(0, 8, 0, 0); a.setInterpolator(new CycleInterpolator(2)); a.setDuration(500); Runnable r = new Runnable() { @Override public void run() { if (view == null) return; boolean local = false; View t = findViewById(R.id.currentPlayer); t.postDelayed(this, 5000); if (client != null && client.game != null) local = client.game.isLocalPlayer(); if (!local) return; t.startAnimation(a); } }; findViewById(R.id.currentPlayer).postDelayed(r, 1000); */ } }
app/src/main/java/de/saschahlusiak/freebloks/game/PlayerDetailFragment.kt
762214819
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.test.decode.internal import android.graphics.BitmapFactory import android.graphics.Rect import androidx.exifinterface.media.ExifInterface import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.panpf.sketch.cache.internal.LruBitmapPool import com.github.panpf.sketch.datasource.AssetDataSource import com.github.panpf.sketch.datasource.FileDataSource import com.github.panpf.sketch.datasource.ResourceDataSource import com.github.panpf.sketch.decode.internal.ExifOrientationHelper import com.github.panpf.sketch.decode.internal.exifOrientationName import com.github.panpf.sketch.decode.internal.readExifOrientation import com.github.panpf.sketch.decode.internal.readExifOrientationWithMimeType import com.github.panpf.sketch.fetch.newAssetUri import com.github.panpf.sketch.fetch.newResourceUri import com.github.panpf.sketch.request.LoadRequest import com.github.panpf.sketch.resize.Resize import com.github.panpf.sketch.resize.Scale.CENTER_CROP import com.github.panpf.sketch.resize.Scale.END_CROP import com.github.panpf.sketch.resize.Scale.FILL import com.github.panpf.sketch.resize.Scale.START_CROP import com.github.panpf.sketch.test.R import com.github.panpf.sketch.test.utils.ExifOrientationTestFileHelper import com.github.panpf.sketch.test.utils.cornerA import com.github.panpf.sketch.test.utils.cornerB import com.github.panpf.sketch.test.utils.cornerC import com.github.panpf.sketch.test.utils.cornerD import com.github.panpf.sketch.test.utils.corners import com.github.panpf.sketch.test.utils.getTestContext import com.github.panpf.sketch.test.utils.getTestContextAndNewSketch import com.github.panpf.sketch.util.Size import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ExifOrientationHelperTest { @Test fun testConstructor() { ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED).apply { Assert.assertEquals(ExifInterface.ORIENTATION_UNDEFINED, exifOrientation) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270).apply { Assert.assertEquals(ExifInterface.ORIENTATION_ROTATE_270, exifOrientation) } } @Test fun testReadExifOrientation() { val (context, sketch) = getTestContextAndNewSketch() Assert.assertEquals( ExifInterface.ORIENTATION_NORMAL, AssetDataSource( sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg" ).readExifOrientation() ) Assert.assertEquals( ExifInterface.ORIENTATION_UNDEFINED, AssetDataSource( sketch, LoadRequest(context, newAssetUri("sample.webp")), "sample.webp" ).readExifOrientation() ) ExifOrientationTestFileHelper(context, "exif_origin_clock_hor.jpeg").files().forEach { Assert.assertEquals( it.exifOrientation, FileDataSource( sketch, LoadRequest(context, it.file.path), it.file ).readExifOrientation() ) } Assert.assertEquals( ExifInterface.ORIENTATION_UNDEFINED, ResourceDataSource( sketch, LoadRequest(context, newResourceUri(R.xml.network_security_config)), packageName = context.packageName, context.resources, R.xml.network_security_config ).readExifOrientation() ) } @Test fun testReadExifOrientationWithMimeType() { val (context, sketch) = getTestContextAndNewSketch() Assert.assertEquals( ExifInterface.ORIENTATION_NORMAL, AssetDataSource( sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg" ).readExifOrientationWithMimeType("image/jpeg") ) Assert.assertEquals( ExifInterface.ORIENTATION_UNDEFINED, AssetDataSource( sketch, LoadRequest(context, newAssetUri("sample.jpeg")), "sample.jpeg" ).readExifOrientationWithMimeType("image/bmp") ) Assert.assertEquals( ExifInterface.ORIENTATION_UNDEFINED, AssetDataSource( sketch, LoadRequest(context, newAssetUri("sample.webp")), "sample.webp" ).readExifOrientationWithMimeType("image/webp") ) ExifOrientationTestFileHelper(context, "exif_origin_clock_hor.jpeg").files().forEach { Assert.assertEquals( it.exifOrientation, FileDataSource(sketch, LoadRequest(context, it.file.path), it.file) .readExifOrientationWithMimeType("image/jpeg") ) Assert.assertEquals( ExifInterface.ORIENTATION_UNDEFINED, FileDataSource(sketch, LoadRequest(context, it.file.path), it.file) .readExifOrientationWithMimeType("image/bmp") ) } Assert.assertEquals( ExifInterface.ORIENTATION_UNDEFINED, ResourceDataSource( sketch, LoadRequest(context, newResourceUri(R.xml.network_security_config)), packageName = context.packageName, context.resources, R.xml.network_security_config ).readExifOrientationWithMimeType("image/jpeg") ) } @Test fun testExifOrientationName() { Assert.assertEquals("ROTATE_90", exifOrientationName(ExifInterface.ORIENTATION_ROTATE_90)) Assert.assertEquals("TRANSPOSE", exifOrientationName(ExifInterface.ORIENTATION_TRANSPOSE)) Assert.assertEquals("ROTATE_180", exifOrientationName(ExifInterface.ORIENTATION_ROTATE_180)) Assert.assertEquals( "FLIP_VERTICAL", exifOrientationName(ExifInterface.ORIENTATION_FLIP_VERTICAL) ) Assert.assertEquals("ROTATE_270", exifOrientationName(ExifInterface.ORIENTATION_ROTATE_270)) Assert.assertEquals("TRANSVERSE", exifOrientationName(ExifInterface.ORIENTATION_TRANSVERSE)) Assert.assertEquals( "FLIP_HORIZONTAL", exifOrientationName(ExifInterface.ORIENTATION_FLIP_HORIZONTAL) ) Assert.assertEquals("UNDEFINED", exifOrientationName(ExifInterface.ORIENTATION_UNDEFINED)) Assert.assertEquals("NORMAL", exifOrientationName(ExifInterface.ORIENTATION_NORMAL)) Assert.assertEquals("-1", exifOrientationName(-1)) Assert.assertEquals("100", exifOrientationName(100)) } @Test fun testIsFlipped() { Assert.assertFalse(ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90).isFlipped) Assert.assertTrue(ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE).isFlipped) Assert.assertFalse(ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180).isFlipped) Assert.assertTrue(ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL).isFlipped) Assert.assertFalse(ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270).isFlipped) Assert.assertTrue(ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE).isFlipped) Assert.assertTrue(ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL).isFlipped) Assert.assertFalse(ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED).isFlipped) Assert.assertFalse(ExifOrientationHelper(ExifInterface.ORIENTATION_NORMAL).isFlipped) Assert.assertFalse(ExifOrientationHelper(-1).isFlipped) Assert.assertFalse(ExifOrientationHelper(100).isFlipped) } @Test fun testRotationDegrees() { Assert.assertEquals( 90, ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90).rotationDegrees ) Assert.assertEquals( 270, ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE).rotationDegrees ) Assert.assertEquals( 180, ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180).rotationDegrees ) Assert.assertEquals( 180, ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL).rotationDegrees ) Assert.assertEquals( 270, ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270).rotationDegrees ) Assert.assertEquals( 90, ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE).rotationDegrees ) Assert.assertEquals( 0, ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL).rotationDegrees ) Assert.assertEquals( 0, ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED).rotationDegrees ) Assert.assertEquals( 0, ExifOrientationHelper(ExifInterface.ORIENTATION_NORMAL).rotationDegrees ) Assert.assertEquals(0, ExifOrientationHelper(-1).rotationDegrees) Assert.assertEquals(0, ExifOrientationHelper(100).rotationDegrees) } @Test fun testApplyToBitmap() { val context = getTestContext() val bitmapPool = LruBitmapPool(44124124) val inBitmap = context.assets.open("sample.jpeg").use { BitmapFactory.decodeStream(it) } Assert.assertTrue( inBitmap.cornerA != inBitmap.cornerB && inBitmap.cornerA != inBitmap.cornerC && inBitmap.cornerA != inBitmap.cornerD ) ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90) .applyToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerD, cornerA, cornerB, cornerC) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE) .applyToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> // Flip horizontally and apply ORIENTATION_ROTATE_90 Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerC, cornerB, cornerA, cornerD) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180) .applyToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerC, cornerD, cornerA, cornerB) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL) .applyToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> // Flip horizontally and apply ORIENTATION_ROTATE_180 Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerD, cornerC, cornerB, cornerA) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270) .applyToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerB, cornerC, cornerD, cornerA) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE) .applyToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> // Flip horizontally and apply ORIENTATION_ROTATE_270 Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerD, cornerC, cornerB) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL) .applyToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerB, cornerA, cornerD, cornerC) }.toString(), ) } Assert.assertNull( ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED).applyToBitmap( inBitmap, bitmapPool, false ) ) Assert.assertNull( ExifOrientationHelper(ExifInterface.ORIENTATION_NORMAL).applyToBitmap( inBitmap, bitmapPool, false ) ) Assert.assertNull( ExifOrientationHelper(-1).applyToBitmap(inBitmap, bitmapPool, false) ) Assert.assertNull( ExifOrientationHelper(100).applyToBitmap(inBitmap, bitmapPool, false) ) } @Test fun testAddToBitmap() { val context = getTestContext() val bitmapPool = LruBitmapPool(44124124) val inBitmap = context.assets.open("sample.jpeg").use { BitmapFactory.decodeStream(it) } Assert.assertTrue( inBitmap.cornerA != inBitmap.cornerB && inBitmap.cornerA != inBitmap.cornerC && inBitmap.cornerA != inBitmap.cornerD ) ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90) .addToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerB, cornerC, cornerD, cornerA) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE) .addToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> // Flip horizontally based on ORIENTATION_ROTATE_90 Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerC, cornerB, cornerA, cornerD) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180) .addToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerC, cornerD, cornerA, cornerB) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL) .addToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> // Flip horizontally based on ORIENTATION_ROTATE_180 Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerD, cornerC, cornerB, cornerA) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270) .addToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerD, cornerA, cornerB, cornerC) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE) .addToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> // Flip horizontally based on ORIENTATION_ROTATE_270 Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerD, cornerC, cornerB) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL) .addToBitmap(inBitmap, bitmapPool, false)!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerB, cornerA, cornerD, cornerC) }.toString(), ) } Assert.assertNull( ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED) .addToBitmap(inBitmap, bitmapPool, false) ) Assert.assertNull( ExifOrientationHelper(ExifInterface.ORIENTATION_NORMAL) .addToBitmap(inBitmap, bitmapPool, false) ) Assert.assertNull( ExifOrientationHelper(-1).addToBitmap(inBitmap, bitmapPool, false) ) Assert.assertNull( ExifOrientationHelper(100).addToBitmap(inBitmap, bitmapPool, false) ) } @Test fun testAddAndApplyToBitmap() { val context = getTestContext() val bitmapPool = LruBitmapPool(44124124) val inBitmap = context.assets.open("sample.jpeg").use { BitmapFactory.decodeStream(it) } Assert.assertTrue( inBitmap.cornerA != inBitmap.cornerB && inBitmap.cornerA != inBitmap.cornerC && inBitmap.cornerA != inBitmap.cornerD ) ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90).applyToBitmap( ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90) .addToBitmap(inBitmap, bitmapPool, false)!!, bitmapPool, false )!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE).applyToBitmap( ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE) .addToBitmap(inBitmap, bitmapPool, false)!!, bitmapPool, false )!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180).applyToBitmap( ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180) .addToBitmap(inBitmap, bitmapPool, false)!!, bitmapPool, false )!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL).applyToBitmap( ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL) .addToBitmap(inBitmap, bitmapPool, false)!!, bitmapPool, false )!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270).applyToBitmap( ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270) .addToBitmap(inBitmap, bitmapPool, false)!!, bitmapPool, false )!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE).applyToBitmap( ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE) .addToBitmap(inBitmap, bitmapPool, false)!!, bitmapPool, false )!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), ) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL).applyToBitmap( ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL) .addToBitmap(inBitmap, bitmapPool, false)!!, bitmapPool, false )!!.let { outBitmap -> Assert.assertEquals( inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), outBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), inBitmap.corners { listOf(cornerA, cornerB, cornerC, cornerD) }.toString(), ) } } @Test fun testApplyToSize() { Assert.assertEquals( Size(50, 100), ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(50, 100), ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(100, 50), ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(100, 50), ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(50, 100), ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(50, 100), ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(100, 50), ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(100, 50), ExifOrientationHelper(ExifInterface.ORIENTATION_NORMAL) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(100, 50), ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL) .applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(100, 50), ExifOrientationHelper(-1).applyToSize(Size(100, 50)) ) Assert.assertEquals( Size(100, 50), ExifOrientationHelper(100).applyToSize(Size(100, 50)) ) } @Test fun testAddToSize() { ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90).apply { Assert.assertEquals(Size(50, 100), addToSize(Size(100, 50))) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE).apply { Assert.assertEquals(Size(50, 100), addToSize(Size(100, 50))) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180).apply { Assert.assertEquals(Size(100, 50), addToSize(Size(100, 50))) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL).apply { Assert.assertEquals(Size(100, 50), addToSize(Size(100, 50))) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270).apply { Assert.assertEquals(Size(50, 100), addToSize(Size(100, 50))) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE).apply { Assert.assertEquals(Size(50, 100), addToSize(Size(100, 50))) } ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED).apply { Assert.assertEquals(Size(100, 50), addToSize(Size(100, 50))) } ExifOrientationHelper(ExifInterface.ORIENTATION_NORMAL).apply { Assert.assertEquals(Size(100, 50), addToSize(Size(100, 50))) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL).apply { Assert.assertEquals(Size(100, 50), addToSize(Size(100, 50))) } ExifOrientationHelper(-1).apply { Assert.assertEquals(Size(100, 50), addToSize(Size(100, 50))) } ExifOrientationHelper(100).apply { Assert.assertEquals(Size(100, 50), addToSize(Size(100, 50))) } } @Test fun testAddToResize() { ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90).apply { Assert.assertEquals(Resize(5, 10), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(5, 10, END_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, START_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE).apply { Assert.assertEquals(Resize(5, 10), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(5, 10, END_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, START_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, END_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, START_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180).apply { Assert.assertEquals(Resize(10, 5), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL).apply { Assert.assertEquals(Resize(10, 5), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270).apply { Assert.assertEquals(Resize(5, 10), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(5, 10, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, END_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, START_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE).apply { Assert.assertEquals(Resize(5, 10), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(5, 10, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(5, 10, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(5, 10, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED).apply { Assert.assertEquals(Resize(10, 5), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(ExifInterface.ORIENTATION_NORMAL).apply { Assert.assertEquals(Resize(10, 5), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL).apply { Assert.assertEquals(Resize(10, 5), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(-1).apply { Assert.assertEquals(Resize(10, 5), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } ExifOrientationHelper(10).apply { Assert.assertEquals(Resize(10, 5), addToResize(Resize(10, 5), Size(100, 50))) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(100, 50)) ) Assert.assertEquals( Resize(10, 5, START_CROP), addToResize(Resize(10, 5, START_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, CENTER_CROP), addToResize(Resize(10, 5, CENTER_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, END_CROP), addToResize(Resize(10, 5, END_CROP), Size(50, 100)) ) Assert.assertEquals( Resize(10, 5, FILL), addToResize(Resize(10, 5, FILL), Size(50, 100)) ) } } @Test fun testAddToRect() { Assert.assertEquals( Rect(10, 50, 30, 60), ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_90) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(20, 50, 40, 60), ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSVERSE) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(50, 20, 60, 40), ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_180) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(40, 20, 50, 40), ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_VERTICAL) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(20, 40, 40, 50), ExifOrientationHelper(ExifInterface.ORIENTATION_ROTATE_270) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(10, 40, 30, 50), ExifOrientationHelper(ExifInterface.ORIENTATION_TRANSPOSE) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(50, 10, 60, 30), ExifOrientationHelper(ExifInterface.ORIENTATION_FLIP_HORIZONTAL) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(40, 10, 50, 30), ExifOrientationHelper(ExifInterface.ORIENTATION_UNDEFINED) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(40, 10, 50, 30), ExifOrientationHelper(ExifInterface.ORIENTATION_NORMAL) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(40, 10, 50, 30), ExifOrientationHelper(-1) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) Assert.assertEquals( Rect(40, 10, 50, 30), ExifOrientationHelper(100) .addToRect(Rect(40, 10, 50, 30), Size(100, 50)) ) } }
sketch/src/androidTest/java/com/github/panpf/sketch/test/decode/internal/ExifOrientationHelperTest.kt
2755293100
package world.player.skill.crafting.hideTanning /** * An enum representing all tannable hides. */ enum class Hide(val hide: Int, val tan: Int, val cost: Int, val displayName: String) { SOFT_LEATHER(hide = 1739, tan = 1741, cost = 2, displayName = "Soft leather"), HARD_LEATHER(hide = 1739, tan = 1743, cost = 3, displayName = "Hard leather"), SWAMP_SNAKESKIN(hide = 7801, tan = 6289, cost = 20, displayName = "Snakeskin"), SNAKESKIN(hide = 6287, tan = 6289, cost = 15, displayName = "Snakeskin"), GREEN_D_LEATHER(hide = 1753, tan = 1745, cost = 20, displayName = "Green d'hide"), BLUE_D_LEATHER(hide = 1751, tan = 2505, cost = 20, displayName = "Blue d'hide"), RED_D_LEATHER(hide = 1749, tan = 2507, cost = 20, displayName = "Red d'hide"), BLACK_D_LEATHER(hide = 1747, tan = 2509, cost = 20, displayName = "Black d'hide"); companion object { /** * Mappings of [Hide.tan] to [Hide]. */ val TAN_TO_HIDE = values().associateBy { it.tan } } }
plugins/world/player/skill/crafting/hideTanning/Hide.kt
2028464949
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.test.request import android.R.color import android.R.drawable import android.graphics.Bitmap.Config.ARGB_8888 import android.graphics.Bitmap.Config.RGB_565 import android.graphics.Color import android.graphics.ColorSpace import android.graphics.ColorSpace.Named.ACES import android.graphics.ColorSpace.Named.ADOBE_RGB import android.graphics.ColorSpace.Named.BT709 import android.graphics.drawable.ColorDrawable import android.os.Build.VERSION import android.os.Build.VERSION_CODES import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.panpf.sketch.ComponentRegistry import com.github.panpf.sketch.cache.CachePolicy.DISABLED import com.github.panpf.sketch.cache.CachePolicy.ENABLED import com.github.panpf.sketch.cache.CachePolicy.READ_ONLY import com.github.panpf.sketch.cache.CachePolicy.WRITE_ONLY import com.github.panpf.sketch.decode.BitmapConfig import com.github.panpf.sketch.decode.internal.DefaultBitmapDecoder import com.github.panpf.sketch.decode.internal.DefaultDrawableDecoder import com.github.panpf.sketch.fetch.HttpUriFetcher import com.github.panpf.sketch.fetch.newAssetUri import com.github.panpf.sketch.http.HttpHeaders import com.github.panpf.sketch.request.Depth.LOCAL import com.github.panpf.sketch.request.Depth.NETWORK import com.github.panpf.sketch.request.GlobalLifecycle import com.github.panpf.sketch.request.ImageOptions import com.github.panpf.sketch.request.ImageRequest import com.github.panpf.sketch.request.LoadRequest import com.github.panpf.sketch.request.LoadResult import com.github.panpf.sketch.request.Parameters import com.github.panpf.sketch.request.get import com.github.panpf.sketch.request.internal.CombinedListener import com.github.panpf.sketch.request.internal.CombinedProgressListener import com.github.panpf.sketch.resize.FixedPrecisionDecider import com.github.panpf.sketch.resize.FixedScaleDecider import com.github.panpf.sketch.resize.FixedSizeResolver import com.github.panpf.sketch.resize.LongImageClipPrecisionDecider import com.github.panpf.sketch.resize.LongImageScaleDecider import com.github.panpf.sketch.resize.Precision.EXACTLY import com.github.panpf.sketch.resize.Precision.LESS_PIXELS import com.github.panpf.sketch.resize.Precision.SAME_ASPECT_RATIO import com.github.panpf.sketch.resize.Scale.CENTER_CROP import com.github.panpf.sketch.resize.Scale.END_CROP import com.github.panpf.sketch.resize.Scale.FILL import com.github.panpf.sketch.resize.Scale.START_CROP import com.github.panpf.sketch.resize.internal.DisplaySizeResolver import com.github.panpf.sketch.stateimage.ColorStateImage import com.github.panpf.sketch.stateimage.CurrentStateImage import com.github.panpf.sketch.stateimage.DrawableStateImage import com.github.panpf.sketch.stateimage.ErrorStateImage import com.github.panpf.sketch.stateimage.IconStateImage import com.github.panpf.sketch.stateimage.ThumbnailMemoryCacheStateImage import com.github.panpf.sketch.stateimage.IntColor import com.github.panpf.sketch.stateimage.MemoryCacheStateImage import com.github.panpf.sketch.stateimage.ResColor import com.github.panpf.sketch.target.LoadTarget import com.github.panpf.sketch.test.utils.TestActivity import com.github.panpf.sketch.test.utils.TestAssets import com.github.panpf.sketch.test.utils.TestBitmapDecodeInterceptor import com.github.panpf.sketch.test.utils.TestBitmapDecoder import com.github.panpf.sketch.test.utils.TestDrawableDecodeInterceptor import com.github.panpf.sketch.test.utils.TestDrawableDecoder import com.github.panpf.sketch.test.utils.TestFetcher import com.github.panpf.sketch.test.utils.TestRequestInterceptor import com.github.panpf.sketch.test.utils.getTestContext import com.github.panpf.sketch.test.utils.getTestContextAndNewSketch import com.github.panpf.sketch.transform.BlurTransformation import com.github.panpf.sketch.transform.CircleCropTransformation import com.github.panpf.sketch.transform.RotateTransformation import com.github.panpf.sketch.transform.RoundedCornersTransformation import com.github.panpf.sketch.transition.CrossfadeTransition import com.github.panpf.sketch.util.Size import com.github.panpf.tools4a.test.ktx.getActivitySync import com.github.panpf.tools4a.test.ktx.launchActivity import kotlinx.coroutines.runBlocking import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class LoadRequestTest { @Test fun testFun() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest(context1, uriString1).apply { Assert.assertSame(context1, this.context) Assert.assertEquals("asset://sample.jpeg", uriString) Assert.assertNull(this.listener) Assert.assertNull(this.progressListener) Assert.assertNull(this.target) Assert.assertSame(GlobalLifecycle, this.lifecycle) Assert.assertEquals(NETWORK, this.depth) Assert.assertNull(this.parameters) Assert.assertNull(this.httpHeaders) Assert.assertEquals(ENABLED, this.downloadCachePolicy) Assert.assertNull(this.bitmapConfig) if (VERSION.SDK_INT >= VERSION_CODES.O) { Assert.assertNull(this.colorSpace) } @Suppress("DEPRECATION") Assert.assertFalse(this.preferQualityOverSpeed) Assert.assertEquals(DisplaySizeResolver(context1), this.resizeSizeResolver) Assert.assertEquals(FixedPrecisionDecider(LESS_PIXELS), this.resizePrecisionDecider) Assert.assertEquals(FixedScaleDecider(CENTER_CROP), this.resizeScaleDecider) Assert.assertNull(this.transformations) Assert.assertFalse(this.disallowReuseBitmap) Assert.assertFalse(this.ignoreExifOrientation) Assert.assertEquals(ENABLED, this.resultCachePolicy) Assert.assertNull(this.placeholder) Assert.assertNull(this.error) Assert.assertNull(this.transitionFactory) Assert.assertFalse(this.disallowAnimatedImage) Assert.assertFalse(this.resizeApplyToDrawable) Assert.assertEquals(ENABLED, this.memoryCachePolicy) } } @Suppress("UNUSED_ANONYMOUS_PARAMETER") @Test fun testNewBuilder() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest(context1, uriString1).newBuilder().build().apply { Assert.assertEquals(NETWORK, depth) } LoadRequest(context1, uriString1).newBuilder { depth(LOCAL) }.build().apply { Assert.assertEquals(LOCAL, depth) } (LoadRequest(context1, uriString1) as ImageRequest).newBuilder { depth(LOCAL) }.build().apply { Assert.assertEquals(LOCAL, depth) } LoadRequest(context1, uriString1).newRequest().apply { Assert.assertEquals(NETWORK, depth) } LoadRequest(context1, uriString1).newRequest { depth(LOCAL) }.apply { Assert.assertEquals(LOCAL, depth) } (LoadRequest(context1, uriString1) as ImageRequest).newRequest { depth(LOCAL) }.apply { Assert.assertEquals(LOCAL, depth) } LoadRequest(context1, uriString1).newLoadBuilder().build().apply { Assert.assertEquals(NETWORK, depth) Assert.assertNull(listener) Assert.assertNull(progressListener) } LoadRequest(context1, uriString1).newLoadBuilder { depth(LOCAL) listener( onStart = { request: LoadRequest -> }, onCancel = { request: LoadRequest -> }, onError = { request: LoadRequest, result: LoadResult.Error -> }, onSuccess = { request: LoadRequest, result: LoadResult.Success -> }, ) progressListener { request: LoadRequest, totalLength: Long, completedLength: Long -> } }.build().apply { Assert.assertEquals(LOCAL, depth) Assert.assertNotNull(listener) Assert.assertNotNull(progressListener) } LoadRequest(context1, uriString1).newLoadRequest().apply { Assert.assertEquals(NETWORK, depth) Assert.assertNull(listener) Assert.assertNull(progressListener) } LoadRequest(context1, uriString1).newLoadRequest { depth(LOCAL) listener( onStart = { request: LoadRequest -> }, onCancel = { request: LoadRequest -> }, onError = { request: LoadRequest, result: LoadResult.Error -> }, onSuccess = { request: LoadRequest, result: LoadResult.Success -> }, ) progressListener { request: LoadRequest, totalLength: Long, completedLength: Long -> } }.apply { Assert.assertEquals(LOCAL, depth) Assert.assertNotNull(listener) Assert.assertNotNull(progressListener) } } @Test fun testContext() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest(context1, uriString1).apply { Assert.assertEquals(context1, context) Assert.assertNotEquals(context1, context.applicationContext) } } @Test fun testTarget() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest(context1, uriString1).apply { Assert.assertNull(target) } LoadRequest(context1, uriString1) { target(object : LoadTarget { }) }.apply { Assert.assertNotNull(target) } LoadRequest(context1, uriString1) { target(null) }.apply { Assert.assertNull(target) } LoadRequest(context1, uriString1) { target(onStart = {}, onSuccess = {}, onError = {}) }.apply { Assert.assertNotNull(target) } LoadRequest(context1, uriString1) { target(onStart = {}) }.apply { Assert.assertNotNull(target) } LoadRequest(context1, uriString1) { target(onSuccess = {}) }.apply { Assert.assertNotNull(target) } LoadRequest(context1, uriString1) { target(onError = {}) }.apply { Assert.assertNotNull(target) } } @Test fun testLifecycle() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") var lifecycle1: Lifecycle? = null val lifecycleOwner = LifecycleOwner { lifecycle1!! } lifecycle1 = LifecycleRegistry(lifecycleOwner) LoadRequest(context1, uriString1).apply { Assert.assertEquals(GlobalLifecycle, this.lifecycle) } LoadRequest(context1, uriString1) { lifecycle(lifecycle1) }.apply { Assert.assertEquals(lifecycle1, this.lifecycle) } val activity = TestActivity::class.launchActivity().getActivitySync() LoadRequest(activity, uriString1).apply { Assert.assertEquals(activity.lifecycle, this.lifecycle) } } @Test fun testDefinedOptions() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest(context1, uriString1).apply { Assert.assertEquals(ImageOptions(), definedOptions) } LoadRequest(context1, uriString1) { resizeSize(100, 50) addTransformations(CircleCropTransformation()) crossfade() }.apply { Assert.assertEquals(ImageOptions { resizeSize(100, 50) addTransformations(CircleCropTransformation()) crossfade() }, definedOptions) } } @Test fun testDefault() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest(context1, uriString1).apply { Assert.assertNull(defaultOptions) } val options = ImageOptions { resizeSize(100, 50) addTransformations(CircleCropTransformation()) crossfade() } LoadRequest(context1, uriString1) { default(options) }.apply { Assert.assertSame(options, defaultOptions) } } @Test fun testMerge() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertEquals(NETWORK, depth) Assert.assertNull(parameters) } merge(ImageOptions { resizeSize(100, 50) memoryCachePolicy(DISABLED) addTransformations(CircleCropTransformation()) crossfade() }) build().apply { Assert.assertEquals(FixedSizeResolver(100, 50), resizeSizeResolver) Assert.assertEquals(DISABLED, memoryCachePolicy) Assert.assertEquals(listOf(CircleCropTransformation()), transformations) Assert.assertEquals(CrossfadeTransition.Factory(), transitionFactory) } merge(ImageOptions { memoryCachePolicy(READ_ONLY) }) build().apply { Assert.assertEquals(FixedSizeResolver(100, 50), resizeSizeResolver) Assert.assertEquals(DISABLED, memoryCachePolicy) Assert.assertEquals(listOf(CircleCropTransformation()), transformations) Assert.assertEquals(CrossfadeTransition.Factory(), transitionFactory) } } } @Test fun testDepth() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest(context1, uriString1).apply { Assert.assertEquals(NETWORK, depth) Assert.assertNull(depthFrom) } LoadRequest(context1, uriString1) { depth(LOCAL) }.apply { Assert.assertEquals(LOCAL, depth) Assert.assertNull(depthFrom) } LoadRequest(context1, uriString1) { depth(null) }.apply { Assert.assertEquals(NETWORK, depth) Assert.assertNull(depthFrom) } LoadRequest(context1, uriString1) { depth(LOCAL, null) }.apply { Assert.assertEquals(LOCAL, depth) Assert.assertNull(depthFrom) } LoadRequest(context1, uriString1) { depth(null, "TestDepthFrom") }.apply { Assert.assertEquals(NETWORK, depth) Assert.assertNull(depthFrom) } LoadRequest(context1, uriString1) { depth(LOCAL, "TestDepthFrom") }.apply { Assert.assertEquals(LOCAL, depth) Assert.assertEquals("TestDepthFrom", depthFrom) } } @Test fun testParameters() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertNull(parameters) } /* parameters() */ parameters(Parameters()) build().apply { Assert.assertNull(parameters) } parameters(Parameters.Builder().set("key1", "value1").build()) build().apply { Assert.assertEquals(1, parameters?.size) Assert.assertEquals("value1", parameters?.get("key1")) } parameters(null) build().apply { Assert.assertNull(parameters) } /* setParameter(), removeParameter() */ setParameter("key1", "value1") setParameter("key2", "value2", "value2") build().apply { Assert.assertEquals(2, parameters?.size) Assert.assertEquals("value1", parameters?.get("key1")) Assert.assertEquals("value2", parameters?.get("key2")) } setParameter("key2", "value2.1", null) build().apply { Assert.assertEquals(2, parameters?.size) Assert.assertEquals("value1", parameters?.get("key1")) Assert.assertEquals("value2.1", parameters?.get("key2")) } removeParameter("key2") build().apply { Assert.assertEquals(1, parameters?.size) Assert.assertEquals("value1", parameters?.get("key1")) } removeParameter("key1") build().apply { Assert.assertNull(parameters) } } } @Test fun testHttpHeaders() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertNull(httpHeaders) } /* httpHeaders() */ httpHeaders(HttpHeaders()) build().apply { Assert.assertNull(httpHeaders) } httpHeaders(HttpHeaders.Builder().set("key1", "value1").build()) build().apply { Assert.assertEquals(1, httpHeaders?.size) Assert.assertEquals("value1", httpHeaders?.getSet("key1")) } httpHeaders(null) build().apply { Assert.assertNull(httpHeaders) } /* setHttpHeader(), addHttpHeader(), removeHttpHeader() */ setHttpHeader("key1", "value1") setHttpHeader("key2", "value2") addHttpHeader("key3", "value3") addHttpHeader("key3", "value3.1") build().apply { Assert.assertEquals(4, httpHeaders?.size) Assert.assertEquals(2, httpHeaders?.setSize) Assert.assertEquals(2, httpHeaders?.addSize) Assert.assertEquals("value1", httpHeaders?.getSet("key1")) Assert.assertEquals("value2", httpHeaders?.getSet("key2")) Assert.assertEquals(listOf("value3", "value3.1"), httpHeaders?.getAdd("key3")) } setHttpHeader("key2", "value2.1") build().apply { Assert.assertEquals(4, httpHeaders?.size) Assert.assertEquals(2, httpHeaders?.setSize) Assert.assertEquals(2, httpHeaders?.addSize) Assert.assertEquals("value1", httpHeaders?.getSet("key1")) Assert.assertEquals("value2.1", httpHeaders?.getSet("key2")) Assert.assertEquals(listOf("value3", "value3.1"), httpHeaders?.getAdd("key3")) } removeHttpHeader("key3") build().apply { Assert.assertEquals(2, httpHeaders?.size) Assert.assertEquals("value1", httpHeaders?.getSet("key1")) Assert.assertEquals("value2.1", httpHeaders?.getSet("key2")) } removeHttpHeader("key2") build().apply { Assert.assertEquals(1, httpHeaders?.size) Assert.assertEquals("value1", httpHeaders?.getSet("key1")) } removeHttpHeader("key1") build().apply { Assert.assertNull(httpHeaders) } } } @Test fun testLoadDiskCachePolicy() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertEquals(ENABLED, downloadCachePolicy) } downloadCachePolicy(READ_ONLY) build().apply { Assert.assertEquals(READ_ONLY, downloadCachePolicy) } downloadCachePolicy(DISABLED) build().apply { Assert.assertEquals(DISABLED, downloadCachePolicy) } downloadCachePolicy(null) build().apply { Assert.assertEquals(ENABLED, downloadCachePolicy) } } } @Test fun testBitmapConfig() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertNull(bitmapConfig) } bitmapConfig(BitmapConfig(RGB_565)) build().apply { Assert.assertEquals(BitmapConfig(RGB_565), bitmapConfig) } bitmapConfig(ARGB_8888) build().apply { Assert.assertEquals(BitmapConfig(ARGB_8888), bitmapConfig) } bitmapConfig(BitmapConfig.LowQuality) build().apply { Assert.assertEquals(BitmapConfig.LowQuality, bitmapConfig) } bitmapConfig(BitmapConfig.HighQuality) build().apply { Assert.assertEquals(BitmapConfig.HighQuality, bitmapConfig) } bitmapConfig(null) build().apply { Assert.assertNull(bitmapConfig) } } } @Test fun testColorSpace() { if (VERSION.SDK_INT < VERSION_CODES.O) return val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertNull(colorSpace) } colorSpace(ColorSpace.get(ACES)) build().apply { Assert.assertEquals(ColorSpace.get(ACES), colorSpace) } colorSpace(ColorSpace.get(BT709)) build().apply { Assert.assertEquals(ColorSpace.get(BT709), colorSpace) } colorSpace(null) build().apply { Assert.assertNull(colorSpace) } } } @Test @Suppress("DEPRECATION") fun testPreferQualityOverSpeed() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertFalse(preferQualityOverSpeed) } preferQualityOverSpeed() build().apply { Assert.assertEquals(true, preferQualityOverSpeed) } preferQualityOverSpeed(false) build().apply { Assert.assertEquals(false, preferQualityOverSpeed) } preferQualityOverSpeed(null) build().apply { Assert.assertFalse(preferQualityOverSpeed) } } } @Test fun testResize() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertNull(definedOptions.resizeSizeResolver) Assert.assertNull(definedOptions.resizePrecisionDecider) Assert.assertNull(definedOptions.resizeScaleDecider) Assert.assertEquals(DisplaySizeResolver(context1), resizeSizeResolver) Assert.assertEquals(FixedPrecisionDecider(LESS_PIXELS), resizePrecisionDecider) Assert.assertEquals(FixedScaleDecider(CENTER_CROP), resizeScaleDecider) } resize(100, 100, SAME_ASPECT_RATIO, START_CROP) build().apply { Assert.assertEquals(FixedSizeResolver(100, 100), definedOptions.resizeSizeResolver) Assert.assertEquals( FixedPrecisionDecider(SAME_ASPECT_RATIO), definedOptions.resizePrecisionDecider ) Assert.assertEquals( FixedScaleDecider(START_CROP), definedOptions.resizeScaleDecider ) Assert.assertEquals(FixedSizeResolver(100, 100), resizeSizeResolver) Assert.assertEquals( FixedPrecisionDecider(SAME_ASPECT_RATIO), resizePrecisionDecider ) Assert.assertEquals(FixedScaleDecider(START_CROP), resizeScaleDecider) } resize(100, 100) build().apply { Assert.assertEquals(FixedSizeResolver(100, 100), definedOptions.resizeSizeResolver) Assert.assertNull(definedOptions.resizePrecisionDecider) Assert.assertNull(definedOptions.resizeScaleDecider) Assert.assertEquals(FixedSizeResolver(100, 100), resizeSizeResolver) Assert.assertEquals(FixedPrecisionDecider(LESS_PIXELS), resizePrecisionDecider) Assert.assertEquals(FixedScaleDecider(CENTER_CROP), resizeScaleDecider) } resize(100, 100, SAME_ASPECT_RATIO, START_CROP) resize(100, 100, EXACTLY) build().apply { Assert.assertEquals(FixedSizeResolver(100, 100), definedOptions.resizeSizeResolver) Assert.assertEquals( FixedPrecisionDecider(EXACTLY), definedOptions.resizePrecisionDecider ) Assert.assertNull(definedOptions.resizeScaleDecider) Assert.assertEquals(FixedSizeResolver(100, 100), resizeSizeResolver) Assert.assertEquals(FixedPrecisionDecider(EXACTLY), resizePrecisionDecider) Assert.assertEquals(FixedScaleDecider(CENTER_CROP), resizeScaleDecider) } resize(100, 100, SAME_ASPECT_RATIO, START_CROP) resize(100, 100, scale = END_CROP) build().apply { Assert.assertEquals(FixedSizeResolver(100, 100), definedOptions.resizeSizeResolver) Assert.assertNull(definedOptions.resizePrecisionDecider) Assert.assertEquals(FixedScaleDecider(END_CROP), definedOptions.resizeScaleDecider) Assert.assertEquals(FixedSizeResolver(100, 100), resizeSizeResolver) Assert.assertEquals(FixedPrecisionDecider(LESS_PIXELS), resizePrecisionDecider) Assert.assertEquals(FixedScaleDecider(END_CROP), resizeScaleDecider) } resize(100, 100, SAME_ASPECT_RATIO, START_CROP) resize(null) build().apply { Assert.assertNull(definedOptions.resizeSizeResolver) Assert.assertNull(definedOptions.resizePrecisionDecider) Assert.assertNull(definedOptions.resizeScaleDecider) Assert.assertEquals(DisplaySizeResolver(context1), resizeSizeResolver) Assert.assertEquals(FixedPrecisionDecider(LESS_PIXELS), resizePrecisionDecider) Assert.assertEquals(FixedScaleDecider(CENTER_CROP), resizeScaleDecider) } resize(Size(100, 100), SAME_ASPECT_RATIO, START_CROP) build().apply { Assert.assertEquals( FixedSizeResolver(Size(100, 100)), definedOptions.resizeSizeResolver ) Assert.assertEquals( FixedPrecisionDecider(SAME_ASPECT_RATIO), definedOptions.resizePrecisionDecider ) Assert.assertEquals( FixedScaleDecider(START_CROP), definedOptions.resizeScaleDecider ) Assert.assertEquals(FixedSizeResolver(Size(100, 100)), resizeSizeResolver) Assert.assertEquals( FixedPrecisionDecider(SAME_ASPECT_RATIO), resizePrecisionDecider ) Assert.assertEquals(FixedScaleDecider(START_CROP), resizeScaleDecider) } resize(Size(100, 100)) build().apply { Assert.assertEquals( FixedSizeResolver(Size(100, 100)), definedOptions.resizeSizeResolver ) Assert.assertNull(definedOptions.resizePrecisionDecider) Assert.assertNull(definedOptions.resizeScaleDecider) Assert.assertEquals(FixedSizeResolver(Size(100, 100)), resizeSizeResolver) Assert.assertEquals(FixedPrecisionDecider(LESS_PIXELS), resizePrecisionDecider) Assert.assertEquals(FixedScaleDecider(CENTER_CROP), resizeScaleDecider) } resize(Size(100, 100), SAME_ASPECT_RATIO, START_CROP) resize(Size(100, 100), EXACTLY) build().apply { Assert.assertEquals( FixedSizeResolver(Size(100, 100)), definedOptions.resizeSizeResolver ) Assert.assertEquals( FixedPrecisionDecider(EXACTLY), definedOptions.resizePrecisionDecider ) Assert.assertNull(definedOptions.resizeScaleDecider) Assert.assertEquals(FixedSizeResolver(Size(100, 100)), resizeSizeResolver) Assert.assertEquals(FixedPrecisionDecider(EXACTLY), resizePrecisionDecider) Assert.assertEquals(FixedScaleDecider(CENTER_CROP), resizeScaleDecider) } resize(Size(100, 100), SAME_ASPECT_RATIO, START_CROP) resize(Size(100, 100), scale = END_CROP) build().apply { Assert.assertEquals( FixedSizeResolver(Size(100, 100)), definedOptions.resizeSizeResolver ) Assert.assertNull(definedOptions.resizePrecisionDecider) Assert.assertEquals(FixedScaleDecider(END_CROP), definedOptions.resizeScaleDecider) Assert.assertEquals(FixedSizeResolver(Size(100, 100)), resizeSizeResolver) Assert.assertEquals(FixedPrecisionDecider(LESS_PIXELS), resizePrecisionDecider) Assert.assertEquals(FixedScaleDecider(END_CROP), resizeScaleDecider) } resize(Size(100, 100), SAME_ASPECT_RATIO, START_CROP) resize(null) build().apply { Assert.assertNull(definedOptions.resizeSizeResolver) Assert.assertNull(definedOptions.resizePrecisionDecider) Assert.assertNull(definedOptions.resizeScaleDecider) Assert.assertEquals(DisplaySizeResolver(context1), resizeSizeResolver) Assert.assertEquals(FixedPrecisionDecider(LESS_PIXELS), resizePrecisionDecider) Assert.assertEquals(FixedScaleDecider(CENTER_CROP), resizeScaleDecider) } } } @Test fun testResizeSize() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertNull(definedOptions.resizeSizeResolver) Assert.assertEquals(DisplaySizeResolver(context1), resizeSizeResolver) } resizeSize(Size(100, 100)) build().apply { Assert.assertEquals(FixedSizeResolver(100, 100), definedOptions.resizeSizeResolver) Assert.assertEquals(FixedSizeResolver(100, 100), resizeSizeResolver) } resizeSize(200, 200) build().apply { Assert.assertEquals(FixedSizeResolver(200, 200), definedOptions.resizeSizeResolver) Assert.assertEquals(FixedSizeResolver(200, 200), resizeSizeResolver) } resizeSize(FixedSizeResolver(300, 200)) build().apply { Assert.assertEquals(FixedSizeResolver(300, 200), definedOptions.resizeSizeResolver) Assert.assertEquals(FixedSizeResolver(300, 200), resizeSizeResolver) } resizeSize(null) build().apply { Assert.assertNull(definedOptions.resizeSizeResolver) Assert.assertEquals(DisplaySizeResolver(context1), resizeSizeResolver) } } } @Test fun testResizePrecision() { val (context, sketch) = getTestContextAndNewSketch() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context, uriString1).apply { build().apply { Assert.assertEquals(FixedPrecisionDecider(LESS_PIXELS), resizePrecisionDecider) } resizePrecision(LongImageClipPrecisionDecider(EXACTLY)) build().apply { Assert.assertEquals(LongImageClipPrecisionDecider(EXACTLY), resizePrecisionDecider) } resizePrecision(SAME_ASPECT_RATIO) build().apply { Assert.assertEquals( FixedPrecisionDecider(SAME_ASPECT_RATIO), resizePrecisionDecider ) } resizePrecision(null) build().apply { Assert.assertEquals(FixedPrecisionDecider(LESS_PIXELS), resizePrecisionDecider) } } val request = LoadRequest(context, uriString1).apply { Assert.assertEquals(DisplaySizeResolver(context), resizeSizeResolver) Assert.assertEquals(FixedPrecisionDecider(LESS_PIXELS), resizePrecisionDecider) } val size = runBlocking { DisplaySizeResolver(context).size() } val request1 = request.newLoadRequest { resizeSize(size) }.apply { Assert.assertEquals(FixedSizeResolver(size), resizeSizeResolver) Assert.assertEquals(FixedPrecisionDecider(LESS_PIXELS), resizePrecisionDecider) } request1.newLoadRequest().apply { Assert.assertEquals(FixedSizeResolver(size), resizeSizeResolver) Assert.assertEquals(FixedPrecisionDecider(LESS_PIXELS), resizePrecisionDecider) } request.apply { Assert.assertEquals(FixedPrecisionDecider(LESS_PIXELS), resizePrecisionDecider) } runBlocking { sketch.execute(request) }.apply { Assert.assertEquals( FixedPrecisionDecider(LESS_PIXELS), this.request.resizePrecisionDecider ) } } @Test fun testResizeScale() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertEquals(FixedScaleDecider(CENTER_CROP), resizeScaleDecider) } resizeScale(LongImageScaleDecider(START_CROP, END_CROP)) build().apply { Assert.assertEquals(LongImageScaleDecider(START_CROP, END_CROP), resizeScaleDecider) } resizeScale(FILL) build().apply { Assert.assertEquals(FixedScaleDecider(FILL), resizeScaleDecider) } resizeScale(null) build().apply { Assert.assertEquals(FixedScaleDecider(CENTER_CROP), resizeScaleDecider) } } } @Test fun testTransformations() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertNull(transformations) } /* transformations() */ transformations(listOf(CircleCropTransformation())) build().apply { Assert.assertEquals( listOf(CircleCropTransformation()), transformations ) } transformations(RoundedCornersTransformation(), RotateTransformation(40)) build().apply { Assert.assertEquals( listOf(RoundedCornersTransformation(), RotateTransformation(40)), transformations ) } transformations(null) build().apply { Assert.assertNull(transformations) } /* addTransformations(List), removeTransformations(List) */ addTransformations(listOf(CircleCropTransformation())) build().apply { Assert.assertEquals( listOf(CircleCropTransformation()), transformations ) } addTransformations(listOf(CircleCropTransformation(), RotateTransformation(40))) build().apply { Assert.assertEquals( listOf(CircleCropTransformation(), RotateTransformation(40)), transformations ) } removeTransformations(listOf(RotateTransformation(40))) build().apply { Assert.assertEquals( listOf(CircleCropTransformation()), transformations ) } removeTransformations(listOf(CircleCropTransformation())) build().apply { Assert.assertNull(transformations) } /* addTransformations(vararg), removeTransformations(vararg) */ addTransformations(CircleCropTransformation()) build().apply { Assert.assertEquals( listOf(CircleCropTransformation()), transformations ) } addTransformations(CircleCropTransformation(), RotateTransformation(40)) build().apply { Assert.assertEquals( listOf(CircleCropTransformation(), RotateTransformation(40)), transformations ) } removeTransformations(RotateTransformation(40)) build().apply { Assert.assertEquals( listOf(CircleCropTransformation()), transformations ) } removeTransformations(CircleCropTransformation()) build().apply { Assert.assertNull(transformations) } } } @Test fun testDisallowReuseBitmap() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertFalse(disallowReuseBitmap) } disallowReuseBitmap() build().apply { Assert.assertEquals(true, disallowReuseBitmap) } disallowReuseBitmap(false) build().apply { Assert.assertEquals(false, disallowReuseBitmap) } disallowReuseBitmap(null) build().apply { Assert.assertFalse(disallowReuseBitmap) } } } @Test fun testIgnoreExifOrientation() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertFalse(ignoreExifOrientation) } ignoreExifOrientation(true) build().apply { Assert.assertEquals(true, ignoreExifOrientation) } ignoreExifOrientation(false) build().apply { Assert.assertEquals(false, ignoreExifOrientation) } ignoreExifOrientation(null) build().apply { Assert.assertFalse(ignoreExifOrientation) } } } @Test fun testResultCachePolicy() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertEquals(ENABLED, resultCachePolicy) } resultCachePolicy(READ_ONLY) build().apply { Assert.assertEquals(READ_ONLY, resultCachePolicy) } resultCachePolicy(DISABLED) build().apply { Assert.assertEquals(DISABLED, resultCachePolicy) } resultCachePolicy(null) build().apply { Assert.assertEquals(ENABLED, resultCachePolicy) } } } @Test fun testDisallowAnimatedImage() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertFalse(disallowAnimatedImage) } disallowAnimatedImage(true) build().apply { Assert.assertEquals(true, disallowAnimatedImage) } disallowAnimatedImage(false) build().apply { Assert.assertEquals(false, disallowAnimatedImage) } disallowAnimatedImage(null) build().apply { Assert.assertFalse(disallowAnimatedImage) } } } @Test fun testPlaceholder() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertNull(placeholder) } placeholder(ColorStateImage(IntColor(Color.BLUE))) build().apply { Assert.assertEquals(ColorStateImage(IntColor(Color.BLUE)), placeholder) } placeholder(ColorDrawable(Color.GREEN)) build().apply { Assert.assertEquals(true, placeholder is DrawableStateImage) } placeholder(drawable.bottom_bar) build().apply { Assert.assertEquals( DrawableStateImage(drawable.bottom_bar), placeholder ) } placeholder(null) build().apply { Assert.assertNull(placeholder) } } } @Test fun testError() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertNull(error) } error(ColorStateImage(IntColor(Color.BLUE))) build().apply { Assert.assertEquals( ErrorStateImage(ColorStateImage(IntColor(Color.BLUE))), error ) } error(ColorDrawable(Color.GREEN)) build().apply { Assert.assertEquals(true, error is ErrorStateImage) } error(drawable.bottom_bar) build().apply { Assert.assertEquals( ErrorStateImage(DrawableStateImage(drawable.bottom_bar)), error ) } error(drawable.bottom_bar) { uriEmptyError(drawable.alert_dark_frame) } build().apply { Assert.assertEquals( ErrorStateImage(DrawableStateImage(drawable.bottom_bar)) { uriEmptyError(drawable.alert_dark_frame) }, error ) } error() build().apply { Assert.assertNull(error) } error { uriEmptyError(drawable.btn_dialog) } build().apply { Assert.assertNotNull(error) } } } @Test fun testTransitionFactory() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertNull(transitionFactory) } transitionFactory(CrossfadeTransition.Factory()) build().apply { Assert.assertEquals(CrossfadeTransition.Factory(), transitionFactory) } transitionFactory(null) build().apply { Assert.assertNull(transitionFactory) } } } @Test fun testResizeApplyToDrawable() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertFalse(resizeApplyToDrawable) } resizeApplyToDrawable() build().apply { Assert.assertEquals(true, resizeApplyToDrawable) } resizeApplyToDrawable(false) build().apply { Assert.assertEquals(false, resizeApplyToDrawable) } resizeApplyToDrawable(null) build().apply { Assert.assertFalse(resizeApplyToDrawable) } } } @Test fun testMemoryCachePolicy() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertEquals(ENABLED, memoryCachePolicy) } memoryCachePolicy(READ_ONLY) build().apply { Assert.assertEquals(READ_ONLY, memoryCachePolicy) } memoryCachePolicy(DISABLED) build().apply { Assert.assertEquals(DISABLED, memoryCachePolicy) } memoryCachePolicy(null) build().apply { Assert.assertEquals(ENABLED, memoryCachePolicy) } } } @Test fun testListener() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertNull(listener) } listener(onStart = {}, onCancel = {}, onError = { _, _ -> }, onSuccess = { _, _ -> }) build().apply { Assert.assertNotNull(listener) Assert.assertTrue(listener !is CombinedListener<*, *, *>) } build().newLoadRequest().apply { Assert.assertNotNull(listener) Assert.assertTrue(listener !is CombinedListener<*, *, *>) } listener(onStart = {}) build().apply { Assert.assertNotNull(listener) Assert.assertTrue(listener !is CombinedListener<*, *, *>) } listener(onCancel = {}) build().apply { Assert.assertNotNull(listener) Assert.assertTrue(listener !is CombinedListener<*, *, *>) } listener(onError = { _, _ -> }) build().apply { Assert.assertNotNull(listener) Assert.assertTrue(listener !is CombinedListener<*, *, *>) } listener(onSuccess = { _, _ -> }) build().apply { Assert.assertNotNull(listener) Assert.assertTrue(listener !is CombinedListener<*, *, *>) } listener(null) build().apply { Assert.assertNull(listener) } } } @Test fun testProgressListener() { val context1 = getTestContext() val uriString1 = newAssetUri("sample.jpeg") LoadRequest.Builder(context1, uriString1).apply { build().apply { Assert.assertNull(progressListener) } progressListener { _, _, _ -> } build().apply { Assert.assertNotNull(progressListener) Assert.assertTrue(progressListener !is CombinedProgressListener<*>) } build().newLoadRequest().apply { Assert.assertNotNull(progressListener) Assert.assertTrue(progressListener !is CombinedProgressListener<*>) } progressListener(null) build().apply { Assert.assertNull(progressListener) } } } @Test fun testComponents() { val context = getTestContext() LoadRequest(context, TestAssets.SAMPLE_JPEG_URI).apply { Assert.assertNull(componentRegistry) } LoadRequest(context, TestAssets.SAMPLE_JPEG_URI) { components { addFetcher(HttpUriFetcher.Factory()) addFetcher(TestFetcher.Factory()) addBitmapDecoder(DefaultBitmapDecoder.Factory()) addBitmapDecoder(TestBitmapDecoder.Factory()) addDrawableDecoder(DefaultDrawableDecoder.Factory()) addDrawableDecoder(TestDrawableDecoder.Factory()) addRequestInterceptor(TestRequestInterceptor()) addBitmapDecodeInterceptor(TestBitmapDecodeInterceptor()) addDrawableDecodeInterceptor(TestDrawableDecodeInterceptor()) } }.apply { Assert.assertEquals( ComponentRegistry.Builder().apply { addFetcher(HttpUriFetcher.Factory()) addFetcher(TestFetcher.Factory()) addBitmapDecoder(DefaultBitmapDecoder.Factory()) addBitmapDecoder(TestBitmapDecoder.Factory()) addDrawableDecoder(DefaultDrawableDecoder.Factory()) addDrawableDecoder(TestDrawableDecoder.Factory()) addRequestInterceptor(TestRequestInterceptor()) addBitmapDecodeInterceptor(TestBitmapDecodeInterceptor()) addDrawableDecodeInterceptor(TestDrawableDecodeInterceptor()) }.build(), componentRegistry ) } } @Test fun testEqualsAndHashCode() { val context = getTestContext() val element1 = LoadRequest(context, TestAssets.SAMPLE_JPEG_URI) val element11 = LoadRequest(context, TestAssets.SAMPLE_JPEG_URI) val element2 = LoadRequest(context, TestAssets.SAMPLE_PNG_URI) Assert.assertNotSame(element1, element11) Assert.assertNotSame(element1, element2) Assert.assertNotSame(element2, element11) Assert.assertEquals(element1, element1) Assert.assertEquals(element1, element11) Assert.assertNotEquals(element1, element2) Assert.assertNotEquals(element2, element11) Assert.assertNotEquals(element1, null) Assert.assertNotEquals(element1, Any()) Assert.assertEquals(element1.hashCode(), element1.hashCode()) Assert.assertEquals(element1.hashCode(), element11.hashCode()) Assert.assertNotEquals(element1.hashCode(), element2.hashCode()) Assert.assertNotEquals(element2.hashCode(), element11.hashCode()) LoadRequest(context, TestAssets.SAMPLE_JPEG_URI).apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { listener(onStart = {}) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { progressListener { _, _, _ -> } }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { target() }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { default(ImageOptions()) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { depth(LOCAL, "test") }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { setParameter("type", "list") setParameter("big", "true") }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { setHttpHeader("from", "china") setHttpHeader("job", "Programmer") addHttpHeader("Host", "www.google.com") }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { downloadCachePolicy(READ_ONLY) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { bitmapConfig(RGB_565) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { if (VERSION.SDK_INT >= VERSION_CODES.O) { colorSpace(ColorSpace.get(ADOBE_RGB)) } }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { @Suppress("DEPRECATION") preferQualityOverSpeed(true) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { resizeSize(300, 200) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { resizePrecision(EXACTLY) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { resizePrecision(LongImageClipPrecisionDecider()) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { resizeScale(END_CROP) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { resizeScale(LongImageScaleDecider()) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { transformations(CircleCropTransformation(), BlurTransformation()) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { disallowReuseBitmap(true) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { ignoreExifOrientation(true) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { resultCachePolicy(WRITE_ONLY) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { placeholder(IconStateImage(drawable.ic_delete, color.background_dark)) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { placeholder(ColorStateImage(Color.BLUE)) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { placeholder(ColorStateImage(ResColor(color.background_dark))) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { placeholder(DrawableStateImage(context.getDrawable(drawable.ic_delete)!!)) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { placeholder(DrawableStateImage(drawable.ic_delete)) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { placeholder(CurrentStateImage(drawable.ic_delete)) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { placeholder(MemoryCacheStateImage("uri", ColorStateImage(Color.BLUE))) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { placeholder(ThumbnailMemoryCacheStateImage("uri", ColorStateImage(Color.BLUE))) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { error(DrawableStateImage(drawable.ic_delete)) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { error(DrawableStateImage(drawable.ic_delete)) { uriEmptyError(ColorStateImage(Color.BLUE)) } }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { transitionFactory(CrossfadeTransition.Factory()) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { transitionFactory(CrossfadeTransition.Factory(fadeStart = false, alwaysUse = true)) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { disallowAnimatedImage(true) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { resizeApplyToDrawable(true) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { memoryCachePolicy(WRITE_ONLY) }.apply { Assert.assertEquals(this, this.newLoadRequest()) }.newLoadRequest { components { addFetcher(TestFetcher.Factory()) addRequestInterceptor(TestRequestInterceptor()) addDrawableDecodeInterceptor(TestDrawableDecodeInterceptor()) addDrawableDecoder(TestDrawableDecoder.Factory()) addBitmapDecodeInterceptor(TestBitmapDecodeInterceptor()) addBitmapDecoder(TestBitmapDecoder.Factory()) } }.apply { Assert.assertEquals(this, this.newLoadRequest()) } } }
sketch/src/androidTest/java/com/github/panpf/sketch/test/request/LoadRequestTest.kt
780410976
package com.icapps.niddler.ui.form.ui import com.icapps.niddler.lib.connection.model.NiddlerServerInfo /** * @author nicolaverbeeck */ interface NiddlerStatusbar { fun onDebuggerAttached() fun onDebuggerStatusChanged(active: Boolean) fun onConnected() fun onDisconnected() fun onApplicationInfo(information: NiddlerServerInfo) }
niddler-ui/src/main/kotlin/com/icapps/niddler/ui/form/ui/NiddlerStatusbar.kt
569123524
package org.jackJew.biz.engine.test import com.google.gson.JsonObject import org.jackJew.biz.engine.JsEngine import org.jackJew.biz.engine.JsEngineNashorn import org.jackJew.biz.engine.util.IOUtils import org.junit.Test class CrawlerTest { @Test fun crawl() { val start = System.currentTimeMillis() val scriptFile = "org/jackJew/biz/engine/test/config/dd_shop.js" val url = "http://category.dangdang.com/cid4001867.html" val cl = Thread.currentThread().contextClassLoader cl.getResourceAsStream(scriptFile).use { val script = IOUtils.toString(it, JsEngine.DEFAULT_CHARSET) val config = JsonObject().apply { addProperty("url", url) } val result = JsEngineNashorn.INSTANCE.runScript2JSON( String.format("(function(args){%s})(%s);", script, config.toString()) ) println(result) println("time cost: ${System.currentTimeMillis() - start} ms.") } } }
src/test/java/org/jackJew/biz/engine/test/CrawlerTest.kt
4243422777
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.task import android.content.Context import de.vanita5.twittnuker.model.SingleResponse abstract class ExceptionHandlingAbstractTask<Params, Result, TaskException : Exception, Callback>( context: Context ) : BaseAbstractTask<Params, SingleResponse<Result>, Callback>(context) { protected abstract val exceptionClass: Class<TaskException> override final fun afterExecute(callback: Callback?, results: SingleResponse<Result>) { @Suppress("UNCHECKED_CAST") afterExecute(callback, results.data, results.exception as? TaskException) if (results.data != null) { onSucceed(callback, results.data) } else if (results.exception != null) { if (exceptionClass.isInstance(results.exception)) { @Suppress("UNCHECKED_CAST") onException(callback, results.exception as TaskException) } else { throw results.exception } } } override final fun doLongOperation(params: Params): SingleResponse<Result> { try { return SingleResponse(onExecute(params)) } catch (tr: Exception) { if (exceptionClass.isInstance(tr)) return SingleResponse(tr) throw tr } } open fun afterExecute(callback: Callback?, result: Result?, exception: TaskException?) { } open fun onSucceed(callback: Callback?, result: Result) { } open fun onException(callback: Callback?, exception: TaskException) { } abstract fun onExecute(params: Params): Result }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/task/ExceptionHandlingAbstractTask.kt
3252321750